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 "ToolTipFormatter.h"
18 #include "ColorCache.h"
20 #include "GuiClipboard.h"
21 #include "GuiKeySymbol.h"
22 #include "GuiSelection.h"
25 #include "qt_helpers.h"
28 #include "frontends/alert.h"
29 #include "frontends/Application.h"
30 #include "frontends/FontLoader.h"
31 #include "frontends/FontMetrics.h"
34 #include "BufferList.h"
35 #include "BufferParams.h"
36 #include "BufferView.h"
39 #include "Converter.h"
40 #include "CutAndPaste.h"
41 #include "ErrorList.h"
43 #include "FuncRequest.h"
44 #include "FuncStatus.h"
45 #include "GuiWorkArea.h"
49 #include "LaTeXPackages.h"
52 #include "LyXAction.h"
54 #include "Paragraph.h"
57 #include "SpellChecker.h"
58 #include "Thesaurus.h"
61 #include "insets/InsetText.h"
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/ExceptionMessage.h"
66 #include "support/FileName.h"
67 #include "support/filetools.h"
68 #include "support/ForkedCalls.h"
69 #include "support/gettext.h"
70 #include "support/lassert.h"
71 #include "support/lstrings.h"
72 #include "support/lyxalgo.h" // sorted
73 #include "support/textutils.h"
74 #include "support/Messages.h"
75 #include "support/os.h"
76 #include "support/Package.h"
77 #include "support/TempFile.h"
80 #include "support/AppleScript.h"
81 #include "support/linkback/LinkBackProxy.h"
86 #include <QFontDatabase>
90 #include <QDesktopWidget>
94 #include <QFileOpenEvent>
98 #include <QImageReader>
101 #include <QLibraryInfo>
107 #include <QPixmapCache>
109 #include <QSessionManager>
111 #include <QShowEvent>
112 #include <QSocketNotifier>
113 #include <QSortFilterProxyModel>
114 #include <QStandardItemModel>
115 #include <QTextCodec>
117 #include <QTranslator>
118 #include <QThreadPool>
122 #include <X11/Xatom.h>
123 #include <X11/Xlib.h>
127 #elif defined(QPA_XCB)
129 #ifdef HAVE_QT5_X11_EXTRAS
130 #include <QtX11Extras/QX11Info>
134 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
135 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
136 #if (QT_VERSION < 0x050000)
137 #include <QWindowsMime>
138 #define QWINDOWSMIME QWindowsMime
141 #define QWINDOWSMIME QWinMime
151 #include <QMacPasteboardMime>
154 #include <boost/crc.hpp>
161 using namespace lyx::support;
164 static void initializeResources()
166 static bool initialized = false;
168 Q_INIT_RESOURCE(Resources);
176 frontend::Application * createApplication(int & argc, char * argv[])
178 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
179 // prune -geometry argument(s) by shifting
180 // the following ones 2 places down.
181 for (int i = 0 ; i < argc ; ++i) {
182 if (strcmp(argv[i], "-geometry") == 0) {
183 int const remove = (i+1) < argc ? 2 : 1;
185 for (int j = i; j < argc; ++j)
186 argv[j] = argv[j + remove];
191 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
192 // I'd rather do that in the constructor, but I do not think that
193 // the palette is accessible there.
194 guiApp->colorCache().setPalette(guiApp->palette());
203 if (lyxrc.gui_language == "auto") {
204 theLocale = QLocale::system();
205 code = fromqstr(theLocale.name());
207 Language const * l = languages.getLanguage(lyxrc.gui_language);
208 code = l ? l->code() : "C";
209 theLocale = QLocale(toqstr(code));
211 // Qt tries to outsmart us and transforms en_US to C.
212 Messages::guiLanguage((code == "C") ? "en_US" : code);
213 QLocale::setDefault(theLocale);
214 setlocale(LC_NUMERIC, "C");
221 /// Return the list of loadable formats.
222 vector<string> loadableImageFormats()
226 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
228 LYXERR(Debug::GRAPHICS,
229 "\nThe image loader can load the following directly:\n");
231 if (qt_formats.empty())
232 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
234 bool jpeg_found = false;
235 bool jpg_found = false;
236 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
238 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
240 string ext = ascii_lowercase((const char *) *it);
248 else if (ext == "jpg") {
253 else if (lyxrc.use_converter_cache &&
254 (ext == "svg" || ext == "svgz") &&
255 theConverters().isReachable("svg", "png"))
256 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
257 // the SVG as in the output. However we require that the converter
258 // cache is enabled since this is expensive. We also require that
259 // an explicit svg->png converter is defined, since the default
260 // converter could produce bad quality as well. This assumes that
261 // png can always be loaded.
270 ////////////////////////////////////////////////////////////////////////
272 // Icon loading support code
274 ////////////////////////////////////////////////////////////////////////
284 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
286 return lhs.key < rhs.key;
292 CompareKey(QString const & name) : name_(name) {}
293 bool operator()(ImgMap const & other) const { return other.key == name_; }
299 // this must be sorted alphabetically
300 // Upper case comes before lower case
301 // Please don't change the formatting, this list is parsed by
302 // development/tools/generate_symbols_images.py.
303 ImgMap sorted_img_map[] = {
304 { "Arrownot", "arrownot2"},
305 { "Arrowvert", "arrowvert2"},
306 { "Bowtie", "bowtie2" },
308 { "Bumpeq", "bumpeq2" },
309 { "CIRCLE", "circle3" },
311 { "CheckedBox", "checkedbox2" },
312 { "Circle", "circle2" },
313 { "Colonapprox", "colonapprox2" },
314 { "Coloneq", "coloneq2" },
315 { "Coloneqq", "coloneqq2" },
316 { "Colonsim", "colonsim2" },
318 { "DOWNarrow", "downarrow3" },
319 { "Delta", "delta2" },
320 { "Diamond", "diamond2" },
321 { "Doteq", "doteq2" },
322 { "Downarrow", "downarrow2" },
323 { "Eqcolon", "eqcolon2" },
324 { "Eqqcolon", "eqqcolon2" },
325 { "Gamma", "gamma2" },
327 { "LEFTCIRCLE", "leftcircle3" },
328 { "LEFTarrow", "leftarrow3" },
329 { "LEFTcircle", "leftcircle4" },
331 { "Lambda", "lambda2" },
333 { "Leftarrow", "leftarrow2" },
334 { "Leftcircle", "leftcircle2" },
335 { "Leftrightarrow", "leftrightarrow2" },
336 { "Longarrownot", "longarrownot2"},
337 { "Longleftarrow", "longleftarrow2" },
338 { "Longleftrightarrow", "longleftrightarrow2" },
339 { "Longmapsfrom", "longmapsfrom2"},
340 { "Longmapsto", "longmapsto2"},
341 { "Longrightarrow", "longrightarrow2" },
342 { "Mapsfrom", "mapsfrom2"},
343 { "Mapsfromchar", "mapsfromchar2"},
344 { "Mapsto", "mapsto2"},
345 { "Mapstochar", "mapstochar2"},
346 { "Omega", "omega2" },
351 { "RIGHTCIRCLE", "rightcircle3" },
352 { "RIGHTarrow", "rightarrow3" },
353 { "RIGHTcircle", "rightcircle4" },
355 { "Rightarrow", "rightarrow2" },
356 { "Rightcircle", "rightcircle2" },
357 { "Sigma", "sigma2" },
358 { "Square", "square2" },
359 { "Subset", "subset2" },
360 { "Supset", "supset2" },
361 { "Theta", "theta2" },
362 { "Thorn", "thorn2" },
363 { "UParrow", "uparrow3" },
364 { "Uparrow", "uparrow2" },
365 { "Updownarrow", "updownarrow2" },
366 { "Upsilon", "upsilon2" },
367 { "Vdash", "vdash3" },
372 { "lVert", "vert2" },
374 { "nLeftarrow", "nleftarrow2" },
375 { "nLeftrightarrow", "nleftrightarrow2" },
376 { "nRightarrow", "nrightarrow2" },
377 { "nVDash", "nvdash3" },
378 { "nVdash", "nvdash4" },
379 { "nvDash", "nvdash2" },
380 { "rVert", "vert2" },
382 { "textrm \\AA", "textrm_AA"},
383 { "textrm \\O", "textrm_O"},
384 { "vDash", "vdash2" },
385 { "varDelta", "vardelta2" },
386 { "varGamma", "vargamma2" },
387 { "varLambda", "varlambda2" },
388 { "varOmega", "varomega2" },
389 { "varPhi", "varphi2" },
390 { "varPi", "varpi2" },
391 { "varPsi", "varpsi2" },
392 { "varSigma", "varsigma2" },
393 { "varTheta", "vartheta2" },
394 { "varUpsilon", "varupsilon2" },
395 { "varXi", "varxi2" }
399 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
401 // This list specifies which system's theme icon is related to which lyx
402 // command. It was based on:
403 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
404 // this must be sorted alphabetically
405 // Upper case comes before lower case
406 ImgMap sorted_theme_icon_map[] = {
407 { "bookmark-goto 0", "go-jump" },
408 { "buffer-new", "document-new" },
409 { "buffer-write", "document-save" },
410 { "buffer-write-as", "document-save-as" },
411 { "buffer-zoom-in", "zoom-in" },
412 { "buffer-zoom-out", "zoom-out" },
413 { "copy", "edit-copy" },
414 { "cut", "edit-cut" },
415 { "depth-decrement", "format-indent-less" },
416 { "depth-increment", "format-indent-more" },
417 { "dialog-show spellchecker", "tools-check-spelling" },
418 { "dialog-show-new-inset graphics", "insert-image" },
419 { "dialog-toggle findreplaceadv", "edit-find-replace" },
420 { "file-open", "document-open" },
421 { "font-bold", "format-text-bold" },
422 { "font-ital", "format-text-italic" },
423 { "font-strikeout", "format-text-strikethrough" },
424 { "font-underline", "format-text-underline" },
425 { "lyx-quit", "application-exit" },
426 { "paste", "edit-paste" },
427 { "redo", "edit-redo" },
428 { "undo", "edit-undo" },
429 { "window-close", "window-close" },
430 { "window-new", "window-new" }
433 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
436 QString findImg(QString const & name)
438 ImgMap const * const begin = sorted_img_map;
439 ImgMap const * const end = begin + nr_sorted_img_map;
440 LATTEST(sorted(begin, end));
442 ImgMap const * const it = find_if(begin, end, CompareKey(name));
446 img_name = it->value;
449 img_name.replace('_', "underscore");
450 img_name.replace(' ', '_');
452 // This way we can have "math-delim { }" on the toolbar.
453 img_name.replace('(', "lparen");
454 img_name.replace(')', "rparen");
455 img_name.replace('[', "lbracket");
456 img_name.replace(']', "rbracket");
457 img_name.replace('{', "lbrace");
458 img_name.replace('}', "rbrace");
459 img_name.replace('|', "bars");
460 img_name.replace(',', "thinspace");
461 img_name.replace(':', "mediumspace");
462 img_name.replace(';', "thickspace");
463 img_name.replace('!', "negthinspace");
466 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
467 << "Looking for math icon called \"" << img_name << '"');
474 QString themeIconName(QString const & action)
476 ImgMap const * const begin = sorted_theme_icon_map;
477 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
478 LASSERT(sorted(begin, end), /**/);
480 ImgMap const * const it = find_if(begin, end, CompareKey(action));
488 QString iconName(FuncRequest const & f, bool unknown)
490 initializeResources();
494 switch (f.action()) {
495 case LFUN_MATH_INSERT:
496 if (!f.argument().empty()) {
498 name1 = findImg(toqstr(f.argument()).mid(1));
501 case LFUN_MATH_DELIM:
502 case LFUN_MATH_BIGDELIM:
504 name1 = findImg(toqstr(f.argument()));
508 name1 = toqstr(f.argument());
510 case LFUN_COMMAND_ALTERNATIVES: {
511 // use the first of the alternative commands
513 docstring dummy = split(f.argument(), firstcom, ';');
514 name1 = toqstr(firstcom);
515 name1.replace(' ', '_');
519 name2 = toqstr(lyxaction.getActionName(f.action()));
522 if (!f.argument().empty()) {
523 name1 = name2 + ' ' + toqstr(f.argument());
524 name1.replace(' ', '_');
525 name1.replace('\\', "backslash");
529 QStringList imagedirs;
530 imagedirs << "images/" << "images/ipa/";
531 search_mode mode = theGuiApp()->imageSearchMode();
532 for (int i = 0; i < imagedirs.size(); ++i) {
533 QString imagedir = imagedirs.at(i) + path;
534 FileName fname = imageLibFileSearch(imagedir, name1, "svgz,png", mode);
536 return toqstr(fname.absFileName());
538 fname = imageLibFileSearch(imagedir, name2, "svgz,png", mode);
540 return toqstr(fname.absFileName());
543 path = ":/images/" + path;
546 LYXERR0("Directory " << path << " not found in resource!");
549 if (res.exists(name1 + ".svgz"))
550 return path + name1 + ".svgz";
551 else if (res.exists(name1 + ".png"))
552 return path + name1 + ".png";
554 if (res.exists(name2 + ".svgz"))
555 return path + name2 + ".svgz";
556 else if (res.exists(name2 + ".png"))
557 return path + name2 + ".png";
559 LYXERR(Debug::GUI, "Cannot find icon with filename "
560 << "\"" << name1 << ".{svgz,png}\""
562 << "\"" << name2 << ".{svgz,png}\""
564 << lyxaction.getActionName(f.action())
565 << '(' << to_utf8(f.argument()) << ")\"");
568 QString imagedir = "images/";
569 FileName fname = imageLibFileSearch(imagedir, "unknown", "svgz,png", mode);
571 return toqstr(fname.absFileName());
572 return QString(":/images/unknown.svgz");
579 bool getPixmap(QPixmap & pixmap, QString const & path)
581 return pixmap.load(path);
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 // use the icons from system theme that are available
618 QString action = toqstr(lyxaction.getActionName(f.action()));
619 if (!f.argument().empty())
620 action += " " + toqstr(f.argument());
621 QString const theme_icon = themeIconName(action);
622 if (QIcon::hasThemeIcon(theme_icon)) {
623 QIcon const thmicn = QIcon::fromTheme(theme_icon);
624 if (!thmicn.isNull())
630 QString icon = iconName(f, unknown);
634 //LYXERR(Debug::GUI, "Found icon: " << icon);
635 QPixmap pixmap = QPixmap();
636 if (!getPixmap(pixmap,icon)) {
637 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
641 return QIcon(pixmap);
645 ////////////////////////////////////////////////////////////////////////
647 // LyX server support code.
649 ////////////////////////////////////////////////////////////////////////
651 class SocketNotifier : public QSocketNotifier
654 /// connect a connection notification from the LyXServerSocket
655 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
656 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
660 /// The callback function
661 Application::SocketCallback func_;
665 ////////////////////////////////////////////////////////////////////////
667 // Mac specific stuff goes here...
669 ////////////////////////////////////////////////////////////////////////
671 class MenuTranslator : public QTranslator
674 MenuTranslator(QObject * parent)
675 : QTranslator(parent)
678 #if QT_VERSION >= 0x050000
679 virtual QString translate(const char * /* context */,
680 const char *sourceText,
681 const char * /* disambiguation */ = 0, int /* n */ = -1) const
683 QString translate(const char * /*context*/,
684 const char * sourceText,
685 const char * /*comment*/ = 0) const
688 string const s = sourceText;
689 if (s == N_("About %1") || s == N_("Preferences")
690 || s == N_("Reconfigure") || s == N_("Quit %1"))
698 // QMacPasteboardMimeGraphics can only be compiled on Mac.
700 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
703 QMacPasteboardMimeGraphics()
704 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
707 QString convertorName() { return "Graphics"; }
709 QString flavorFor(QString const & mime)
711 LYXERR(Debug::ACTION, "flavorFor " << mime);
712 if (mime == pdfMimeType())
713 return QLatin1String("com.adobe.pdf");
717 QString mimeFor(QString flav)
719 LYXERR(Debug::ACTION, "mimeFor " << flav);
720 if (flav == QLatin1String("com.adobe.pdf"))
721 return pdfMimeType();
725 bool canConvert(QString const & mime, QString flav)
727 return mimeFor(flav) == mime;
730 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
734 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
738 QList<QByteArray> convertFromMime(QString const & /*mime*/,
739 QVariant data, QString /*flav*/)
741 QList<QByteArray> ret;
742 ret.append(data.toByteArray());
748 ///////////////////////////////////////////////////////////////
750 // You can find more platform specific stuff at the end of this file...
752 ///////////////////////////////////////////////////////////////
754 ////////////////////////////////////////////////////////////////////////
755 // Windows specific stuff goes here...
757 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
758 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
759 // QWindowsMimeMetafile can only be compiled on Windows.
761 static FORMATETC cfFromMime(QString const & mimetype)
764 if (mimetype == emfMimeType()) {
765 formatetc.cfFormat = CF_ENHMETAFILE;
766 formatetc.tymed = TYMED_ENHMF;
767 } else if (mimetype == wmfMimeType()) {
768 formatetc.cfFormat = CF_METAFILEPICT;
769 formatetc.tymed = TYMED_MFPICT;
772 formatetc.dwAspect = DVASPECT_CONTENT;
773 formatetc.lindex = -1;
778 class QWindowsMimeMetafile : public QWINDOWSMIME {
780 QWindowsMimeMetafile() {}
782 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
783 QMimeData const * /*mimedata*/) const
788 bool canConvertToMime(QString const & mimetype,
789 IDataObject * pDataObj) const
791 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
793 FORMATETC formatetc = cfFromMime(mimetype);
794 return pDataObj->QueryGetData(&formatetc) == S_OK;
797 bool convertFromMime(FORMATETC const & /*formatetc*/,
798 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const
803 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
804 QVariant::Type /*preferredType*/) const
807 if (!canConvertToMime(mimetype, pDataObj))
810 FORMATETC formatetc = cfFromMime(mimetype);
812 if (pDataObj->GetData(&formatetc, &s) != S_OK)
816 if (s.tymed == TYMED_ENHMF) {
817 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
818 data.resize(dataSize);
819 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
820 (LPBYTE)data.data());
821 } else if (s.tymed == TYMED_MFPICT) {
822 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
823 data.resize(dataSize);
824 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
825 (LPBYTE)data.data());
828 ReleaseStgMedium(&s);
834 QVector<FORMATETC> formatsForMime(QString const & mimetype,
835 QMimeData const * /*mimedata*/) const
837 QVector<FORMATETC> formats;
838 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
839 formats += cfFromMime(mimetype);
843 QString mimeForFormat(FORMATETC const & formatetc) const
845 switch (formatetc.cfFormat) {
847 return emfMimeType();
848 case CF_METAFILEPICT:
849 return wmfMimeType();
859 /// Allows to check whether ESC was pressed during a long operation
860 class KeyChecker : public QObject {
865 KeyChecker() : pressed_(false), started_(false) {}
868 QCoreApplication::instance()->installEventFilter(this);
873 QCoreApplication::instance()->removeEventFilter(this);
877 QCoreApplication::processEvents();
880 bool started() const {
883 bool eventFilter(QObject *obj, QEvent *event) {
884 LYXERR(Debug::ACTION, "Event Type: " << event->type());
885 switch (event->type()) {
889 case QEvent::UpdateRequest:
890 case QEvent::CursorChange:
891 case QEvent::ActionChanged:
892 case QEvent::EnabledChange:
893 case QEvent::SockAct:
896 case QEvent::ToolTipChange:
897 case QEvent::LayoutRequest:
898 case QEvent::MetaCall:
899 return QObject::eventFilter(obj, event);
901 // FIXME Blocking all these events is a bad idea.
902 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
903 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
911 ////////////////////////////////////////////////////////////////////////
912 // GuiApplication::Private definition and implementation.
913 ////////////////////////////////////////////////////////////////////////
915 struct GuiApplication::Private
917 Private(): language_model_(0), meta_fake_bit(NoModifier),
920 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
921 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
922 /// WMF Mime handler for Windows clipboard.
923 wmf_mime_ = new QWindowsMimeMetafile;
926 initKeySequences(&theTopLevelKeymap());
929 void initKeySequences(KeyMap * kb)
931 keyseq = KeySequence(kb, kb);
932 cancel_meta_seq = KeySequence(kb, kb);
936 QSortFilterProxyModel * language_model_;
938 GuiClipboard clipboard_;
940 GuiSelection selection_;
942 FontLoader font_loader_;
944 ColorCache color_cache_;
946 QTranslator qt_trans_;
948 QHash<int, SocketNotifier *> socket_notifiers_;
952 /// The global instance
955 /// this timer is used for any regular events one wants to
956 /// perform. at present it is used to check if forked processes
958 QTimer general_timer_;
960 /// delayed FuncRequests
961 std::queue<FuncRequest> func_request_queue_;
966 KeySequence cancel_meta_seq;
968 KeyModifier meta_fake_bit;
970 /// The result of last dispatch action
971 DispatchResult dispatch_result_;
973 /// Multiple views container.
975 * Warning: This must not be a smart pointer as the destruction of the
976 * object is handled by Qt when the view is closed
977 * \sa Qt::WA_DeleteOnClose attribute.
979 QHash<int, GuiView *> views_;
981 /// Only used on mac.
982 QMenuBar * global_menubar_;
985 /// Linkback mime handler for MacOSX.
986 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
989 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
990 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
991 /// WMF Mime handler for Windows clipboard.
992 QWindowsMimeMetafile * wmf_mime_;
996 /// Allows to check whether ESC was pressed during a long operation
997 KeyChecker key_checker_;
1001 GuiApplication * guiApp;
1003 GuiApplication::~GuiApplication()
1006 closeAllLinkBackLinks();
1012 GuiApplication::GuiApplication(int & argc, char ** argv)
1013 : QApplication(argc, argv), current_view_(0),
1014 d(new GuiApplication::Private)
1016 QString app_name = "LyX";
1017 QCoreApplication::setOrganizationName(app_name);
1018 QCoreApplication::setOrganizationDomain("lyx.org");
1019 QCoreApplication::setApplicationName(lyx_package);
1020 #if QT_VERSION >= 0x050000
1021 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1024 qsrand(QDateTime::currentDateTime().toTime_t());
1026 // Install translator for GUI elements.
1027 installTranslator(&d->qt_trans_);
1030 // Enable reception of XCB events.
1031 installNativeEventFilter(this);
1034 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1035 // lyxrc setting for this in order to let the application stay resident.
1036 // But then we need some kind of dock icon, at least on Windows.
1038 if (lyxrc.quit_on_last_window_closed)
1039 setQuitOnLastWindowClosed(false);
1042 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1043 // seems to be the default case for applications like LyX.
1044 setQuitOnLastWindowClosed(false);
1045 // This allows to translate the strings that appear in the LyX menu.
1046 /// A translator suitable for the entries in the LyX menu.
1047 /// Only needed with Qt/Mac.
1048 installTranslator(new MenuTranslator(this));
1053 #if defined(Q_WS_X11) || defined(QPA_XCB)
1054 // doubleClickInterval() is 400 ms on X11 which is just too long.
1055 // On Windows and Mac OS X, the operating system's value is used.
1056 // On Microsoft Windows, calling this function sets the double
1057 // click interval for all applications. So we don't!
1058 QApplication::setDoubleClickInterval(300);
1061 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1063 // needs to be done before reading lyxrc
1065 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1069 // Set the cache to 5120 kilobytes which corresponds to screen size of
1070 // 1280 by 1024 pixels with a color depth of 32 bits.
1071 QPixmapCache::setCacheLimit(5120);
1073 // Initialize RC Fonts
1074 if (lyxrc.roman_font_name.empty())
1075 lyxrc.roman_font_name = fromqstr(romanFontName());
1077 if (lyxrc.sans_font_name.empty())
1078 lyxrc.sans_font_name = fromqstr(sansFontName());
1080 if (lyxrc.typewriter_font_name.empty())
1081 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1083 d->general_timer_.setInterval(500);
1084 connect(&d->general_timer_, SIGNAL(timeout()),
1085 this, SLOT(handleRegularEvents()));
1086 d->general_timer_.start();
1088 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1089 // This is clearly not enough in a time where we use threads for
1090 // document preview and/or export. 20 should be OK.
1091 QThreadPool::globalInstance()->setMaxThreadCount(20);
1093 // make sure tooltips are formatted
1094 installEventFilter(new ToolTipFormatter(this));
1098 GuiApplication * theGuiApp()
1100 return dynamic_cast<GuiApplication *>(theApp());
1104 double GuiApplication::pixelRatio() const
1106 #if QT_VERSION >= 0x050000
1107 return qt_scale_factor * devicePixelRatio();
1114 void GuiApplication::clearSession()
1121 docstring Application::iconName(FuncRequest const & f, bool unknown)
1123 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1127 docstring Application::mathIcon(docstring const & c)
1129 return qstring_to_ucs4(findImg(toqstr(c)));
1133 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1137 BufferView * bv = 0;
1138 BufferView * doc_bv = 0;
1140 if (cmd.action() == LFUN_NOACTION) {
1141 status.message(from_utf8(N_("Nothing to do")));
1142 status.setEnabled(false);
1145 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1146 status.setUnknown(true);
1147 status.message(from_utf8(N_("Unknown action")));
1148 status.setEnabled(false);
1151 // Does the GuiApplication know something?
1152 else if (getStatus(cmd, status)) { }
1154 // If we do not have a GuiView, then other functions are disabled
1155 else if (!current_view_)
1156 status.setEnabled(false);
1158 // Does the GuiView know something?
1159 else if (current_view_->getStatus(cmd, status)) { }
1161 // In LyX/Mac, when a dialog is open, the menus of the
1162 // application can still be accessed without giving focus to
1163 // the main window. In this case, we want to disable the menu
1164 // entries that are buffer or view-related.
1165 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1167 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1168 status.setEnabled(false);
1171 // If we do not have a BufferView, then other functions are disabled
1172 else if (!(bv = current_view_->currentBufferView()))
1173 status.setEnabled(false);
1175 // Does the current BufferView know something?
1176 else if (bv->getStatus(cmd, status)) { }
1178 // Does the current Buffer know something?
1179 else if (bv->buffer().getStatus(cmd, status)) { }
1181 // If we do not have a document BufferView, different from the
1182 // current BufferView, then other functions are disabled
1183 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1184 status.setEnabled(false);
1186 // Does the document Buffer know something?
1187 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1190 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1191 status.message(from_utf8(N_("Command not handled")));
1192 status.setEnabled(false);
1195 // the default error message if we disable the command
1196 if (!status.enabled() && status.message().empty())
1197 status.message(from_utf8(N_("Command disabled")));
1203 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1205 // I would really like to avoid having this switch and rather try to
1206 // encode this in the function itself.
1207 // -- And I'd rather let an inset decide which LFUNs it is willing
1208 // to handle (Andre')
1210 switch (cmd.action()) {
1212 // This could be used for the no-GUI version. The GUI version is handled in
1213 // GuiView::getStatus(). See above.
1215 case LFUN_BUFFER_WRITE:
1216 case LFUN_BUFFER_WRITE_AS: {
1217 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1218 enable = b && (b->isUnnamed() || !b->isClean());
1223 case LFUN_BOOKMARK_GOTO: {
1224 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1225 enable = theSession().bookmarks().isValid(num);
1229 case LFUN_BOOKMARK_CLEAR:
1230 enable = theSession().bookmarks().hasValid();
1233 // this one is difficult to get right. As a half-baked
1234 // solution, we consider only the first action of the sequence
1235 case LFUN_COMMAND_SEQUENCE: {
1236 // argument contains ';'-terminated commands
1237 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1238 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1239 func.setOrigin(cmd.origin());
1240 flag = getStatus(func);
1244 // we want to check if at least one of these is enabled
1245 case LFUN_COMMAND_ALTERNATIVES: {
1246 // argument contains ';'-terminated commands
1247 string arg = to_utf8(cmd.argument());
1248 while (!arg.empty()) {
1250 arg = split(arg, first, ';');
1251 FuncRequest func(lyxaction.lookupFunc(first));
1252 func.setOrigin(cmd.origin());
1253 flag = getStatus(func);
1254 // if this one is enabled, the whole thing is
1263 string name = to_utf8(cmd.argument());
1264 if (theTopLevelCmdDef().lock(name, func)) {
1265 func.setOrigin(cmd.origin());
1266 flag = getStatus(func);
1267 theTopLevelCmdDef().release(name);
1269 // catch recursion or unknown command
1270 // definition. all operations until the
1271 // recursion or unknown command definition
1272 // occurs are performed, so set the state to
1279 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1281 case LFUN_PREFERENCES_SAVE:
1282 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1283 case LFUN_DEBUG_LEVEL_SET:
1284 // these are handled in our dispatch()
1287 case LFUN_WINDOW_CLOSE:
1288 enable = d->views_.size() > 0;
1291 case LFUN_BUFFER_NEW:
1292 case LFUN_BUFFER_NEW_TEMPLATE:
1293 case LFUN_FILE_OPEN:
1294 case LFUN_HELP_OPEN:
1295 case LFUN_SCREEN_FONT_UPDATE:
1296 case LFUN_SET_COLOR:
1297 case LFUN_WINDOW_NEW:
1299 case LFUN_LYXRC_APPLY:
1300 case LFUN_COMMAND_PREFIX:
1302 case LFUN_META_PREFIX:
1303 case LFUN_RECONFIGURE:
1304 case LFUN_SERVER_GET_FILENAME:
1305 case LFUN_SERVER_NOTIFY:
1309 case LFUN_BUFFER_FORALL: {
1310 if (theBufferList().empty()) {
1311 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1312 flag.setEnabled(false);
1316 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1317 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1318 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1319 flag.setEnabled(false);
1324 case LFUN_DIALOG_SHOW: {
1325 string const name = cmd.getArg(0);
1326 return name == "aboutlyx"
1328 || name == "texinfo"
1329 || name == "progress"
1330 || name == "compare";
1338 flag.setEnabled(false);
1342 /// make a post-dispatch status message
1343 static docstring makeDispatchMessage(docstring const & msg,
1344 FuncRequest const & cmd)
1346 const bool verbose = (cmd.origin() == FuncRequest::MENU
1347 || cmd.origin() == FuncRequest::TOOLBAR
1348 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1350 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1351 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1355 docstring dispatch_msg = msg;
1356 if (!dispatch_msg.empty())
1357 dispatch_msg += ' ';
1359 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1361 bool argsadded = false;
1363 if (!cmd.argument().empty()) {
1364 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1365 comname += ' ' + cmd.argument();
1369 docstring const shortcuts = theTopLevelKeymap().
1370 printBindings(cmd, KeySequence::ForGui);
1372 if (!shortcuts.empty())
1373 comname += ": " + shortcuts;
1374 else if (!argsadded && !cmd.argument().empty())
1375 comname += ' ' + cmd.argument();
1377 if (!comname.empty()) {
1378 comname = rtrim(comname);
1379 dispatch_msg += '(' + rtrim(comname) + ')';
1381 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1382 return dispatch_msg;
1386 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1388 Buffer * buffer = 0;
1389 if (current_view_ && current_view_->currentBufferView()) {
1390 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1391 buffer = ¤t_view_->currentBufferView()->buffer();
1393 buffer->undo().beginUndoGroup();
1397 // redraw the screen at the end (first of the two drawing steps).
1398 // This is done unless explicitly requested otherwise
1399 dr.screenUpdate(Update::FitCursor);
1401 updateCurrentView(cmd, dr);
1403 // the buffer may have been closed by one action
1404 if (theBufferList().isLoaded(buffer))
1405 buffer->undo().endUndoGroup();
1407 d->dispatch_result_ = dr;
1408 return d->dispatch_result_;
1412 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1417 BufferView * bv = current_view_->currentBufferView();
1419 if (dr.needBufferUpdate()) {
1420 bv->cursor().clearBufferUpdate();
1421 bv->buffer().updateBuffer();
1422 } else if (dr.needChangesUpdate()) {
1423 // updateBuffer() already updates the change-tracking presence flag
1424 bv->buffer().updateChangesPresent();
1426 // BufferView::update() updates the ViewMetricsInfo and
1427 // also initializes the position cache for all insets in
1428 // (at least partially) visible top-level paragraphs.
1429 // We will redraw the screen only if needed.
1430 bv->processUpdateFlags(dr.screenUpdate());
1432 // Do we have a selection?
1433 theSelection().haveSelection(bv->cursor().selection());
1436 current_view_->restartCursor();
1438 if (dr.needMessageUpdate()) {
1439 // Some messages may already be translated, so we cannot use _()
1440 current_view_->message(makeDispatchMessage(
1441 translateIfPossible(dr.message()), cmd));
1446 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1447 bool switchToBuffer)
1449 if (!theSession().bookmarks().isValid(idx))
1451 BookmarksSection::Bookmark const & bm =
1452 theSession().bookmarks().bookmark(idx);
1453 LASSERT(!bm.filename.empty(), return);
1454 string const file = bm.filename.absFileName();
1455 // if the file is not opened, open it.
1456 if (!theBufferList().exists(bm.filename)) {
1458 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1462 // open may fail, so we need to test it again
1463 if (!theBufferList().exists(bm.filename))
1466 // bm can be changed when saving
1467 BookmarksSection::Bookmark tmp = bm;
1469 // Special case idx == 0 used for back-from-back jump navigation
1471 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1473 // if the current buffer is not that one, switch to it.
1474 BufferView * doc_bv = current_view_ ?
1475 current_view_->documentBufferView() : 0;
1476 Cursor const * old = doc_bv ? &doc_bv->cursor() : 0;
1477 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1478 if (switchToBuffer) {
1479 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1482 doc_bv = current_view_->documentBufferView();
1487 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1488 if (!doc_bv || !doc_bv->moveToPosition(
1489 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1492 Cursor & cur = doc_bv->cursor();
1493 if (old && cur != *old)
1494 notifyCursorLeavesOrEnters(*old, cur);
1500 // Cursor jump succeeded!
1501 pit_type new_pit = cur.pit();
1502 pos_type new_pos = cur.pos();
1503 int new_id = cur.paragraph().id();
1505 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1506 // see http://www.lyx.org/trac/ticket/3092
1507 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1508 || bm.top_id != new_id) {
1509 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1510 new_pit, new_pos, new_id);
1514 // This function runs "configure" and then rereads lyx.defaults to
1515 // reconfigure the automatic settings.
1516 void GuiApplication::reconfigure(string const & option)
1518 // emit message signal.
1520 current_view_->message(_("Running configure..."));
1522 // Run configure in user lyx directory
1523 string const lock_file = package().getConfigureLockName();
1524 int fd = fileLock(lock_file.c_str());
1525 int const ret = package().reconfigureUserLyXDir(option);
1526 // emit message signal.
1528 current_view_->message(_("Reloading configuration..."));
1529 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1530 // Re-read packages.lst
1531 LaTeXPackages::getAvailable();
1532 fileUnlock(fd, lock_file.c_str());
1535 Alert::information(_("System reconfiguration failed"),
1536 _("The system reconfiguration has failed.\n"
1537 "Default textclass is used but LyX may\n"
1538 "not be able to work properly.\n"
1539 "Please reconfigure again if needed."));
1541 Alert::information(_("System reconfigured"),
1542 _("The system has been reconfigured.\n"
1543 "You need to restart LyX to make use of any\n"
1544 "updated document class specifications."));
1547 void GuiApplication::validateCurrentView()
1549 if (!d->views_.empty() && !current_view_) {
1550 // currently at least one view exists but no view has the focus.
1551 // choose the last view to make it current.
1552 // a view without any open document is preferred.
1553 GuiView * candidate = 0;
1554 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1555 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1556 for (; it != end; ++it) {
1558 if (!candidate->documentBufferView())
1561 setCurrentView(candidate);
1565 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1567 string const argument = to_utf8(cmd.argument());
1568 FuncCode const action = cmd.action();
1570 LYXERR(Debug::ACTION, "cmd: " << cmd);
1572 // we have not done anything wrong yet.
1575 FuncStatus const flag = getStatus(cmd);
1576 if (!flag.enabled()) {
1577 // We cannot use this function here
1578 LYXERR(Debug::ACTION, "action "
1579 << lyxaction.getActionName(action)
1580 << " [" << action << "] is disabled at this location");
1581 dr.setMessage(flag.message());
1583 dr.dispatched(false);
1584 dr.screenUpdate(Update::None);
1585 dr.clearBufferUpdate();
1589 if (cmd.origin() == FuncRequest::LYXSERVER) {
1590 if (current_view_ && current_view_->currentBufferView())
1591 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1592 // we will also need to redraw the screen at the end
1593 dr.screenUpdate(Update::FitCursor);
1596 // Assumes that the action will be dispatched.
1597 dr.dispatched(true);
1599 switch (cmd.action()) {
1601 case LFUN_WINDOW_NEW:
1602 createView(toqstr(cmd.argument()));
1605 case LFUN_WINDOW_CLOSE:
1606 // update bookmark pit of the current buffer before window close
1607 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1608 gotoBookmark(i+1, false, false);
1609 // clear the last opened list, because
1610 // maybe this will end the session
1611 theSession().lastOpened().clear();
1612 // check for valid current_view_
1613 validateCurrentView();
1615 current_view_->closeScheduled();
1619 // quitting is triggered by the gui code
1620 // (leaving the event loop).
1622 current_view_->message(from_utf8(N_("Exiting.")));
1623 if (closeAllViews())
1627 case LFUN_SCREEN_FONT_UPDATE: {
1628 // handle the screen font changes.
1629 d->font_loader_.update();
1630 // Backup current_view_
1631 GuiView * view = current_view_;
1632 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1633 // to skip the refresh.
1635 theBufferList().changed(false);
1636 // Restore current_view_
1637 current_view_ = view;
1641 case LFUN_BUFFER_NEW:
1642 validateCurrentView();
1643 if (d->views_.empty()
1644 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1645 createView(QString(), false); // keep hidden
1646 current_view_->newDocument(to_utf8(cmd.argument()), false);
1647 current_view_->show();
1648 setActiveWindow(current_view_);
1650 current_view_->newDocument(to_utf8(cmd.argument()), false);
1654 case LFUN_BUFFER_NEW_TEMPLATE:
1655 validateCurrentView();
1656 if (d->views_.empty()
1657 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1659 current_view_->newDocument(to_utf8(cmd.argument()), true);
1660 if (!current_view_->documentBufferView())
1661 current_view_->close();
1663 current_view_->newDocument(to_utf8(cmd.argument()), true);
1667 case LFUN_FILE_OPEN: {
1668 validateCurrentView();
1669 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1670 string const fname = to_utf8(cmd.argument());
1671 bool const is_open = FileName::isAbsolute(fname)
1672 && theBufferList().getBuffer(FileName(fname));
1673 if (d->views_.empty()
1674 || (!lyxrc.open_buffers_in_tabs
1675 && current_view_->documentBufferView() != 0
1677 // We want the ui session to be saved per document and not per
1678 // window number. The filename crc is a good enough identifier.
1679 boost::crc_32_type crc;
1680 crc = for_each(fname.begin(), fname.end(), crc);
1681 createView(crc.checksum());
1682 // we know current_view_ is non-null, because createView sets it.
1683 // but let's make sure
1684 LASSERT(current_view_, break);
1685 current_view_->openDocument(fname);
1686 if (!current_view_->documentBufferView())
1687 current_view_->close();
1688 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1689 current_view_->raise();
1690 current_view_->activateWindow();
1691 current_view_->showNormal();
1694 // we know !d->views.empty(), so this should be ok
1695 // but let's make sure
1696 LASSERT(current_view_, break);
1697 current_view_->openDocument(fname);
1698 if (cmd.origin() == FuncRequest::LYXSERVER) {
1699 current_view_->raise();
1700 current_view_->activateWindow();
1701 current_view_->showNormal();
1707 case LFUN_HELP_OPEN: {
1708 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1709 if (current_view_ == 0)
1711 string const arg = to_utf8(cmd.argument());
1713 current_view_->message(_("Missing argument"));
1716 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1718 fname = i18nLibFileSearch("examples", arg, "lyx");
1720 if (fname.empty()) {
1721 lyxerr << "LyX: unable to find documentation file `"
1722 << arg << "'. Bad installation?" << endl;
1725 current_view_->message(bformat(_("Opening help file %1$s..."),
1726 makeDisplayPath(fname.absFileName())));
1727 Buffer * buf = current_view_->loadDocument(fname, false);
1729 #ifndef DEVEL_VERSION
1731 buf->setReadonly(true);
1738 case LFUN_SET_COLOR: {
1740 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1741 if (lyx_name.empty() || x11_name.empty()) {
1743 current_view_->message(
1744 _("Syntax: set-color <lyx_name> <x11_name>"));
1749 // FIXME: The graphics cache no longer has a changeDisplay method.
1750 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1751 bool const graphicsbg_changed =
1752 lyx_name == graphicsbg && x11_name != graphicsbg;
1753 if (graphicsbg_changed)
1754 graphics::GCache::get().changeDisplay(true);
1757 if (!lcolor.setColor(lyx_name, x11_name)) {
1759 current_view_->message(
1760 bformat(_("Set-color \"%1$s\" failed "
1761 "- color is undefined or "
1762 "may not be redefined"),
1763 from_utf8(lyx_name)));
1766 // Make sure we don't keep old colors in cache.
1767 d->color_cache_.clear();
1768 // Update the current view
1769 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1773 case LFUN_LYXRC_APPLY: {
1774 // reset active key sequences, since the bindings
1775 // are updated (bug 6064)
1777 LyXRC const lyxrc_orig = lyxrc;
1779 istringstream ss(to_utf8(cmd.argument()));
1780 bool const success = lyxrc.read(ss);
1783 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1784 << "Unable to read lyxrc data"
1789 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1791 // If the request comes from the minibuffer, then we can't reset
1792 // the GUI, since that would destory the minibuffer itself and
1793 // cause a crash, since we are currently in one of the methods of
1794 // GuiCommandBuffer. See bug #8540.
1795 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1798 // FIXME Unfortunately, that leaves a bug here, since we cannot
1799 // reset the GUI in this case. If the changes to lyxrc affected the
1800 // UI, then, nothing would happen. This seems fairly unlikely, but
1801 // it definitely is a bug.
1806 case LFUN_COMMAND_PREFIX:
1807 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1812 d->meta_fake_bit = NoModifier;
1813 GuiView * gv = currentView();
1814 if (gv && gv->currentBufferView())
1815 // cancel any selection
1816 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1817 dr.setMessage(from_ascii(N_("Cancel")));
1820 case LFUN_META_PREFIX:
1821 d->meta_fake_bit = AltModifier;
1822 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1825 // --- Menus -----------------------------------------------
1826 case LFUN_RECONFIGURE:
1827 // argument is any additional parameter to the configure.py command
1828 reconfigure(to_utf8(cmd.argument()));
1831 // --- lyxserver commands ----------------------------
1832 case LFUN_SERVER_GET_FILENAME: {
1833 if (current_view_ && current_view_->documentBufferView()) {
1834 docstring const fname = from_utf8(
1835 current_view_->documentBufferView()->buffer().absFileName());
1836 dr.setMessage(fname);
1837 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1839 dr.setMessage(docstring());
1840 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1845 case LFUN_SERVER_NOTIFY: {
1846 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1847 dr.setMessage(dispatch_buffer);
1848 theServer().notifyClient(to_utf8(dispatch_buffer));
1852 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1853 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1859 string rest = split(argument, countstr, ' ');
1860 int const count = convert<int>(countstr);
1861 // an arbitrary number to limit number of iterations
1862 int const max_iter = 10000;
1863 if (count > max_iter) {
1864 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1867 for (int i = 0; i < count; ++i)
1868 dispatch(lyxaction.lookupFunc(rest));
1873 case LFUN_COMMAND_SEQUENCE: {
1874 // argument contains ';'-terminated commands
1875 string arg = argument;
1876 // FIXME: this LFUN should also work without any view.
1877 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1878 ? &(current_view_->documentBufferView()->buffer()) : 0;
1880 buffer->undo().beginUndoGroup();
1881 while (!arg.empty()) {
1883 arg = split(arg, first, ';');
1884 FuncRequest func(lyxaction.lookupFunc(first));
1885 func.setOrigin(cmd.origin());
1888 // the buffer may have been closed by one action
1889 if (theBufferList().isLoaded(buffer))
1890 buffer->undo().endUndoGroup();
1894 case LFUN_BUFFER_FORALL: {
1895 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1897 map<Buffer *, GuiView *> views_lVisible;
1898 map<GuiView *, Buffer *> activeBuffers;
1900 QList<GuiView *> allViews = d->views_.values();
1902 // this for does not modify any buffer. It just collects info on local
1903 // visibility of buffers and on which buffer is active in each view.
1904 Buffer * const last = theBufferList().last();
1905 for(GuiView * view : allViews) {
1906 // all of the buffers might be locally hidden. That is, there is no
1908 if (!view || !view->currentBufferView())
1909 activeBuffers[view] = 0;
1911 activeBuffers[view] = &view->currentBufferView()->buffer();
1913 // find out if each is locally visible or locally hidden.
1914 // we don't use a for loop as the buffer list cycles.
1915 Buffer * b = theBufferList().first();
1917 bool const locallyVisible = view && view->workArea(*b);
1918 if (locallyVisible) {
1919 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1920 // only need to overwrite/add if we don't already know a buffer is globally
1921 // visible or we do know but we would prefer to dispatch LFUN from the
1922 // current view because of cursor position issues.
1923 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1924 views_lVisible[b] = view;
1928 b = theBufferList().next(b);
1932 GuiView * const homeView = currentView();
1933 Buffer * b = theBufferList().first();
1934 Buffer * nextBuf = 0;
1935 int numProcessed = 0;
1938 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1940 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1942 // first change to a view where b is locally visible, preferably current_view_.
1943 GuiView * const vLv = views_lVisible[b];
1945 lyx::dispatch(funcToRun);
1953 // put things back to how they were (if possible).
1954 for (GuiView * view : allViews) {
1955 Buffer * originalBuf = activeBuffers[view];
1956 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1957 if (theBufferList().isLoaded(originalBuf))
1958 view->setBuffer(originalBuf);
1960 homeView->setFocus();
1962 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1966 case LFUN_COMMAND_ALTERNATIVES: {
1967 // argument contains ';'-terminated commands
1968 string arg = argument;
1969 while (!arg.empty()) {
1971 arg = split(arg, first, ';');
1972 FuncRequest func(lyxaction.lookupFunc(first));
1973 func.setOrigin(cmd.origin());
1974 FuncStatus const stat = getStatus(func);
1975 if (stat.enabled()) {
1985 if (theTopLevelCmdDef().lock(argument, func)) {
1986 func.setOrigin(cmd.origin());
1988 theTopLevelCmdDef().release(argument);
1990 if (func.action() == LFUN_UNKNOWN_ACTION) {
1991 // unknown command definition
1992 lyxerr << "Warning: unknown command definition `"
1996 // recursion detected
1997 lyxerr << "Warning: Recursion in the command definition `"
1998 << argument << "' detected"
2005 case LFUN_PREFERENCES_SAVE:
2006 lyxrc.write(support::makeAbsPath("preferences",
2007 package().user_support().absFileName()), false);
2010 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2011 string const fname = addName(addPath(package().user_support().absFileName(),
2012 "templates/"), "defaults.lyx");
2013 Buffer defaults(fname);
2015 istringstream ss(argument);
2020 // We need to make sure that, after we recreat the DocumentClass,
2021 // which we do in readHeader, we apply it to the document itself.
2022 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2023 int const unknown_tokens = defaults.readHeader(lex);
2024 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2026 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2027 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2029 if (unknown_tokens != 0) {
2030 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2031 << unknown_tokens << " unknown token"
2032 << (unknown_tokens == 1 ? "" : "s")
2036 if (defaults.writeFile(FileName(defaults.absFileName())))
2037 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2038 makeDisplayPath(fname)));
2041 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2046 case LFUN_BOOKMARK_GOTO:
2047 // go to bookmark, open unopened file and switch to buffer if necessary
2048 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2049 dr.screenUpdate(Update::Force | Update::FitCursor);
2052 case LFUN_BOOKMARK_CLEAR:
2053 theSession().bookmarks().clear();
2056 case LFUN_DEBUG_LEVEL_SET:
2057 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2060 case LFUN_DIALOG_SHOW: {
2061 string const name = cmd.getArg(0);
2063 if ( name == "aboutlyx"
2065 || name == "texinfo"
2066 || name == "progress"
2067 || name == "compare")
2069 // work around: on Mac OS the application
2070 // is not terminated when closing the last view.
2071 // Create a new one to be able to dispatch the
2072 // LFUN_DIALOG_SHOW to this view.
2073 if (current_view_ == 0)
2080 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2083 current_view_->dispatch(cmd, dr);
2087 if (cmd.origin() == FuncRequest::LYXSERVER)
2088 updateCurrentView(cmd, dr);
2092 docstring GuiApplication::viewStatusMessage()
2094 // When meta-fake key is pressed, show the key sequence so far + "M-".
2095 if (d->meta_fake_bit != NoModifier)
2096 return d->keyseq.print(KeySequence::ForGui) + "M-";
2098 // Else, when a non-complete key sequence is pressed,
2099 // show the available options.
2100 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2101 return d->keyseq.printOptions(true);
2107 void GuiApplication::handleKeyFunc(FuncCode action)
2111 if (d->keyseq.length())
2113 GuiView * gv = currentView();
2114 LASSERT(gv && gv->currentBufferView(), return);
2115 BufferView * bv = gv->currentBufferView();
2116 bv->getIntl().getTransManager().deadkey(
2117 c, get_accent(action).accent, bv->cursor().innerText(),
2119 // Need to clear, in case the minibuffer calls these
2122 // copied verbatim from do_accent_char
2123 bv->cursor().resetAnchor();
2127 //Keep this in sync with GuiApplication::processKeySym below
2128 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2129 KeyModifier state) const
2131 // Do nothing if we have nothing
2132 if (!keysym.isOK() || keysym.isModifier())
2134 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2136 FuncRequest func = seq.addkey(keysym, state);
2137 // When not cancel or meta-fake, do the normal lookup.
2138 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2140 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2142 // Maybe user can only reach the key via holding down shift.
2143 // Let's see. But only if shift is the only modifier
2144 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2145 // If addkey looked up a command and did not find further commands then
2146 // seq has been reset at this point
2147 func = seq.addkey(keysym, NoModifier);
2149 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2150 << seq.print(KeySequence::Portable) << ']');
2151 return func.action() != LFUN_UNKNOWN_ACTION;
2155 //Keep this in sync with GuiApplication::queryKeySym above
2156 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2158 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2160 // Do nothing if we have nothing (JMarc)
2161 if (!keysym.isOK() || keysym.isModifier()) {
2163 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2165 current_view_->restartCursor();
2169 char_type encoded_last_key = keysym.getUCSEncoded();
2171 // Do a one-deep top-level lookup for
2172 // cancel and meta-fake keys. RVDK_PATCH_5
2173 d->cancel_meta_seq.reset();
2175 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2176 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2178 // When not cancel or meta-fake, do the normal lookup.
2179 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2180 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2181 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2182 // remove Caps Lock and Mod2 as a modifiers
2183 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2184 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2187 // Dont remove this unless you know what you are doing.
2188 d->meta_fake_bit = NoModifier;
2190 // Can this happen now ?
2191 if (func.action() == LFUN_NOACTION)
2192 func = FuncRequest(LFUN_COMMAND_PREFIX);
2194 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2195 << d->keyseq.print(KeySequence::Portable) << ']');
2197 // already here we know if it any point in going further
2198 // why not return already here if action == -1 and
2199 // num_bytes == 0? (Lgb)
2201 if (d->keyseq.length() > 1 && current_view_)
2202 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2205 // Maybe user can only reach the key via holding down shift.
2206 // Let's see. But only if shift is the only modifier
2207 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2208 LYXERR(Debug::KEY, "Trying without shift");
2209 // If addkey looked up a command and did not find further commands then
2210 // seq has been reset at this point
2211 func = d->keyseq.addkey(keysym, NoModifier);
2212 LYXERR(Debug::KEY, "Action now " << func.action());
2215 if (func.action() == LFUN_UNKNOWN_ACTION) {
2216 // We didn't match any of the key sequences.
2217 // See if it's normal insertable text not already
2218 // covered by a binding
2219 if (keysym.isText() && d->keyseq.length() == 1) {
2220 // Non-printable characters (such as ASCII control characters)
2221 // must not be inserted (#5704)
2222 if (!isPrintable(encoded_last_key)) {
2223 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2225 current_view_->restartCursor();
2228 // The following modifier check is not needed on Mac.
2229 // The keysym is either not text or it is different
2230 // from the non-modifier keysym. See #9875 for the
2231 // broken alt-modifier effect of having this code active.
2232 #if !defined(Q_OS_MAC)
2233 // If a non-Shift Modifier is used we have a non-bound key sequence
2234 // (such as Alt+j = j). This should be omitted (#5575).
2235 // On Windows, AltModifier and ControlModifier are both
2236 // set when AltGr is pressed. Therefore, in order to not
2237 // break AltGr-bound symbols (see #5575 for details),
2238 // unbound Ctrl+Alt key sequences are allowed.
2239 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2240 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2241 && !(state & AltModifier && state & ControlModifier)
2245 if (current_view_) {
2246 current_view_->message(_("Unknown function."));
2247 current_view_->restartCursor();
2252 // Since all checks above were passed, we now really have text that
2253 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2254 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2256 LYXERR(Debug::KEY, "isText() is true, inserting.");
2257 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2259 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2260 if (current_view_) {
2261 current_view_->message(_("Unknown function."));
2262 current_view_->restartCursor();
2268 if (func.action() == LFUN_SELF_INSERT) {
2269 if (encoded_last_key != 0) {
2270 docstring const arg(1, encoded_last_key);
2271 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2272 FuncRequest::KEYBOARD));
2273 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2276 processFuncRequest(func);
2280 void GuiApplication::processFuncRequest(FuncRequest const & func)
2282 lyx::dispatch(func);
2286 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2288 addToFuncRequestQueue(func);
2289 processFuncRequestQueueAsync();
2293 void GuiApplication::processFuncRequestQueue()
2295 while (!d->func_request_queue_.empty()) {
2296 processFuncRequest(d->func_request_queue_.front());
2297 d->func_request_queue_.pop();
2302 void GuiApplication::processFuncRequestQueueAsync()
2304 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2308 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2310 d->func_request_queue_.push(func);
2314 void GuiApplication::resetGui()
2316 // Set the language defined by the user.
2320 if (!readUIFile(toqstr(lyxrc.ui_file)))
2321 // Gives some error box here.
2324 if (d->global_menubar_)
2325 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2327 QHash<int, GuiView *>::iterator it;
2328 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2331 gv->setLayoutDirection(layoutDirection());
2335 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2339 void GuiApplication::createView(int view_id)
2341 createView(QString(), true, view_id);
2345 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2348 // release the keyboard which might have been grabed by the global
2349 // menubar on Mac to catch shortcuts even without any GuiView.
2350 if (d->global_menubar_)
2351 d->global_menubar_->releaseKeyboard();
2355 while (d->views_.find(id) != d->views_.end())
2358 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2359 GuiView * view = new GuiView(id);
2361 d->views_[id] = view;
2365 setActiveWindow(view);
2368 if (!geometry_arg.isEmpty()) {
2369 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2373 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2374 re.indexIn(geometry_arg);
2375 w = re.cap(1).toInt();
2376 h = re.cap(2).toInt();
2377 x = re.cap(3).toInt();
2378 y = re.cap(4).toInt();
2379 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2380 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2381 // Set initial geometry such that we can get the frame size.
2382 view->setGeometry(x, y, w, h);
2383 int framewidth = view->geometry().x() - view->x();
2384 int titleheight = view->geometry().y() - view->y();
2385 // Negative displacements must be interpreted as distances
2386 // from the right or bottom screen borders.
2387 if (sx == '-' || sy == '-') {
2388 QRect rec = QApplication::desktop()->screenGeometry();
2390 x += rec.width() - w - framewidth;
2392 y += rec.height() - h - titleheight;
2393 view->setGeometry(x, y, w, h);
2395 // Make sure that the left and top frame borders are visible.
2396 if (view->x() < 0 || view->y() < 0) {
2401 view->setGeometry(x, y, w, h);
2409 Clipboard & GuiApplication::clipboard()
2411 return d->clipboard_;
2415 Selection & GuiApplication::selection()
2417 return d->selection_;
2421 FontLoader & GuiApplication::fontLoader()
2423 return d->font_loader_;
2427 Toolbars const & GuiApplication::toolbars() const
2429 return d->toolbars_;
2433 Toolbars & GuiApplication::toolbars()
2435 return d->toolbars_;
2439 Menus const & GuiApplication::menus() const
2445 Menus & GuiApplication::menus()
2451 QList<int> GuiApplication::viewIds() const
2453 return d->views_.keys();
2457 ColorCache & GuiApplication::colorCache()
2459 return d->color_cache_;
2463 int GuiApplication::exec()
2465 // asynchronously handle batch commands. This event will be in
2466 // the event queue in front of other asynchronous events. Hence,
2467 // we can assume in the latter that the gui is setup already.
2468 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2470 return QApplication::exec();
2474 void GuiApplication::exit(int status)
2476 QApplication::exit(status);
2480 void GuiApplication::setGuiLanguage()
2484 // install translation file for Qt built-in dialogs
2485 QString const language_name = QString("qt_") + theLocale.name();
2486 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2487 // Short-named translator can be loaded from a long name, but not the
2488 // opposite. Therefore, long name should be used without truncation.
2489 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2490 if (!d->qt_trans_.load(language_name,
2491 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2492 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2495 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2499 switch (theLocale.language()) {
2500 case QLocale::Arabic :
2501 case QLocale::Hebrew :
2502 case QLocale::Persian :
2503 case QLocale::Urdu :
2504 setLayoutDirection(Qt::RightToLeft);
2507 setLayoutDirection(Qt::LeftToRight);
2512 void GuiApplication::execBatchCommands()
2517 if (!readUIFile(toqstr(lyxrc.ui_file)))
2518 // Gives some error box here.
2522 #if QT_VERSION > 0x040600
2523 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2525 #if QT_VERSION > 0x050100
2526 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2528 // Create the global default menubar which is shown for the dialogs
2529 // and if no GuiView is visible.
2530 // This must be done after the session was recovered to know the "last files".
2531 d->global_menubar_ = new QMenuBar(0);
2532 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2535 lyx::execBatchCommands();
2539 QAbstractItemModel * GuiApplication::languageModel()
2541 if (d->language_model_)
2542 return d->language_model_;
2544 QStandardItemModel * lang_model = new QStandardItemModel(this);
2545 lang_model->insertColumns(0, 3);
2546 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2547 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2548 Languages::const_iterator it = lyx::languages.begin();
2549 Languages::const_iterator end = lyx::languages.end();
2550 for (; it != end; ++it) {
2551 int current_row = lang_model->rowCount();
2552 lang_model->insertRows(current_row, 1);
2553 QModelIndex pl_item = lang_model->index(current_row, 0);
2554 QModelIndex sp_item = lang_model->index(current_row, 1);
2555 QModelIndex th_item = lang_model->index(current_row, 2);
2556 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2557 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2558 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2559 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2560 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2561 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2562 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2563 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2564 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2565 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2567 d->language_model_ = new QSortFilterProxyModel(this);
2568 d->language_model_->setSourceModel(lang_model);
2569 d->language_model_->setSortLocaleAware(true);
2570 return d->language_model_;
2574 void GuiApplication::restoreGuiSession()
2576 if (!lyxrc.load_session)
2579 Session & session = theSession();
2580 LastOpenedSection::LastOpened const & lastopened =
2581 session.lastOpened().getfiles();
2583 validateCurrentView();
2585 FileName active_file;
2586 // do not add to the lastfile list since these files are restored from
2587 // last session, and should be already there (regular files), or should
2588 // not be added at all (help files).
2589 for (size_t i = 0; i < lastopened.size(); ++i) {
2590 FileName const & file_name = lastopened[i].file_name;
2591 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2592 && current_view_->documentBufferView() != 0)) {
2593 boost::crc_32_type crc;
2594 string const & fname = file_name.absFileName();
2595 crc = for_each(fname.begin(), fname.end(), crc);
2596 createView(crc.checksum());
2598 current_view_->loadDocument(file_name, false);
2600 if (lastopened[i].active)
2601 active_file = file_name;
2604 // Restore last active buffer
2605 Buffer * buffer = theBufferList().getBuffer(active_file);
2606 if (buffer && current_view_)
2607 current_view_->setBuffer(buffer);
2609 // clear this list to save a few bytes of RAM
2610 session.lastOpened().clear();
2614 QString const GuiApplication::romanFontName()
2617 font.setStyleHint(QFont::Serif);
2618 font.setFamily("serif");
2620 return QFontInfo(font).family();
2624 QString const GuiApplication::sansFontName()
2627 font.setStyleHint(QFont::SansSerif);
2628 font.setFamily("sans");
2630 return QFontInfo(font).family();
2634 QString const GuiApplication::typewriterFontName()
2636 return QFontInfo(typewriterSystemFont()).family();
2641 // We cannot use QFont::fixedPitch() because it doesn't
2642 // return the fact but only if it is requested.
2643 static bool isFixedPitch(const QFont & font) {
2644 const QFontInfo fi(font);
2645 return fi.fixedPitch();
2650 QFont const GuiApplication::typewriterSystemFont()
2652 #if QT_VERSION >= 0x050200
2653 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2655 QFont font("monospace");
2657 if (!isFixedPitch(font)) {
2658 // try to enforce a real monospaced font
2659 font.setStyleHint(QFont::Monospace);
2660 if (!isFixedPitch(font)) {
2661 font.setStyleHint(QFont::TypeWriter);
2662 if (!isFixedPitch(font)) font.setFamily("courier");
2666 // On a Mac the result is too small and it's not practical to
2667 // rely on Qtconfig utility to change the system settings of Qt.
2668 font.setPointSize(12);
2674 void GuiApplication::handleRegularEvents()
2676 ForkedCallsController::handleCompletedProcesses();
2680 bool GuiApplication::event(QEvent * e)
2683 case QEvent::FileOpen: {
2684 // Open a file; this happens only on Mac OS X for now.
2686 // We do this asynchronously because on startup the batch
2687 // commands are not executed here yet and the gui is not ready
2689 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2690 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2691 processFuncRequestAsync(fr);
2696 return QApplication::event(e);
2701 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2704 return QApplication::notify(receiver, event);
2706 catch (ExceptionMessage const & e) {
2708 case ErrorException:
2710 setQuitOnLastWindowClosed(false);
2712 Alert::error(e.title_, e.details_);
2714 // Properly crash in debug mode in order to get a useful backtrace.
2717 // In release mode, try to exit gracefully.
2720 case BufferException: {
2721 if (!current_view_ || !current_view_->documentBufferView())
2723 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2724 docstring details = e.details_ + '\n';
2725 details += buf->emergencyWrite();
2726 theBufferList().release(buf);
2727 details += "\n" + _("The current document was closed.");
2728 Alert::error(e.title_, details);
2731 case WarningException:
2732 Alert::warning(e.title_, e.details_);
2736 catch (exception const & e) {
2737 docstring s = _("LyX has caught an exception, it will now "
2738 "attempt to save all unsaved documents and exit."
2740 s += from_ascii(e.what());
2741 Alert::error(_("Software exception Detected"), s);
2745 docstring s = _("LyX has caught some really weird exception, it will "
2746 "now attempt to save all unsaved documents and exit.");
2747 Alert::error(_("Software exception Detected"), s);
2755 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2757 QColor const & qcol = d->color_cache_.get(col);
2758 if (!qcol.isValid()) {
2764 rgbcol.r = qcol.red();
2765 rgbcol.g = qcol.green();
2766 rgbcol.b = qcol.blue();
2771 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2773 QColor const qcol(lcolor.getX11Name(col).c_str());
2774 if (!qcol.isValid()) {
2780 rgbcol.r = qcol.red();
2781 rgbcol.g = qcol.green();
2782 rgbcol.b = qcol.blue();
2787 string const GuiApplication::hexName(ColorCode col)
2789 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2793 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2795 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2796 d->socket_notifiers_[fd] = sn;
2797 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2801 void GuiApplication::socketDataReceived(int fd)
2803 d->socket_notifiers_[fd]->func_();
2807 void GuiApplication::unregisterSocketCallback(int fd)
2809 d->socket_notifiers_.take(fd)->setEnabled(false);
2813 void GuiApplication::commitData(QSessionManager & sm)
2815 /** The implementation is required to avoid an application exit
2816 ** when session state save is triggered by session manager.
2817 ** The default implementation sends a close event to all
2818 ** visible top level widgets when session managment allows
2820 ** We are changing that to check the state of each buffer in all
2821 ** views and ask the users what to do if buffers are dirty.
2822 ** Furthermore, we save the session state.
2823 ** We do NOT close the views here since the user still can cancel
2824 ** the logout process (see #9277); also, this would hide LyX from
2825 ** an OSes own session handling (application restoration).
2827 #ifdef QT_NO_SESSIONMANAGER
2829 #warning Qt is compiled without session manager
2831 #pragma message("warning: Qt is compiled without session manager")
2835 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2843 void GuiApplication::unregisterView(GuiView * gv)
2845 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2846 d->views_.remove(gv->id());
2847 if (current_view_ == gv)
2853 bool GuiApplication::closeAllViews()
2855 if (d->views_.empty())
2858 // When a view/window was closed before without quitting LyX, there
2859 // are already entries in the lastOpened list.
2860 theSession().lastOpened().clear();
2862 QList<GuiView *> const views = d->views_.values();
2863 for (GuiView * view : views) {
2864 if (!view->closeScheduled())
2873 bool GuiApplication::prepareAllViewsForLogout()
2875 if (d->views_.empty())
2878 QList<GuiView *> const views = d->views_.values();
2879 for (GuiView * view : views) {
2880 if (!view->prepareAllBuffersForLogout())
2888 GuiView & GuiApplication::view(int id) const
2890 LAPPERR(d->views_.contains(id));
2891 return *d->views_.value(id);
2895 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2897 QList<GuiView *> const views = d->views_.values();
2898 for (GuiView * view : views)
2899 view->hideDialog(name, inset);
2903 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2905 Buffer const * buffer_ = 0;
2906 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2907 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2908 if (Buffer const * ptr = (*it)->updateInset(inset))
2915 bool GuiApplication::searchMenu(FuncRequest const & func,
2916 docstring_list & names) const
2918 return d->menus_.searchMenu(func, names);
2922 // Ensure that a file is read only once (prevents include loops)
2923 static QStringList uifiles;
2924 // store which ui files define Toolbars
2925 static QStringList toolbar_uifiles;
2928 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2939 LexerKeyword uitags[] = {
2940 { "format", ui_format },
2941 { "include", ui_include },
2942 { "menuset", ui_menuset },
2943 { "toolbars", ui_toolbars },
2944 { "toolbarset", ui_toolbarset }
2948 lex.setFile(ui_path);
2950 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2954 if (lyxerr.debugging(Debug::PARSER))
2955 lex.printTable(lyxerr);
2958 // format before introduction of format tag
2959 unsigned int format = 0;
2960 while (lex.isOK()) {
2961 int const status = lex.lex();
2963 // we have to do this check here, outside the switch,
2964 // because otherwise we would start reading include files,
2965 // e.g., if the first tag we hit was an include tag.
2966 if (status == ui_format)
2968 format = lex.getInteger();
2972 // this will trigger unless the first tag we hit is a format
2973 // tag, with the right format.
2974 if (format != LFUN_FORMAT)
2975 return FormatMismatch;
2978 case Lexer::LEX_FEOF:
2983 QString const file = toqstr(lex.getString());
2984 bool const success = readUIFile(file, true);
2986 LYXERR0("Failed to read included file: " << fromqstr(file));
2993 d->menus_.read(lex);
2997 d->toolbars_.readToolbars(lex);
3001 d->toolbars_.readToolbarSettings(lex);
3002 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3006 if (!rtrim(lex.getString()).empty())
3007 lex.printError("LyX::ReadUIFile: "
3008 "Unknown menu tag: `$$Token'");
3010 LYXERR0("Error with status: " << status);
3016 return (error ? ReadError : ReadOK);
3020 bool GuiApplication::readUIFile(QString const & name, bool include)
3022 LYXERR(Debug::INIT, "About to read " << name << "...");
3026 ui_path = libFileSearch("ui", name, "inc");
3027 if (ui_path.empty())
3028 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3030 ui_path = libFileSearch("ui", name, "ui");
3033 if (ui_path.empty()) {
3034 static const QString defaultUIFile = "default";
3035 LYXERR(Debug::INIT, "Could not find " << name);
3037 Alert::warning(_("Could not find UI definition file"),
3038 bformat(_("Error while reading the included file\n%1$s\n"
3039 "Please check your installation."), qstring_to_ucs4(name)));
3042 if (name == defaultUIFile) {
3043 LYXERR(Debug::INIT, "Could not find default UI file!!");
3044 Alert::warning(_("Could not find default UI file"),
3045 _("LyX could not find the default UI file!\n"
3046 "Please check your installation."));
3049 Alert::warning(_("Could not find UI definition file"),
3050 bformat(_("Error while reading the configuration file\n%1$s\n"
3051 "Falling back to default.\n"
3052 "Please look under Tools>Preferences>User Interface and\n"
3053 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3054 return readUIFile(defaultUIFile, false);
3057 QString const uifile = toqstr(ui_path.absFileName());
3058 if (uifiles.contains(uifile)) {
3060 // We are reading again the top uifile so reset the safeguard:
3063 d->toolbars_.reset();
3065 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3066 << "Is this an include loop?");
3070 uifiles.push_back(uifile);
3072 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3074 ReturnValues retval = readUIFile(ui_path);
3076 if (retval == FormatMismatch) {
3077 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3078 TempFile tmp("convertXXXXXX.ui");
3079 FileName const tempfile = tmp.name();
3080 bool const success = prefs2prefs(ui_path, tempfile, true);
3082 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3083 " to format " << LFUN_FORMAT << ".");
3085 retval = readUIFile(tempfile);
3089 if (retval != ReadOK) {
3090 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3098 settings.beginGroup("ui_files");
3099 bool touched = false;
3100 for (int i = 0; i != uifiles.size(); ++i) {
3101 QFileInfo fi(uifiles[i]);
3102 QDateTime const date_value = fi.lastModified();
3103 QString const name_key = QString::number(i);
3104 // if an ui file which defines Toolbars has changed,
3105 // we have to reset the settings
3106 if (toolbar_uifiles.contains(uifiles[i])
3107 && (!settings.contains(name_key)
3108 || settings.value(name_key).toString() != uifiles[i]
3109 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3111 settings.setValue(name_key, uifiles[i]);
3112 settings.setValue(name_key + "/date", date_value);
3115 settings.endGroup();
3117 settings.remove("views");
3123 void GuiApplication::onLastWindowClosed()
3125 if (d->global_menubar_)
3126 d->global_menubar_->grabKeyboard();
3130 void GuiApplication::startLongOperation() {
3131 d->key_checker_.start();
3135 bool GuiApplication::longOperationCancelled() {
3136 return d->key_checker_.pressed();
3140 void GuiApplication::stopLongOperation() {
3141 d->key_checker_.stop();
3145 bool GuiApplication::longOperationStarted() {
3146 return d->key_checker_.started();
3150 ////////////////////////////////////////////////////////////////////////
3152 // X11 specific stuff goes here...
3155 bool GuiApplication::x11EventFilter(XEvent * xev)
3160 switch (xev->type) {
3161 case SelectionRequest: {
3162 if (xev->xselectionrequest.selection != XA_PRIMARY)
3164 LYXERR(Debug::SELECTION, "X requested selection.");
3165 BufferView * bv = current_view_->currentBufferView();
3167 docstring const sel = bv->requestSelection();
3169 d->selection_.put(sel);
3170 // Refresh the selection request timestamp.
3171 // We have to do this by ourselves as Qt seems
3172 // not doing that, maybe because of our
3173 // "persistent selection" implementation
3174 // (see comments in GuiSelection.cpp).
3175 XSelectionEvent nev;
3176 nev.type = SelectionNotify;
3177 nev.display = xev->xselectionrequest.display;
3178 nev.requestor = xev->xselectionrequest.requestor;
3179 nev.selection = xev->xselectionrequest.selection;
3180 nev.target = xev->xselectionrequest.target;
3181 nev.property = 0L; // None
3182 nev.time = CurrentTime;
3183 XSendEvent(QX11Info::display(),
3184 nev.requestor, False, 0,
3185 reinterpret_cast<XEvent *>(&nev));
3191 case SelectionClear: {
3192 if (xev->xselectionclear.selection != XA_PRIMARY)
3194 LYXERR(Debug::SELECTION, "Lost selection.");
3195 BufferView * bv = current_view_->currentBufferView();
3197 bv->clearSelection();
3203 #elif defined(QPA_XCB)
3204 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3205 void * message, long *)
3207 if (!current_view_ || eventType != "xcb_generic_event_t")
3210 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3212 switch (ev->response_type) {
3213 case XCB_SELECTION_REQUEST: {
3214 xcb_selection_request_event_t * srev =
3215 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3216 if (srev->selection != XCB_ATOM_PRIMARY)
3218 LYXERR(Debug::SELECTION, "X requested selection.");
3219 BufferView * bv = current_view_->currentBufferView();
3221 docstring const sel = bv->requestSelection();
3223 d->selection_.put(sel);
3224 #ifdef HAVE_QT5_X11_EXTRAS
3225 // Refresh the selection request timestamp.
3226 // We have to do this by ourselves as Qt seems
3227 // not doing that, maybe because of our
3228 // "persistent selection" implementation
3229 // (see comments in GuiSelection.cpp).
3230 xcb_selection_notify_event_t nev;
3231 nev.response_type = XCB_SELECTION_NOTIFY;
3232 nev.requestor = srev->requestor;
3233 nev.selection = srev->selection;
3234 nev.target = srev->target;
3235 nev.property = XCB_NONE;
3236 nev.time = XCB_CURRENT_TIME;
3237 xcb_connection_t * con = QX11Info::connection();
3238 xcb_send_event(con, 0, srev->requestor,
3239 XCB_EVENT_MASK_NO_EVENT,
3240 reinterpret_cast<char const *>(&nev));
3248 case XCB_SELECTION_CLEAR: {
3249 xcb_selection_clear_event_t * scev =
3250 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3251 if (scev->selection != XCB_ATOM_PRIMARY)
3253 LYXERR(Debug::SELECTION, "Lost selection.");
3254 BufferView * bv = current_view_->currentBufferView();
3256 bv->clearSelection();
3264 } // namespace frontend
3267 void hideDialogs(std::string const & name, Inset * inset)
3270 frontend::guiApp->hideDialogs(name, inset);
3274 ////////////////////////////////////////////////////////////////////
3278 ////////////////////////////////////////////////////////////////////
3280 frontend::FontLoader & theFontLoader()
3282 LAPPERR(frontend::guiApp);
3283 return frontend::guiApp->fontLoader();
3287 frontend::FontMetrics const & theFontMetrics(Font const & f)
3289 return theFontMetrics(f.fontInfo());
3293 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3295 LAPPERR(frontend::guiApp);
3296 return frontend::guiApp->fontLoader().metrics(f);
3300 ////////////////////////////////////////////////////////////////////
3304 ////////////////////////////////////////////////////////////////////
3306 frontend::Clipboard & theClipboard()
3308 LAPPERR(frontend::guiApp);
3309 return frontend::guiApp->clipboard();
3313 frontend::Selection & theSelection()
3315 LAPPERR(frontend::guiApp);
3316 return frontend::guiApp->selection();
3322 #include "moc_GuiApplication.cpp"