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 // FIXME It's possible that doc_bv is null!!
1477 // See coverity #102061
1478 Cursor const old = doc_bv->cursor();
1479 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1480 if (switchToBuffer) {
1481 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1484 doc_bv = current_view_->documentBufferView();
1489 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1490 if (!doc_bv->moveToPosition(
1491 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1494 Cursor & cur = doc_bv->cursor();
1496 notifyCursorLeavesOrEnters(old, cur);
1502 // Cursor jump succeeded!
1503 pit_type new_pit = cur.pit();
1504 pos_type new_pos = cur.pos();
1505 int new_id = cur.paragraph().id();
1507 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1508 // see http://www.lyx.org/trac/ticket/3092
1509 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1510 || bm.top_id != new_id) {
1511 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1512 new_pit, new_pos, new_id);
1516 // This function runs "configure" and then rereads lyx.defaults to
1517 // reconfigure the automatic settings.
1518 void GuiApplication::reconfigure(string const & option)
1520 // emit message signal.
1522 current_view_->message(_("Running configure..."));
1524 // Run configure in user lyx directory
1525 string const lock_file = package().getConfigureLockName();
1526 int fd = fileLock(lock_file.c_str());
1527 int const ret = package().reconfigureUserLyXDir(option);
1528 // emit message signal.
1530 current_view_->message(_("Reloading configuration..."));
1531 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1532 // Re-read packages.lst
1533 LaTeXPackages::getAvailable();
1534 fileUnlock(fd, lock_file.c_str());
1537 Alert::information(_("System reconfiguration failed"),
1538 _("The system reconfiguration has failed.\n"
1539 "Default textclass is used but LyX may\n"
1540 "not be able to work properly.\n"
1541 "Please reconfigure again if needed."));
1543 Alert::information(_("System reconfigured"),
1544 _("The system has been reconfigured.\n"
1545 "You need to restart LyX to make use of any\n"
1546 "updated document class specifications."));
1549 void GuiApplication::validateCurrentView()
1551 if (!d->views_.empty() && !current_view_) {
1552 // currently at least one view exists but no view has the focus.
1553 // choose the last view to make it current.
1554 // a view without any open document is preferred.
1555 GuiView * candidate = 0;
1556 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1557 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1558 for (; it != end; ++it) {
1560 if (!candidate->documentBufferView())
1563 setCurrentView(candidate);
1567 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1569 string const argument = to_utf8(cmd.argument());
1570 FuncCode const action = cmd.action();
1572 LYXERR(Debug::ACTION, "cmd: " << cmd);
1574 // we have not done anything wrong yet.
1577 FuncStatus const flag = getStatus(cmd);
1578 if (!flag.enabled()) {
1579 // We cannot use this function here
1580 LYXERR(Debug::ACTION, "action "
1581 << lyxaction.getActionName(action)
1582 << " [" << action << "] is disabled at this location");
1583 dr.setMessage(flag.message());
1585 dr.dispatched(false);
1586 dr.screenUpdate(Update::None);
1587 dr.clearBufferUpdate();
1591 if (cmd.origin() == FuncRequest::LYXSERVER) {
1592 if (current_view_ && current_view_->currentBufferView())
1593 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1594 // we will also need to redraw the screen at the end
1595 dr.screenUpdate(Update::FitCursor);
1598 // Assumes that the action will be dispatched.
1599 dr.dispatched(true);
1601 switch (cmd.action()) {
1603 case LFUN_WINDOW_NEW:
1604 createView(toqstr(cmd.argument()));
1607 case LFUN_WINDOW_CLOSE:
1608 // update bookmark pit of the current buffer before window close
1609 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1610 gotoBookmark(i+1, false, false);
1611 // clear the last opened list, because
1612 // maybe this will end the session
1613 theSession().lastOpened().clear();
1614 // check for valid current_view_
1615 validateCurrentView();
1617 current_view_->closeScheduled();
1621 // quitting is triggered by the gui code
1622 // (leaving the event loop).
1624 current_view_->message(from_utf8(N_("Exiting.")));
1625 if (closeAllViews())
1629 case LFUN_SCREEN_FONT_UPDATE: {
1630 // handle the screen font changes.
1631 d->font_loader_.update();
1632 // Backup current_view_
1633 GuiView * view = current_view_;
1634 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1635 // to skip the refresh.
1637 theBufferList().changed(false);
1638 // Restore current_view_
1639 current_view_ = view;
1643 case LFUN_BUFFER_NEW:
1644 validateCurrentView();
1645 if (d->views_.empty()
1646 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1647 createView(QString(), false); // keep hidden
1648 current_view_->newDocument(to_utf8(cmd.argument()), false);
1649 current_view_->show();
1650 setActiveWindow(current_view_);
1652 current_view_->newDocument(to_utf8(cmd.argument()), false);
1656 case LFUN_BUFFER_NEW_TEMPLATE:
1657 validateCurrentView();
1658 if (d->views_.empty()
1659 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1661 current_view_->newDocument(to_utf8(cmd.argument()), true);
1662 if (!current_view_->documentBufferView())
1663 current_view_->close();
1665 current_view_->newDocument(to_utf8(cmd.argument()), true);
1669 case LFUN_FILE_OPEN: {
1670 validateCurrentView();
1671 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1672 string const fname = to_utf8(cmd.argument());
1673 bool const is_open = FileName::isAbsolute(fname)
1674 && theBufferList().getBuffer(FileName(fname));
1675 if (d->views_.empty()
1676 || (!lyxrc.open_buffers_in_tabs
1677 && current_view_->documentBufferView() != 0
1679 // We want the ui session to be saved per document and not per
1680 // window number. The filename crc is a good enough identifier.
1681 boost::crc_32_type crc;
1682 crc = for_each(fname.begin(), fname.end(), crc);
1683 createView(crc.checksum());
1684 // we know current_view_ is non-null, because createView sets it.
1685 // but let's make sure
1686 LASSERT(current_view_, break);
1687 current_view_->openDocument(fname);
1688 if (!current_view_->documentBufferView())
1689 current_view_->close();
1690 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1691 current_view_->raise();
1692 current_view_->activateWindow();
1693 current_view_->showNormal();
1696 // we know !d->views.empty(), so this should be ok
1697 // but let's make sure
1698 LASSERT(current_view_, break);
1699 current_view_->openDocument(fname);
1700 if (cmd.origin() == FuncRequest::LYXSERVER) {
1701 current_view_->raise();
1702 current_view_->activateWindow();
1703 current_view_->showNormal();
1709 case LFUN_HELP_OPEN: {
1710 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1711 if (current_view_ == 0)
1713 string const arg = to_utf8(cmd.argument());
1715 current_view_->message(_("Missing argument"));
1718 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1720 fname = i18nLibFileSearch("examples", arg, "lyx");
1722 if (fname.empty()) {
1723 lyxerr << "LyX: unable to find documentation file `"
1724 << arg << "'. Bad installation?" << endl;
1727 current_view_->message(bformat(_("Opening help file %1$s..."),
1728 makeDisplayPath(fname.absFileName())));
1729 Buffer * buf = current_view_->loadDocument(fname, false);
1731 #ifndef DEVEL_VERSION
1733 buf->setReadonly(true);
1740 case LFUN_SET_COLOR: {
1742 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1743 if (lyx_name.empty() || x11_name.empty()) {
1745 current_view_->message(
1746 _("Syntax: set-color <lyx_name> <x11_name>"));
1751 // FIXME: The graphics cache no longer has a changeDisplay method.
1752 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1753 bool const graphicsbg_changed =
1754 lyx_name == graphicsbg && x11_name != graphicsbg;
1755 if (graphicsbg_changed)
1756 graphics::GCache::get().changeDisplay(true);
1759 if (!lcolor.setColor(lyx_name, x11_name)) {
1761 current_view_->message(
1762 bformat(_("Set-color \"%1$s\" failed "
1763 "- color is undefined or "
1764 "may not be redefined"),
1765 from_utf8(lyx_name)));
1768 // Make sure we don't keep old colors in cache.
1769 d->color_cache_.clear();
1770 // Update the current view
1771 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1775 case LFUN_LYXRC_APPLY: {
1776 // reset active key sequences, since the bindings
1777 // are updated (bug 6064)
1779 LyXRC const lyxrc_orig = lyxrc;
1781 istringstream ss(to_utf8(cmd.argument()));
1782 bool const success = lyxrc.read(ss);
1785 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1786 << "Unable to read lyxrc data"
1791 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1793 // If the request comes from the minibuffer, then we can't reset
1794 // the GUI, since that would destory the minibuffer itself and
1795 // cause a crash, since we are currently in one of the methods of
1796 // GuiCommandBuffer. See bug #8540.
1797 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1800 // FIXME Unfortunately, that leaves a bug here, since we cannot
1801 // reset the GUI in this case. If the changes to lyxrc affected the
1802 // UI, then, nothing would happen. This seems fairly unlikely, but
1803 // it definitely is a bug.
1808 case LFUN_COMMAND_PREFIX:
1809 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1814 d->meta_fake_bit = NoModifier;
1815 GuiView * gv = currentView();
1816 if (gv && gv->currentBufferView())
1817 // cancel any selection
1818 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1819 dr.setMessage(from_ascii(N_("Cancel")));
1822 case LFUN_META_PREFIX:
1823 d->meta_fake_bit = AltModifier;
1824 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1827 // --- Menus -----------------------------------------------
1828 case LFUN_RECONFIGURE:
1829 // argument is any additional parameter to the configure.py command
1830 reconfigure(to_utf8(cmd.argument()));
1833 // --- lyxserver commands ----------------------------
1834 case LFUN_SERVER_GET_FILENAME: {
1835 if (current_view_ && current_view_->documentBufferView()) {
1836 docstring const fname = from_utf8(
1837 current_view_->documentBufferView()->buffer().absFileName());
1838 dr.setMessage(fname);
1839 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1841 dr.setMessage(docstring());
1842 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1847 case LFUN_SERVER_NOTIFY: {
1848 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1849 dr.setMessage(dispatch_buffer);
1850 theServer().notifyClient(to_utf8(dispatch_buffer));
1854 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1855 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1861 string rest = split(argument, countstr, ' ');
1862 istringstream is(countstr);
1865 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1866 for (int i = 0; i < count; ++i)
1867 dispatch(lyxaction.lookupFunc(rest));
1871 case LFUN_COMMAND_SEQUENCE: {
1872 // argument contains ';'-terminated commands
1873 string arg = argument;
1874 // FIXME: this LFUN should also work without any view.
1875 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1876 ? &(current_view_->documentBufferView()->buffer()) : 0;
1878 buffer->undo().beginUndoGroup();
1879 while (!arg.empty()) {
1881 arg = split(arg, first, ';');
1882 FuncRequest func(lyxaction.lookupFunc(first));
1883 func.setOrigin(cmd.origin());
1886 // the buffer may have been closed by one action
1887 if (theBufferList().isLoaded(buffer))
1888 buffer->undo().endUndoGroup();
1892 case LFUN_BUFFER_FORALL: {
1893 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1895 map<Buffer *, GuiView *> views_lVisible;
1896 map<GuiView *, Buffer *> activeBuffers;
1898 QList<GuiView *> allViews = d->views_.values();
1900 // this for does not modify any buffer. It just collects info on local
1901 // visibility of buffers and on which buffer is active in each view.
1902 Buffer * const last = theBufferList().last();
1903 for(GuiView * view : allViews) {
1904 // all of the buffers might be locally hidden. That is, there is no
1906 if (!view || !view->currentBufferView())
1907 activeBuffers[view] = 0;
1909 activeBuffers[view] = &view->currentBufferView()->buffer();
1911 // find out if each is locally visible or locally hidden.
1912 // we don't use a for loop as the buffer list cycles.
1913 Buffer * b = theBufferList().first();
1915 bool const locallyVisible = view && view->workArea(*b);
1916 if (locallyVisible) {
1917 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1918 // only need to overwrite/add if we don't already know a buffer is globally
1919 // visible or we do know but we would prefer to dispatch LFUN from the
1920 // current view because of cursor position issues.
1921 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1922 views_lVisible[b] = view;
1926 b = theBufferList().next(b);
1930 GuiView * const homeView = currentView();
1931 Buffer * b = theBufferList().first();
1932 Buffer * nextBuf = 0;
1933 int numProcessed = 0;
1936 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1938 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1940 // first change to a view where b is locally visible, preferably current_view_.
1941 GuiView * const vLv = views_lVisible[b];
1943 lyx::dispatch(funcToRun);
1951 // put things back to how they were (if possible).
1952 for (GuiView * view : allViews) {
1953 Buffer * originalBuf = activeBuffers[view];
1954 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1955 if (theBufferList().isLoaded(originalBuf))
1956 view->setBuffer(originalBuf);
1958 homeView->setFocus();
1960 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1964 case LFUN_COMMAND_ALTERNATIVES: {
1965 // argument contains ';'-terminated commands
1966 string arg = argument;
1967 while (!arg.empty()) {
1969 arg = split(arg, first, ';');
1970 FuncRequest func(lyxaction.lookupFunc(first));
1971 func.setOrigin(cmd.origin());
1972 FuncStatus const stat = getStatus(func);
1973 if (stat.enabled()) {
1983 if (theTopLevelCmdDef().lock(argument, func)) {
1984 func.setOrigin(cmd.origin());
1986 theTopLevelCmdDef().release(argument);
1988 if (func.action() == LFUN_UNKNOWN_ACTION) {
1989 // unknown command definition
1990 lyxerr << "Warning: unknown command definition `"
1994 // recursion detected
1995 lyxerr << "Warning: Recursion in the command definition `"
1996 << argument << "' detected"
2003 case LFUN_PREFERENCES_SAVE:
2004 lyxrc.write(support::makeAbsPath("preferences",
2005 package().user_support().absFileName()), false);
2008 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2009 string const fname = addName(addPath(package().user_support().absFileName(),
2010 "templates/"), "defaults.lyx");
2011 Buffer defaults(fname);
2013 istringstream ss(argument);
2018 // We need to make sure that, after we recreat the DocumentClass,
2019 // which we do in readHeader, we apply it to the document itself.
2020 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2021 int const unknown_tokens = defaults.readHeader(lex);
2022 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2024 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2025 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2027 if (unknown_tokens != 0) {
2028 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2029 << unknown_tokens << " unknown token"
2030 << (unknown_tokens == 1 ? "" : "s")
2034 if (defaults.writeFile(FileName(defaults.absFileName())))
2035 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2036 makeDisplayPath(fname)));
2039 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2044 case LFUN_BOOKMARK_GOTO:
2045 // go to bookmark, open unopened file and switch to buffer if necessary
2046 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2047 dr.screenUpdate(Update::Force | Update::FitCursor);
2050 case LFUN_BOOKMARK_CLEAR:
2051 theSession().bookmarks().clear();
2054 case LFUN_DEBUG_LEVEL_SET:
2055 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2058 case LFUN_DIALOG_SHOW: {
2059 string const name = cmd.getArg(0);
2061 if ( name == "aboutlyx"
2063 || name == "texinfo"
2064 || name == "progress"
2065 || name == "compare")
2067 // work around: on Mac OS the application
2068 // is not terminated when closing the last view.
2069 // Create a new one to be able to dispatch the
2070 // LFUN_DIALOG_SHOW to this view.
2071 if (current_view_ == 0)
2078 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2081 current_view_->dispatch(cmd, dr);
2085 if (cmd.origin() == FuncRequest::LYXSERVER)
2086 updateCurrentView(cmd, dr);
2090 docstring GuiApplication::viewStatusMessage()
2092 // When meta-fake key is pressed, show the key sequence so far + "M-".
2093 if (d->meta_fake_bit != NoModifier)
2094 return d->keyseq.print(KeySequence::ForGui) + "M-";
2096 // Else, when a non-complete key sequence is pressed,
2097 // show the available options.
2098 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2099 return d->keyseq.printOptions(true);
2105 void GuiApplication::handleKeyFunc(FuncCode action)
2109 if (d->keyseq.length())
2111 GuiView * gv = currentView();
2112 LASSERT(gv && gv->currentBufferView(), return);
2113 BufferView * bv = gv->currentBufferView();
2114 bv->getIntl().getTransManager().deadkey(
2115 c, get_accent(action).accent, bv->cursor().innerText(),
2117 // Need to clear, in case the minibuffer calls these
2120 // copied verbatim from do_accent_char
2121 bv->cursor().resetAnchor();
2125 //Keep this in sync with GuiApplication::processKeySym below
2126 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2127 KeyModifier state) const
2129 // Do nothing if we have nothing
2130 if (!keysym.isOK() || keysym.isModifier())
2132 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2134 FuncRequest func = seq.addkey(keysym, state);
2135 // When not cancel or meta-fake, do the normal lookup.
2136 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2138 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2140 // Maybe user can only reach the key via holding down shift.
2141 // Let's see. But only if shift is the only modifier
2142 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2143 // If addkey looked up a command and did not find further commands then
2144 // seq has been reset at this point
2145 func = seq.addkey(keysym, NoModifier);
2147 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2148 << seq.print(KeySequence::Portable) << ']');
2149 return func.action() != LFUN_UNKNOWN_ACTION;
2153 //Keep this in sync with GuiApplication::queryKeySym above
2154 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2156 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2158 // Do nothing if we have nothing (JMarc)
2159 if (!keysym.isOK() || keysym.isModifier()) {
2161 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2163 current_view_->restartCursor();
2167 char_type encoded_last_key = keysym.getUCSEncoded();
2169 // Do a one-deep top-level lookup for
2170 // cancel and meta-fake keys. RVDK_PATCH_5
2171 d->cancel_meta_seq.reset();
2173 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2174 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2176 // When not cancel or meta-fake, do the normal lookup.
2177 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2178 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2179 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2180 // remove Caps Lock and Mod2 as a modifiers
2181 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2182 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2185 // Dont remove this unless you know what you are doing.
2186 d->meta_fake_bit = NoModifier;
2188 // Can this happen now ?
2189 if (func.action() == LFUN_NOACTION)
2190 func = FuncRequest(LFUN_COMMAND_PREFIX);
2192 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2193 << d->keyseq.print(KeySequence::Portable) << ']');
2195 // already here we know if it any point in going further
2196 // why not return already here if action == -1 and
2197 // num_bytes == 0? (Lgb)
2199 if (d->keyseq.length() > 1 && current_view_)
2200 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2203 // Maybe user can only reach the key via holding down shift.
2204 // Let's see. But only if shift is the only modifier
2205 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2206 LYXERR(Debug::KEY, "Trying without shift");
2207 // If addkey looked up a command and did not find further commands then
2208 // seq has been reset at this point
2209 func = d->keyseq.addkey(keysym, NoModifier);
2210 LYXERR(Debug::KEY, "Action now " << func.action());
2213 if (func.action() == LFUN_UNKNOWN_ACTION) {
2214 // We didn't match any of the key sequences.
2215 // See if it's normal insertable text not already
2216 // covered by a binding
2217 if (keysym.isText() && d->keyseq.length() == 1) {
2218 // Non-printable characters (such as ASCII control characters)
2219 // must not be inserted (#5704)
2220 if (!isPrintable(encoded_last_key)) {
2221 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2223 current_view_->restartCursor();
2226 // The following modifier check is not needed on Mac.
2227 // The keysym is either not text or it is different
2228 // from the non-modifier keysym. See #9875 for the
2229 // broken alt-modifier effect of having this code active.
2230 #if !defined(Q_OS_MAC)
2231 // If a non-Shift Modifier is used we have a non-bound key sequence
2232 // (such as Alt+j = j). This should be omitted (#5575).
2233 // On Windows, AltModifier and ControlModifier are both
2234 // set when AltGr is pressed. Therefore, in order to not
2235 // break AltGr-bound symbols (see #5575 for details),
2236 // unbound Ctrl+Alt key sequences are allowed.
2237 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2238 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2239 && !(state & AltModifier && state & ControlModifier)
2243 if (current_view_) {
2244 current_view_->message(_("Unknown function."));
2245 current_view_->restartCursor();
2250 // Since all checks above were passed, we now really have text that
2251 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2252 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2254 LYXERR(Debug::KEY, "isText() is true, inserting.");
2255 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2257 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2258 if (current_view_) {
2259 current_view_->message(_("Unknown function."));
2260 current_view_->restartCursor();
2266 if (func.action() == LFUN_SELF_INSERT) {
2267 if (encoded_last_key != 0) {
2268 docstring const arg(1, encoded_last_key);
2269 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2270 FuncRequest::KEYBOARD));
2271 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2274 processFuncRequest(func);
2278 void GuiApplication::processFuncRequest(FuncRequest const & func)
2280 lyx::dispatch(func);
2284 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2286 addToFuncRequestQueue(func);
2287 processFuncRequestQueueAsync();
2291 void GuiApplication::processFuncRequestQueue()
2293 while (!d->func_request_queue_.empty()) {
2294 processFuncRequest(d->func_request_queue_.front());
2295 d->func_request_queue_.pop();
2300 void GuiApplication::processFuncRequestQueueAsync()
2302 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2306 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2308 d->func_request_queue_.push(func);
2312 void GuiApplication::resetGui()
2314 // Set the language defined by the user.
2318 if (!readUIFile(toqstr(lyxrc.ui_file)))
2319 // Gives some error box here.
2322 if (d->global_menubar_)
2323 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2325 QHash<int, GuiView *>::iterator it;
2326 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2329 gv->setLayoutDirection(layoutDirection());
2333 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2337 void GuiApplication::createView(int view_id)
2339 createView(QString(), true, view_id);
2343 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2346 // release the keyboard which might have been grabed by the global
2347 // menubar on Mac to catch shortcuts even without any GuiView.
2348 if (d->global_menubar_)
2349 d->global_menubar_->releaseKeyboard();
2353 while (d->views_.find(id) != d->views_.end())
2356 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2357 GuiView * view = new GuiView(id);
2359 d->views_[id] = view;
2363 setActiveWindow(view);
2366 if (!geometry_arg.isEmpty()) {
2367 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2371 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2372 re.indexIn(geometry_arg);
2373 w = re.cap(1).toInt();
2374 h = re.cap(2).toInt();
2375 x = re.cap(3).toInt();
2376 y = re.cap(4).toInt();
2377 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2378 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2379 // Set initial geometry such that we can get the frame size.
2380 view->setGeometry(x, y, w, h);
2381 int framewidth = view->geometry().x() - view->x();
2382 int titleheight = view->geometry().y() - view->y();
2383 // Negative displacements must be interpreted as distances
2384 // from the right or bottom screen borders.
2385 if (sx == '-' || sy == '-') {
2386 QRect rec = QApplication::desktop()->screenGeometry();
2388 x += rec.width() - w - framewidth;
2390 y += rec.height() - h - titleheight;
2391 view->setGeometry(x, y, w, h);
2393 // Make sure that the left and top frame borders are visible.
2394 if (view->x() < 0 || view->y() < 0) {
2399 view->setGeometry(x, y, w, h);
2407 Clipboard & GuiApplication::clipboard()
2409 return d->clipboard_;
2413 Selection & GuiApplication::selection()
2415 return d->selection_;
2419 FontLoader & GuiApplication::fontLoader()
2421 return d->font_loader_;
2425 Toolbars const & GuiApplication::toolbars() const
2427 return d->toolbars_;
2431 Toolbars & GuiApplication::toolbars()
2433 return d->toolbars_;
2437 Menus const & GuiApplication::menus() const
2443 Menus & GuiApplication::menus()
2449 QList<int> GuiApplication::viewIds() const
2451 return d->views_.keys();
2455 ColorCache & GuiApplication::colorCache()
2457 return d->color_cache_;
2461 int GuiApplication::exec()
2463 // asynchronously handle batch commands. This event will be in
2464 // the event queue in front of other asynchronous events. Hence,
2465 // we can assume in the latter that the gui is setup already.
2466 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2468 return QApplication::exec();
2472 void GuiApplication::exit(int status)
2474 QApplication::exit(status);
2478 void GuiApplication::setGuiLanguage()
2482 // install translation file for Qt built-in dialogs
2483 QString const language_name = QString("qt_") + theLocale.name();
2484 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2485 // Short-named translator can be loaded from a long name, but not the
2486 // opposite. Therefore, long name should be used without truncation.
2487 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2488 if (!d->qt_trans_.load(language_name,
2489 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2490 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2493 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2497 switch (theLocale.language()) {
2498 case QLocale::Arabic :
2499 case QLocale::Hebrew :
2500 case QLocale::Persian :
2501 case QLocale::Urdu :
2502 setLayoutDirection(Qt::RightToLeft);
2505 setLayoutDirection(Qt::LeftToRight);
2510 void GuiApplication::execBatchCommands()
2515 if (!readUIFile(toqstr(lyxrc.ui_file)))
2516 // Gives some error box here.
2520 #if QT_VERSION > 0x040600
2521 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2523 #if QT_VERSION > 0x050100
2524 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2526 // Create the global default menubar which is shown for the dialogs
2527 // and if no GuiView is visible.
2528 // This must be done after the session was recovered to know the "last files".
2529 d->global_menubar_ = new QMenuBar(0);
2530 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2533 lyx::execBatchCommands();
2537 QAbstractItemModel * GuiApplication::languageModel()
2539 if (d->language_model_)
2540 return d->language_model_;
2542 QStandardItemModel * lang_model = new QStandardItemModel(this);
2543 lang_model->insertColumns(0, 3);
2544 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2545 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2546 Languages::const_iterator it = lyx::languages.begin();
2547 Languages::const_iterator end = lyx::languages.end();
2548 for (; it != end; ++it) {
2549 int current_row = lang_model->rowCount();
2550 lang_model->insertRows(current_row, 1);
2551 QModelIndex pl_item = lang_model->index(current_row, 0);
2552 QModelIndex sp_item = lang_model->index(current_row, 1);
2553 QModelIndex th_item = lang_model->index(current_row, 2);
2554 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2555 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2556 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2557 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2558 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2559 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2560 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2561 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2562 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2563 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2565 d->language_model_ = new QSortFilterProxyModel(this);
2566 d->language_model_->setSourceModel(lang_model);
2567 d->language_model_->setSortLocaleAware(true);
2568 return d->language_model_;
2572 void GuiApplication::restoreGuiSession()
2574 if (!lyxrc.load_session)
2577 Session & session = theSession();
2578 LastOpenedSection::LastOpened const & lastopened =
2579 session.lastOpened().getfiles();
2581 validateCurrentView();
2583 FileName active_file;
2584 // do not add to the lastfile list since these files are restored from
2585 // last session, and should be already there (regular files), or should
2586 // not be added at all (help files).
2587 for (size_t i = 0; i < lastopened.size(); ++i) {
2588 FileName const & file_name = lastopened[i].file_name;
2589 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2590 && current_view_->documentBufferView() != 0)) {
2591 boost::crc_32_type crc;
2592 string const & fname = file_name.absFileName();
2593 crc = for_each(fname.begin(), fname.end(), crc);
2594 createView(crc.checksum());
2596 current_view_->loadDocument(file_name, false);
2598 if (lastopened[i].active)
2599 active_file = file_name;
2602 // Restore last active buffer
2603 Buffer * buffer = theBufferList().getBuffer(active_file);
2604 if (buffer && current_view_)
2605 current_view_->setBuffer(buffer);
2607 // clear this list to save a few bytes of RAM
2608 session.lastOpened().clear();
2612 QString const GuiApplication::romanFontName()
2615 font.setStyleHint(QFont::Serif);
2616 font.setFamily("serif");
2618 return QFontInfo(font).family();
2622 QString const GuiApplication::sansFontName()
2625 font.setStyleHint(QFont::SansSerif);
2626 font.setFamily("sans");
2628 return QFontInfo(font).family();
2632 QString const GuiApplication::typewriterFontName()
2634 return QFontInfo(typewriterSystemFont()).family();
2639 // We cannot use QFont::fixedPitch() because it doesn't
2640 // return the fact but only if it is requested.
2641 static bool isFixedPitch(const QFont & font) {
2642 const QFontInfo fi(font);
2643 return fi.fixedPitch();
2648 QFont const GuiApplication::typewriterSystemFont()
2650 #if QT_VERSION >= 0x050200
2651 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2653 QFont font("monospace");
2655 if (!isFixedPitch(font)) {
2656 // try to enforce a real monospaced font
2657 font.setStyleHint(QFont::Monospace);
2658 if (!isFixedPitch(font)) {
2659 font.setStyleHint(QFont::TypeWriter);
2660 if (!isFixedPitch(font)) font.setFamily("courier");
2664 // On a Mac the result is too small and it's not practical to
2665 // rely on Qtconfig utility to change the system settings of Qt.
2666 font.setPointSize(12);
2672 void GuiApplication::handleRegularEvents()
2674 ForkedCallsController::handleCompletedProcesses();
2678 bool GuiApplication::event(QEvent * e)
2681 case QEvent::FileOpen: {
2682 // Open a file; this happens only on Mac OS X for now.
2684 // We do this asynchronously because on startup the batch
2685 // commands are not executed here yet and the gui is not ready
2687 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2688 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2689 processFuncRequestAsync(fr);
2694 return QApplication::event(e);
2699 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2702 return QApplication::notify(receiver, event);
2704 catch (ExceptionMessage const & e) {
2706 case ErrorException:
2708 setQuitOnLastWindowClosed(false);
2710 Alert::error(e.title_, e.details_);
2712 // Properly crash in debug mode in order to get a useful backtrace.
2715 // In release mode, try to exit gracefully.
2718 case BufferException: {
2719 if (!current_view_ || !current_view_->documentBufferView())
2721 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2722 docstring details = e.details_ + '\n';
2723 details += buf->emergencyWrite();
2724 theBufferList().release(buf);
2725 details += "\n" + _("The current document was closed.");
2726 Alert::error(e.title_, details);
2729 case WarningException:
2730 Alert::warning(e.title_, e.details_);
2734 catch (exception const & e) {
2735 docstring s = _("LyX has caught an exception, it will now "
2736 "attempt to save all unsaved documents and exit."
2738 s += from_ascii(e.what());
2739 Alert::error(_("Software exception Detected"), s);
2743 docstring s = _("LyX has caught some really weird exception, it will "
2744 "now attempt to save all unsaved documents and exit.");
2745 Alert::error(_("Software exception Detected"), s);
2753 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2755 QColor const & qcol = d->color_cache_.get(col);
2756 if (!qcol.isValid()) {
2762 rgbcol.r = qcol.red();
2763 rgbcol.g = qcol.green();
2764 rgbcol.b = qcol.blue();
2769 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2771 QColor const qcol(lcolor.getX11Name(col).c_str());
2772 if (!qcol.isValid()) {
2778 rgbcol.r = qcol.red();
2779 rgbcol.g = qcol.green();
2780 rgbcol.b = qcol.blue();
2785 string const GuiApplication::hexName(ColorCode col)
2787 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2791 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2793 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2794 d->socket_notifiers_[fd] = sn;
2795 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2799 void GuiApplication::socketDataReceived(int fd)
2801 d->socket_notifiers_[fd]->func_();
2805 void GuiApplication::unregisterSocketCallback(int fd)
2807 d->socket_notifiers_.take(fd)->setEnabled(false);
2811 void GuiApplication::commitData(QSessionManager & sm)
2813 /** The implementation is required to avoid an application exit
2814 ** when session state save is triggered by session manager.
2815 ** The default implementation sends a close event to all
2816 ** visible top level widgets when session managment allows
2818 ** We are changing that to check the state of each buffer in all
2819 ** views and ask the users what to do if buffers are dirty.
2820 ** Furthermore, we save the session state.
2821 ** We do NOT close the views here since the user still can cancel
2822 ** the logout process (see #9277); also, this would hide LyX from
2823 ** an OSes own session handling (application restoration).
2825 #ifdef QT_NO_SESSIONMANAGER
2827 #warning Qt is compiled without session manager
2829 #pragma message("warning: Qt is compiled without session manager")
2833 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2841 void GuiApplication::unregisterView(GuiView * gv)
2843 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2844 d->views_.remove(gv->id());
2845 if (current_view_ == gv)
2851 bool GuiApplication::closeAllViews()
2853 if (d->views_.empty())
2856 // When a view/window was closed before without quitting LyX, there
2857 // are already entries in the lastOpened list.
2858 theSession().lastOpened().clear();
2860 QList<GuiView *> const views = d->views_.values();
2861 for (GuiView * view : views) {
2862 if (!view->closeScheduled())
2871 bool GuiApplication::prepareAllViewsForLogout()
2873 if (d->views_.empty())
2876 QList<GuiView *> const views = d->views_.values();
2877 for (GuiView * view : views) {
2878 if (!view->prepareAllBuffersForLogout())
2886 GuiView & GuiApplication::view(int id) const
2888 LAPPERR(d->views_.contains(id));
2889 return *d->views_.value(id);
2893 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2895 QList<GuiView *> const views = d->views_.values();
2896 for (GuiView * view : views)
2897 view->hideDialog(name, inset);
2901 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2903 Buffer const * buffer_ = 0;
2904 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2905 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2906 if (Buffer const * ptr = (*it)->updateInset(inset))
2913 bool GuiApplication::searchMenu(FuncRequest const & func,
2914 docstring_list & names) const
2916 return d->menus_.searchMenu(func, names);
2920 // Ensure that a file is read only once (prevents include loops)
2921 static QStringList uifiles;
2922 // store which ui files define Toolbars
2923 static QStringList toolbar_uifiles;
2926 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2937 LexerKeyword uitags[] = {
2938 { "format", ui_format },
2939 { "include", ui_include },
2940 { "menuset", ui_menuset },
2941 { "toolbars", ui_toolbars },
2942 { "toolbarset", ui_toolbarset }
2946 lex.setFile(ui_path);
2948 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2952 if (lyxerr.debugging(Debug::PARSER))
2953 lex.printTable(lyxerr);
2956 // format before introduction of format tag
2957 unsigned int format = 0;
2958 while (lex.isOK()) {
2959 int const status = lex.lex();
2961 // we have to do this check here, outside the switch,
2962 // because otherwise we would start reading include files,
2963 // e.g., if the first tag we hit was an include tag.
2964 if (status == ui_format)
2966 format = lex.getInteger();
2970 // this will trigger unless the first tag we hit is a format
2971 // tag, with the right format.
2972 if (format != LFUN_FORMAT)
2973 return FormatMismatch;
2976 case Lexer::LEX_FEOF:
2981 QString const file = toqstr(lex.getString());
2982 bool const success = readUIFile(file, true);
2984 LYXERR0("Failed to read included file: " << fromqstr(file));
2991 d->menus_.read(lex);
2995 d->toolbars_.readToolbars(lex);
2999 d->toolbars_.readToolbarSettings(lex);
3000 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3004 if (!rtrim(lex.getString()).empty())
3005 lex.printError("LyX::ReadUIFile: "
3006 "Unknown menu tag: `$$Token'");
3008 LYXERR0("Error with status: " << status);
3014 return (error ? ReadError : ReadOK);
3018 bool GuiApplication::readUIFile(QString const & name, bool include)
3020 LYXERR(Debug::INIT, "About to read " << name << "...");
3024 ui_path = libFileSearch("ui", name, "inc");
3025 if (ui_path.empty())
3026 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3028 ui_path = libFileSearch("ui", name, "ui");
3031 if (ui_path.empty()) {
3032 static const QString defaultUIFile = "default";
3033 LYXERR(Debug::INIT, "Could not find " << name);
3035 Alert::warning(_("Could not find UI definition file"),
3036 bformat(_("Error while reading the included file\n%1$s\n"
3037 "Please check your installation."), qstring_to_ucs4(name)));
3040 if (name == defaultUIFile) {
3041 LYXERR(Debug::INIT, "Could not find default UI file!!");
3042 Alert::warning(_("Could not find default UI file"),
3043 _("LyX could not find the default UI file!\n"
3044 "Please check your installation."));
3047 Alert::warning(_("Could not find UI definition file"),
3048 bformat(_("Error while reading the configuration file\n%1$s\n"
3049 "Falling back to default.\n"
3050 "Please look under Tools>Preferences>User Interface and\n"
3051 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3052 return readUIFile(defaultUIFile, false);
3055 QString const uifile = toqstr(ui_path.absFileName());
3056 if (uifiles.contains(uifile)) {
3058 // We are reading again the top uifile so reset the safeguard:
3061 d->toolbars_.reset();
3063 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3064 << "Is this an include loop?");
3068 uifiles.push_back(uifile);
3070 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3072 ReturnValues retval = readUIFile(ui_path);
3074 if (retval == FormatMismatch) {
3075 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3076 TempFile tmp("convertXXXXXX.ui");
3077 FileName const tempfile = tmp.name();
3078 bool const success = prefs2prefs(ui_path, tempfile, true);
3080 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3081 " to format " << LFUN_FORMAT << ".");
3083 retval = readUIFile(tempfile);
3087 if (retval != ReadOK) {
3088 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3096 settings.beginGroup("ui_files");
3097 bool touched = false;
3098 for (int i = 0; i != uifiles.size(); ++i) {
3099 QFileInfo fi(uifiles[i]);
3100 QDateTime const date_value = fi.lastModified();
3101 QString const name_key = QString::number(i);
3102 // if an ui file which defines Toolbars has changed,
3103 // we have to reset the settings
3104 if (toolbar_uifiles.contains(uifiles[i])
3105 && (!settings.contains(name_key)
3106 || settings.value(name_key).toString() != uifiles[i]
3107 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3109 settings.setValue(name_key, uifiles[i]);
3110 settings.setValue(name_key + "/date", date_value);
3113 settings.endGroup();
3115 settings.remove("views");
3121 void GuiApplication::onLastWindowClosed()
3123 if (d->global_menubar_)
3124 d->global_menubar_->grabKeyboard();
3128 void GuiApplication::startLongOperation() {
3129 d->key_checker_.start();
3133 bool GuiApplication::longOperationCancelled() {
3134 return d->key_checker_.pressed();
3138 void GuiApplication::stopLongOperation() {
3139 d->key_checker_.stop();
3143 bool GuiApplication::longOperationStarted() {
3144 return d->key_checker_.started();
3148 ////////////////////////////////////////////////////////////////////////
3150 // X11 specific stuff goes here...
3153 bool GuiApplication::x11EventFilter(XEvent * xev)
3158 switch (xev->type) {
3159 case SelectionRequest: {
3160 if (xev->xselectionrequest.selection != XA_PRIMARY)
3162 LYXERR(Debug::SELECTION, "X requested selection.");
3163 BufferView * bv = current_view_->currentBufferView();
3165 docstring const sel = bv->requestSelection();
3167 d->selection_.put(sel);
3168 // Refresh the selection request timestamp.
3169 // We have to do this by ourselves as Qt seems
3170 // not doing that, maybe because of our
3171 // "persistent selection" implementation
3172 // (see comments in GuiSelection.cpp).
3173 XSelectionEvent nev;
3174 nev.type = SelectionNotify;
3175 nev.display = xev->xselectionrequest.display;
3176 nev.requestor = xev->xselectionrequest.requestor;
3177 nev.selection = xev->xselectionrequest.selection;
3178 nev.target = xev->xselectionrequest.target;
3179 nev.property = 0L; // None
3180 nev.time = CurrentTime;
3181 XSendEvent(QX11Info::display(),
3182 nev.requestor, False, 0,
3183 reinterpret_cast<XEvent *>(&nev));
3189 case SelectionClear: {
3190 if (xev->xselectionclear.selection != XA_PRIMARY)
3192 LYXERR(Debug::SELECTION, "Lost selection.");
3193 BufferView * bv = current_view_->currentBufferView();
3195 bv->clearSelection();
3201 #elif defined(QPA_XCB)
3202 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3203 void * message, long *)
3205 if (!current_view_ || eventType != "xcb_generic_event_t")
3208 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3210 switch (ev->response_type) {
3211 case XCB_SELECTION_REQUEST: {
3212 xcb_selection_request_event_t * srev =
3213 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3214 if (srev->selection != XCB_ATOM_PRIMARY)
3216 LYXERR(Debug::SELECTION, "X requested selection.");
3217 BufferView * bv = current_view_->currentBufferView();
3219 docstring const sel = bv->requestSelection();
3221 d->selection_.put(sel);
3222 #ifdef HAVE_QT5_X11_EXTRAS
3223 // Refresh the selection request timestamp.
3224 // We have to do this by ourselves as Qt seems
3225 // not doing that, maybe because of our
3226 // "persistent selection" implementation
3227 // (see comments in GuiSelection.cpp).
3228 xcb_selection_notify_event_t nev;
3229 nev.response_type = XCB_SELECTION_NOTIFY;
3230 nev.requestor = srev->requestor;
3231 nev.selection = srev->selection;
3232 nev.target = srev->target;
3233 nev.property = XCB_NONE;
3234 nev.time = XCB_CURRENT_TIME;
3235 xcb_connection_t * con = QX11Info::connection();
3236 xcb_send_event(con, 0, srev->requestor,
3237 XCB_EVENT_MASK_NO_EVENT,
3238 reinterpret_cast<char const *>(&nev));
3246 case XCB_SELECTION_CLEAR: {
3247 xcb_selection_clear_event_t * scev =
3248 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3249 if (scev->selection != XCB_ATOM_PRIMARY)
3251 LYXERR(Debug::SELECTION, "Lost selection.");
3252 BufferView * bv = current_view_->currentBufferView();
3254 bv->clearSelection();
3262 } // namespace frontend
3265 void hideDialogs(std::string const & name, Inset * inset)
3268 frontend::guiApp->hideDialogs(name, inset);
3272 ////////////////////////////////////////////////////////////////////
3276 ////////////////////////////////////////////////////////////////////
3278 frontend::FontLoader & theFontLoader()
3280 LAPPERR(frontend::guiApp);
3281 return frontend::guiApp->fontLoader();
3285 frontend::FontMetrics const & theFontMetrics(Font const & f)
3287 return theFontMetrics(f.fontInfo());
3291 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3293 LAPPERR(frontend::guiApp);
3294 return frontend::guiApp->fontLoader().metrics(f);
3298 ////////////////////////////////////////////////////////////////////
3302 ////////////////////////////////////////////////////////////////////
3304 frontend::Clipboard & theClipboard()
3306 LAPPERR(frontend::guiApp);
3307 return frontend::guiApp->clipboard();
3311 frontend::Selection & theSelection()
3313 LAPPERR(frontend::guiApp);
3314 return frontend::guiApp->selection();
3320 #include "moc_GuiApplication.cpp"