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<(ImgMap const & lhs, ImgMap const & rhs)
260 return lhs.key < rhs.key;
266 CompareKey(QString const & name) : name_(name) {}
267 bool operator()(ImgMap 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 ImgMap sorted_img_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_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
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 ImgMap sorted_theme_icon_map[] = {
381 { "bookmark-goto 0", "go-jump" },
382 { "buffer-new", "document-new" },
383 { "buffer-write", "document-save" },
384 { "buffer-write-as", "document-save-as" },
385 { "buffer-zoom-in", "zoom-in" },
386 { "buffer-zoom-out", "zoom-out" },
387 { "copy", "edit-copy" },
388 { "cut", "edit-cut" },
389 { "depth-decrement", "format-indent-less" },
390 { "depth-increment", "format-indent-more" },
391 { "dialog-show spellchecker", "tools-check-spelling" },
392 { "dialog-show-new-inset graphics", "insert-image" },
393 { "dialog-toggle findreplaceadv", "edit-find-replace" },
394 { "file-open", "document-open" },
395 { "font-bold", "format-text-bold" },
396 { "font-ital", "format-text-italic" },
397 { "font-strikeout", "format-text-strikethrough" },
398 { "font-underline", "format-text-underline" },
399 { "lyx-quit", "application-exit" },
400 { "paste", "edit-paste" },
401 { "redo", "edit-redo" },
402 { "undo", "edit-undo" },
403 { "window-close", "window-close" },
404 { "window-new", "window-new" }
407 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
410 QString findImg(QString const & name)
412 ImgMap const * const begin = sorted_img_map;
413 ImgMap const * const end = begin + nr_sorted_img_map;
414 LATTEST(sorted(begin, end));
416 ImgMap const * const it = find_if(begin, end, CompareKey(name));
420 img_name = it->value;
423 img_name.replace('_', "underscore");
424 img_name.replace(' ', '_');
426 // This way we can have "math-delim { }" on the toolbar.
427 img_name.replace('(', "lparen");
428 img_name.replace(')', "rparen");
429 img_name.replace('[', "lbracket");
430 img_name.replace(']', "rbracket");
431 img_name.replace('{', "lbrace");
432 img_name.replace('}', "rbrace");
433 img_name.replace('|', "bars");
434 img_name.replace(',', "thinspace");
435 img_name.replace(':', "mediumspace");
436 img_name.replace(';', "thickspace");
437 img_name.replace('!', "negthinspace");
440 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
441 << "Looking for math icon called \"" << img_name << '"');
448 QString themeIconName(QString const & action)
450 ImgMap const * const begin = sorted_theme_icon_map;
451 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
452 LASSERT(sorted(begin, end), /**/);
454 ImgMap const * const it = find_if(begin, end, CompareKey(action));
462 QString iconName(FuncRequest const & f, bool unknown)
464 initializeResources();
468 switch (f.action()) {
469 case LFUN_MATH_INSERT:
470 if (!f.argument().empty()) {
472 name1 = findImg(toqstr(f.argument()).mid(1));
475 case LFUN_MATH_DELIM:
476 case LFUN_MATH_BIGDELIM:
478 name1 = findImg(toqstr(f.argument()));
482 name1 = toqstr(f.argument());
484 case LFUN_COMMAND_ALTERNATIVES: {
485 // use the first of the alternative commands
487 docstring dummy = split(f.argument(), firstcom, ';');
488 name1 = toqstr(firstcom);
489 // FIXME: we should rename the icons to tabular-xxx instead of
490 // "tabular-feature-xxx"
491 name1.replace("inset-modify tabular", "tabular-feature");
492 name1.replace(' ', '_');
495 case LFUN_INSET_MODIFY: {
496 // FIXME: we should rename the icons to tabular-xxx instead of
497 // "tabular-feature-xxx" and generalize this naming to all
498 // insets, not to tabular using ones.
500 string const command = split(to_utf8(f.argument()), inset_name, ' ');
501 if (insetCode(inset_name) == TABULAR_CODE) {
502 name1 = "tabular-feature "+ toqstr(command);
503 name1.replace(' ', '_');
508 name2 = toqstr(lyxaction.getActionName(f.action()));
511 if (!f.argument().empty()) {
512 name1 = name2 + ' ' + toqstr(f.argument());
513 name1.replace(' ', '_');
514 name1.replace('\\', "backslash");
518 QStringList imagedirs;
519 imagedirs << "images/" << "images/ipa/";
520 search_mode mode = theGuiApp()->imageSearchMode();
521 for (int i = 0; i < imagedirs.size(); ++i) {
522 QString imagedir = imagedirs.at(i) + path;
523 FileName fname = imageLibFileSearch(imagedir, name1, "svgz,png", mode);
525 return toqstr(fname.absFileName());
527 fname = imageLibFileSearch(imagedir, name2, "svgz,png", mode);
529 return toqstr(fname.absFileName());
532 path = ":/images/" + path;
535 LYXERR0("Directory " << path << " not found in resource!");
538 if (res.exists(name1 + ".svgz"))
539 return path + name1 + ".svgz";
540 else if (res.exists(name1 + ".png"))
541 return path + name1 + ".png";
543 if (res.exists(name2 + ".svgz"))
544 return path + name2 + ".svgz";
545 else if (res.exists(name2 + ".png"))
546 return path + name2 + ".png";
548 LYXERR(Debug::GUI, "Cannot find icon with filename "
549 << "\"" << name1 << ".{svgz,png}\""
551 << "\"" << name2 << ".{svgz,png}\""
553 << lyxaction.getActionName(f.action())
554 << '(' << to_utf8(f.argument()) << ")\"");
557 QString imagedir = "images/";
558 FileName fname = imageLibFileSearch(imagedir, "unknown", "svgz,png", mode);
560 return toqstr(fname.absFileName());
561 return QString(":/images/unknown.svgz");
568 bool getPixmap(QPixmap & pixmap, QString const & path)
570 if (pixmap.load(path)) {
571 #if QT_VERSION >= 0x050000
572 if (path.endsWith(".svgz") || path.endsWith(".svg") ) {
573 GuiApplication const * guiApp = theGuiApp();
575 pixmap.setDevicePixelRatio(guiApp->pixelRatio());
585 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
587 QString imagedir = path;
588 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
589 QString fpath = toqstr(fname.absFileName());
590 QPixmap pixmap = QPixmap();
592 if (getPixmap(pixmap, fpath)) {
596 QStringList exts = ext.split(",");
597 fpath = ":/" + path + name + ".";
598 for (int i = 0; i < exts.size(); ++i) {
599 if (getPixmap(pixmap, fpath + exts.at(i))) {
604 bool const list = ext.contains(",");
605 LYXERR0("Cannot load pixmap \""
606 << path << name << "." << (list ? "{" : "") << ext
607 << (list ? "}" : "") << "\", please verify resource system!");
613 QIcon getIcon(FuncRequest const & f, bool unknown)
615 #if (QT_VERSION >= 0x040600)
616 if (lyxrc.use_system_theme_icons) {
617 QString action = toqstr(lyxaction.getActionName(f.action()));
618 if (!f.argument().empty())
619 action += " " + toqstr(f.argument());
620 QString const theme_icon = themeIconName(action);
621 if (QIcon::hasThemeIcon(theme_icon))
622 return QIcon::fromTheme(theme_icon);
626 QString icon = iconName(f, unknown);
630 //LYXERR(Debug::GUI, "Found icon: " << icon);
631 QPixmap pixmap = QPixmap();
632 if (!getPixmap(pixmap,icon)) {
633 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
637 return QIcon(pixmap);
641 ////////////////////////////////////////////////////////////////////////
643 // LyX server support code.
645 ////////////////////////////////////////////////////////////////////////
647 class SocketNotifier : public QSocketNotifier
650 /// connect a connection notification from the LyXServerSocket
651 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
652 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
656 /// The callback function
657 Application::SocketCallback func_;
661 ////////////////////////////////////////////////////////////////////////
663 // Mac specific stuff goes here...
665 ////////////////////////////////////////////////////////////////////////
667 class MenuTranslator : public QTranslator
670 MenuTranslator(QObject * parent)
671 : QTranslator(parent)
674 #if QT_VERSION >= 0x050000
675 virtual QString translate(const char * /* context */,
676 const char *sourceText,
677 const char * /* disambiguation */ = 0, int /* n */ = -1) const
679 QString translate(const char * /*context*/,
680 const char * sourceText,
681 const char * /*comment*/ = 0) const
684 string const s = sourceText;
685 if (s == N_("About %1") || s == N_("Preferences")
686 || s == N_("Reconfigure") || s == N_("Quit %1"))
694 // QMacPasteboardMimeGraphics can only be compiled on Mac.
696 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
699 QMacPasteboardMimeGraphics()
700 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
703 QString convertorName() { return "Graphics"; }
705 QString flavorFor(QString const & mime)
707 LYXERR(Debug::ACTION, "flavorFor " << mime);
708 if (mime == pdfMimeType())
709 return QLatin1String("com.adobe.pdf");
713 QString mimeFor(QString flav)
715 LYXERR(Debug::ACTION, "mimeFor " << flav);
716 if (flav == QLatin1String("com.adobe.pdf"))
717 return pdfMimeType();
721 bool canConvert(QString const & mime, QString flav)
723 return mimeFor(flav) == mime;
726 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
730 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
734 QList<QByteArray> convertFromMime(QString const & /*mime*/,
735 QVariant data, QString /*flav*/)
737 QList<QByteArray> ret;
738 ret.append(data.toByteArray());
744 ///////////////////////////////////////////////////////////////
746 // You can find more platform specific stuff at the end of this file...
748 ///////////////////////////////////////////////////////////////
750 ////////////////////////////////////////////////////////////////////////
751 // Windows specific stuff goes here...
753 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
754 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
755 // QWindowsMimeMetafile can only be compiled on Windows.
757 static FORMATETC cfFromMime(QString const & mimetype)
760 if (mimetype == emfMimeType()) {
761 formatetc.cfFormat = CF_ENHMETAFILE;
762 formatetc.tymed = TYMED_ENHMF;
763 } else if (mimetype == wmfMimeType()) {
764 formatetc.cfFormat = CF_METAFILEPICT;
765 formatetc.tymed = TYMED_MFPICT;
768 formatetc.dwAspect = DVASPECT_CONTENT;
769 formatetc.lindex = -1;
774 class QWindowsMimeMetafile : public QWINDOWSMIME {
776 QWindowsMimeMetafile() {}
778 bool canConvertFromMime(FORMATETC const & formatetc,
779 QMimeData const * mimedata) const
784 bool canConvertToMime(QString const & mimetype,
785 IDataObject * pDataObj) const
787 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
789 FORMATETC formatetc = cfFromMime(mimetype);
790 return pDataObj->QueryGetData(&formatetc) == S_OK;
793 bool convertFromMime(FORMATETC const & formatetc,
794 const QMimeData * mimedata, STGMEDIUM * pmedium) const
799 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
800 QVariant::Type preferredType) const
803 if (!canConvertToMime(mimetype, pDataObj))
806 FORMATETC formatetc = cfFromMime(mimetype);
808 if (pDataObj->GetData(&formatetc, &s) != S_OK)
812 if (s.tymed == TYMED_ENHMF) {
813 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
814 data.resize(dataSize);
815 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
816 (LPBYTE)data.data());
817 } else if (s.tymed == TYMED_MFPICT) {
818 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
819 data.resize(dataSize);
820 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
821 (LPBYTE)data.data());
824 ReleaseStgMedium(&s);
830 QVector<FORMATETC> formatsForMime(QString const & mimetype,
831 QMimeData const * mimedata) const
833 QVector<FORMATETC> formats;
834 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
835 formats += cfFromMime(mimetype);
839 QString mimeForFormat(FORMATETC const & formatetc) const
841 switch (formatetc.cfFormat) {
843 return emfMimeType();
844 case CF_METAFILEPICT:
845 return wmfMimeType();
855 /// Allows to check whether ESC was pressed during a long operation
856 class KeyChecker : public QObject {
861 KeyChecker() : pressed_(false), started_(false) {}
864 QCoreApplication::instance()->installEventFilter(this);
869 QCoreApplication::instance()->removeEventFilter(this);
873 QCoreApplication::processEvents();
876 bool started() const {
879 bool eventFilter(QObject *obj, QEvent *event) {
880 LYXERR(Debug::ACTION, "Event Type: " << event->type());
881 switch (event->type()) {
885 case QEvent::UpdateRequest:
886 case QEvent::CursorChange:
887 case QEvent::ActionChanged:
888 case QEvent::EnabledChange:
889 case QEvent::SockAct:
892 case QEvent::ToolTipChange:
893 case QEvent::LayoutRequest:
894 case QEvent::MetaCall:
895 return QObject::eventFilter(obj, event);
897 // FIXME Blocking all these events is a bad idea.
898 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
899 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
907 ////////////////////////////////////////////////////////////////////////
908 // GuiApplication::Private definition and implementation.
909 ////////////////////////////////////////////////////////////////////////
911 struct GuiApplication::Private
913 Private(): language_model_(0), meta_fake_bit(NoModifier),
916 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
917 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
918 /// WMF Mime handler for Windows clipboard.
919 wmf_mime_ = new QWindowsMimeMetafile;
922 initKeySequences(&theTopLevelKeymap());
925 void initKeySequences(KeyMap * kb)
927 keyseq = KeySequence(kb, kb);
928 cancel_meta_seq = KeySequence(kb, kb);
932 QSortFilterProxyModel * language_model_;
934 GuiClipboard clipboard_;
936 GuiSelection selection_;
938 FontLoader font_loader_;
940 ColorCache color_cache_;
942 QTranslator qt_trans_;
944 QHash<int, SocketNotifier *> socket_notifiers_;
948 /// The global instance
951 /// this timer is used for any regular events one wants to
952 /// perform. at present it is used to check if forked processes
954 QTimer general_timer_;
956 /// delayed FuncRequests
957 std::queue<FuncRequest> func_request_queue_;
962 KeySequence cancel_meta_seq;
964 KeyModifier meta_fake_bit;
966 /// The result of last dispatch action
967 DispatchResult dispatch_result_;
969 /// Multiple views container.
971 * Warning: This must not be a smart pointer as the destruction of the
972 * object is handled by Qt when the view is closed
973 * \sa Qt::WA_DeleteOnClose attribute.
975 QHash<int, GuiView *> views_;
977 /// Only used on mac.
978 QMenuBar * global_menubar_;
981 /// Linkback mime handler for MacOSX.
982 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
985 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
986 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
987 /// WMF Mime handler for Windows clipboard.
988 QWindowsMimeMetafile * wmf_mime_;
992 /// Allows to check whether ESC was pressed during a long operation
993 KeyChecker key_checker_;
997 GuiApplication * guiApp;
999 GuiApplication::~GuiApplication()
1002 closeAllLinkBackLinks();
1008 GuiApplication::GuiApplication(int & argc, char ** argv)
1009 : QApplication(argc, argv), current_view_(0),
1010 d(new GuiApplication::Private)
1012 QString app_name = "LyX";
1013 QCoreApplication::setOrganizationName(app_name);
1014 QCoreApplication::setOrganizationDomain("lyx.org");
1015 QCoreApplication::setApplicationName(lyx_package);
1017 qsrand(QDateTime::currentDateTime().toTime_t());
1019 // Install translator for GUI elements.
1020 installTranslator(&d->qt_trans_);
1023 // Enable reception of XCB events.
1024 installNativeEventFilter(this);
1027 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1028 // lyxrc setting for this in order to let the application stay resident.
1029 // But then we need some kind of dock icon, at least on Windows.
1031 if (lyxrc.quit_on_last_window_closed)
1032 setQuitOnLastWindowClosed(false);
1035 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1036 // seems to be the default case for applications like LyX.
1037 setQuitOnLastWindowClosed(false);
1038 // This allows to translate the strings that appear in the LyX menu.
1039 /// A translator suitable for the entries in the LyX menu.
1040 /// Only needed with Qt/Mac.
1041 installTranslator(new MenuTranslator(this));
1046 #if defined(Q_WS_X11) || defined(QPA_XCB)
1047 // doubleClickInterval() is 400 ms on X11 which is just too long.
1048 // On Windows and Mac OS X, the operating system's value is used.
1049 // On Microsoft Windows, calling this function sets the double
1050 // click interval for all applications. So we don't!
1051 QApplication::setDoubleClickInterval(300);
1054 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1056 // needs to be done before reading lyxrc
1058 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1062 // Set the cache to 5120 kilobytes which corresponds to screen size of
1063 // 1280 by 1024 pixels with a color depth of 32 bits.
1064 QPixmapCache::setCacheLimit(5120);
1066 // Initialize RC Fonts
1067 if (lyxrc.roman_font_name.empty())
1068 lyxrc.roman_font_name = fromqstr(romanFontName());
1070 if (lyxrc.sans_font_name.empty())
1071 lyxrc.sans_font_name = fromqstr(sansFontName());
1073 if (lyxrc.typewriter_font_name.empty())
1074 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1076 d->general_timer_.setInterval(500);
1077 connect(&d->general_timer_, SIGNAL(timeout()),
1078 this, SLOT(handleRegularEvents()));
1079 d->general_timer_.start();
1081 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1082 // This is clearly not enough in a time where we use threads for
1083 // document preview and/or export. 20 should be OK.
1084 QThreadPool::globalInstance()->setMaxThreadCount(20);
1088 GuiApplication * theGuiApp()
1090 return dynamic_cast<GuiApplication *>(theApp());
1094 double GuiApplication::pixelRatio() const
1096 #if QT_VERSION >= 0x050000
1097 return devicePixelRatio();
1104 void GuiApplication::clearSession()
1111 docstring Application::iconName(FuncRequest const & f, bool unknown)
1113 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1117 docstring Application::mathIcon(docstring const & c)
1119 return qstring_to_ucs4(findImg(toqstr(c)));
1123 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1127 BufferView * bv = 0;
1128 BufferView * doc_bv = 0;
1130 if (cmd.action() == LFUN_NOACTION) {
1131 status.message(from_utf8(N_("Nothing to do")));
1132 status.setEnabled(false);
1135 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1136 status.setUnknown(true);
1137 status.message(from_utf8(N_("Unknown action")));
1138 status.setEnabled(false);
1141 // Does the GuiApplication know something?
1142 else if (getStatus(cmd, status)) { }
1144 // If we do not have a GuiView, then other functions are disabled
1145 else if (!current_view_)
1146 status.setEnabled(false);
1148 // Does the GuiView know something?
1149 else if (current_view_->getStatus(cmd, status)) { }
1151 // In LyX/Mac, when a dialog is open, the menus of the
1152 // application can still be accessed without giving focus to
1153 // the main window. In this case, we want to disable the menu
1154 // entries that are buffer or view-related.
1155 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1157 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1158 status.setEnabled(false);
1161 // If we do not have a BufferView, then other functions are disabled
1162 else if (!(bv = current_view_->currentBufferView()))
1163 status.setEnabled(false);
1165 // Does the current BufferView know something?
1166 else if (bv->getStatus(cmd, status)) { }
1168 // Does the current Buffer know something?
1169 else if (bv->buffer().getStatus(cmd, status)) { }
1171 // If we do not have a document BufferView, different from the
1172 // current BufferView, then other functions are disabled
1173 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1174 status.setEnabled(false);
1176 // Does the document Buffer know something?
1177 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1180 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1181 status.message(from_utf8(N_("Command not handled")));
1182 status.setEnabled(false);
1185 // the default error message if we disable the command
1186 if (!status.enabled() && status.message().empty())
1187 status.message(from_utf8(N_("Command disabled")));
1193 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1195 // I would really like to avoid having this switch and rather try to
1196 // encode this in the function itself.
1197 // -- And I'd rather let an inset decide which LFUNs it is willing
1198 // to handle (Andre')
1200 switch (cmd.action()) {
1202 // This could be used for the no-GUI version. The GUI version is handled in
1203 // GuiView::getStatus(). See above.
1205 case LFUN_BUFFER_WRITE:
1206 case LFUN_BUFFER_WRITE_AS: {
1207 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1208 enable = b && (b->isUnnamed() || !b->isClean());
1213 case LFUN_BOOKMARK_GOTO: {
1214 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1215 enable = theSession().bookmarks().isValid(num);
1219 case LFUN_BOOKMARK_CLEAR:
1220 enable = theSession().bookmarks().hasValid();
1223 // this one is difficult to get right. As a half-baked
1224 // solution, we consider only the first action of the sequence
1225 case LFUN_COMMAND_SEQUENCE: {
1226 // argument contains ';'-terminated commands
1227 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1228 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1229 func.setOrigin(cmd.origin());
1230 flag = getStatus(func);
1234 // we want to check if at least one of these is enabled
1235 case LFUN_COMMAND_ALTERNATIVES: {
1236 // argument contains ';'-terminated commands
1237 string arg = to_utf8(cmd.argument());
1238 while (!arg.empty()) {
1240 arg = split(arg, first, ';');
1241 FuncRequest func(lyxaction.lookupFunc(first));
1242 func.setOrigin(cmd.origin());
1243 flag = getStatus(func);
1244 // if this one is enabled, the whole thing is
1253 string name = to_utf8(cmd.argument());
1254 if (theTopLevelCmdDef().lock(name, func)) {
1255 func.setOrigin(cmd.origin());
1256 flag = getStatus(func);
1257 theTopLevelCmdDef().release(name);
1259 // catch recursion or unknown command
1260 // definition. all operations until the
1261 // recursion or unknown command definition
1262 // occurs are performed, so set the state to
1269 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1271 case LFUN_PREFERENCES_SAVE:
1272 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1273 case LFUN_DEBUG_LEVEL_SET:
1274 // these are handled in our dispatch()
1277 case LFUN_WINDOW_CLOSE:
1278 enable = d->views_.size() > 0;
1281 case LFUN_BUFFER_NEW:
1282 case LFUN_BUFFER_NEW_TEMPLATE:
1283 case LFUN_FILE_OPEN:
1284 case LFUN_HELP_OPEN:
1285 case LFUN_SCREEN_FONT_UPDATE:
1286 case LFUN_SET_COLOR:
1287 case LFUN_WINDOW_NEW:
1289 case LFUN_LYXRC_APPLY:
1290 case LFUN_COMMAND_PREFIX:
1292 case LFUN_META_PREFIX:
1293 case LFUN_RECONFIGURE:
1294 case LFUN_SERVER_GET_FILENAME:
1295 case LFUN_SERVER_NOTIFY:
1299 case LFUN_BUFFER_FORALL: {
1300 if (theBufferList().empty()) {
1301 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1302 flag.setEnabled(false);
1306 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1307 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1308 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1309 flag.setEnabled(false);
1314 case LFUN_DIALOG_SHOW: {
1315 string const name = cmd.getArg(0);
1316 return name == "aboutlyx"
1318 || name == "texinfo"
1319 || name == "progress"
1320 || name == "compare";
1328 flag.setEnabled(false);
1332 /// make a post-dispatch status message
1333 static docstring makeDispatchMessage(docstring const & msg,
1334 FuncRequest const & cmd)
1336 const bool verbose = (cmd.origin() == FuncRequest::MENU
1337 || cmd.origin() == FuncRequest::TOOLBAR
1338 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1340 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1341 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1345 docstring dispatch_msg = msg;
1346 if (!dispatch_msg.empty())
1347 dispatch_msg += ' ';
1349 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1351 bool argsadded = false;
1353 if (!cmd.argument().empty()) {
1354 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1355 comname += ' ' + cmd.argument();
1359 docstring const shortcuts = theTopLevelKeymap().
1360 printBindings(cmd, KeySequence::ForGui);
1362 if (!shortcuts.empty())
1363 comname += ": " + shortcuts;
1364 else if (!argsadded && !cmd.argument().empty())
1365 comname += ' ' + cmd.argument();
1367 if (!comname.empty()) {
1368 comname = rtrim(comname);
1369 dispatch_msg += '(' + rtrim(comname) + ')';
1371 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1372 return dispatch_msg;
1376 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1378 Buffer * buffer = 0;
1379 if (current_view_ && current_view_->currentBufferView()) {
1380 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1381 buffer = ¤t_view_->currentBufferView()->buffer();
1383 buffer->undo().beginUndoGroup();
1387 // redraw the screen at the end (first of the two drawing steps).
1388 // This is done unless explicitly requested otherwise
1389 dr.screenUpdate(Update::FitCursor);
1391 updateCurrentView(cmd, dr);
1393 // the buffer may have been closed by one action
1394 if (theBufferList().isLoaded(buffer))
1395 buffer->undo().endUndoGroup();
1397 d->dispatch_result_ = dr;
1398 return d->dispatch_result_;
1402 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1407 BufferView * bv = current_view_->currentBufferView();
1409 if (dr.needBufferUpdate()) {
1410 bv->cursor().clearBufferUpdate();
1411 bv->buffer().updateBuffer();
1413 // BufferView::update() updates the ViewMetricsInfo and
1414 // also initializes the position cache for all insets in
1415 // (at least partially) visible top-level paragraphs.
1416 // We will redraw the screen only if needed.
1417 bv->processUpdateFlags(dr.screenUpdate());
1419 // Do we have a selection?
1420 theSelection().haveSelection(bv->cursor().selection());
1423 current_view_->restartCursor();
1425 if (dr.needMessageUpdate()) {
1426 // Some messages may already be translated, so we cannot use _()
1427 current_view_->message(makeDispatchMessage(
1428 translateIfPossible(dr.message()), cmd));
1433 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1434 bool switchToBuffer)
1436 if (!theSession().bookmarks().isValid(idx))
1438 BookmarksSection::Bookmark const & bm =
1439 theSession().bookmarks().bookmark(idx);
1440 LASSERT(!bm.filename.empty(), return);
1441 string const file = bm.filename.absFileName();
1442 // if the file is not opened, open it.
1443 if (!theBufferList().exists(bm.filename)) {
1445 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1449 // open may fail, so we need to test it again
1450 if (!theBufferList().exists(bm.filename))
1453 // bm can be changed when saving
1454 BookmarksSection::Bookmark tmp = bm;
1456 // Special case idx == 0 used for back-from-back jump navigation
1458 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1460 // if the current buffer is not that one, switch to it.
1461 BufferView * doc_bv = current_view_ ?
1462 current_view_->documentBufferView() : 0;
1463 Cursor const old = doc_bv->cursor();
1464 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1465 if (switchToBuffer) {
1466 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1469 doc_bv = current_view_->documentBufferView();
1474 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1475 if (!doc_bv->moveToPosition(
1476 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1479 Cursor & cur = doc_bv->cursor();
1481 notifyCursorLeavesOrEnters(old, cur);
1487 // Cursor jump succeeded!
1488 pit_type new_pit = cur.pit();
1489 pos_type new_pos = cur.pos();
1490 int new_id = cur.paragraph().id();
1492 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1493 // see http://www.lyx.org/trac/ticket/3092
1494 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1495 || bm.top_id != new_id) {
1496 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1497 new_pit, new_pos, new_id);
1501 // This function runs "configure" and then rereads lyx.defaults to
1502 // reconfigure the automatic settings.
1503 void GuiApplication::reconfigure(string const & option)
1505 // emit message signal.
1507 current_view_->message(_("Running configure..."));
1509 // Run configure in user lyx directory
1510 string const lock_file = package().getConfigureLockName();
1511 int fd = fileLock(lock_file.c_str());
1512 int const ret = package().reconfigureUserLyXDir(option);
1513 // emit message signal.
1515 current_view_->message(_("Reloading configuration..."));
1516 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1517 // Re-read packages.lst
1518 LaTeXPackages::getAvailable();
1519 fileUnlock(fd, lock_file.c_str());
1522 Alert::information(_("System reconfiguration failed"),
1523 _("The system reconfiguration has failed.\n"
1524 "Default textclass is used but LyX may\n"
1525 "not be able to work properly.\n"
1526 "Please reconfigure again if needed."));
1528 Alert::information(_("System reconfigured"),
1529 _("The system has been reconfigured.\n"
1530 "You need to restart LyX to make use of any\n"
1531 "updated document class specifications."));
1534 void GuiApplication::validateCurrentView()
1536 if (!d->views_.empty() && !current_view_) {
1537 // currently at least one view exists but no view has the focus.
1538 // choose the last view to make it current.
1539 // a view without any open document is preferred.
1540 GuiView * candidate = 0;
1541 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1542 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1543 for (; it != end; ++it) {
1545 if (!candidate->documentBufferView())
1548 setCurrentView(candidate);
1552 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1554 string const argument = to_utf8(cmd.argument());
1555 FuncCode const action = cmd.action();
1557 LYXERR(Debug::ACTION, "cmd: " << cmd);
1559 // we have not done anything wrong yet.
1562 FuncStatus const flag = getStatus(cmd);
1563 if (!flag.enabled()) {
1564 // We cannot use this function here
1565 LYXERR(Debug::ACTION, "action "
1566 << lyxaction.getActionName(action)
1567 << " [" << action << "] is disabled at this location");
1568 dr.setMessage(flag.message());
1570 dr.dispatched(false);
1571 dr.screenUpdate(Update::None);
1572 dr.clearBufferUpdate();
1576 if (cmd.origin() == FuncRequest::LYXSERVER) {
1577 if (current_view_ && current_view_->currentBufferView())
1578 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1579 // we will also need to redraw the screen at the end
1580 dr.screenUpdate(Update::FitCursor);
1583 // Assumes that the action will be dispatched.
1584 dr.dispatched(true);
1586 switch (cmd.action()) {
1588 case LFUN_WINDOW_NEW:
1589 createView(toqstr(cmd.argument()));
1592 case LFUN_WINDOW_CLOSE:
1593 // update bookmark pit of the current buffer before window close
1594 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1595 gotoBookmark(i+1, false, false);
1596 // clear the last opened list, because
1597 // maybe this will end the session
1598 theSession().lastOpened().clear();
1599 // check for valid current_view_
1600 validateCurrentView();
1602 current_view_->closeScheduled();
1606 // quitting is triggered by the gui code
1607 // (leaving the event loop).
1609 current_view_->message(from_utf8(N_("Exiting.")));
1610 if (closeAllViews())
1614 case LFUN_SCREEN_FONT_UPDATE: {
1615 // handle the screen font changes.
1616 d->font_loader_.update();
1617 // Backup current_view_
1618 GuiView * view = current_view_;
1619 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1620 // to skip the refresh.
1622 theBufferList().changed(false);
1623 // Restore current_view_
1624 current_view_ = view;
1628 case LFUN_BUFFER_NEW:
1629 validateCurrentView();
1630 if (d->views_.empty()
1631 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1632 createView(QString(), false); // keep hidden
1633 current_view_->newDocument(to_utf8(cmd.argument()), false);
1634 current_view_->show();
1635 setActiveWindow(current_view_);
1637 current_view_->newDocument(to_utf8(cmd.argument()), false);
1641 case LFUN_BUFFER_NEW_TEMPLATE:
1642 validateCurrentView();
1643 if (d->views_.empty()
1644 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1646 current_view_->newDocument(to_utf8(cmd.argument()), true);
1647 if (!current_view_->documentBufferView())
1648 current_view_->close();
1650 current_view_->newDocument(to_utf8(cmd.argument()), true);
1654 case LFUN_FILE_OPEN: {
1655 validateCurrentView();
1656 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1657 string const fname = to_utf8(cmd.argument());
1658 bool const is_open = FileName::isAbsolute(fname)
1659 && theBufferList().getBuffer(FileName(fname));
1660 if (d->views_.empty()
1661 || (!lyxrc.open_buffers_in_tabs
1662 && current_view_->documentBufferView() != 0
1664 // We want the ui session to be saved per document and not per
1665 // window number. The filename crc is a good enough identifier.
1666 boost::crc_32_type crc;
1667 crc = for_each(fname.begin(), fname.end(), crc);
1668 createView(crc.checksum());
1669 current_view_->openDocument(fname);
1670 if (current_view_ && !current_view_->documentBufferView())
1671 current_view_->close();
1673 current_view_->openDocument(fname);
1677 case LFUN_HELP_OPEN: {
1678 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1679 if (current_view_ == 0)
1681 string const arg = to_utf8(cmd.argument());
1683 current_view_->message(_("Missing argument"));
1686 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1688 fname = i18nLibFileSearch("examples", arg, "lyx");
1690 if (fname.empty()) {
1691 lyxerr << "LyX: unable to find documentation file `"
1692 << arg << "'. Bad installation?" << endl;
1695 current_view_->message(bformat(_("Opening help file %1$s..."),
1696 makeDisplayPath(fname.absFileName())));
1697 Buffer * buf = current_view_->loadDocument(fname, false);
1699 #ifndef DEVEL_VERSION
1701 buf->setReadonly(true);
1708 case LFUN_SET_COLOR: {
1710 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1711 if (lyx_name.empty() || x11_name.empty()) {
1713 current_view_->message(
1714 _("Syntax: set-color <lyx_name> <x11_name>"));
1719 // FIXME: The graphics cache no longer has a changeDisplay method.
1720 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1721 bool const graphicsbg_changed =
1722 lyx_name == graphicsbg && x11_name != graphicsbg;
1723 if (graphicsbg_changed)
1724 graphics::GCache::get().changeDisplay(true);
1727 if (!lcolor.setColor(lyx_name, x11_name)) {
1729 current_view_->message(
1730 bformat(_("Set-color \"%1$s\" failed "
1731 "- color is undefined or "
1732 "may not be redefined"),
1733 from_utf8(lyx_name)));
1736 // Make sure we don't keep old colors in cache.
1737 d->color_cache_.clear();
1738 // Update the current view
1739 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1743 case LFUN_LYXRC_APPLY: {
1744 // reset active key sequences, since the bindings
1745 // are updated (bug 6064)
1747 LyXRC const lyxrc_orig = lyxrc;
1749 istringstream ss(to_utf8(cmd.argument()));
1750 bool const success = lyxrc.read(ss);
1753 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1754 << "Unable to read lyxrc data"
1759 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1761 // If the request comes from the minibuffer, then we can't reset
1762 // the GUI, since that would destory the minibuffer itself and
1763 // cause a crash, since we are currently in one of the methods of
1764 // GuiCommandBuffer. See bug #8540.
1765 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1768 // FIXME Unfortunately, that leaves a bug here, since we cannot
1769 // reset the GUI in this case. If the changes to lyxrc affected the
1770 // UI, then, nothing would happen. This seems fairly unlikely, but
1771 // it definitely is a bug.
1776 case LFUN_COMMAND_PREFIX:
1777 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1782 d->meta_fake_bit = NoModifier;
1783 GuiView * gv = currentView();
1784 if (gv && gv->currentBufferView())
1785 // cancel any selection
1786 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1787 dr.setMessage(from_ascii(N_("Cancel")));
1790 case LFUN_META_PREFIX:
1791 d->meta_fake_bit = AltModifier;
1792 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1795 // --- Menus -----------------------------------------------
1796 case LFUN_RECONFIGURE:
1797 // argument is any additional parameter to the configure.py command
1798 reconfigure(to_utf8(cmd.argument()));
1801 // --- lyxserver commands ----------------------------
1802 case LFUN_SERVER_GET_FILENAME: {
1803 if (current_view_ && current_view_->documentBufferView()) {
1804 docstring const fname = from_utf8(
1805 current_view_->documentBufferView()->buffer().absFileName());
1806 dr.setMessage(fname);
1807 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1809 dr.setMessage(docstring());
1810 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1815 case LFUN_SERVER_NOTIFY: {
1816 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1817 dr.setMessage(dispatch_buffer);
1818 theServer().notifyClient(to_utf8(dispatch_buffer));
1822 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1823 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1829 string rest = split(argument, countstr, ' ');
1830 istringstream is(countstr);
1833 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1834 for (int i = 0; i < count; ++i)
1835 dispatch(lyxaction.lookupFunc(rest));
1839 case LFUN_COMMAND_SEQUENCE: {
1840 // argument contains ';'-terminated commands
1841 string arg = argument;
1842 // FIXME: this LFUN should also work without any view.
1843 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1844 ? &(current_view_->documentBufferView()->buffer()) : 0;
1846 buffer->undo().beginUndoGroup();
1847 while (!arg.empty()) {
1849 arg = split(arg, first, ';');
1850 FuncRequest func(lyxaction.lookupFunc(first));
1851 func.setOrigin(cmd.origin());
1854 // the buffer may have been closed by one action
1855 if (theBufferList().isLoaded(buffer))
1856 buffer->undo().endUndoGroup();
1860 case LFUN_BUFFER_FORALL: {
1861 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1863 map<Buffer *, GuiView *> views_lVisible;
1864 map<GuiView *, Buffer *> activeBuffers;
1866 QList<GuiView *> allViews = d->views_.values();
1868 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1869 // and on which buffer is active in each view.
1870 Buffer * const last = theBufferList().last();
1871 foreach (GuiView * view, allViews) {
1872 // all of the buffers might be locally hidden. That is, there is no active buffer.
1873 if (!view || !view->currentBufferView())
1874 activeBuffers[view] = 0;
1876 activeBuffers[view] = &view->currentBufferView()->buffer();
1878 // find out if each is locally visible or locally hidden.
1879 // we don't use a for loop as the buffer list cycles.
1880 Buffer * b = theBufferList().first();
1882 bool const locallyVisible = view && view->workArea(*b);
1883 if (locallyVisible) {
1884 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1885 // only need to overwrite/add if we don't already know a buffer is globally
1886 // visible or we do know but we would prefer to dispatch LFUN from the
1887 // current view because of cursor position issues.
1888 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1889 views_lVisible[b] = view;
1893 b = theBufferList().next(b);
1897 GuiView * const homeView = currentView();
1898 Buffer * b = theBufferList().first();
1899 Buffer * nextBuf = 0;
1900 int numProcessed = 0;
1903 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1905 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1907 // first change to a view where b is locally visible, preferably current_view_.
1908 GuiView * const vLv = views_lVisible[b];
1910 lyx::dispatch(funcToRun);
1918 // put things back to how they were (if possible).
1919 foreach (GuiView * view, allViews) {
1920 Buffer * originalBuf = activeBuffers[view];
1921 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1922 if (theBufferList().isLoaded(originalBuf))
1923 view->setBuffer(originalBuf);
1925 homeView->setFocus();
1927 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1931 case LFUN_COMMAND_ALTERNATIVES: {
1932 // argument contains ';'-terminated commands
1933 string arg = argument;
1934 while (!arg.empty()) {
1936 arg = split(arg, first, ';');
1937 FuncRequest func(lyxaction.lookupFunc(first));
1938 func.setOrigin(cmd.origin());
1939 FuncStatus const stat = getStatus(func);
1940 if (stat.enabled()) {
1950 if (theTopLevelCmdDef().lock(argument, func)) {
1951 func.setOrigin(cmd.origin());
1953 theTopLevelCmdDef().release(argument);
1955 if (func.action() == LFUN_UNKNOWN_ACTION) {
1956 // unknown command definition
1957 lyxerr << "Warning: unknown command definition `"
1961 // recursion detected
1962 lyxerr << "Warning: Recursion in the command definition `"
1963 << argument << "' detected"
1970 case LFUN_PREFERENCES_SAVE:
1971 lyxrc.write(support::makeAbsPath("preferences",
1972 package().user_support().absFileName()), false);
1975 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1976 string const fname = addName(addPath(package().user_support().absFileName(),
1977 "templates/"), "defaults.lyx");
1978 Buffer defaults(fname);
1980 istringstream ss(argument);
1985 // We need to make sure that, after we recreat the DocumentClass,
1986 // which we do in readHeader, we apply it to the document itself.
1987 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
1988 int const unknown_tokens = defaults.readHeader(lex);
1989 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
1991 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
1992 cap::switchBetweenClasses(olddc, newdc, theinset, el);
1994 if (unknown_tokens != 0) {
1995 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1996 << unknown_tokens << " unknown token"
1997 << (unknown_tokens == 1 ? "" : "s")
2001 if (defaults.writeFile(FileName(defaults.absFileName())))
2002 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2003 makeDisplayPath(fname)));
2006 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2011 case LFUN_BOOKMARK_GOTO:
2012 // go to bookmark, open unopened file and switch to buffer if necessary
2013 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2014 dr.screenUpdate(Update::Force | Update::FitCursor);
2017 case LFUN_BOOKMARK_CLEAR:
2018 theSession().bookmarks().clear();
2021 case LFUN_DEBUG_LEVEL_SET:
2022 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2025 case LFUN_DIALOG_SHOW: {
2026 string const name = cmd.getArg(0);
2028 if ( name == "aboutlyx"
2030 || name == "texinfo"
2031 || name == "progress"
2032 || name == "compare")
2034 // work around: on Mac OS the application
2035 // is not terminated when closing the last view.
2036 // Create a new one to be able to dispatch the
2037 // LFUN_DIALOG_SHOW to this view.
2038 if (current_view_ == 0)
2045 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2048 current_view_->dispatch(cmd, dr);
2052 if (cmd.origin() == FuncRequest::LYXSERVER)
2053 updateCurrentView(cmd, dr);
2057 docstring GuiApplication::viewStatusMessage()
2059 // When meta-fake key is pressed, show the key sequence so far + "M-".
2060 if (d->meta_fake_bit != NoModifier)
2061 return d->keyseq.print(KeySequence::ForGui) + "M-";
2063 // Else, when a non-complete key sequence is pressed,
2064 // show the available options.
2065 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2066 return d->keyseq.printOptions(true);
2072 void GuiApplication::handleKeyFunc(FuncCode action)
2076 if (d->keyseq.length())
2078 GuiView * gv = currentView();
2079 LASSERT(gv && gv->currentBufferView(), return);
2080 BufferView * bv = gv->currentBufferView();
2081 bv->getIntl().getTransManager().deadkey(
2082 c, get_accent(action).accent, bv->cursor().innerText(),
2084 // Need to clear, in case the minibuffer calls these
2087 // copied verbatim from do_accent_char
2088 bv->cursor().resetAnchor();
2092 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2094 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2096 // Do nothing if we have nothing (JMarc)
2097 if (!keysym.isOK()) {
2098 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2100 current_view_->restartCursor();
2104 if (keysym.isModifier()) {
2106 current_view_->restartCursor();
2110 char_type encoded_last_key = keysym.getUCSEncoded();
2112 // Do a one-deep top-level lookup for
2113 // cancel and meta-fake keys. RVDK_PATCH_5
2114 d->cancel_meta_seq.reset();
2116 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2117 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2119 // When not cancel or meta-fake, do the normal lookup.
2120 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2121 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2122 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2123 // remove Caps Lock and Mod2 as a modifiers
2124 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2125 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2128 // Dont remove this unless you know what you are doing.
2129 d->meta_fake_bit = NoModifier;
2131 // Can this happen now ?
2132 if (func.action() == LFUN_NOACTION)
2133 func = FuncRequest(LFUN_COMMAND_PREFIX);
2135 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2136 << d->keyseq.print(KeySequence::Portable) << ']');
2138 // already here we know if it any point in going further
2139 // why not return already here if action == -1 and
2140 // num_bytes == 0? (Lgb)
2142 if (d->keyseq.length() > 1 && current_view_)
2143 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2146 // Maybe user can only reach the key via holding down shift.
2147 // Let's see. But only if shift is the only modifier
2148 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2149 LYXERR(Debug::KEY, "Trying without shift");
2150 func = d->keyseq.addkey(keysym, NoModifier);
2151 LYXERR(Debug::KEY, "Action now " << func.action());
2154 if (func.action() == LFUN_UNKNOWN_ACTION) {
2155 // We didn't match any of the key sequences.
2156 // See if it's normal insertable text not already
2157 // covered by a binding
2158 if (keysym.isText() && d->keyseq.length() == 1) {
2159 // Non-printable characters (such as ASCII control characters)
2160 // must not be inserted (#5704)
2161 if (!isPrintable(encoded_last_key)) {
2162 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2163 current_view_->restartCursor();
2166 // If a non-Shift Modifier is used we have a non-bound key sequence
2167 // (such as Alt+j = j). This should be omitted (#5575).
2168 // On Windows, AltModifier and ControlModifier are both
2169 // set when AltGr is pressed. Therefore, in order to not
2170 // break AltGr-bound symbols (see #5575 for details),
2171 // unbound Ctrl+Alt key sequences are allowed.
2172 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2173 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2174 && !(state & AltModifier && state & ControlModifier)
2177 current_view_->message(_("Unknown function."));
2178 current_view_->restartCursor();
2181 // Since all checks above were passed, we now really have text that
2182 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2183 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2185 LYXERR(Debug::KEY, "isText() is true, inserting.");
2186 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2188 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2189 if (current_view_) {
2190 current_view_->message(_("Unknown function."));
2191 current_view_->restartCursor();
2197 if (func.action() == LFUN_SELF_INSERT) {
2198 if (encoded_last_key != 0) {
2199 docstring const arg(1, encoded_last_key);
2200 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2201 FuncRequest::KEYBOARD));
2202 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2205 processFuncRequest(func);
2209 void GuiApplication::processFuncRequest(FuncRequest const & func)
2211 lyx::dispatch(func);
2215 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2217 addToFuncRequestQueue(func);
2218 processFuncRequestQueueAsync();
2222 void GuiApplication::processFuncRequestQueue()
2224 while (!d->func_request_queue_.empty()) {
2225 processFuncRequest(d->func_request_queue_.front());
2226 d->func_request_queue_.pop();
2231 void GuiApplication::processFuncRequestQueueAsync()
2233 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2237 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2239 d->func_request_queue_.push(func);
2243 void GuiApplication::resetGui()
2245 // Set the language defined by the user.
2249 if (!readUIFile(toqstr(lyxrc.ui_file)))
2250 // Gives some error box here.
2253 if (d->global_menubar_)
2254 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2256 QHash<int, GuiView *>::iterator it;
2257 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2260 gv->setLayoutDirection(layoutDirection());
2264 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2268 void GuiApplication::createView(int view_id)
2270 createView(QString(), true, view_id);
2274 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2277 // release the keyboard which might have been grabed by the global
2278 // menubar on Mac to catch shortcuts even without any GuiView.
2279 if (d->global_menubar_)
2280 d->global_menubar_->releaseKeyboard();
2284 while (d->views_.find(id) != d->views_.end())
2287 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2288 GuiView * view = new GuiView(id);
2290 d->views_[id] = view;
2294 setActiveWindow(view);
2297 if (!geometry_arg.isEmpty()) {
2298 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2302 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2303 re.indexIn(geometry_arg);
2304 w = re.cap(1).toInt();
2305 h = re.cap(2).toInt();
2306 x = re.cap(3).toInt();
2307 y = re.cap(4).toInt();
2308 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2309 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2310 // Set initial geometry such that we can get the frame size.
2311 view->setGeometry(x, y, w, h);
2312 int framewidth = view->geometry().x() - view->x();
2313 int titleheight = view->geometry().y() - view->y();
2314 // Negative displacements must be interpreted as distances
2315 // from the right or bottom screen borders.
2316 if (sx == '-' || sy == '-') {
2317 QRect rec = QApplication::desktop()->screenGeometry();
2319 x += rec.width() - w - framewidth;
2321 y += rec.height() - h - titleheight;
2322 view->setGeometry(x, y, w, h);
2324 // Make sure that the left and top frame borders are visible.
2325 if (view->x() < 0 || view->y() < 0) {
2330 view->setGeometry(x, y, w, h);
2338 Clipboard & GuiApplication::clipboard()
2340 return d->clipboard_;
2344 Selection & GuiApplication::selection()
2346 return d->selection_;
2350 FontLoader & GuiApplication::fontLoader()
2352 return d->font_loader_;
2356 Toolbars const & GuiApplication::toolbars() const
2358 return d->toolbars_;
2362 Toolbars & GuiApplication::toolbars()
2364 return d->toolbars_;
2368 Menus const & GuiApplication::menus() const
2374 Menus & GuiApplication::menus()
2380 QList<int> GuiApplication::viewIds() const
2382 return d->views_.keys();
2386 ColorCache & GuiApplication::colorCache()
2388 return d->color_cache_;
2392 int GuiApplication::exec()
2394 // asynchronously handle batch commands. This event will be in
2395 // the event queue in front of other asynchronous events. Hence,
2396 // we can assume in the latter that the gui is setup already.
2397 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2399 return QApplication::exec();
2403 void GuiApplication::exit(int status)
2405 QApplication::exit(status);
2409 void GuiApplication::setGuiLanguage()
2413 // install translation file for Qt built-in dialogs
2414 QString const language_name = QString("qt_") + theLocale.name();
2415 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2416 // Short-named translator can be loaded from a long name, but not the
2417 // opposite. Therefore, long name should be used without truncation.
2418 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2419 if (!d->qt_trans_.load(language_name,
2420 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2421 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2424 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2428 switch (theLocale.language()) {
2429 case QLocale::Arabic :
2430 case QLocale::Hebrew :
2431 case QLocale::Persian :
2432 case QLocale::Urdu :
2433 setLayoutDirection(Qt::RightToLeft);
2436 setLayoutDirection(Qt::LeftToRight);
2441 void GuiApplication::execBatchCommands()
2446 if (!readUIFile(toqstr(lyxrc.ui_file)))
2447 // Gives some error box here.
2451 #if QT_VERSION > 0x040600
2452 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2454 #if QT_VERSION > 0x050100
2455 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2457 // Create the global default menubar which is shown for the dialogs
2458 // and if no GuiView is visible.
2459 // This must be done after the session was recovered to know the "last files".
2460 d->global_menubar_ = new QMenuBar(0);
2461 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2464 lyx::execBatchCommands();
2468 QAbstractItemModel * GuiApplication::languageModel()
2470 if (d->language_model_)
2471 return d->language_model_;
2473 QStandardItemModel * lang_model = new QStandardItemModel(this);
2474 lang_model->insertColumns(0, 3);
2475 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2476 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2477 Languages::const_iterator it = lyx::languages.begin();
2478 Languages::const_iterator end = lyx::languages.end();
2479 for (; it != end; ++it) {
2480 int current_row = lang_model->rowCount();
2481 lang_model->insertRows(current_row, 1);
2482 QModelIndex pl_item = lang_model->index(current_row, 0);
2483 QModelIndex sp_item = lang_model->index(current_row, 1);
2484 QModelIndex th_item = lang_model->index(current_row, 2);
2485 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2486 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2487 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2488 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2489 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2490 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2491 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2492 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2493 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2494 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2496 d->language_model_ = new QSortFilterProxyModel(this);
2497 d->language_model_->setSourceModel(lang_model);
2498 d->language_model_->setSortLocaleAware(true);
2499 return d->language_model_;
2503 void GuiApplication::restoreGuiSession()
2505 if (!lyxrc.load_session)
2508 Session & session = theSession();
2509 LastOpenedSection::LastOpened const & lastopened =
2510 session.lastOpened().getfiles();
2512 validateCurrentView();
2514 FileName active_file;
2515 // do not add to the lastfile list since these files are restored from
2516 // last session, and should be already there (regular files), or should
2517 // not be added at all (help files).
2518 for (size_t i = 0; i < lastopened.size(); ++i) {
2519 FileName const & file_name = lastopened[i].file_name;
2520 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2521 && current_view_->documentBufferView() != 0)) {
2522 boost::crc_32_type crc;
2523 string const & fname = file_name.absFileName();
2524 crc = for_each(fname.begin(), fname.end(), crc);
2525 createView(crc.checksum());
2527 current_view_->loadDocument(file_name, false);
2529 if (lastopened[i].active)
2530 active_file = file_name;
2533 // Restore last active buffer
2534 Buffer * buffer = theBufferList().getBuffer(active_file);
2535 if (buffer && current_view_)
2536 current_view_->setBuffer(buffer);
2538 // clear this list to save a few bytes of RAM
2539 session.lastOpened().clear();
2543 QString const GuiApplication::romanFontName()
2546 font.setStyleHint(QFont::Serif);
2547 font.setFamily("serif");
2549 return QFontInfo(font).family();
2553 QString const GuiApplication::sansFontName()
2556 font.setStyleHint(QFont::SansSerif);
2557 font.setFamily("sans");
2559 return QFontInfo(font).family();
2563 QString const GuiApplication::typewriterFontName()
2566 font.setStyleHint(QFont::TypeWriter);
2567 font.setFamily("monospace");
2569 return QFontInfo(font).family();
2573 void GuiApplication::handleRegularEvents()
2575 ForkedCallsController::handleCompletedProcesses();
2579 bool GuiApplication::event(QEvent * e)
2582 case QEvent::FileOpen: {
2583 // Open a file; this happens only on Mac OS X for now.
2585 // We do this asynchronously because on startup the batch
2586 // commands are not executed here yet and the gui is not ready
2588 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2589 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2590 processFuncRequestAsync(fr);
2595 return QApplication::event(e);
2600 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2603 return QApplication::notify(receiver, event);
2605 catch (ExceptionMessage const & e) {
2607 case ErrorException:
2609 setQuitOnLastWindowClosed(false);
2611 Alert::error(e.title_, e.details_);
2613 // Properly crash in debug mode in order to get a useful backtrace.
2616 // In release mode, try to exit gracefully.
2619 case BufferException: {
2620 if (!current_view_ || !current_view_->documentBufferView())
2622 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2623 docstring details = e.details_ + '\n';
2624 details += buf->emergencyWrite();
2625 theBufferList().release(buf);
2626 details += "\n" + _("The current document was closed.");
2627 Alert::error(e.title_, details);
2630 case WarningException:
2631 Alert::warning(e.title_, e.details_);
2635 catch (exception const & e) {
2636 docstring s = _("LyX has caught an exception, it will now "
2637 "attempt to save all unsaved documents and exit."
2639 s += from_ascii(e.what());
2640 Alert::error(_("Software exception Detected"), s);
2644 docstring s = _("LyX has caught some really weird exception, it will "
2645 "now attempt to save all unsaved documents and exit.");
2646 Alert::error(_("Software exception Detected"), s);
2654 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2656 QColor const & qcol = d->color_cache_.get(col);
2657 if (!qcol.isValid()) {
2663 rgbcol.r = qcol.red();
2664 rgbcol.g = qcol.green();
2665 rgbcol.b = qcol.blue();
2670 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2672 QColor const qcol(lcolor.getX11Name(col).c_str());
2673 if (!qcol.isValid()) {
2679 rgbcol.r = qcol.red();
2680 rgbcol.g = qcol.green();
2681 rgbcol.b = qcol.blue();
2686 string const GuiApplication::hexName(ColorCode col)
2688 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2692 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2694 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2695 d->socket_notifiers_[fd] = sn;
2696 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2700 void GuiApplication::socketDataReceived(int fd)
2702 d->socket_notifiers_[fd]->func_();
2706 void GuiApplication::unregisterSocketCallback(int fd)
2708 d->socket_notifiers_.take(fd)->setEnabled(false);
2712 void GuiApplication::commitData(QSessionManager & sm)
2714 /** The implementation is required to avoid an application exit
2715 ** when session state save is triggered by session manager.
2716 ** The default implementation sends a close event to all
2717 ** visible top level widgets when session managment allows
2719 ** We are changing that to check the state of each buffer in all
2720 ** views and ask the users what to do if buffers are dirty.
2721 ** Furthermore, we save the session state.
2722 ** We do NOT close the views here since the user still can cancel
2723 ** the logout process (see #9277); also, this would hide LyX from
2724 ** an OSes own session handling (application restoration).
2726 #ifdef QT_NO_SESSIONMANAGER
2728 #warning Qt is compiled without session manager
2730 #pragma message("warning: Qt is compiled without session manager")
2734 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2742 void GuiApplication::unregisterView(GuiView * gv)
2744 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2745 d->views_.remove(gv->id());
2746 if (current_view_ == gv)
2752 bool GuiApplication::closeAllViews()
2754 if (d->views_.empty())
2757 // When a view/window was closed before without quitting LyX, there
2758 // are already entries in the lastOpened list.
2759 theSession().lastOpened().clear();
2761 QList<GuiView *> const views = d->views_.values();
2762 foreach (GuiView * view, views) {
2763 if (!view->closeScheduled())
2772 bool GuiApplication::prepareAllViewsForLogout()
2774 if (d->views_.empty())
2777 QList<GuiView *> const views = d->views_.values();
2778 foreach (GuiView * view, views) {
2779 if (!view->prepareAllBuffersForLogout())
2787 GuiView & GuiApplication::view(int id) const
2789 LAPPERR(d->views_.contains(id));
2790 return *d->views_.value(id);
2794 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2796 QList<GuiView *> const views = d->views_.values();
2797 foreach (GuiView * view, views)
2798 view->hideDialog(name, inset);
2802 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2804 Buffer const * buffer_ = 0;
2805 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2806 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2807 if (Buffer const * ptr = (*it)->updateInset(inset))
2814 bool GuiApplication::searchMenu(FuncRequest const & func,
2815 docstring_list & names) const
2817 return d->menus_.searchMenu(func, names);
2821 // Ensure that a file is read only once (prevents include loops)
2822 static QStringList uifiles;
2823 // store which ui files define Toolbars
2824 static QStringList toolbar_uifiles;
2827 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2838 LexerKeyword uitags[] = {
2839 { "format", ui_format },
2840 { "include", ui_include },
2841 { "menuset", ui_menuset },
2842 { "toolbars", ui_toolbars },
2843 { "toolbarset", ui_toolbarset }
2847 lex.setFile(ui_path);
2849 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2853 if (lyxerr.debugging(Debug::PARSER))
2854 lex.printTable(lyxerr);
2857 // format before introduction of format tag
2858 unsigned int format = 0;
2859 while (lex.isOK()) {
2860 int const status = lex.lex();
2862 // we have to do this check here, outside the switch,
2863 // because otherwise we would start reading include files,
2864 // e.g., if the first tag we hit was an include tag.
2865 if (status == ui_format)
2867 format = lex.getInteger();
2871 // this will trigger unless the first tag we hit is a format
2872 // tag, with the right format.
2873 if (format != LFUN_FORMAT)
2874 return FormatMismatch;
2877 case Lexer::LEX_FEOF:
2882 QString const file = toqstr(lex.getString());
2883 bool const success = readUIFile(file, true);
2885 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2892 d->menus_.read(lex);
2896 d->toolbars_.readToolbars(lex);
2900 d->toolbars_.readToolbarSettings(lex);
2901 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2905 if (!rtrim(lex.getString()).empty())
2906 lex.printError("LyX::ReadUIFile: "
2907 "Unknown menu tag: `$$Token'");
2909 LYXERR0("Error with status: " << status);
2915 return (error ? ReadError : ReadOK);
2919 bool GuiApplication::readUIFile(QString const & name, bool include)
2921 LYXERR(Debug::INIT, "About to read " << name << "...");
2925 ui_path = libFileSearch("ui", name, "inc");
2926 if (ui_path.empty())
2927 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2929 ui_path = libFileSearch("ui", name, "ui");
2932 if (ui_path.empty()) {
2933 static const QString defaultUIFile = "default";
2934 LYXERR(Debug::INIT, "Could not find " << name);
2936 Alert::warning(_("Could not find UI definition file"),
2937 bformat(_("Error while reading the included file\n%1$s\n"
2938 "Please check your installation."), qstring_to_ucs4(name)));
2941 if (name == defaultUIFile) {
2942 LYXERR(Debug::INIT, "Could not find default UI file!!");
2943 Alert::warning(_("Could not find default UI file"),
2944 _("LyX could not find the default UI file!\n"
2945 "Please check your installation."));
2948 Alert::warning(_("Could not find UI definition file"),
2949 bformat(_("Error while reading the configuration file\n%1$s\n"
2950 "Falling back to default.\n"
2951 "Please look under Tools>Preferences>User Interface and\n"
2952 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2953 return readUIFile(defaultUIFile, false);
2956 QString const uifile = toqstr(ui_path.absFileName());
2957 if (uifiles.contains(uifile)) {
2959 // We are reading again the top uifile so reset the safeguard:
2962 d->toolbars_.reset();
2964 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2965 << "Is this an include loop?");
2969 uifiles.push_back(uifile);
2971 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2973 ReturnValues retval = readUIFile(ui_path);
2975 if (retval == FormatMismatch) {
2976 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2977 TempFile tmp("convertXXXXXX.ui");
2978 FileName const tempfile = tmp.name();
2979 bool const success = prefs2prefs(ui_path, tempfile, true);
2981 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2982 " to format " << LFUN_FORMAT << ".");
2984 retval = readUIFile(tempfile);
2988 if (retval != ReadOK) {
2989 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2997 settings.beginGroup("ui_files");
2998 bool touched = false;
2999 for (int i = 0; i != uifiles.size(); ++i) {
3000 QFileInfo fi(uifiles[i]);
3001 QDateTime const date_value = fi.lastModified();
3002 QString const name_key = QString::number(i);
3003 // if an ui file which defines Toolbars has changed,
3004 // we have to reset the settings
3005 if (toolbar_uifiles.contains(uifiles[i])
3006 && (!settings.contains(name_key)
3007 || settings.value(name_key).toString() != uifiles[i]
3008 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3010 settings.setValue(name_key, uifiles[i]);
3011 settings.setValue(name_key + "/date", date_value);
3014 settings.endGroup();
3016 settings.remove("views");
3022 void GuiApplication::onLastWindowClosed()
3024 if (d->global_menubar_)
3025 d->global_menubar_->grabKeyboard();
3029 void GuiApplication::startLongOperation() {
3030 d->key_checker_.start();
3034 bool GuiApplication::longOperationCancelled() {
3035 return d->key_checker_.pressed();
3039 void GuiApplication::stopLongOperation() {
3040 d->key_checker_.stop();
3044 bool GuiApplication::longOperationStarted() {
3045 return d->key_checker_.started();
3049 ////////////////////////////////////////////////////////////////////////
3051 // X11 specific stuff goes here...
3054 bool GuiApplication::x11EventFilter(XEvent * xev)
3059 switch (xev->type) {
3060 case SelectionRequest: {
3061 if (xev->xselectionrequest.selection != XA_PRIMARY)
3063 LYXERR(Debug::SELECTION, "X requested selection.");
3064 BufferView * bv = current_view_->currentBufferView();
3066 docstring const sel = bv->requestSelection();
3068 d->selection_.put(sel);
3072 case SelectionClear: {
3073 if (xev->xselectionclear.selection != XA_PRIMARY)
3075 LYXERR(Debug::SELECTION, "Lost selection.");
3076 BufferView * bv = current_view_->currentBufferView();
3078 bv->clearSelection();
3084 #elif defined(QPA_XCB)
3085 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3086 void * message, long *)
3088 if (!current_view_ || eventType != "xcb_generic_event_t")
3091 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3093 switch (ev->response_type) {
3094 case XCB_SELECTION_REQUEST: {
3095 xcb_selection_request_event_t * srev =
3096 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3097 if (srev->selection != XCB_ATOM_PRIMARY)
3099 LYXERR(Debug::SELECTION, "X requested selection.");
3100 BufferView * bv = current_view_->currentBufferView();
3102 docstring const sel = bv->requestSelection();
3104 d->selection_.put(sel);
3108 case XCB_SELECTION_CLEAR: {
3109 xcb_selection_clear_event_t * scev =
3110 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3111 if (scev->selection != XCB_ATOM_PRIMARY)
3113 LYXERR(Debug::SELECTION, "Lost selection.");
3114 BufferView * bv = current_view_->currentBufferView();
3116 bv->clearSelection();
3124 } // namespace frontend
3127 void hideDialogs(std::string const & name, Inset * inset)
3130 frontend::guiApp->hideDialogs(name, inset);
3134 ////////////////////////////////////////////////////////////////////
3138 ////////////////////////////////////////////////////////////////////
3140 frontend::FontLoader & theFontLoader()
3142 LAPPERR(frontend::guiApp);
3143 return frontend::guiApp->fontLoader();
3147 frontend::FontMetrics const & theFontMetrics(Font const & f)
3149 return theFontMetrics(f.fontInfo());
3153 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3155 LAPPERR(frontend::guiApp);
3156 return frontend::guiApp->fontLoader().metrics(f);
3160 ////////////////////////////////////////////////////////////////////
3164 ////////////////////////////////////////////////////////////////////
3166 frontend::Clipboard & theClipboard()
3168 LAPPERR(frontend::guiApp);
3169 return frontend::guiApp->clipboard();
3173 frontend::Selection & theSelection()
3175 LAPPERR(frontend::guiApp);
3176 return frontend::guiApp->selection();
3182 #include "moc_GuiApplication.cpp"