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/textutils.h"
73 #include "support/Messages.h"
74 #include "support/os.h"
75 #include "support/Package.h"
76 #include "support/TempFile.h"
79 #include "support/AppleScript.h"
80 #include "support/linkback/LinkBackProxy.h"
88 #include <QDesktopWidget>
92 #include <QFileOpenEvent>
96 #include <QImageReader>
99 #include <QLibraryInfo>
105 #include <QPixmapCache>
107 #include <QSessionManager>
109 #include <QShowEvent>
110 #include <QSocketNotifier>
111 #include <QSortFilterProxyModel>
112 #include <QStandardItemModel>
113 #include <QTextCodec>
115 #include <QTranslator>
116 #include <QThreadPool>
120 #include <X11/Xatom.h>
121 #include <X11/Xlib.h>
124 #elif defined(QPA_XCB)
128 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
129 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
130 #if (QT_VERSION < 0x050000)
131 #include <QWindowsMime>
132 #define QWINDOWSMIME QWindowsMime
135 #define QWINDOWSMIME QWinMime
145 #include <QMacPasteboardMime>
148 #include "support/bind.h"
149 #include <boost/crc.hpp>
156 using namespace lyx::support;
159 static void initializeResources()
161 static bool initialized = false;
163 Q_INIT_RESOURCE(Resources);
171 frontend::Application * createApplication(int & argc, char * argv[])
173 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
174 // prune -geometry argument(s) by shifting
175 // the following ones 2 places down.
176 for (int i = 0 ; i < argc ; ++i) {
177 if (strcmp(argv[i], "-geometry") == 0) {
178 int const remove = (i+1) < argc ? 2 : 1;
180 for (int j = i; j < argc; ++j)
181 argv[j] = argv[j + remove];
186 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
187 // I'd rather do that in the constructor, but I do not think that
188 // the palette is accessible there.
189 guiApp->colorCache().setPalette(guiApp->palette());
198 if (lyxrc.gui_language == "auto") {
199 theLocale = QLocale::system();
200 code = fromqstr(theLocale.name());
202 Language const * l = languages.getLanguage(lyxrc.gui_language);
203 code = l ? l->code() : "C";
204 theLocale = QLocale(toqstr(code));
206 // Qt tries to outsmart us and transforms en_US to C.
207 Messages::guiLanguage((code == "C") ? "en_US" : code);
208 QLocale::setDefault(theLocale);
209 setlocale(LC_NUMERIC, "C");
216 /// Return the list of loadable formats.
217 vector<string> loadableImageFormats()
221 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
223 LYXERR(Debug::GRAPHICS,
224 "\nThe image loader can load the following directly:\n");
226 if (qt_formats.empty())
227 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
229 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
231 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
233 string ext = ascii_lowercase((const char *) *it);
244 ////////////////////////////////////////////////////////////////////////
246 // Icon loading support code
248 ////////////////////////////////////////////////////////////////////////
258 bool operator<(PngMap const & lhs, PngMap const & rhs)
260 return lhs.key < rhs.key;
266 CompareKey(QString const & name) : name_(name) {}
267 bool operator()(PngMap const & other) const { return other.key == name_; }
273 // this must be sorted alphabetically
274 // Upper case comes before lower case
275 // Please don't change the formatting, this list is parsed by
276 // development/tools/generate_symbols_images.py.
277 PngMap sorted_png_map[] = {
278 { "Arrownot", "arrownot2"},
279 { "Arrowvert", "arrowvert2"},
280 { "Bowtie", "bowtie2" },
282 { "Bumpeq", "bumpeq2" },
283 { "CIRCLE", "circle3" },
285 { "CheckedBox", "checkedbox2" },
286 { "Circle", "circle2" },
287 { "Colonapprox", "colonapprox2" },
288 { "Coloneq", "coloneq2" },
289 { "Coloneqq", "coloneqq2" },
290 { "Colonsim", "colonsim2" },
292 { "DOWNarrow", "downarrow3" },
293 { "Delta", "delta2" },
294 { "Diamond", "diamond2" },
295 { "Doteq", "doteq2" },
296 { "Downarrow", "downarrow2" },
297 { "Eqcolon", "eqcolon2" },
298 { "Eqqcolon", "eqqcolon2" },
299 { "Gamma", "gamma2" },
301 { "LEFTCIRCLE", "leftcircle3" },
302 { "LEFTarrow", "leftarrow3" },
303 { "LEFTcircle", "leftcircle4" },
305 { "Lambda", "lambda2" },
307 { "Leftarrow", "leftarrow2" },
308 { "Leftcircle", "leftcircle2" },
309 { "Leftrightarrow", "leftrightarrow2" },
310 { "Longarrownot", "longarrownot2"},
311 { "Longleftarrow", "longleftarrow2" },
312 { "Longleftrightarrow", "longleftrightarrow2" },
313 { "Longmapsfrom", "longmapsfrom2"},
314 { "Longmapsto", "longmapsto2"},
315 { "Longrightarrow", "longrightarrow2" },
316 { "Mapsfrom", "mapsfrom2"},
317 { "Mapsfromchar", "mapsfromchar2"},
318 { "Mapsto", "mapsto2"},
319 { "Mapstochar", "mapstochar2"},
320 { "Omega", "omega2" },
325 { "RIGHTCIRCLE", "rightcircle3" },
326 { "RIGHTarrow", "rightarrow3" },
327 { "RIGHTcircle", "rightcircle4" },
329 { "Rightarrow", "rightarrow2" },
330 { "Rightcircle", "rightcircle2" },
331 { "Sigma", "sigma2" },
332 { "Square", "square2" },
333 { "Subset", "subset2" },
334 { "Supset", "supset2" },
335 { "Theta", "theta2" },
336 { "Thorn", "thorn2" },
337 { "UParrow", "uparrow3" },
338 { "Uparrow", "uparrow2" },
339 { "Updownarrow", "updownarrow2" },
340 { "Upsilon", "upsilon2" },
341 { "Vdash", "vdash3" },
346 { "lVert", "vert2" },
348 { "nLeftarrow", "nleftarrow2" },
349 { "nLeftrightarrow", "nleftrightarrow2" },
350 { "nRightarrow", "nrightarrow2" },
351 { "nVDash", "nvdash3" },
352 { "nVdash", "nvdash4" },
353 { "nvDash", "nvdash2" },
354 { "rVert", "vert2" },
356 { "textrm \\AA", "textrm_AA"},
357 { "textrm \\O", "textrm_O"},
358 { "vDash", "vdash2" },
359 { "varDelta", "vardelta2" },
360 { "varGamma", "vargamma2" },
361 { "varLambda", "varlambda2" },
362 { "varOmega", "varomega2" },
363 { "varPhi", "varphi2" },
364 { "varPi", "varpi2" },
365 { "varPsi", "varpsi2" },
366 { "varSigma", "varsigma2" },
367 { "varTheta", "vartheta2" },
368 { "varUpsilon", "varupsilon2" },
369 { "varXi", "varxi2" }
373 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
375 // This list specifies which system's theme icon is related to which lyx
376 // command. It was based on:
377 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
378 // this must be sorted alphabetically
379 // Upper case comes before lower case
380 PngMap sorted_theme_icon_map[] = {
381 { "bookmark-goto 0", "go-jump" },
382 { "buffer-new", "document-new" },
383 { "buffer-print", "document-print" },
384 { "buffer-write", "document-save" },
385 { "buffer-write-as", "document-save-as" },
386 { "buffer-zoom-in", "zoom-in" },
387 { "buffer-zoom-out", "zoom-out" },
388 { "copy", "edit-copy" },
389 { "cut", "edit-cut" },
390 { "depth-decrement", "format-indent-less" },
391 { "depth-increment", "format-indent-more" },
392 { "dialog-show print", "document-print" },
393 { "dialog-show spellchecker", "tools-check-spelling" },
394 { "dialog-show-new-inset graphics", "insert-image" },
395 { "dialog-toggle findreplaceadv", "edit-find-replace" },
396 { "file-open", "document-open" },
397 { "font-bold", "format-text-bold" },
398 { "font-ital", "format-text-italic" },
399 { "font-strikeout", "format-text-strikethrough" },
400 { "font-underline", "format-text-underline" },
401 { "lyx-quit", "application-exit" },
402 { "paste", "edit-paste" },
403 { "redo", "edit-redo" },
404 { "undo", "edit-undo" },
405 { "window-close", "window-close" },
406 { "window-new", "window-new" }
409 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(PngMap);
412 QString findPng(QString const & name)
414 PngMap const * const begin = sorted_png_map;
415 PngMap const * const end = begin + nr_sorted_png_map;
416 LATTEST(sorted(begin, end));
418 PngMap const * const it = find_if(begin, end, CompareKey(name));
422 png_name = it->value;
425 png_name.replace('_', "underscore");
426 png_name.replace(' ', '_');
428 // This way we can have "math-delim { }" on the toolbar.
429 png_name.replace('(', "lparen");
430 png_name.replace(')', "rparen");
431 png_name.replace('[', "lbracket");
432 png_name.replace(']', "rbracket");
433 png_name.replace('{', "lbrace");
434 png_name.replace('}', "rbrace");
435 png_name.replace('|', "bars");
436 png_name.replace(',', "thinspace");
437 png_name.replace(':', "mediumspace");
438 png_name.replace(';', "thickspace");
439 png_name.replace('!', "negthinspace");
442 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
443 << "Looking for math PNG called \"" << png_name << '"');
450 QString themeIconName(QString const & action)
452 PngMap const * const begin = sorted_theme_icon_map;
453 PngMap const * const end = begin + nr_sorted_theme_icon_map;
454 LASSERT(sorted(begin, end), /**/);
456 PngMap const * const it = find_if(begin, end, CompareKey(action));
464 QString iconName(FuncRequest const & f, bool unknown)
466 initializeResources();
470 switch (f.action()) {
471 case LFUN_MATH_INSERT:
472 if (!f.argument().empty()) {
474 name1 = findPng(toqstr(f.argument()).mid(1));
477 case LFUN_MATH_DELIM:
478 case LFUN_MATH_BIGDELIM:
480 name1 = findPng(toqstr(f.argument()));
484 name1 = toqstr(f.argument());
486 case LFUN_COMMAND_ALTERNATIVES: {
487 // use the first of the alternative commands
489 docstring dummy = split(f.argument(), firstcom, ';');
490 name1 = toqstr(firstcom);
491 // FIXME: we should rename the icons to tabular-xxx instead of
492 // "tabular-feature-xxx"
493 name1.replace("inset-modify tabular", "tabular-feature");
494 name1.replace(' ', '_');
497 case LFUN_INSET_MODIFY: {
498 // FIXME: we should rename the icons to tabular-xxx instead of
499 // "tabular-feature-xxx" and generalize this naming to all
500 // insets, not to tabular using ones.
502 string const command = split(to_utf8(f.argument()), inset_name, ' ');
503 if (insetCode(inset_name) == TABULAR_CODE) {
504 name1 = "tabular-feature "+ toqstr(command);
505 name1.replace(' ', '_');
510 name2 = toqstr(lyxaction.getActionName(f.action()));
513 if (!f.argument().empty()) {
514 name1 = name2 + ' ' + toqstr(f.argument());
515 name1.replace(' ', '_');
516 name1.replace('\\', "backslash");
520 QStringList imagedirs;
521 imagedirs << "images/" << "images/ipa/";
522 search_mode mode = theGuiApp()->imageSearchMode();
523 for (int i = 0; i < imagedirs.size(); ++i) {
524 QString imagedir = imagedirs.at(i) + path;
525 FileName fname = imageLibFileSearch(imagedir, name1, "svgz,png", mode);
527 return toqstr(fname.absFileName());
529 fname = imageLibFileSearch(imagedir, name2, "svgz,png", mode);
531 return toqstr(fname.absFileName());
534 path = ":/images/" + path;
537 LYXERR0("Directory " << path << " not found in resource!");
540 if (res.exists(name1 + ".svgz"))
541 return path + name1 + ".svgz";
542 else if (res.exists(name1 + ".png"))
543 return path + name1 + ".png";
545 if (res.exists(name2 + ".svgz"))
546 return path + name2 + ".svgz";
547 else if (res.exists(name2 + ".png"))
548 return path + name2 + ".png";
550 LYXERR(Debug::GUI, "Cannot find icon with filename "
551 << "\"" << name1 << ".{svgz,png}\""
553 << "\"" << name2 << ".{svgz,png}\""
555 << lyxaction.getActionName(f.action())
556 << '(' << to_utf8(f.argument()) << ")\"");
559 QString imagedir = "images/";
560 FileName fname = imageLibFileSearch(imagedir, "unknown", "svgz,png", mode);
562 return toqstr(fname.absFileName());
563 return QString(":/images/unknown.png");
570 bool getPixmap(QPixmap & pixmap, QString const & path)
572 if (pixmap.load(path)) {
573 #if QT_VERSION >= 0x050000
574 if (path.endsWith(".svgz") || path.endsWith(".svg") ) {
575 GuiApplication const * guiApp = theGuiApp();
577 pixmap.setDevicePixelRatio(guiApp->pixelRatio());
587 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
589 QString imagedir = path;
590 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
591 QString fpath = toqstr(fname.absFileName());
592 QPixmap pixmap = QPixmap();
594 if (getPixmap(pixmap, fpath)) {
598 QStringList exts = ext.split(",");
599 fpath = ":/" + path + name + ".";
600 for (int i = 0; i < exts.size(); ++i) {
601 if (getPixmap(pixmap, fpath + exts.at(i))) {
606 bool const list = ext.contains(",");
607 LYXERR0("Cannot load pixmap \""
608 << path << name << "." << (list ? "{" : "") << ext
609 << (list ? "}" : "") << "\", please verify resource system!");
615 QIcon getIcon(FuncRequest const & f, bool unknown)
617 #if (QT_VERSION >= 0x040600)
618 if (lyxrc.use_system_theme_icons) {
619 QString action = toqstr(lyxaction.getActionName(f.action()));
620 if (!f.argument().empty())
621 action += " " + toqstr(f.argument());
622 QString const theme_icon = themeIconName(action);
623 if (QIcon::hasThemeIcon(theme_icon))
624 return QIcon::fromTheme(theme_icon);
628 QString icon = iconName(f, unknown);
632 //LYXERR(Debug::GUI, "Found icon: " << icon);
633 QPixmap pixmap = QPixmap();
634 if (!getPixmap(pixmap,icon)) {
635 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
639 return QIcon(pixmap);
643 ////////////////////////////////////////////////////////////////////////
645 // LyX server support code.
647 ////////////////////////////////////////////////////////////////////////
649 class SocketNotifier : public QSocketNotifier
652 /// connect a connection notification from the LyXServerSocket
653 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
654 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
658 /// The callback function
659 Application::SocketCallback func_;
663 ////////////////////////////////////////////////////////////////////////
665 // Mac specific stuff goes here...
667 ////////////////////////////////////////////////////////////////////////
669 class MenuTranslator : public QTranslator
672 MenuTranslator(QObject * parent)
673 : QTranslator(parent)
676 #if QT_VERSION >= 0x050000
677 virtual QString translate(const char * /* context */,
678 const char *sourceText,
679 const char * /* disambiguation */ = 0, int /* n */ = -1) const
681 QString translate(const char * /*context*/,
682 const char * sourceText,
683 const char * /*comment*/ = 0) const
686 string const s = sourceText;
687 if (s == N_("About %1") || s == N_("Preferences")
688 || s == N_("Reconfigure") || s == N_("Quit %1"))
696 // QMacPasteboardMimeGraphics can only be compiled on Mac.
698 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
701 QMacPasteboardMimeGraphics()
702 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
705 QString convertorName() { return "Graphics"; }
707 QString flavorFor(QString const & mime)
709 LYXERR(Debug::ACTION, "flavorFor " << mime);
710 if (mime == pdfMimeType())
711 return QLatin1String("com.adobe.pdf");
715 QString mimeFor(QString flav)
717 LYXERR(Debug::ACTION, "mimeFor " << flav);
718 if (flav == QLatin1String("com.adobe.pdf"))
719 return pdfMimeType();
723 bool canConvert(QString const & mime, QString flav)
725 return mimeFor(flav) == mime;
728 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
732 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
736 QList<QByteArray> convertFromMime(QString const & /*mime*/,
737 QVariant data, QString /*flav*/)
739 QList<QByteArray> ret;
740 ret.append(data.toByteArray());
746 ///////////////////////////////////////////////////////////////
748 // You can find more platform specific stuff at the end of this file...
750 ///////////////////////////////////////////////////////////////
752 ////////////////////////////////////////////////////////////////////////
753 // Windows specific stuff goes here...
755 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
756 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
757 // QWindowsMimeMetafile can only be compiled on Windows.
759 static FORMATETC cfFromMime(QString const & mimetype)
762 if (mimetype == emfMimeType()) {
763 formatetc.cfFormat = CF_ENHMETAFILE;
764 formatetc.tymed = TYMED_ENHMF;
765 } else if (mimetype == wmfMimeType()) {
766 formatetc.cfFormat = CF_METAFILEPICT;
767 formatetc.tymed = TYMED_MFPICT;
770 formatetc.dwAspect = DVASPECT_CONTENT;
771 formatetc.lindex = -1;
776 class QWindowsMimeMetafile : public QWINDOWSMIME {
778 QWindowsMimeMetafile() {}
780 bool canConvertFromMime(FORMATETC const & formatetc,
781 QMimeData const * mimedata) const
786 bool canConvertToMime(QString const & mimetype,
787 IDataObject * pDataObj) const
789 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
791 FORMATETC formatetc = cfFromMime(mimetype);
792 return pDataObj->QueryGetData(&formatetc) == S_OK;
795 bool convertFromMime(FORMATETC const & formatetc,
796 const QMimeData * mimedata, STGMEDIUM * pmedium) const
801 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
802 QVariant::Type preferredType) const
805 if (!canConvertToMime(mimetype, pDataObj))
808 FORMATETC formatetc = cfFromMime(mimetype);
810 if (pDataObj->GetData(&formatetc, &s) != S_OK)
814 if (s.tymed == TYMED_ENHMF) {
815 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
816 data.resize(dataSize);
817 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
818 (LPBYTE)data.data());
819 } else if (s.tymed == TYMED_MFPICT) {
820 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
821 data.resize(dataSize);
822 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
823 (LPBYTE)data.data());
826 ReleaseStgMedium(&s);
832 QVector<FORMATETC> formatsForMime(QString const & mimetype,
833 QMimeData const * mimedata) const
835 QVector<FORMATETC> formats;
836 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
837 formats += cfFromMime(mimetype);
841 QString mimeForFormat(FORMATETC const & formatetc) const
843 switch (formatetc.cfFormat) {
845 return emfMimeType();
846 case CF_METAFILEPICT:
847 return wmfMimeType();
857 /// Allows to check whether ESC was pressed during a long operation
858 class KeyChecker : public QObject {
863 KeyChecker() : pressed_(false), started_(false) {}
866 QCoreApplication::instance()->installEventFilter(this);
871 QCoreApplication::instance()->removeEventFilter(this);
875 QCoreApplication::processEvents();
878 bool started() const {
881 bool eventFilter(QObject *obj, QEvent *event) {
882 LYXERR(Debug::ACTION, "Event Type: " << event->type());
883 switch (event->type()) {
887 case QEvent::UpdateRequest:
888 case QEvent::CursorChange:
889 case QEvent::ActionChanged:
890 case QEvent::EnabledChange:
891 case QEvent::SockAct:
894 case QEvent::ToolTipChange:
895 case QEvent::LayoutRequest:
896 case QEvent::MetaCall:
897 return QObject::eventFilter(obj, event);
899 // FIXME Blocking all these events is a bad idea.
900 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
901 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
909 ////////////////////////////////////////////////////////////////////////
910 // GuiApplication::Private definition and implementation.
911 ////////////////////////////////////////////////////////////////////////
913 struct GuiApplication::Private
915 Private(): language_model_(0), meta_fake_bit(NoModifier),
918 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
919 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
920 /// WMF Mime handler for Windows clipboard.
921 wmf_mime_ = new QWindowsMimeMetafile;
924 initKeySequences(&theTopLevelKeymap());
927 void initKeySequences(KeyMap * kb)
929 keyseq = KeySequence(kb, kb);
930 cancel_meta_seq = KeySequence(kb, kb);
934 QSortFilterProxyModel * language_model_;
936 GuiClipboard clipboard_;
938 GuiSelection selection_;
940 FontLoader font_loader_;
942 ColorCache color_cache_;
944 QTranslator qt_trans_;
946 QHash<int, SocketNotifier *> socket_notifiers_;
950 /// The global instance
953 /// this timer is used for any regular events one wants to
954 /// perform. at present it is used to check if forked processes
956 QTimer general_timer_;
958 /// delayed FuncRequests
959 std::queue<FuncRequest> func_request_queue_;
964 KeySequence cancel_meta_seq;
966 KeyModifier meta_fake_bit;
968 /// The result of last dispatch action
969 DispatchResult dispatch_result_;
971 /// Multiple views container.
973 * Warning: This must not be a smart pointer as the destruction of the
974 * object is handled by Qt when the view is closed
975 * \sa Qt::WA_DeleteOnClose attribute.
977 QHash<int, GuiView *> views_;
979 /// Only used on mac.
980 QMenuBar * global_menubar_;
983 /// Linkback mime handler for MacOSX.
984 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
987 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
988 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
989 /// WMF Mime handler for Windows clipboard.
990 QWindowsMimeMetafile * wmf_mime_;
994 /// Allows to check whether ESC was pressed during a long operation
995 KeyChecker key_checker_;
999 GuiApplication * guiApp;
1001 GuiApplication::~GuiApplication()
1004 closeAllLinkBackLinks();
1010 GuiApplication::GuiApplication(int & argc, char ** argv)
1011 : QApplication(argc, argv), current_view_(0),
1012 d(new GuiApplication::Private)
1014 QString app_name = "LyX";
1015 QCoreApplication::setOrganizationName(app_name);
1016 QCoreApplication::setOrganizationDomain("lyx.org");
1017 QCoreApplication::setApplicationName(lyx_package);
1019 qsrand(QDateTime::currentDateTime().toTime_t());
1021 // Install translator for GUI elements.
1022 installTranslator(&d->qt_trans_);
1025 // Enable reception of XCB events.
1026 installNativeEventFilter(this);
1029 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1030 // lyxrc setting for this in order to let the application stay resident.
1031 // But then we need some kind of dock icon, at least on Windows.
1033 if (lyxrc.quit_on_last_window_closed)
1034 setQuitOnLastWindowClosed(false);
1037 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1038 // seems to be the default case for applications like LyX.
1039 setQuitOnLastWindowClosed(false);
1040 // This allows to translate the strings that appear in the LyX menu.
1041 /// A translator suitable for the entries in the LyX menu.
1042 /// Only needed with Qt/Mac.
1043 installTranslator(new MenuTranslator(this));
1048 #if defined(Q_WS_X11) || defined(QPA_XCB)
1049 // doubleClickInterval() is 400 ms on X11 which is just too long.
1050 // On Windows and Mac OS X, the operating system's value is used.
1051 // On Microsoft Windows, calling this function sets the double
1052 // click interval for all applications. So we don't!
1053 QApplication::setDoubleClickInterval(300);
1056 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1058 // needs to be done before reading lyxrc
1060 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1064 // Set the cache to 5120 kilobytes which corresponds to screen size of
1065 // 1280 by 1024 pixels with a color depth of 32 bits.
1066 QPixmapCache::setCacheLimit(5120);
1068 // Initialize RC Fonts
1069 if (lyxrc.roman_font_name.empty())
1070 lyxrc.roman_font_name = fromqstr(romanFontName());
1072 if (lyxrc.sans_font_name.empty())
1073 lyxrc.sans_font_name = fromqstr(sansFontName());
1075 if (lyxrc.typewriter_font_name.empty())
1076 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1078 d->general_timer_.setInterval(500);
1079 connect(&d->general_timer_, SIGNAL(timeout()),
1080 this, SLOT(handleRegularEvents()));
1081 d->general_timer_.start();
1083 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1084 // This is clearly not enough in a time where we use threads for
1085 // document preview and/or export. 20 should be OK.
1086 QThreadPool::globalInstance()->setMaxThreadCount(20);
1090 GuiApplication * theGuiApp()
1092 return dynamic_cast<GuiApplication *>(theApp());
1096 double GuiApplication::pixelRatio() const
1098 #if QT_VERSION >= 0x050000
1099 return devicePixelRatio();
1106 void GuiApplication::clearSession()
1113 docstring Application::iconName(FuncRequest const & f, bool unknown)
1115 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1119 docstring Application::mathIcon(docstring const & c)
1121 return qstring_to_ucs4(findPng(toqstr(c)));
1125 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1129 BufferView * bv = 0;
1130 BufferView * doc_bv = 0;
1132 if (cmd.action() == LFUN_NOACTION) {
1133 status.message(from_utf8(N_("Nothing to do")));
1134 status.setEnabled(false);
1137 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1138 status.setUnknown(true);
1139 status.message(from_utf8(N_("Unknown action")));
1140 status.setEnabled(false);
1143 // Does the GuiApplication know something?
1144 else if (getStatus(cmd, status)) { }
1146 // If we do not have a GuiView, then other functions are disabled
1147 else if (!current_view_)
1148 status.setEnabled(false);
1150 // Does the GuiView know something?
1151 else if (current_view_->getStatus(cmd, status)) { }
1153 // In LyX/Mac, when a dialog is open, the menus of the
1154 // application can still be accessed without giving focus to
1155 // the main window. In this case, we want to disable the menu
1156 // entries that are buffer or view-related.
1157 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1159 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1160 status.setEnabled(false);
1163 // If we do not have a BufferView, then other functions are disabled
1164 else if (!(bv = current_view_->currentBufferView()))
1165 status.setEnabled(false);
1167 // Does the current BufferView know something?
1168 else if (bv->getStatus(cmd, status)) { }
1170 // Does the current Buffer know something?
1171 else if (bv->buffer().getStatus(cmd, status)) { }
1173 // If we do not have a document BufferView, different from the
1174 // current BufferView, then other functions are disabled
1175 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1176 status.setEnabled(false);
1178 // Does the document Buffer know something?
1179 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1182 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1183 status.message(from_utf8(N_("Command not handled")));
1184 status.setEnabled(false);
1187 // the default error message if we disable the command
1188 if (!status.enabled() && status.message().empty())
1189 status.message(from_utf8(N_("Command disabled")));
1195 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1197 // I would really like to avoid having this switch and rather try to
1198 // encode this in the function itself.
1199 // -- And I'd rather let an inset decide which LFUNs it is willing
1200 // to handle (Andre')
1202 switch (cmd.action()) {
1204 // This could be used for the no-GUI version. The GUI version is handled in
1205 // GuiView::getStatus(). See above.
1207 case LFUN_BUFFER_WRITE:
1208 case LFUN_BUFFER_WRITE_AS: {
1209 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1210 enable = b && (b->isUnnamed() || !b->isClean());
1215 case LFUN_BOOKMARK_GOTO: {
1216 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1217 enable = theSession().bookmarks().isValid(num);
1221 case LFUN_BOOKMARK_CLEAR:
1222 enable = theSession().bookmarks().hasValid();
1225 // this one is difficult to get right. As a half-baked
1226 // solution, we consider only the first action of the sequence
1227 case LFUN_COMMAND_SEQUENCE: {
1228 // argument contains ';'-terminated commands
1229 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1230 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1231 func.setOrigin(cmd.origin());
1232 flag = getStatus(func);
1236 // we want to check if at least one of these is enabled
1237 case LFUN_COMMAND_ALTERNATIVES: {
1238 // argument contains ';'-terminated commands
1239 string arg = to_utf8(cmd.argument());
1240 while (!arg.empty()) {
1242 arg = split(arg, first, ';');
1243 FuncRequest func(lyxaction.lookupFunc(first));
1244 func.setOrigin(cmd.origin());
1245 flag = getStatus(func);
1246 // if this one is enabled, the whole thing is
1255 string name = to_utf8(cmd.argument());
1256 if (theTopLevelCmdDef().lock(name, func)) {
1257 func.setOrigin(cmd.origin());
1258 flag = getStatus(func);
1259 theTopLevelCmdDef().release(name);
1261 // catch recursion or unknown command
1262 // definition. all operations until the
1263 // recursion or unknown command definition
1264 // occurs are performed, so set the state to
1271 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1273 case LFUN_PREFERENCES_SAVE:
1274 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1275 case LFUN_DEBUG_LEVEL_SET:
1276 // these are handled in our dispatch()
1279 case LFUN_WINDOW_CLOSE:
1280 enable = d->views_.size() > 0;
1283 case LFUN_BUFFER_NEW:
1284 case LFUN_BUFFER_NEW_TEMPLATE:
1285 case LFUN_FILE_OPEN:
1286 case LFUN_HELP_OPEN:
1287 case LFUN_SCREEN_FONT_UPDATE:
1288 case LFUN_SET_COLOR:
1289 case LFUN_WINDOW_NEW:
1291 case LFUN_LYXRC_APPLY:
1292 case LFUN_COMMAND_PREFIX:
1294 case LFUN_META_PREFIX:
1295 case LFUN_RECONFIGURE:
1296 case LFUN_SERVER_GET_FILENAME:
1297 case LFUN_SERVER_NOTIFY:
1301 case LFUN_BUFFER_FORALL: {
1302 if (theBufferList().empty()) {
1303 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1304 flag.setEnabled(false);
1308 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1309 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1310 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1311 flag.setEnabled(false);
1316 case LFUN_DIALOG_SHOW: {
1317 string const name = cmd.getArg(0);
1318 return name == "aboutlyx"
1320 || name == "texinfo"
1321 || name == "progress"
1322 || name == "compare";
1330 flag.setEnabled(false);
1334 /// make a post-dispatch status message
1335 static docstring makeDispatchMessage(docstring const & msg,
1336 FuncRequest const & cmd)
1338 const bool verbose = (cmd.origin() == FuncRequest::MENU
1339 || cmd.origin() == FuncRequest::TOOLBAR
1340 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1342 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1343 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1347 docstring dispatch_msg = msg;
1348 if (!dispatch_msg.empty())
1349 dispatch_msg += ' ';
1351 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1353 bool argsadded = false;
1355 if (!cmd.argument().empty()) {
1356 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1357 comname += ' ' + cmd.argument();
1361 docstring const shortcuts = theTopLevelKeymap().
1362 printBindings(cmd, KeySequence::ForGui);
1364 if (!shortcuts.empty())
1365 comname += ": " + shortcuts;
1366 else if (!argsadded && !cmd.argument().empty())
1367 comname += ' ' + cmd.argument();
1369 if (!comname.empty()) {
1370 comname = rtrim(comname);
1371 dispatch_msg += '(' + rtrim(comname) + ')';
1373 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1374 return dispatch_msg;
1378 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1380 Buffer * buffer = 0;
1381 if (current_view_ && current_view_->currentBufferView()) {
1382 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1383 buffer = ¤t_view_->currentBufferView()->buffer();
1385 buffer->undo().beginUndoGroup();
1389 // redraw the screen at the end (first of the two drawing steps).
1390 // This is done unless explicitly requested otherwise
1391 dr.screenUpdate(Update::FitCursor);
1393 updateCurrentView(cmd, dr);
1395 // the buffer may have been closed by one action
1396 if (theBufferList().isLoaded(buffer))
1397 buffer->undo().endUndoGroup();
1399 d->dispatch_result_ = dr;
1400 return d->dispatch_result_;
1404 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1409 BufferView * bv = current_view_->currentBufferView();
1411 if (dr.needBufferUpdate()) {
1412 bv->cursor().clearBufferUpdate();
1413 bv->buffer().updateBuffer();
1415 // BufferView::update() updates the ViewMetricsInfo and
1416 // also initializes the position cache for all insets in
1417 // (at least partially) visible top-level paragraphs.
1418 // We will redraw the screen only if needed.
1419 bv->processUpdateFlags(dr.screenUpdate());
1421 // Do we have a selection?
1422 theSelection().haveSelection(bv->cursor().selection());
1425 current_view_->restartCursor();
1427 if (dr.needMessageUpdate()) {
1428 // Some messages may already be translated, so we cannot use _()
1429 current_view_->message(makeDispatchMessage(
1430 translateIfPossible(dr.message()), cmd));
1435 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1436 bool switchToBuffer)
1438 if (!theSession().bookmarks().isValid(idx))
1440 BookmarksSection::Bookmark const & bm =
1441 theSession().bookmarks().bookmark(idx);
1442 LASSERT(!bm.filename.empty(), return);
1443 string const file = bm.filename.absFileName();
1444 // if the file is not opened, open it.
1445 if (!theBufferList().exists(bm.filename)) {
1447 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1451 // open may fail, so we need to test it again
1452 if (!theBufferList().exists(bm.filename))
1455 // bm can be changed when saving
1456 BookmarksSection::Bookmark tmp = bm;
1458 // Special case idx == 0 used for back-from-back jump navigation
1460 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1462 // if the current buffer is not that one, switch to it.
1463 BufferView * doc_bv = current_view_ ?
1464 current_view_->documentBufferView() : 0;
1465 Cursor const old = doc_bv->cursor();
1466 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1467 if (switchToBuffer) {
1468 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1471 doc_bv = current_view_->documentBufferView();
1476 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1477 if (!doc_bv->moveToPosition(
1478 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1481 Cursor & cur = doc_bv->cursor();
1483 notifyCursorLeavesOrEnters(old, cur);
1489 // Cursor jump succeeded!
1490 pit_type new_pit = cur.pit();
1491 pos_type new_pos = cur.pos();
1492 int new_id = cur.paragraph().id();
1494 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1495 // see http://www.lyx.org/trac/ticket/3092
1496 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1497 || bm.top_id != new_id) {
1498 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1499 new_pit, new_pos, new_id);
1503 // This function runs "configure" and then rereads lyx.defaults to
1504 // reconfigure the automatic settings.
1505 void GuiApplication::reconfigure(string const & option)
1507 // emit message signal.
1509 current_view_->message(_("Running configure..."));
1511 // Run configure in user lyx directory
1512 string const lock_file = package().getConfigureLockName();
1513 int fd = fileLock(lock_file.c_str());
1514 int const ret = package().reconfigureUserLyXDir(option);
1515 // emit message signal.
1517 current_view_->message(_("Reloading configuration..."));
1518 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1519 // Re-read packages.lst
1520 LaTeXPackages::getAvailable();
1521 fileUnlock(fd, lock_file.c_str());
1524 Alert::information(_("System reconfiguration failed"),
1525 _("The system reconfiguration has failed.\n"
1526 "Default textclass is used but LyX may\n"
1527 "not be able to work properly.\n"
1528 "Please reconfigure again if needed."));
1530 Alert::information(_("System reconfigured"),
1531 _("The system has been reconfigured.\n"
1532 "You need to restart LyX to make use of any\n"
1533 "updated document class specifications."));
1536 void GuiApplication::validateCurrentView()
1538 if (!d->views_.empty() && !current_view_) {
1539 // currently at least one view exists but no view has the focus.
1540 // choose the last view to make it current.
1541 // a view without any open document is preferred.
1542 GuiView * candidate = 0;
1543 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1544 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1545 for (; it != end; ++it) {
1547 if (!candidate->documentBufferView())
1550 setCurrentView(candidate);
1554 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1556 string const argument = to_utf8(cmd.argument());
1557 FuncCode const action = cmd.action();
1559 LYXERR(Debug::ACTION, "cmd: " << cmd);
1561 // we have not done anything wrong yet.
1564 FuncStatus const flag = getStatus(cmd);
1565 if (!flag.enabled()) {
1566 // We cannot use this function here
1567 LYXERR(Debug::ACTION, "action "
1568 << lyxaction.getActionName(action)
1569 << " [" << action << "] is disabled at this location");
1570 dr.setMessage(flag.message());
1572 dr.dispatched(false);
1573 dr.screenUpdate(Update::None);
1574 dr.clearBufferUpdate();
1578 if (cmd.origin() == FuncRequest::LYXSERVER) {
1579 if (current_view_ && current_view_->currentBufferView())
1580 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1581 // we will also need to redraw the screen at the end
1582 dr.screenUpdate(Update::FitCursor);
1585 // Assumes that the action will be dispatched.
1586 dr.dispatched(true);
1588 switch (cmd.action()) {
1590 case LFUN_WINDOW_NEW:
1591 createView(toqstr(cmd.argument()));
1594 case LFUN_WINDOW_CLOSE:
1595 // update bookmark pit of the current buffer before window close
1596 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1597 gotoBookmark(i+1, false, false);
1598 // clear the last opened list, because
1599 // maybe this will end the session
1600 theSession().lastOpened().clear();
1601 // check for valid current_view_
1602 validateCurrentView();
1604 current_view_->closeScheduled();
1608 // quitting is triggered by the gui code
1609 // (leaving the event loop).
1611 current_view_->message(from_utf8(N_("Exiting.")));
1612 if (closeAllViews())
1616 case LFUN_SCREEN_FONT_UPDATE: {
1617 // handle the screen font changes.
1618 d->font_loader_.update();
1619 // Backup current_view_
1620 GuiView * view = current_view_;
1621 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1622 // to skip the refresh.
1624 theBufferList().changed(false);
1625 // Restore current_view_
1626 current_view_ = view;
1630 case LFUN_BUFFER_NEW:
1631 validateCurrentView();
1632 if (d->views_.empty()
1633 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1634 createView(QString(), false); // keep hidden
1635 current_view_->newDocument(to_utf8(cmd.argument()), false);
1636 current_view_->show();
1637 setActiveWindow(current_view_);
1639 current_view_->newDocument(to_utf8(cmd.argument()), false);
1643 case LFUN_BUFFER_NEW_TEMPLATE:
1644 validateCurrentView();
1645 if (d->views_.empty()
1646 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1648 current_view_->newDocument(to_utf8(cmd.argument()), true);
1649 if (!current_view_->documentBufferView())
1650 current_view_->close();
1652 current_view_->newDocument(to_utf8(cmd.argument()), true);
1656 case LFUN_FILE_OPEN: {
1657 validateCurrentView();
1658 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1659 string const fname = to_utf8(cmd.argument());
1660 bool const is_open = FileName::isAbsolute(fname)
1661 && theBufferList().getBuffer(FileName(fname));
1662 if (d->views_.empty()
1663 || (!lyxrc.open_buffers_in_tabs
1664 && current_view_->documentBufferView() != 0
1666 // We want the ui session to be saved per document and not per
1667 // window number. The filename crc is a good enough identifier.
1668 boost::crc_32_type crc;
1669 crc = for_each(fname.begin(), fname.end(), crc);
1670 createView(crc.checksum());
1671 current_view_->openDocument(fname);
1672 if (current_view_ && !current_view_->documentBufferView())
1673 current_view_->close();
1675 current_view_->openDocument(fname);
1679 case LFUN_HELP_OPEN: {
1680 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1681 if (current_view_ == 0)
1683 string const arg = to_utf8(cmd.argument());
1685 current_view_->message(_("Missing argument"));
1688 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1690 fname = i18nLibFileSearch("examples", arg, "lyx");
1692 if (fname.empty()) {
1693 lyxerr << "LyX: unable to find documentation file `"
1694 << arg << "'. Bad installation?" << endl;
1697 current_view_->message(bformat(_("Opening help file %1$s..."),
1698 makeDisplayPath(fname.absFileName())));
1699 Buffer * buf = current_view_->loadDocument(fname, false);
1701 #ifndef DEVEL_VERSION
1703 buf->setReadonly(true);
1710 case LFUN_SET_COLOR: {
1712 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1713 if (lyx_name.empty() || x11_name.empty()) {
1715 current_view_->message(
1716 _("Syntax: set-color <lyx_name> <x11_name>"));
1721 // FIXME: The graphics cache no longer has a changeDisplay method.
1722 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1723 bool const graphicsbg_changed =
1724 lyx_name == graphicsbg && x11_name != graphicsbg;
1725 if (graphicsbg_changed)
1726 graphics::GCache::get().changeDisplay(true);
1729 if (!lcolor.setColor(lyx_name, x11_name)) {
1731 current_view_->message(
1732 bformat(_("Set-color \"%1$s\" failed "
1733 "- color is undefined or "
1734 "may not be redefined"),
1735 from_utf8(lyx_name)));
1738 // Make sure we don't keep old colors in cache.
1739 d->color_cache_.clear();
1740 // Update the current view
1741 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1745 case LFUN_LYXRC_APPLY: {
1746 // reset active key sequences, since the bindings
1747 // are updated (bug 6064)
1749 LyXRC const lyxrc_orig = lyxrc;
1751 istringstream ss(to_utf8(cmd.argument()));
1752 bool const success = lyxrc.read(ss);
1755 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1756 << "Unable to read lyxrc data"
1761 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1763 // If the request comes from the minibuffer, then we can't reset
1764 // the GUI, since that would destory the minibuffer itself and
1765 // cause a crash, since we are currently in one of the methods of
1766 // GuiCommandBuffer. See bug #8540.
1767 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1770 // FIXME Unfortunately, that leaves a bug here, since we cannot
1771 // reset the GUI in this case. If the changes to lyxrc affected the
1772 // UI, then, nothing would happen. This seems fairly unlikely, but
1773 // it definitely is a bug.
1778 case LFUN_COMMAND_PREFIX:
1779 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1784 d->meta_fake_bit = NoModifier;
1785 GuiView * gv = currentView();
1786 if (gv && gv->currentBufferView())
1787 // cancel any selection
1788 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1789 dr.setMessage(from_ascii(N_("Cancel")));
1792 case LFUN_META_PREFIX:
1793 d->meta_fake_bit = AltModifier;
1794 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1797 // --- Menus -----------------------------------------------
1798 case LFUN_RECONFIGURE:
1799 // argument is any additional parameter to the configure.py command
1800 reconfigure(to_utf8(cmd.argument()));
1803 // --- lyxserver commands ----------------------------
1804 case LFUN_SERVER_GET_FILENAME: {
1805 if (current_view_ && current_view_->documentBufferView()) {
1806 docstring const fname = from_utf8(
1807 current_view_->documentBufferView()->buffer().absFileName());
1808 dr.setMessage(fname);
1809 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1811 dr.setMessage(docstring());
1812 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1817 case LFUN_SERVER_NOTIFY: {
1818 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1819 dr.setMessage(dispatch_buffer);
1820 theServer().notifyClient(to_utf8(dispatch_buffer));
1824 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1825 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1831 string rest = split(argument, countstr, ' ');
1832 istringstream is(countstr);
1835 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1836 for (int i = 0; i < count; ++i)
1837 dispatch(lyxaction.lookupFunc(rest));
1841 case LFUN_COMMAND_SEQUENCE: {
1842 // argument contains ';'-terminated commands
1843 string arg = argument;
1844 // FIXME: this LFUN should also work without any view.
1845 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1846 ? &(current_view_->documentBufferView()->buffer()) : 0;
1848 buffer->undo().beginUndoGroup();
1849 while (!arg.empty()) {
1851 arg = split(arg, first, ';');
1852 FuncRequest func(lyxaction.lookupFunc(first));
1853 func.setOrigin(cmd.origin());
1856 // the buffer may have been closed by one action
1857 if (theBufferList().isLoaded(buffer))
1858 buffer->undo().endUndoGroup();
1862 case LFUN_BUFFER_FORALL: {
1863 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1865 map<Buffer *, GuiView *> views_lVisible;
1866 map<GuiView *, Buffer *> activeBuffers;
1868 QList<GuiView *> allViews = d->views_.values();
1870 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1871 // and on which buffer is active in each view.
1872 Buffer * const last = theBufferList().last();
1873 foreach (GuiView * view, allViews) {
1874 // all of the buffers might be locally hidden. That is, there is no active buffer.
1875 if (!view || !view->currentBufferView())
1876 activeBuffers[view] = 0;
1878 activeBuffers[view] = &view->currentBufferView()->buffer();
1880 // find out if each is locally visible or locally hidden.
1881 // we don't use a for loop as the buffer list cycles.
1882 Buffer * b = theBufferList().first();
1884 bool const locallyVisible = view && view->workArea(*b);
1885 if (locallyVisible) {
1886 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1887 // only need to overwrite/add if we don't already know a buffer is globally
1888 // visible or we do know but we would prefer to dispatch LFUN from the
1889 // current view because of cursor position issues.
1890 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1891 views_lVisible[b] = view;
1895 b = theBufferList().next(b);
1899 GuiView * const homeView = currentView();
1900 Buffer * b = theBufferList().first();
1901 Buffer * nextBuf = 0;
1902 int numProcessed = 0;
1905 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1907 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1909 // first change to a view where b is locally visible, preferably current_view_.
1910 GuiView * const vLv = views_lVisible[b];
1912 lyx::dispatch(funcToRun);
1920 // put things back to how they were (if possible).
1921 foreach (GuiView * view, allViews) {
1922 Buffer * originalBuf = activeBuffers[view];
1923 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1924 if (theBufferList().isLoaded(originalBuf))
1925 view->setBuffer(originalBuf);
1927 homeView->setFocus();
1929 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1933 case LFUN_COMMAND_ALTERNATIVES: {
1934 // argument contains ';'-terminated commands
1935 string arg = argument;
1936 while (!arg.empty()) {
1938 arg = split(arg, first, ';');
1939 FuncRequest func(lyxaction.lookupFunc(first));
1940 func.setOrigin(cmd.origin());
1941 FuncStatus const stat = getStatus(func);
1942 if (stat.enabled()) {
1952 if (theTopLevelCmdDef().lock(argument, func)) {
1953 func.setOrigin(cmd.origin());
1955 theTopLevelCmdDef().release(argument);
1957 if (func.action() == LFUN_UNKNOWN_ACTION) {
1958 // unknown command definition
1959 lyxerr << "Warning: unknown command definition `"
1963 // recursion detected
1964 lyxerr << "Warning: Recursion in the command definition `"
1965 << argument << "' detected"
1972 case LFUN_PREFERENCES_SAVE:
1973 lyxrc.write(support::makeAbsPath("preferences",
1974 package().user_support().absFileName()), false);
1977 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1978 string const fname = addName(addPath(package().user_support().absFileName(),
1979 "templates/"), "defaults.lyx");
1980 Buffer defaults(fname);
1982 istringstream ss(argument);
1987 // We need to make sure that, after we recreat the DocumentClass,
1988 // which we do in readHeader, we apply it to the document itself.
1989 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
1990 int const unknown_tokens = defaults.readHeader(lex);
1991 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
1993 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
1994 cap::switchBetweenClasses(olddc, newdc, theinset, el);
1996 if (unknown_tokens != 0) {
1997 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1998 << unknown_tokens << " unknown token"
1999 << (unknown_tokens == 1 ? "" : "s")
2003 if (defaults.writeFile(FileName(defaults.absFileName())))
2004 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2005 makeDisplayPath(fname)));
2008 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2013 case LFUN_BOOKMARK_GOTO:
2014 // go to bookmark, open unopened file and switch to buffer if necessary
2015 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2016 dr.screenUpdate(Update::Force | Update::FitCursor);
2019 case LFUN_BOOKMARK_CLEAR:
2020 theSession().bookmarks().clear();
2023 case LFUN_DEBUG_LEVEL_SET:
2024 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2027 case LFUN_DIALOG_SHOW: {
2028 string const name = cmd.getArg(0);
2030 if ( name == "aboutlyx"
2032 || name == "texinfo"
2033 || name == "progress"
2034 || name == "compare")
2036 // work around: on Mac OS the application
2037 // is not terminated when closing the last view.
2038 // Create a new one to be able to dispatch the
2039 // LFUN_DIALOG_SHOW to this view.
2040 if (current_view_ == 0)
2047 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2050 current_view_->dispatch(cmd, dr);
2054 if (cmd.origin() == FuncRequest::LYXSERVER)
2055 updateCurrentView(cmd, dr);
2059 docstring GuiApplication::viewStatusMessage()
2061 // When meta-fake key is pressed, show the key sequence so far + "M-".
2062 if (d->meta_fake_bit != NoModifier)
2063 return d->keyseq.print(KeySequence::ForGui) + "M-";
2065 // Else, when a non-complete key sequence is pressed,
2066 // show the available options.
2067 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2068 return d->keyseq.printOptions(true);
2074 void GuiApplication::handleKeyFunc(FuncCode action)
2078 if (d->keyseq.length())
2080 GuiView * gv = currentView();
2081 LASSERT(gv && gv->currentBufferView(), return);
2082 BufferView * bv = gv->currentBufferView();
2083 bv->getIntl().getTransManager().deadkey(
2084 c, get_accent(action).accent, bv->cursor().innerText(),
2086 // Need to clear, in case the minibuffer calls these
2089 // copied verbatim from do_accent_char
2090 bv->cursor().resetAnchor();
2094 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2096 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2098 // Do nothing if we have nothing (JMarc)
2099 if (!keysym.isOK()) {
2100 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2102 current_view_->restartCursor();
2106 if (keysym.isModifier()) {
2108 current_view_->restartCursor();
2112 char_type encoded_last_key = keysym.getUCSEncoded();
2114 // Do a one-deep top-level lookup for
2115 // cancel and meta-fake keys. RVDK_PATCH_5
2116 d->cancel_meta_seq.reset();
2118 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2119 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2121 // When not cancel or meta-fake, do the normal lookup.
2122 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2123 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2124 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2125 // remove Caps Lock and Mod2 as a modifiers
2126 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2127 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2130 // Dont remove this unless you know what you are doing.
2131 d->meta_fake_bit = NoModifier;
2133 // Can this happen now ?
2134 if (func.action() == LFUN_NOACTION)
2135 func = FuncRequest(LFUN_COMMAND_PREFIX);
2137 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2138 << d->keyseq.print(KeySequence::Portable) << ']');
2140 // already here we know if it any point in going further
2141 // why not return already here if action == -1 and
2142 // num_bytes == 0? (Lgb)
2144 if (d->keyseq.length() > 1 && current_view_)
2145 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2148 // Maybe user can only reach the key via holding down shift.
2149 // Let's see. But only if shift is the only modifier
2150 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2151 LYXERR(Debug::KEY, "Trying without shift");
2152 func = d->keyseq.addkey(keysym, NoModifier);
2153 LYXERR(Debug::KEY, "Action now " << func.action());
2156 if (func.action() == LFUN_UNKNOWN_ACTION) {
2157 // We didn't match any of the key sequences.
2158 // See if it's normal insertable text not already
2159 // covered by a binding
2160 if (keysym.isText() && d->keyseq.length() == 1) {
2161 // Non-printable characters (such as ASCII control characters)
2162 // must not be inserted (#5704)
2163 if (!isPrintable(encoded_last_key)) {
2164 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2165 current_view_->restartCursor();
2168 // If a non-Shift Modifier is used we have a non-bound key sequence
2169 // (such as Alt+j = j). This should be omitted (#5575).
2170 // On Windows, AltModifier and ControlModifier are both
2171 // set when AltGr is pressed. Therefore, in order to not
2172 // break AltGr-bound symbols (see #5575 for details),
2173 // unbound Ctrl+Alt key sequences are allowed.
2174 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2175 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2176 && !(state & AltModifier && state & ControlModifier)
2179 current_view_->message(_("Unknown function."));
2180 current_view_->restartCursor();
2183 // Since all checks above were passed, we now really have text that
2184 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2185 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2187 LYXERR(Debug::KEY, "isText() is true, inserting.");
2188 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2190 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2191 if (current_view_) {
2192 current_view_->message(_("Unknown function."));
2193 current_view_->restartCursor();
2199 if (func.action() == LFUN_SELF_INSERT) {
2200 if (encoded_last_key != 0) {
2201 docstring const arg(1, encoded_last_key);
2202 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2203 FuncRequest::KEYBOARD));
2204 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2207 processFuncRequest(func);
2211 void GuiApplication::processFuncRequest(FuncRequest const & func)
2213 lyx::dispatch(func);
2217 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2219 addToFuncRequestQueue(func);
2220 processFuncRequestQueueAsync();
2224 void GuiApplication::processFuncRequestQueue()
2226 while (!d->func_request_queue_.empty()) {
2227 processFuncRequest(d->func_request_queue_.front());
2228 d->func_request_queue_.pop();
2233 void GuiApplication::processFuncRequestQueueAsync()
2235 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2239 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2241 d->func_request_queue_.push(func);
2245 void GuiApplication::resetGui()
2247 // Set the language defined by the user.
2251 if (!readUIFile(toqstr(lyxrc.ui_file)))
2252 // Gives some error box here.
2255 if (d->global_menubar_)
2256 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2258 QHash<int, GuiView *>::iterator it;
2259 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2262 gv->setLayoutDirection(layoutDirection());
2266 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2270 void GuiApplication::createView(int view_id)
2272 createView(QString(), true, view_id);
2276 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2279 // release the keyboard which might have been grabed by the global
2280 // menubar on Mac to catch shortcuts even without any GuiView.
2281 if (d->global_menubar_)
2282 d->global_menubar_->releaseKeyboard();
2286 while (d->views_.find(id) != d->views_.end())
2289 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2290 GuiView * view = new GuiView(id);
2292 d->views_[id] = view;
2296 setActiveWindow(view);
2299 if (!geometry_arg.isEmpty()) {
2300 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2304 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2305 re.indexIn(geometry_arg);
2306 w = re.cap(1).toInt();
2307 h = re.cap(2).toInt();
2308 x = re.cap(3).toInt();
2309 y = re.cap(4).toInt();
2310 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2311 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2312 // Set initial geometry such that we can get the frame size.
2313 view->setGeometry(x, y, w, h);
2314 int framewidth = view->geometry().x() - view->x();
2315 int titleheight = view->geometry().y() - view->y();
2316 // Negative displacements must be interpreted as distances
2317 // from the right or bottom screen borders.
2318 if (sx == '-' || sy == '-') {
2319 QRect rec = QApplication::desktop()->screenGeometry();
2321 x += rec.width() - w - framewidth;
2323 y += rec.height() - h - titleheight;
2324 view->setGeometry(x, y, w, h);
2326 // Make sure that the left and top frame borders are visible.
2327 if (view->x() < 0 || view->y() < 0) {
2332 view->setGeometry(x, y, w, h);
2340 Clipboard & GuiApplication::clipboard()
2342 return d->clipboard_;
2346 Selection & GuiApplication::selection()
2348 return d->selection_;
2352 FontLoader & GuiApplication::fontLoader()
2354 return d->font_loader_;
2358 Toolbars const & GuiApplication::toolbars() const
2360 return d->toolbars_;
2364 Toolbars & GuiApplication::toolbars()
2366 return d->toolbars_;
2370 Menus const & GuiApplication::menus() const
2376 Menus & GuiApplication::menus()
2382 QList<int> GuiApplication::viewIds() const
2384 return d->views_.keys();
2388 ColorCache & GuiApplication::colorCache()
2390 return d->color_cache_;
2394 int GuiApplication::exec()
2396 // asynchronously handle batch commands. This event will be in
2397 // the event queue in front of other asynchronous events. Hence,
2398 // we can assume in the latter that the gui is setup already.
2399 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2401 return QApplication::exec();
2405 void GuiApplication::exit(int status)
2407 QApplication::exit(status);
2411 void GuiApplication::setGuiLanguage()
2415 // install translation file for Qt built-in dialogs
2416 QString const language_name = QString("qt_") + theLocale.name();
2417 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2418 // Short-named translator can be loaded from a long name, but not the
2419 // opposite. Therefore, long name should be used without truncation.
2420 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2421 if (!d->qt_trans_.load(language_name,
2422 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2423 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2426 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2430 switch (theLocale.language()) {
2431 case QLocale::Arabic :
2432 case QLocale::Hebrew :
2433 case QLocale::Persian :
2434 case QLocale::Urdu :
2435 setLayoutDirection(Qt::RightToLeft);
2438 setLayoutDirection(Qt::LeftToRight);
2443 void GuiApplication::execBatchCommands()
2448 if (!readUIFile(toqstr(lyxrc.ui_file)))
2449 // Gives some error box here.
2453 #if QT_VERSION > 0x040600
2454 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2456 #if QT_VERSION > 0x050100
2457 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2459 // Create the global default menubar which is shown for the dialogs
2460 // and if no GuiView is visible.
2461 // This must be done after the session was recovered to know the "last files".
2462 d->global_menubar_ = new QMenuBar(0);
2463 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2466 lyx::execBatchCommands();
2470 QAbstractItemModel * GuiApplication::languageModel()
2472 if (d->language_model_)
2473 return d->language_model_;
2475 QStandardItemModel * lang_model = new QStandardItemModel(this);
2476 lang_model->insertColumns(0, 3);
2477 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2478 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2479 Languages::const_iterator it = lyx::languages.begin();
2480 Languages::const_iterator end = lyx::languages.end();
2481 for (; it != end; ++it) {
2482 int current_row = lang_model->rowCount();
2483 lang_model->insertRows(current_row, 1);
2484 QModelIndex pl_item = lang_model->index(current_row, 0);
2485 QModelIndex sp_item = lang_model->index(current_row, 1);
2486 QModelIndex th_item = lang_model->index(current_row, 2);
2487 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2488 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2489 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2490 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2491 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2492 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2493 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2494 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2495 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2496 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2498 d->language_model_ = new QSortFilterProxyModel(this);
2499 d->language_model_->setSourceModel(lang_model);
2500 d->language_model_->setSortLocaleAware(true);
2501 return d->language_model_;
2505 void GuiApplication::restoreGuiSession()
2507 if (!lyxrc.load_session)
2510 Session & session = theSession();
2511 LastOpenedSection::LastOpened const & lastopened =
2512 session.lastOpened().getfiles();
2514 validateCurrentView();
2516 FileName active_file;
2517 // do not add to the lastfile list since these files are restored from
2518 // last session, and should be already there (regular files), or should
2519 // not be added at all (help files).
2520 for (size_t i = 0; i < lastopened.size(); ++i) {
2521 FileName const & file_name = lastopened[i].file_name;
2522 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2523 && current_view_->documentBufferView() != 0)) {
2524 boost::crc_32_type crc;
2525 string const & fname = file_name.absFileName();
2526 crc = for_each(fname.begin(), fname.end(), crc);
2527 createView(crc.checksum());
2529 current_view_->loadDocument(file_name, false);
2531 if (lastopened[i].active)
2532 active_file = file_name;
2535 // Restore last active buffer
2536 Buffer * buffer = theBufferList().getBuffer(active_file);
2537 if (buffer && current_view_)
2538 current_view_->setBuffer(buffer);
2540 // clear this list to save a few bytes of RAM
2541 session.lastOpened().clear();
2545 QString const GuiApplication::romanFontName()
2548 font.setStyleHint(QFont::Serif);
2549 font.setFamily("serif");
2551 return QFontInfo(font).family();
2555 QString const GuiApplication::sansFontName()
2558 font.setStyleHint(QFont::SansSerif);
2559 font.setFamily("sans");
2561 return QFontInfo(font).family();
2565 QString const GuiApplication::typewriterFontName()
2568 font.setStyleHint(QFont::TypeWriter);
2569 font.setFamily("monospace");
2571 return QFontInfo(font).family();
2575 void GuiApplication::handleRegularEvents()
2577 ForkedCallsController::handleCompletedProcesses();
2581 bool GuiApplication::event(QEvent * e)
2584 case QEvent::FileOpen: {
2585 // Open a file; this happens only on Mac OS X for now.
2587 // We do this asynchronously because on startup the batch
2588 // commands are not executed here yet and the gui is not ready
2590 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2591 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2592 processFuncRequestAsync(fr);
2597 return QApplication::event(e);
2602 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2605 return QApplication::notify(receiver, event);
2607 catch (ExceptionMessage const & e) {
2609 case ErrorException:
2611 setQuitOnLastWindowClosed(false);
2613 Alert::error(e.title_, e.details_);
2615 // Properly crash in debug mode in order to get a useful backtrace.
2618 // In release mode, try to exit gracefully.
2621 case BufferException: {
2622 if (!current_view_ || !current_view_->documentBufferView())
2624 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2625 docstring details = e.details_ + '\n';
2626 details += buf->emergencyWrite();
2627 theBufferList().release(buf);
2628 details += "\n" + _("The current document was closed.");
2629 Alert::error(e.title_, details);
2632 case WarningException:
2633 Alert::warning(e.title_, e.details_);
2637 catch (exception const & e) {
2638 docstring s = _("LyX has caught an exception, it will now "
2639 "attempt to save all unsaved documents and exit."
2641 s += from_ascii(e.what());
2642 Alert::error(_("Software exception Detected"), s);
2646 docstring s = _("LyX has caught some really weird exception, it will "
2647 "now attempt to save all unsaved documents and exit.");
2648 Alert::error(_("Software exception Detected"), s);
2656 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2658 QColor const & qcol = d->color_cache_.get(col);
2659 if (!qcol.isValid()) {
2665 rgbcol.r = qcol.red();
2666 rgbcol.g = qcol.green();
2667 rgbcol.b = qcol.blue();
2672 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2674 QColor const qcol(lcolor.getX11Name(col).c_str());
2675 if (!qcol.isValid()) {
2681 rgbcol.r = qcol.red();
2682 rgbcol.g = qcol.green();
2683 rgbcol.b = qcol.blue();
2688 string const GuiApplication::hexName(ColorCode col)
2690 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2694 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2696 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2697 d->socket_notifiers_[fd] = sn;
2698 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2702 void GuiApplication::socketDataReceived(int fd)
2704 d->socket_notifiers_[fd]->func_();
2708 void GuiApplication::unregisterSocketCallback(int fd)
2710 d->socket_notifiers_.take(fd)->setEnabled(false);
2714 void GuiApplication::commitData(QSessionManager & sm)
2716 /** The implementation is required to avoid an application exit
2717 ** when session state save is triggered by session manager.
2718 ** The default implementation sends a close event to all
2719 ** visible top level widgets when session managment allows
2721 ** We are changing that to check the state of each buffer in all
2722 ** views and ask the users what to do if buffers are dirty.
2723 ** Furthermore, we save the session state.
2724 ** We do NOT close the views here since the user still can cancel
2725 ** the logout process (see #9277); also, this would hide LyX from
2726 ** an OSes own session handling (application restoration).
2728 #ifdef QT_NO_SESSIONMANAGER
2730 #warning Qt is compiled without session manager
2732 #pragma message("warning: Qt is compiled without session manager")
2736 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2744 void GuiApplication::unregisterView(GuiView * gv)
2746 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2747 d->views_.remove(gv->id());
2748 if (current_view_ == gv)
2754 bool GuiApplication::closeAllViews()
2756 if (d->views_.empty())
2759 // When a view/window was closed before without quitting LyX, there
2760 // are already entries in the lastOpened list.
2761 theSession().lastOpened().clear();
2763 QList<GuiView *> const views = d->views_.values();
2764 foreach (GuiView * view, views) {
2765 if (!view->closeScheduled())
2774 bool GuiApplication::prepareAllViewsForLogout()
2776 if (d->views_.empty())
2779 QList<GuiView *> const views = d->views_.values();
2780 foreach (GuiView * view, views) {
2781 if (!view->prepareAllBuffersForLogout())
2789 GuiView & GuiApplication::view(int id) const
2791 LAPPERR(d->views_.contains(id));
2792 return *d->views_.value(id);
2796 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2798 QList<GuiView *> const views = d->views_.values();
2799 foreach (GuiView * view, views)
2800 view->hideDialog(name, inset);
2804 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2806 Buffer const * buffer_ = 0;
2807 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2808 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2809 if (Buffer const * ptr = (*it)->updateInset(inset))
2816 bool GuiApplication::searchMenu(FuncRequest const & func,
2817 docstring_list & names) const
2819 return d->menus_.searchMenu(func, names);
2823 // Ensure that a file is read only once (prevents include loops)
2824 static QStringList uifiles;
2825 // store which ui files define Toolbars
2826 static QStringList toolbar_uifiles;
2829 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2840 LexerKeyword uitags[] = {
2841 { "format", ui_format },
2842 { "include", ui_include },
2843 { "menuset", ui_menuset },
2844 { "toolbars", ui_toolbars },
2845 { "toolbarset", ui_toolbarset }
2849 lex.setFile(ui_path);
2851 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2855 if (lyxerr.debugging(Debug::PARSER))
2856 lex.printTable(lyxerr);
2859 // format before introduction of format tag
2860 unsigned int format = 0;
2861 while (lex.isOK()) {
2862 int const status = lex.lex();
2864 // we have to do this check here, outside the switch,
2865 // because otherwise we would start reading include files,
2866 // e.g., if the first tag we hit was an include tag.
2867 if (status == ui_format)
2869 format = lex.getInteger();
2873 // this will trigger unless the first tag we hit is a format
2874 // tag, with the right format.
2875 if (format != LFUN_FORMAT)
2876 return FormatMismatch;
2879 case Lexer::LEX_FEOF:
2884 QString const file = toqstr(lex.getString());
2885 bool const success = readUIFile(file, true);
2887 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2894 d->menus_.read(lex);
2898 d->toolbars_.readToolbars(lex);
2902 d->toolbars_.readToolbarSettings(lex);
2903 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2907 if (!rtrim(lex.getString()).empty())
2908 lex.printError("LyX::ReadUIFile: "
2909 "Unknown menu tag: `$$Token'");
2911 LYXERR0("Error with status: " << status);
2917 return (error ? ReadError : ReadOK);
2921 bool GuiApplication::readUIFile(QString const & name, bool include)
2923 LYXERR(Debug::INIT, "About to read " << name << "...");
2927 ui_path = libFileSearch("ui", name, "inc");
2928 if (ui_path.empty())
2929 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2931 ui_path = libFileSearch("ui", name, "ui");
2934 if (ui_path.empty()) {
2935 static const QString defaultUIFile = "default";
2936 LYXERR(Debug::INIT, "Could not find " << name);
2938 Alert::warning(_("Could not find UI definition file"),
2939 bformat(_("Error while reading the included file\n%1$s\n"
2940 "Please check your installation."), qstring_to_ucs4(name)));
2943 if (name == defaultUIFile) {
2944 LYXERR(Debug::INIT, "Could not find default UI file!!");
2945 Alert::warning(_("Could not find default UI file"),
2946 _("LyX could not find the default UI file!\n"
2947 "Please check your installation."));
2950 Alert::warning(_("Could not find UI definition file"),
2951 bformat(_("Error while reading the configuration file\n%1$s\n"
2952 "Falling back to default.\n"
2953 "Please look under Tools>Preferences>User Interface and\n"
2954 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2955 return readUIFile(defaultUIFile, false);
2958 QString const uifile = toqstr(ui_path.absFileName());
2959 if (uifiles.contains(uifile)) {
2961 // We are reading again the top uifile so reset the safeguard:
2964 d->toolbars_.reset();
2966 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2967 << "Is this an include loop?");
2971 uifiles.push_back(uifile);
2973 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2975 ReturnValues retval = readUIFile(ui_path);
2977 if (retval == FormatMismatch) {
2978 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2979 TempFile tmp("convertXXXXXX.ui");
2980 FileName const tempfile = tmp.name();
2981 bool const success = prefs2prefs(ui_path, tempfile, true);
2983 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2984 " to format " << LFUN_FORMAT << ".");
2986 retval = readUIFile(tempfile);
2990 if (retval != ReadOK) {
2991 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2999 settings.beginGroup("ui_files");
3000 bool touched = false;
3001 for (int i = 0; i != uifiles.size(); ++i) {
3002 QFileInfo fi(uifiles[i]);
3003 QDateTime const date_value = fi.lastModified();
3004 QString const name_key = QString::number(i);
3005 // if an ui file which defines Toolbars has changed,
3006 // we have to reset the settings
3007 if (toolbar_uifiles.contains(uifiles[i])
3008 && (!settings.contains(name_key)
3009 || settings.value(name_key).toString() != uifiles[i]
3010 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3012 settings.setValue(name_key, uifiles[i]);
3013 settings.setValue(name_key + "/date", date_value);
3016 settings.endGroup();
3018 settings.remove("views");
3024 void GuiApplication::onLastWindowClosed()
3026 if (d->global_menubar_)
3027 d->global_menubar_->grabKeyboard();
3031 void GuiApplication::startLongOperation() {
3032 d->key_checker_.start();
3036 bool GuiApplication::longOperationCancelled() {
3037 return d->key_checker_.pressed();
3041 void GuiApplication::stopLongOperation() {
3042 d->key_checker_.stop();
3046 bool GuiApplication::longOperationStarted() {
3047 return d->key_checker_.started();
3051 ////////////////////////////////////////////////////////////////////////
3053 // X11 specific stuff goes here...
3056 bool GuiApplication::x11EventFilter(XEvent * xev)
3061 switch (xev->type) {
3062 case SelectionRequest: {
3063 if (xev->xselectionrequest.selection != XA_PRIMARY)
3065 LYXERR(Debug::SELECTION, "X requested selection.");
3066 BufferView * bv = current_view_->currentBufferView();
3068 docstring const sel = bv->requestSelection();
3070 d->selection_.put(sel);
3074 case SelectionClear: {
3075 if (xev->xselectionclear.selection != XA_PRIMARY)
3077 LYXERR(Debug::SELECTION, "Lost selection.");
3078 BufferView * bv = current_view_->currentBufferView();
3080 bv->clearSelection();
3086 #elif defined(QPA_XCB)
3087 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3088 void * message, long *)
3090 if (!current_view_ || eventType != "xcb_generic_event_t")
3093 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3095 switch (ev->response_type) {
3096 case XCB_SELECTION_REQUEST: {
3097 xcb_selection_request_event_t * srev =
3098 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3099 if (srev->selection != XCB_ATOM_PRIMARY)
3101 LYXERR(Debug::SELECTION, "X requested selection.");
3102 BufferView * bv = current_view_->currentBufferView();
3104 docstring const sel = bv->requestSelection();
3106 d->selection_.put(sel);
3110 case XCB_SELECTION_CLEAR: {
3111 xcb_selection_clear_event_t * scev =
3112 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3113 if (scev->selection != XCB_ATOM_PRIMARY)
3115 LYXERR(Debug::SELECTION, "Lost selection.");
3116 BufferView * bv = current_view_->currentBufferView();
3118 bv->clearSelection();
3126 } // namespace frontend
3129 void hideDialogs(std::string const & name, Inset * inset)
3132 frontend::guiApp->hideDialogs(name, inset);
3136 ////////////////////////////////////////////////////////////////////
3140 ////////////////////////////////////////////////////////////////////
3142 frontend::FontLoader & theFontLoader()
3144 LAPPERR(frontend::guiApp);
3145 return frontend::guiApp->fontLoader();
3149 frontend::FontMetrics const & theFontMetrics(Font const & f)
3151 return theFontMetrics(f.fontInfo());
3155 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3157 LAPPERR(frontend::guiApp);
3158 return frontend::guiApp->fontLoader().metrics(f);
3162 ////////////////////////////////////////////////////////////////////
3166 ////////////////////////////////////////////////////////////////////
3168 frontend::Clipboard & theClipboard()
3170 LAPPERR(frontend::guiApp);
3171 return frontend::guiApp->clipboard();
3175 frontend::Selection & theSelection()
3177 LAPPERR(frontend::guiApp);
3178 return frontend::guiApp->selection();
3184 #include "moc_GuiApplication.cpp"