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);
1021 qsrand(QDateTime::currentDateTime().toTime_t());
1023 // Install translator for GUI elements.
1024 installTranslator(&d->qt_trans_);
1027 // Enable reception of XCB events.
1028 installNativeEventFilter(this);
1031 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1032 // lyxrc setting for this in order to let the application stay resident.
1033 // But then we need some kind of dock icon, at least on Windows.
1035 if (lyxrc.quit_on_last_window_closed)
1036 setQuitOnLastWindowClosed(false);
1039 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1040 // seems to be the default case for applications like LyX.
1041 setQuitOnLastWindowClosed(false);
1042 // This allows to translate the strings that appear in the LyX menu.
1043 /// A translator suitable for the entries in the LyX menu.
1044 /// Only needed with Qt/Mac.
1045 installTranslator(new MenuTranslator(this));
1050 #if defined(Q_WS_X11) || defined(QPA_XCB)
1051 // doubleClickInterval() is 400 ms on X11 which is just too long.
1052 // On Windows and Mac OS X, the operating system's value is used.
1053 // On Microsoft Windows, calling this function sets the double
1054 // click interval for all applications. So we don't!
1055 QApplication::setDoubleClickInterval(300);
1058 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1060 // needs to be done before reading lyxrc
1062 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1066 // Set the cache to 5120 kilobytes which corresponds to screen size of
1067 // 1280 by 1024 pixels with a color depth of 32 bits.
1068 QPixmapCache::setCacheLimit(5120);
1070 // Initialize RC Fonts
1071 if (lyxrc.roman_font_name.empty())
1072 lyxrc.roman_font_name = fromqstr(romanFontName());
1074 if (lyxrc.sans_font_name.empty())
1075 lyxrc.sans_font_name = fromqstr(sansFontName());
1077 if (lyxrc.typewriter_font_name.empty())
1078 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1080 d->general_timer_.setInterval(500);
1081 connect(&d->general_timer_, SIGNAL(timeout()),
1082 this, SLOT(handleRegularEvents()));
1083 d->general_timer_.start();
1085 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1086 // This is clearly not enough in a time where we use threads for
1087 // document preview and/or export. 20 should be OK.
1088 QThreadPool::globalInstance()->setMaxThreadCount(20);
1090 // make sure tooltips are formatted
1091 installEventFilter(new ToolTipFormatter(this));
1095 GuiApplication * theGuiApp()
1097 return dynamic_cast<GuiApplication *>(theApp());
1101 double GuiApplication::pixelRatio() const
1103 #if QT_VERSION >= 0x050000
1104 return devicePixelRatio();
1111 void GuiApplication::clearSession()
1118 docstring Application::iconName(FuncRequest const & f, bool unknown)
1120 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1124 docstring Application::mathIcon(docstring const & c)
1126 return qstring_to_ucs4(findImg(toqstr(c)));
1130 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1134 BufferView * bv = 0;
1135 BufferView * doc_bv = 0;
1137 if (cmd.action() == LFUN_NOACTION) {
1138 status.message(from_utf8(N_("Nothing to do")));
1139 status.setEnabled(false);
1142 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1143 status.setUnknown(true);
1144 status.message(from_utf8(N_("Unknown action")));
1145 status.setEnabled(false);
1148 // Does the GuiApplication know something?
1149 else if (getStatus(cmd, status)) { }
1151 // If we do not have a GuiView, then other functions are disabled
1152 else if (!current_view_)
1153 status.setEnabled(false);
1155 // Does the GuiView know something?
1156 else if (current_view_->getStatus(cmd, status)) { }
1158 // In LyX/Mac, when a dialog is open, the menus of the
1159 // application can still be accessed without giving focus to
1160 // the main window. In this case, we want to disable the menu
1161 // entries that are buffer or view-related.
1162 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1164 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1165 status.setEnabled(false);
1168 // If we do not have a BufferView, then other functions are disabled
1169 else if (!(bv = current_view_->currentBufferView()))
1170 status.setEnabled(false);
1172 // Does the current BufferView know something?
1173 else if (bv->getStatus(cmd, status)) { }
1175 // Does the current Buffer know something?
1176 else if (bv->buffer().getStatus(cmd, status)) { }
1178 // If we do not have a document BufferView, different from the
1179 // current BufferView, then other functions are disabled
1180 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1181 status.setEnabled(false);
1183 // Does the document Buffer know something?
1184 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1187 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1188 status.message(from_utf8(N_("Command not handled")));
1189 status.setEnabled(false);
1192 // the default error message if we disable the command
1193 if (!status.enabled() && status.message().empty())
1194 status.message(from_utf8(N_("Command disabled")));
1200 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1202 // I would really like to avoid having this switch and rather try to
1203 // encode this in the function itself.
1204 // -- And I'd rather let an inset decide which LFUNs it is willing
1205 // to handle (Andre')
1207 switch (cmd.action()) {
1209 // This could be used for the no-GUI version. The GUI version is handled in
1210 // GuiView::getStatus(). See above.
1212 case LFUN_BUFFER_WRITE:
1213 case LFUN_BUFFER_WRITE_AS: {
1214 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1215 enable = b && (b->isUnnamed() || !b->isClean());
1220 case LFUN_BOOKMARK_GOTO: {
1221 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1222 enable = theSession().bookmarks().isValid(num);
1226 case LFUN_BOOKMARK_CLEAR:
1227 enable = theSession().bookmarks().hasValid();
1230 // this one is difficult to get right. As a half-baked
1231 // solution, we consider only the first action of the sequence
1232 case LFUN_COMMAND_SEQUENCE: {
1233 // argument contains ';'-terminated commands
1234 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1235 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1236 func.setOrigin(cmd.origin());
1237 flag = getStatus(func);
1241 // we want to check if at least one of these is enabled
1242 case LFUN_COMMAND_ALTERNATIVES: {
1243 // argument contains ';'-terminated commands
1244 string arg = to_utf8(cmd.argument());
1245 while (!arg.empty()) {
1247 arg = split(arg, first, ';');
1248 FuncRequest func(lyxaction.lookupFunc(first));
1249 func.setOrigin(cmd.origin());
1250 flag = getStatus(func);
1251 // if this one is enabled, the whole thing is
1260 string name = to_utf8(cmd.argument());
1261 if (theTopLevelCmdDef().lock(name, func)) {
1262 func.setOrigin(cmd.origin());
1263 flag = getStatus(func);
1264 theTopLevelCmdDef().release(name);
1266 // catch recursion or unknown command
1267 // definition. all operations until the
1268 // recursion or unknown command definition
1269 // occurs are performed, so set the state to
1276 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1278 case LFUN_PREFERENCES_SAVE:
1279 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1280 case LFUN_DEBUG_LEVEL_SET:
1281 // these are handled in our dispatch()
1284 case LFUN_WINDOW_CLOSE:
1285 enable = d->views_.size() > 0;
1288 case LFUN_BUFFER_NEW:
1289 case LFUN_BUFFER_NEW_TEMPLATE:
1290 case LFUN_FILE_OPEN:
1291 case LFUN_HELP_OPEN:
1292 case LFUN_SCREEN_FONT_UPDATE:
1293 case LFUN_SET_COLOR:
1294 case LFUN_WINDOW_NEW:
1296 case LFUN_LYXRC_APPLY:
1297 case LFUN_COMMAND_PREFIX:
1299 case LFUN_META_PREFIX:
1300 case LFUN_RECONFIGURE:
1301 case LFUN_SERVER_GET_FILENAME:
1302 case LFUN_SERVER_NOTIFY:
1306 case LFUN_BUFFER_FORALL: {
1307 if (theBufferList().empty()) {
1308 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1309 flag.setEnabled(false);
1313 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1314 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1315 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1316 flag.setEnabled(false);
1321 case LFUN_DIALOG_SHOW: {
1322 string const name = cmd.getArg(0);
1323 return name == "aboutlyx"
1325 || name == "texinfo"
1326 || name == "progress"
1327 || name == "compare";
1335 flag.setEnabled(false);
1339 /// make a post-dispatch status message
1340 static docstring makeDispatchMessage(docstring const & msg,
1341 FuncRequest const & cmd)
1343 const bool verbose = (cmd.origin() == FuncRequest::MENU
1344 || cmd.origin() == FuncRequest::TOOLBAR
1345 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1347 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1348 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1352 docstring dispatch_msg = msg;
1353 if (!dispatch_msg.empty())
1354 dispatch_msg += ' ';
1356 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1358 bool argsadded = false;
1360 if (!cmd.argument().empty()) {
1361 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1362 comname += ' ' + cmd.argument();
1366 docstring const shortcuts = theTopLevelKeymap().
1367 printBindings(cmd, KeySequence::ForGui);
1369 if (!shortcuts.empty())
1370 comname += ": " + shortcuts;
1371 else if (!argsadded && !cmd.argument().empty())
1372 comname += ' ' + cmd.argument();
1374 if (!comname.empty()) {
1375 comname = rtrim(comname);
1376 dispatch_msg += '(' + rtrim(comname) + ')';
1378 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1379 return dispatch_msg;
1383 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1385 Buffer * buffer = 0;
1386 if (current_view_ && current_view_->currentBufferView()) {
1387 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1388 buffer = ¤t_view_->currentBufferView()->buffer();
1390 buffer->undo().beginUndoGroup();
1394 // redraw the screen at the end (first of the two drawing steps).
1395 // This is done unless explicitly requested otherwise
1396 dr.screenUpdate(Update::FitCursor);
1398 updateCurrentView(cmd, dr);
1400 // the buffer may have been closed by one action
1401 if (theBufferList().isLoaded(buffer))
1402 buffer->undo().endUndoGroup();
1404 d->dispatch_result_ = dr;
1405 return d->dispatch_result_;
1409 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1414 BufferView * bv = current_view_->currentBufferView();
1416 if (dr.needBufferUpdate()) {
1417 bv->cursor().clearBufferUpdate();
1418 bv->buffer().updateBuffer();
1419 } else if (dr.needChangesUpdate()) {
1420 // updateBuffer() already updates the change-tracking presence flag
1421 bv->buffer().updateChangesPresent();
1423 // BufferView::update() updates the ViewMetricsInfo and
1424 // also initializes the position cache for all insets in
1425 // (at least partially) visible top-level paragraphs.
1426 // We will redraw the screen only if needed.
1427 bv->processUpdateFlags(dr.screenUpdate());
1429 // Do we have a selection?
1430 theSelection().haveSelection(bv->cursor().selection());
1433 current_view_->restartCursor();
1435 if (dr.needMessageUpdate()) {
1436 // Some messages may already be translated, so we cannot use _()
1437 current_view_->message(makeDispatchMessage(
1438 translateIfPossible(dr.message()), cmd));
1443 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1444 bool switchToBuffer)
1446 if (!theSession().bookmarks().isValid(idx))
1448 BookmarksSection::Bookmark const & bm =
1449 theSession().bookmarks().bookmark(idx);
1450 LASSERT(!bm.filename.empty(), return);
1451 string const file = bm.filename.absFileName();
1452 // if the file is not opened, open it.
1453 if (!theBufferList().exists(bm.filename)) {
1455 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1459 // open may fail, so we need to test it again
1460 if (!theBufferList().exists(bm.filename))
1463 // bm can be changed when saving
1464 BookmarksSection::Bookmark tmp = bm;
1466 // Special case idx == 0 used for back-from-back jump navigation
1468 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1470 // if the current buffer is not that one, switch to it.
1471 BufferView * doc_bv = current_view_ ?
1472 current_view_->documentBufferView() : 0;
1473 // FIXME It's possible that doc_bv is null!!
1474 // See coverity #102061
1475 Cursor const old = doc_bv->cursor();
1476 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1477 if (switchToBuffer) {
1478 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1481 doc_bv = current_view_->documentBufferView();
1486 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1487 if (!doc_bv->moveToPosition(
1488 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1491 Cursor & cur = doc_bv->cursor();
1493 notifyCursorLeavesOrEnters(old, cur);
1499 // Cursor jump succeeded!
1500 pit_type new_pit = cur.pit();
1501 pos_type new_pos = cur.pos();
1502 int new_id = cur.paragraph().id();
1504 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1505 // see http://www.lyx.org/trac/ticket/3092
1506 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1507 || bm.top_id != new_id) {
1508 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1509 new_pit, new_pos, new_id);
1513 // This function runs "configure" and then rereads lyx.defaults to
1514 // reconfigure the automatic settings.
1515 void GuiApplication::reconfigure(string const & option)
1517 // emit message signal.
1519 current_view_->message(_("Running configure..."));
1521 // Run configure in user lyx directory
1522 string const lock_file = package().getConfigureLockName();
1523 int fd = fileLock(lock_file.c_str());
1524 int const ret = package().reconfigureUserLyXDir(option);
1525 // emit message signal.
1527 current_view_->message(_("Reloading configuration..."));
1528 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1529 // Re-read packages.lst
1530 LaTeXPackages::getAvailable();
1531 fileUnlock(fd, lock_file.c_str());
1534 Alert::information(_("System reconfiguration failed"),
1535 _("The system reconfiguration has failed.\n"
1536 "Default textclass is used but LyX may\n"
1537 "not be able to work properly.\n"
1538 "Please reconfigure again if needed."));
1540 Alert::information(_("System reconfigured"),
1541 _("The system has been reconfigured.\n"
1542 "You need to restart LyX to make use of any\n"
1543 "updated document class specifications."));
1546 void GuiApplication::validateCurrentView()
1548 if (!d->views_.empty() && !current_view_) {
1549 // currently at least one view exists but no view has the focus.
1550 // choose the last view to make it current.
1551 // a view without any open document is preferred.
1552 GuiView * candidate = 0;
1553 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1554 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1555 for (; it != end; ++it) {
1557 if (!candidate->documentBufferView())
1560 setCurrentView(candidate);
1564 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1566 string const argument = to_utf8(cmd.argument());
1567 FuncCode const action = cmd.action();
1569 LYXERR(Debug::ACTION, "cmd: " << cmd);
1571 // we have not done anything wrong yet.
1574 FuncStatus const flag = getStatus(cmd);
1575 if (!flag.enabled()) {
1576 // We cannot use this function here
1577 LYXERR(Debug::ACTION, "action "
1578 << lyxaction.getActionName(action)
1579 << " [" << action << "] is disabled at this location");
1580 dr.setMessage(flag.message());
1582 dr.dispatched(false);
1583 dr.screenUpdate(Update::None);
1584 dr.clearBufferUpdate();
1588 if (cmd.origin() == FuncRequest::LYXSERVER) {
1589 if (current_view_ && current_view_->currentBufferView())
1590 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1591 // we will also need to redraw the screen at the end
1592 dr.screenUpdate(Update::FitCursor);
1595 // Assumes that the action will be dispatched.
1596 dr.dispatched(true);
1598 switch (cmd.action()) {
1600 case LFUN_WINDOW_NEW:
1601 createView(toqstr(cmd.argument()));
1604 case LFUN_WINDOW_CLOSE:
1605 // update bookmark pit of the current buffer before window close
1606 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1607 gotoBookmark(i+1, false, false);
1608 // clear the last opened list, because
1609 // maybe this will end the session
1610 theSession().lastOpened().clear();
1611 // check for valid current_view_
1612 validateCurrentView();
1614 current_view_->closeScheduled();
1618 // quitting is triggered by the gui code
1619 // (leaving the event loop).
1621 current_view_->message(from_utf8(N_("Exiting.")));
1622 if (closeAllViews())
1626 case LFUN_SCREEN_FONT_UPDATE: {
1627 // handle the screen font changes.
1628 d->font_loader_.update();
1629 // Backup current_view_
1630 GuiView * view = current_view_;
1631 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1632 // to skip the refresh.
1634 theBufferList().changed(false);
1635 // Restore current_view_
1636 current_view_ = view;
1640 case LFUN_BUFFER_NEW:
1641 validateCurrentView();
1642 if (d->views_.empty()
1643 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1644 createView(QString(), false); // keep hidden
1645 current_view_->newDocument(to_utf8(cmd.argument()), false);
1646 current_view_->show();
1647 setActiveWindow(current_view_);
1649 current_view_->newDocument(to_utf8(cmd.argument()), false);
1653 case LFUN_BUFFER_NEW_TEMPLATE:
1654 validateCurrentView();
1655 if (d->views_.empty()
1656 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1658 current_view_->newDocument(to_utf8(cmd.argument()), true);
1659 if (!current_view_->documentBufferView())
1660 current_view_->close();
1662 current_view_->newDocument(to_utf8(cmd.argument()), true);
1666 case LFUN_FILE_OPEN: {
1667 validateCurrentView();
1668 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1669 string const fname = to_utf8(cmd.argument());
1670 bool const is_open = FileName::isAbsolute(fname)
1671 && theBufferList().getBuffer(FileName(fname));
1672 if (d->views_.empty()
1673 || (!lyxrc.open_buffers_in_tabs
1674 && current_view_->documentBufferView() != 0
1676 // We want the ui session to be saved per document and not per
1677 // window number. The filename crc is a good enough identifier.
1678 boost::crc_32_type crc;
1679 crc = for_each(fname.begin(), fname.end(), crc);
1680 createView(crc.checksum());
1681 // we know current_view_ is non-null, because createView sets it.
1682 // but let's make sure
1683 LASSERT(current_view_, break);
1684 current_view_->openDocument(fname);
1685 if (!current_view_->documentBufferView())
1686 current_view_->close();
1687 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1688 current_view_->raise();
1689 current_view_->activateWindow();
1690 current_view_->showNormal();
1693 // we know !d->views.empty(), so this should be ok
1694 // but let's make sure
1695 LASSERT(current_view_, break);
1696 current_view_->openDocument(fname);
1697 if (cmd.origin() == FuncRequest::LYXSERVER) {
1698 current_view_->raise();
1699 current_view_->activateWindow();
1700 current_view_->showNormal();
1706 case LFUN_HELP_OPEN: {
1707 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1708 if (current_view_ == 0)
1710 string const arg = to_utf8(cmd.argument());
1712 current_view_->message(_("Missing argument"));
1715 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1717 fname = i18nLibFileSearch("examples", arg, "lyx");
1719 if (fname.empty()) {
1720 lyxerr << "LyX: unable to find documentation file `"
1721 << arg << "'. Bad installation?" << endl;
1724 current_view_->message(bformat(_("Opening help file %1$s..."),
1725 makeDisplayPath(fname.absFileName())));
1726 Buffer * buf = current_view_->loadDocument(fname, false);
1728 #ifndef DEVEL_VERSION
1730 buf->setReadonly(true);
1737 case LFUN_SET_COLOR: {
1739 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1740 if (lyx_name.empty() || x11_name.empty()) {
1742 current_view_->message(
1743 _("Syntax: set-color <lyx_name> <x11_name>"));
1748 // FIXME: The graphics cache no longer has a changeDisplay method.
1749 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1750 bool const graphicsbg_changed =
1751 lyx_name == graphicsbg && x11_name != graphicsbg;
1752 if (graphicsbg_changed)
1753 graphics::GCache::get().changeDisplay(true);
1756 if (!lcolor.setColor(lyx_name, x11_name)) {
1758 current_view_->message(
1759 bformat(_("Set-color \"%1$s\" failed "
1760 "- color is undefined or "
1761 "may not be redefined"),
1762 from_utf8(lyx_name)));
1765 // Make sure we don't keep old colors in cache.
1766 d->color_cache_.clear();
1767 // Update the current view
1768 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1772 case LFUN_LYXRC_APPLY: {
1773 // reset active key sequences, since the bindings
1774 // are updated (bug 6064)
1776 LyXRC const lyxrc_orig = lyxrc;
1778 istringstream ss(to_utf8(cmd.argument()));
1779 bool const success = lyxrc.read(ss);
1782 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1783 << "Unable to read lyxrc data"
1788 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1790 // If the request comes from the minibuffer, then we can't reset
1791 // the GUI, since that would destory the minibuffer itself and
1792 // cause a crash, since we are currently in one of the methods of
1793 // GuiCommandBuffer. See bug #8540.
1794 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1797 // FIXME Unfortunately, that leaves a bug here, since we cannot
1798 // reset the GUI in this case. If the changes to lyxrc affected the
1799 // UI, then, nothing would happen. This seems fairly unlikely, but
1800 // it definitely is a bug.
1805 case LFUN_COMMAND_PREFIX:
1806 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1811 d->meta_fake_bit = NoModifier;
1812 GuiView * gv = currentView();
1813 if (gv && gv->currentBufferView())
1814 // cancel any selection
1815 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1816 dr.setMessage(from_ascii(N_("Cancel")));
1819 case LFUN_META_PREFIX:
1820 d->meta_fake_bit = AltModifier;
1821 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1824 // --- Menus -----------------------------------------------
1825 case LFUN_RECONFIGURE:
1826 // argument is any additional parameter to the configure.py command
1827 reconfigure(to_utf8(cmd.argument()));
1830 // --- lyxserver commands ----------------------------
1831 case LFUN_SERVER_GET_FILENAME: {
1832 if (current_view_ && current_view_->documentBufferView()) {
1833 docstring const fname = from_utf8(
1834 current_view_->documentBufferView()->buffer().absFileName());
1835 dr.setMessage(fname);
1836 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1838 dr.setMessage(docstring());
1839 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1844 case LFUN_SERVER_NOTIFY: {
1845 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1846 dr.setMessage(dispatch_buffer);
1847 theServer().notifyClient(to_utf8(dispatch_buffer));
1851 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1852 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1858 string rest = split(argument, countstr, ' ');
1859 istringstream is(countstr);
1862 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1863 for (int i = 0; i < count; ++i)
1864 dispatch(lyxaction.lookupFunc(rest));
1868 case LFUN_COMMAND_SEQUENCE: {
1869 // argument contains ';'-terminated commands
1870 string arg = argument;
1871 // FIXME: this LFUN should also work without any view.
1872 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1873 ? &(current_view_->documentBufferView()->buffer()) : 0;
1875 buffer->undo().beginUndoGroup();
1876 while (!arg.empty()) {
1878 arg = split(arg, first, ';');
1879 FuncRequest func(lyxaction.lookupFunc(first));
1880 func.setOrigin(cmd.origin());
1883 // the buffer may have been closed by one action
1884 if (theBufferList().isLoaded(buffer))
1885 buffer->undo().endUndoGroup();
1889 case LFUN_BUFFER_FORALL: {
1890 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1892 map<Buffer *, GuiView *> views_lVisible;
1893 map<GuiView *, Buffer *> activeBuffers;
1895 QList<GuiView *> allViews = d->views_.values();
1897 // this for does not modify any buffer. It just collects info on local
1898 // visibility of buffers and on which buffer is active in each view.
1899 Buffer * const last = theBufferList().last();
1900 for(GuiView * view : allViews) {
1901 // all of the buffers might be locally hidden. That is, there is no
1903 if (!view || !view->currentBufferView())
1904 activeBuffers[view] = 0;
1906 activeBuffers[view] = &view->currentBufferView()->buffer();
1908 // find out if each is locally visible or locally hidden.
1909 // we don't use a for loop as the buffer list cycles.
1910 Buffer * b = theBufferList().first();
1912 bool const locallyVisible = view && view->workArea(*b);
1913 if (locallyVisible) {
1914 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1915 // only need to overwrite/add if we don't already know a buffer is globally
1916 // visible or we do know but we would prefer to dispatch LFUN from the
1917 // current view because of cursor position issues.
1918 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1919 views_lVisible[b] = view;
1923 b = theBufferList().next(b);
1927 GuiView * const homeView = currentView();
1928 Buffer * b = theBufferList().first();
1929 Buffer * nextBuf = 0;
1930 int numProcessed = 0;
1933 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1935 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1937 // first change to a view where b is locally visible, preferably current_view_.
1938 GuiView * const vLv = views_lVisible[b];
1940 lyx::dispatch(funcToRun);
1948 // put things back to how they were (if possible).
1949 for (GuiView * view : allViews) {
1950 Buffer * originalBuf = activeBuffers[view];
1951 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1952 if (theBufferList().isLoaded(originalBuf))
1953 view->setBuffer(originalBuf);
1955 homeView->setFocus();
1957 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1961 case LFUN_COMMAND_ALTERNATIVES: {
1962 // argument contains ';'-terminated commands
1963 string arg = argument;
1964 while (!arg.empty()) {
1966 arg = split(arg, first, ';');
1967 FuncRequest func(lyxaction.lookupFunc(first));
1968 func.setOrigin(cmd.origin());
1969 FuncStatus const stat = getStatus(func);
1970 if (stat.enabled()) {
1980 if (theTopLevelCmdDef().lock(argument, func)) {
1981 func.setOrigin(cmd.origin());
1983 theTopLevelCmdDef().release(argument);
1985 if (func.action() == LFUN_UNKNOWN_ACTION) {
1986 // unknown command definition
1987 lyxerr << "Warning: unknown command definition `"
1991 // recursion detected
1992 lyxerr << "Warning: Recursion in the command definition `"
1993 << argument << "' detected"
2000 case LFUN_PREFERENCES_SAVE:
2001 lyxrc.write(support::makeAbsPath("preferences",
2002 package().user_support().absFileName()), false);
2005 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2006 string const fname = addName(addPath(package().user_support().absFileName(),
2007 "templates/"), "defaults.lyx");
2008 Buffer defaults(fname);
2010 istringstream ss(argument);
2015 // We need to make sure that, after we recreat the DocumentClass,
2016 // which we do in readHeader, we apply it to the document itself.
2017 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2018 int const unknown_tokens = defaults.readHeader(lex);
2019 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2021 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2022 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2024 if (unknown_tokens != 0) {
2025 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2026 << unknown_tokens << " unknown token"
2027 << (unknown_tokens == 1 ? "" : "s")
2031 if (defaults.writeFile(FileName(defaults.absFileName())))
2032 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2033 makeDisplayPath(fname)));
2036 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2041 case LFUN_BOOKMARK_GOTO:
2042 // go to bookmark, open unopened file and switch to buffer if necessary
2043 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2044 dr.screenUpdate(Update::Force | Update::FitCursor);
2047 case LFUN_BOOKMARK_CLEAR:
2048 theSession().bookmarks().clear();
2051 case LFUN_DEBUG_LEVEL_SET:
2052 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2055 case LFUN_DIALOG_SHOW: {
2056 string const name = cmd.getArg(0);
2058 if ( name == "aboutlyx"
2060 || name == "texinfo"
2061 || name == "progress"
2062 || name == "compare")
2064 // work around: on Mac OS the application
2065 // is not terminated when closing the last view.
2066 // Create a new one to be able to dispatch the
2067 // LFUN_DIALOG_SHOW to this view.
2068 if (current_view_ == 0)
2075 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2078 current_view_->dispatch(cmd, dr);
2082 if (cmd.origin() == FuncRequest::LYXSERVER)
2083 updateCurrentView(cmd, dr);
2087 docstring GuiApplication::viewStatusMessage()
2089 // When meta-fake key is pressed, show the key sequence so far + "M-".
2090 if (d->meta_fake_bit != NoModifier)
2091 return d->keyseq.print(KeySequence::ForGui) + "M-";
2093 // Else, when a non-complete key sequence is pressed,
2094 // show the available options.
2095 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2096 return d->keyseq.printOptions(true);
2102 void GuiApplication::handleKeyFunc(FuncCode action)
2106 if (d->keyseq.length())
2108 GuiView * gv = currentView();
2109 LASSERT(gv && gv->currentBufferView(), return);
2110 BufferView * bv = gv->currentBufferView();
2111 bv->getIntl().getTransManager().deadkey(
2112 c, get_accent(action).accent, bv->cursor().innerText(),
2114 // Need to clear, in case the minibuffer calls these
2117 // copied verbatim from do_accent_char
2118 bv->cursor().resetAnchor();
2122 //Keep this in sync with GuiApplication::processKeySym below
2123 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2124 KeyModifier state) const
2126 // Do nothing if we have nothing
2127 if (!keysym.isOK() || keysym.isModifier())
2129 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2131 FuncRequest func = seq.addkey(keysym, state);
2132 // When not cancel or meta-fake, do the normal lookup.
2133 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2135 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2137 // Maybe user can only reach the key via holding down shift.
2138 // Let's see. But only if shift is the only modifier
2139 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2140 // If addkey looked up a command and did not find further commands then
2141 // seq has been reset at this point
2142 func = seq.addkey(keysym, NoModifier);
2144 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2145 << seq.print(KeySequence::Portable) << ']');
2146 return func.action() != LFUN_UNKNOWN_ACTION;
2150 //Keep this in sync with GuiApplication::queryKeySym above
2151 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2153 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2155 // Do nothing if we have nothing (JMarc)
2156 if (!keysym.isOK() || keysym.isModifier()) {
2158 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2160 current_view_->restartCursor();
2164 char_type encoded_last_key = keysym.getUCSEncoded();
2166 // Do a one-deep top-level lookup for
2167 // cancel and meta-fake keys. RVDK_PATCH_5
2168 d->cancel_meta_seq.reset();
2170 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2171 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2173 // When not cancel or meta-fake, do the normal lookup.
2174 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2175 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2176 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2177 // remove Caps Lock and Mod2 as a modifiers
2178 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2179 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2182 // Dont remove this unless you know what you are doing.
2183 d->meta_fake_bit = NoModifier;
2185 // Can this happen now ?
2186 if (func.action() == LFUN_NOACTION)
2187 func = FuncRequest(LFUN_COMMAND_PREFIX);
2189 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2190 << d->keyseq.print(KeySequence::Portable) << ']');
2192 // already here we know if it any point in going further
2193 // why not return already here if action == -1 and
2194 // num_bytes == 0? (Lgb)
2196 if (d->keyseq.length() > 1 && current_view_)
2197 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2200 // Maybe user can only reach the key via holding down shift.
2201 // Let's see. But only if shift is the only modifier
2202 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2203 LYXERR(Debug::KEY, "Trying without shift");
2204 // If addkey looked up a command and did not find further commands then
2205 // seq has been reset at this point
2206 func = d->keyseq.addkey(keysym, NoModifier);
2207 LYXERR(Debug::KEY, "Action now " << func.action());
2210 if (func.action() == LFUN_UNKNOWN_ACTION) {
2211 // We didn't match any of the key sequences.
2212 // See if it's normal insertable text not already
2213 // covered by a binding
2214 if (keysym.isText() && d->keyseq.length() == 1) {
2215 // Non-printable characters (such as ASCII control characters)
2216 // must not be inserted (#5704)
2217 if (!isPrintable(encoded_last_key)) {
2218 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2220 current_view_->restartCursor();
2223 // The following modifier check is not needed on Mac.
2224 // The keysym is either not text or it is different
2225 // from the non-modifier keysym. See #9875 for the
2226 // broken alt-modifier effect of having this code active.
2227 #if !defined(Q_OS_MAC)
2228 // If a non-Shift Modifier is used we have a non-bound key sequence
2229 // (such as Alt+j = j). This should be omitted (#5575).
2230 // On Windows, AltModifier and ControlModifier are both
2231 // set when AltGr is pressed. Therefore, in order to not
2232 // break AltGr-bound symbols (see #5575 for details),
2233 // unbound Ctrl+Alt key sequences are allowed.
2234 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2235 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2236 && !(state & AltModifier && state & ControlModifier)
2240 if (current_view_) {
2241 current_view_->message(_("Unknown function."));
2242 current_view_->restartCursor();
2247 // Since all checks above were passed, we now really have text that
2248 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2249 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2251 LYXERR(Debug::KEY, "isText() is true, inserting.");
2252 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2254 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2255 if (current_view_) {
2256 current_view_->message(_("Unknown function."));
2257 current_view_->restartCursor();
2263 if (func.action() == LFUN_SELF_INSERT) {
2264 if (encoded_last_key != 0) {
2265 docstring const arg(1, encoded_last_key);
2266 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2267 FuncRequest::KEYBOARD));
2268 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2271 processFuncRequest(func);
2275 void GuiApplication::processFuncRequest(FuncRequest const & func)
2277 lyx::dispatch(func);
2281 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2283 addToFuncRequestQueue(func);
2284 processFuncRequestQueueAsync();
2288 void GuiApplication::processFuncRequestQueue()
2290 while (!d->func_request_queue_.empty()) {
2291 processFuncRequest(d->func_request_queue_.front());
2292 d->func_request_queue_.pop();
2297 void GuiApplication::processFuncRequestQueueAsync()
2299 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2303 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2305 d->func_request_queue_.push(func);
2309 void GuiApplication::resetGui()
2311 // Set the language defined by the user.
2315 if (!readUIFile(toqstr(lyxrc.ui_file)))
2316 // Gives some error box here.
2319 if (d->global_menubar_)
2320 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2322 QHash<int, GuiView *>::iterator it;
2323 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2326 gv->setLayoutDirection(layoutDirection());
2330 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2334 void GuiApplication::createView(int view_id)
2336 createView(QString(), true, view_id);
2340 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2343 // release the keyboard which might have been grabed by the global
2344 // menubar on Mac to catch shortcuts even without any GuiView.
2345 if (d->global_menubar_)
2346 d->global_menubar_->releaseKeyboard();
2350 while (d->views_.find(id) != d->views_.end())
2353 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2354 GuiView * view = new GuiView(id);
2356 d->views_[id] = view;
2360 setActiveWindow(view);
2363 if (!geometry_arg.isEmpty()) {
2364 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2368 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2369 re.indexIn(geometry_arg);
2370 w = re.cap(1).toInt();
2371 h = re.cap(2).toInt();
2372 x = re.cap(3).toInt();
2373 y = re.cap(4).toInt();
2374 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2375 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2376 // Set initial geometry such that we can get the frame size.
2377 view->setGeometry(x, y, w, h);
2378 int framewidth = view->geometry().x() - view->x();
2379 int titleheight = view->geometry().y() - view->y();
2380 // Negative displacements must be interpreted as distances
2381 // from the right or bottom screen borders.
2382 if (sx == '-' || sy == '-') {
2383 QRect rec = QApplication::desktop()->screenGeometry();
2385 x += rec.width() - w - framewidth;
2387 y += rec.height() - h - titleheight;
2388 view->setGeometry(x, y, w, h);
2390 // Make sure that the left and top frame borders are visible.
2391 if (view->x() < 0 || view->y() < 0) {
2396 view->setGeometry(x, y, w, h);
2404 Clipboard & GuiApplication::clipboard()
2406 return d->clipboard_;
2410 Selection & GuiApplication::selection()
2412 return d->selection_;
2416 FontLoader & GuiApplication::fontLoader()
2418 return d->font_loader_;
2422 Toolbars const & GuiApplication::toolbars() const
2424 return d->toolbars_;
2428 Toolbars & GuiApplication::toolbars()
2430 return d->toolbars_;
2434 Menus const & GuiApplication::menus() const
2440 Menus & GuiApplication::menus()
2446 QList<int> GuiApplication::viewIds() const
2448 return d->views_.keys();
2452 ColorCache & GuiApplication::colorCache()
2454 return d->color_cache_;
2458 int GuiApplication::exec()
2460 // asynchronously handle batch commands. This event will be in
2461 // the event queue in front of other asynchronous events. Hence,
2462 // we can assume in the latter that the gui is setup already.
2463 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2465 return QApplication::exec();
2469 void GuiApplication::exit(int status)
2471 QApplication::exit(status);
2475 void GuiApplication::setGuiLanguage()
2479 // install translation file for Qt built-in dialogs
2480 QString const language_name = QString("qt_") + theLocale.name();
2481 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2482 // Short-named translator can be loaded from a long name, but not the
2483 // opposite. Therefore, long name should be used without truncation.
2484 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2485 if (!d->qt_trans_.load(language_name,
2486 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2487 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2490 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2494 switch (theLocale.language()) {
2495 case QLocale::Arabic :
2496 case QLocale::Hebrew :
2497 case QLocale::Persian :
2498 case QLocale::Urdu :
2499 setLayoutDirection(Qt::RightToLeft);
2502 setLayoutDirection(Qt::LeftToRight);
2507 void GuiApplication::execBatchCommands()
2512 if (!readUIFile(toqstr(lyxrc.ui_file)))
2513 // Gives some error box here.
2517 #if QT_VERSION > 0x040600
2518 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2520 #if QT_VERSION > 0x050100
2521 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2523 // Create the global default menubar which is shown for the dialogs
2524 // and if no GuiView is visible.
2525 // This must be done after the session was recovered to know the "last files".
2526 d->global_menubar_ = new QMenuBar(0);
2527 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2530 lyx::execBatchCommands();
2534 QAbstractItemModel * GuiApplication::languageModel()
2536 if (d->language_model_)
2537 return d->language_model_;
2539 QStandardItemModel * lang_model = new QStandardItemModel(this);
2540 lang_model->insertColumns(0, 3);
2541 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2542 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2543 Languages::const_iterator it = lyx::languages.begin();
2544 Languages::const_iterator end = lyx::languages.end();
2545 for (; it != end; ++it) {
2546 int current_row = lang_model->rowCount();
2547 lang_model->insertRows(current_row, 1);
2548 QModelIndex pl_item = lang_model->index(current_row, 0);
2549 QModelIndex sp_item = lang_model->index(current_row, 1);
2550 QModelIndex th_item = lang_model->index(current_row, 2);
2551 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2552 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2553 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2554 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2555 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2556 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2557 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2558 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2559 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2560 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2562 d->language_model_ = new QSortFilterProxyModel(this);
2563 d->language_model_->setSourceModel(lang_model);
2564 d->language_model_->setSortLocaleAware(true);
2565 return d->language_model_;
2569 void GuiApplication::restoreGuiSession()
2571 if (!lyxrc.load_session)
2574 Session & session = theSession();
2575 LastOpenedSection::LastOpened const & lastopened =
2576 session.lastOpened().getfiles();
2578 validateCurrentView();
2580 FileName active_file;
2581 // do not add to the lastfile list since these files are restored from
2582 // last session, and should be already there (regular files), or should
2583 // not be added at all (help files).
2584 for (size_t i = 0; i < lastopened.size(); ++i) {
2585 FileName const & file_name = lastopened[i].file_name;
2586 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2587 && current_view_->documentBufferView() != 0)) {
2588 boost::crc_32_type crc;
2589 string const & fname = file_name.absFileName();
2590 crc = for_each(fname.begin(), fname.end(), crc);
2591 createView(crc.checksum());
2593 current_view_->loadDocument(file_name, false);
2595 if (lastopened[i].active)
2596 active_file = file_name;
2599 // Restore last active buffer
2600 Buffer * buffer = theBufferList().getBuffer(active_file);
2601 if (buffer && current_view_)
2602 current_view_->setBuffer(buffer);
2604 // clear this list to save a few bytes of RAM
2605 session.lastOpened().clear();
2609 QString const GuiApplication::romanFontName()
2612 font.setStyleHint(QFont::Serif);
2613 font.setFamily("serif");
2615 return QFontInfo(font).family();
2619 QString const GuiApplication::sansFontName()
2622 font.setStyleHint(QFont::SansSerif);
2623 font.setFamily("sans");
2625 return QFontInfo(font).family();
2629 QString const GuiApplication::typewriterFontName()
2631 return QFontInfo(typewriterSystemFont()).family();
2636 // We cannot use QFont::fixedPitch() because it doesn't
2637 // return the fact but only if it is requested.
2638 static bool isFixedPitch(const QFont & font) {
2639 const QFontInfo fi(font);
2640 return fi.fixedPitch();
2645 QFont const GuiApplication::typewriterSystemFont()
2647 #if QT_VERSION >= 0x050200
2648 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2650 QFont font("monospace");
2652 if (!isFixedPitch(font)) {
2653 // try to enforce a real monospaced font
2654 font.setStyleHint(QFont::Monospace);
2655 if (!isFixedPitch(font)) {
2656 font.setStyleHint(QFont::TypeWriter);
2657 if (!isFixedPitch(font)) font.setFamily("courier");
2661 // On a Mac the result is too small and it's not practical to
2662 // rely on Qtconfig utility to change the system settings of Qt.
2663 font.setPointSize(12);
2669 void GuiApplication::handleRegularEvents()
2671 ForkedCallsController::handleCompletedProcesses();
2675 bool GuiApplication::event(QEvent * e)
2678 case QEvent::FileOpen: {
2679 // Open a file; this happens only on Mac OS X for now.
2681 // We do this asynchronously because on startup the batch
2682 // commands are not executed here yet and the gui is not ready
2684 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2685 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2686 processFuncRequestAsync(fr);
2691 return QApplication::event(e);
2696 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2699 return QApplication::notify(receiver, event);
2701 catch (ExceptionMessage const & e) {
2703 case ErrorException:
2705 setQuitOnLastWindowClosed(false);
2707 Alert::error(e.title_, e.details_);
2709 // Properly crash in debug mode in order to get a useful backtrace.
2712 // In release mode, try to exit gracefully.
2715 case BufferException: {
2716 if (!current_view_ || !current_view_->documentBufferView())
2718 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2719 docstring details = e.details_ + '\n';
2720 details += buf->emergencyWrite();
2721 theBufferList().release(buf);
2722 details += "\n" + _("The current document was closed.");
2723 Alert::error(e.title_, details);
2726 case WarningException:
2727 Alert::warning(e.title_, e.details_);
2731 catch (exception const & e) {
2732 docstring s = _("LyX has caught an exception, it will now "
2733 "attempt to save all unsaved documents and exit."
2735 s += from_ascii(e.what());
2736 Alert::error(_("Software exception Detected"), s);
2740 docstring s = _("LyX has caught some really weird exception, it will "
2741 "now attempt to save all unsaved documents and exit.");
2742 Alert::error(_("Software exception Detected"), s);
2750 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2752 QColor const & qcol = d->color_cache_.get(col);
2753 if (!qcol.isValid()) {
2759 rgbcol.r = qcol.red();
2760 rgbcol.g = qcol.green();
2761 rgbcol.b = qcol.blue();
2766 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2768 QColor const qcol(lcolor.getX11Name(col).c_str());
2769 if (!qcol.isValid()) {
2775 rgbcol.r = qcol.red();
2776 rgbcol.g = qcol.green();
2777 rgbcol.b = qcol.blue();
2782 string const GuiApplication::hexName(ColorCode col)
2784 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2788 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2790 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2791 d->socket_notifiers_[fd] = sn;
2792 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2796 void GuiApplication::socketDataReceived(int fd)
2798 d->socket_notifiers_[fd]->func_();
2802 void GuiApplication::unregisterSocketCallback(int fd)
2804 d->socket_notifiers_.take(fd)->setEnabled(false);
2808 void GuiApplication::commitData(QSessionManager & sm)
2810 /** The implementation is required to avoid an application exit
2811 ** when session state save is triggered by session manager.
2812 ** The default implementation sends a close event to all
2813 ** visible top level widgets when session managment allows
2815 ** We are changing that to check the state of each buffer in all
2816 ** views and ask the users what to do if buffers are dirty.
2817 ** Furthermore, we save the session state.
2818 ** We do NOT close the views here since the user still can cancel
2819 ** the logout process (see #9277); also, this would hide LyX from
2820 ** an OSes own session handling (application restoration).
2822 #ifdef QT_NO_SESSIONMANAGER
2824 #warning Qt is compiled without session manager
2826 #pragma message("warning: Qt is compiled without session manager")
2830 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2838 void GuiApplication::unregisterView(GuiView * gv)
2840 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2841 d->views_.remove(gv->id());
2842 if (current_view_ == gv)
2848 bool GuiApplication::closeAllViews()
2850 if (d->views_.empty())
2853 // When a view/window was closed before without quitting LyX, there
2854 // are already entries in the lastOpened list.
2855 theSession().lastOpened().clear();
2857 QList<GuiView *> const views = d->views_.values();
2858 for (GuiView * view : views) {
2859 if (!view->closeScheduled())
2868 bool GuiApplication::prepareAllViewsForLogout()
2870 if (d->views_.empty())
2873 QList<GuiView *> const views = d->views_.values();
2874 for (GuiView * view : views) {
2875 if (!view->prepareAllBuffersForLogout())
2883 GuiView & GuiApplication::view(int id) const
2885 LAPPERR(d->views_.contains(id));
2886 return *d->views_.value(id);
2890 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2892 QList<GuiView *> const views = d->views_.values();
2893 for (GuiView * view : views)
2894 view->hideDialog(name, inset);
2898 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2900 Buffer const * buffer_ = 0;
2901 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2902 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2903 if (Buffer const * ptr = (*it)->updateInset(inset))
2910 bool GuiApplication::searchMenu(FuncRequest const & func,
2911 docstring_list & names) const
2913 return d->menus_.searchMenu(func, names);
2917 // Ensure that a file is read only once (prevents include loops)
2918 static QStringList uifiles;
2919 // store which ui files define Toolbars
2920 static QStringList toolbar_uifiles;
2923 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2934 LexerKeyword uitags[] = {
2935 { "format", ui_format },
2936 { "include", ui_include },
2937 { "menuset", ui_menuset },
2938 { "toolbars", ui_toolbars },
2939 { "toolbarset", ui_toolbarset }
2943 lex.setFile(ui_path);
2945 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2949 if (lyxerr.debugging(Debug::PARSER))
2950 lex.printTable(lyxerr);
2953 // format before introduction of format tag
2954 unsigned int format = 0;
2955 while (lex.isOK()) {
2956 int const status = lex.lex();
2958 // we have to do this check here, outside the switch,
2959 // because otherwise we would start reading include files,
2960 // e.g., if the first tag we hit was an include tag.
2961 if (status == ui_format)
2963 format = lex.getInteger();
2967 // this will trigger unless the first tag we hit is a format
2968 // tag, with the right format.
2969 if (format != LFUN_FORMAT)
2970 return FormatMismatch;
2973 case Lexer::LEX_FEOF:
2978 QString const file = toqstr(lex.getString());
2979 bool const success = readUIFile(file, true);
2981 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2988 d->menus_.read(lex);
2992 d->toolbars_.readToolbars(lex);
2996 d->toolbars_.readToolbarSettings(lex);
2997 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3001 if (!rtrim(lex.getString()).empty())
3002 lex.printError("LyX::ReadUIFile: "
3003 "Unknown menu tag: `$$Token'");
3005 LYXERR0("Error with status: " << status);
3011 return (error ? ReadError : ReadOK);
3015 bool GuiApplication::readUIFile(QString const & name, bool include)
3017 LYXERR(Debug::INIT, "About to read " << name << "...");
3021 ui_path = libFileSearch("ui", name, "inc");
3022 if (ui_path.empty())
3023 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3025 ui_path = libFileSearch("ui", name, "ui");
3028 if (ui_path.empty()) {
3029 static const QString defaultUIFile = "default";
3030 LYXERR(Debug::INIT, "Could not find " << name);
3032 Alert::warning(_("Could not find UI definition file"),
3033 bformat(_("Error while reading the included file\n%1$s\n"
3034 "Please check your installation."), qstring_to_ucs4(name)));
3037 if (name == defaultUIFile) {
3038 LYXERR(Debug::INIT, "Could not find default UI file!!");
3039 Alert::warning(_("Could not find default UI file"),
3040 _("LyX could not find the default UI file!\n"
3041 "Please check your installation."));
3044 Alert::warning(_("Could not find UI definition file"),
3045 bformat(_("Error while reading the configuration file\n%1$s\n"
3046 "Falling back to default.\n"
3047 "Please look under Tools>Preferences>User Interface and\n"
3048 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3049 return readUIFile(defaultUIFile, false);
3052 QString const uifile = toqstr(ui_path.absFileName());
3053 if (uifiles.contains(uifile)) {
3055 // We are reading again the top uifile so reset the safeguard:
3058 d->toolbars_.reset();
3060 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3061 << "Is this an include loop?");
3065 uifiles.push_back(uifile);
3067 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3069 ReturnValues retval = readUIFile(ui_path);
3071 if (retval == FormatMismatch) {
3072 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3073 TempFile tmp("convertXXXXXX.ui");
3074 FileName const tempfile = tmp.name();
3075 bool const success = prefs2prefs(ui_path, tempfile, true);
3077 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3078 " to format " << LFUN_FORMAT << ".");
3080 retval = readUIFile(tempfile);
3084 if (retval != ReadOK) {
3085 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3093 settings.beginGroup("ui_files");
3094 bool touched = false;
3095 for (int i = 0; i != uifiles.size(); ++i) {
3096 QFileInfo fi(uifiles[i]);
3097 QDateTime const date_value = fi.lastModified();
3098 QString const name_key = QString::number(i);
3099 // if an ui file which defines Toolbars has changed,
3100 // we have to reset the settings
3101 if (toolbar_uifiles.contains(uifiles[i])
3102 && (!settings.contains(name_key)
3103 || settings.value(name_key).toString() != uifiles[i]
3104 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3106 settings.setValue(name_key, uifiles[i]);
3107 settings.setValue(name_key + "/date", date_value);
3110 settings.endGroup();
3112 settings.remove("views");
3118 void GuiApplication::onLastWindowClosed()
3120 if (d->global_menubar_)
3121 d->global_menubar_->grabKeyboard();
3125 void GuiApplication::startLongOperation() {
3126 d->key_checker_.start();
3130 bool GuiApplication::longOperationCancelled() {
3131 return d->key_checker_.pressed();
3135 void GuiApplication::stopLongOperation() {
3136 d->key_checker_.stop();
3140 bool GuiApplication::longOperationStarted() {
3141 return d->key_checker_.started();
3145 ////////////////////////////////////////////////////////////////////////
3147 // X11 specific stuff goes here...
3150 bool GuiApplication::x11EventFilter(XEvent * xev)
3155 switch (xev->type) {
3156 case SelectionRequest: {
3157 if (xev->xselectionrequest.selection != XA_PRIMARY)
3159 LYXERR(Debug::SELECTION, "X requested selection.");
3160 BufferView * bv = current_view_->currentBufferView();
3162 docstring const sel = bv->requestSelection();
3164 d->selection_.put(sel);
3165 // Refresh the selection request timestamp.
3166 // We have to do this by ourselves as Qt seems
3167 // not doing that, maybe because of our
3168 // "persistent selection" implementation
3169 // (see comments in GuiSelection.cpp).
3170 XSelectionEvent nev;
3171 nev.type = SelectionNotify;
3172 nev.display = xev->xselectionrequest.display;
3173 nev.requestor = xev->xselectionrequest.requestor;
3174 nev.selection = xev->xselectionrequest.selection;
3175 nev.target = xev->xselectionrequest.target;
3176 nev.property = 0L; // None
3177 nev.time = CurrentTime;
3178 XSendEvent(QX11Info::display(),
3179 nev.requestor, False, 0,
3180 reinterpret_cast<XEvent *>(&nev));
3186 case SelectionClear: {
3187 if (xev->xselectionclear.selection != XA_PRIMARY)
3189 LYXERR(Debug::SELECTION, "Lost selection.");
3190 BufferView * bv = current_view_->currentBufferView();
3192 bv->clearSelection();
3198 #elif defined(QPA_XCB)
3199 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3200 void * message, long *)
3202 if (!current_view_ || eventType != "xcb_generic_event_t")
3205 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3207 switch (ev->response_type) {
3208 case XCB_SELECTION_REQUEST: {
3209 xcb_selection_request_event_t * srev =
3210 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3211 if (srev->selection != XCB_ATOM_PRIMARY)
3213 LYXERR(Debug::SELECTION, "X requested selection.");
3214 BufferView * bv = current_view_->currentBufferView();
3216 docstring const sel = bv->requestSelection();
3218 d->selection_.put(sel);
3219 #ifdef HAVE_QT5_X11_EXTRAS
3220 // Refresh the selection request timestamp.
3221 // We have to do this by ourselves as Qt seems
3222 // not doing that, maybe because of our
3223 // "persistent selection" implementation
3224 // (see comments in GuiSelection.cpp).
3225 xcb_selection_notify_event_t nev;
3226 nev.response_type = XCB_SELECTION_NOTIFY;
3227 nev.requestor = srev->requestor;
3228 nev.selection = srev->selection;
3229 nev.target = srev->target;
3230 nev.property = XCB_NONE;
3231 nev.time = XCB_CURRENT_TIME;
3232 xcb_connection_t * con = QX11Info::connection();
3233 xcb_send_event(con, 0, srev->requestor,
3234 XCB_EVENT_MASK_NO_EVENT,
3235 reinterpret_cast<char const *>(&nev));
3243 case XCB_SELECTION_CLEAR: {
3244 xcb_selection_clear_event_t * scev =
3245 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3246 if (scev->selection != XCB_ATOM_PRIMARY)
3248 LYXERR(Debug::SELECTION, "Lost selection.");
3249 BufferView * bv = current_view_->currentBufferView();
3251 bv->clearSelection();
3259 } // namespace frontend
3262 void hideDialogs(std::string const & name, Inset * inset)
3265 frontend::guiApp->hideDialogs(name, inset);
3269 ////////////////////////////////////////////////////////////////////
3273 ////////////////////////////////////////////////////////////////////
3275 frontend::FontLoader & theFontLoader()
3277 LAPPERR(frontend::guiApp);
3278 return frontend::guiApp->fontLoader();
3282 frontend::FontMetrics const & theFontMetrics(Font const & f)
3284 return theFontMetrics(f.fontInfo());
3288 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3290 LAPPERR(frontend::guiApp);
3291 return frontend::guiApp->fontLoader().metrics(f);
3295 ////////////////////////////////////////////////////////////////////
3299 ////////////////////////////////////////////////////////////////////
3301 frontend::Clipboard & theClipboard()
3303 LAPPERR(frontend::guiApp);
3304 return frontend::guiApp->clipboard();
3308 frontend::Selection & theSelection()
3310 LAPPERR(frontend::guiApp);
3311 return frontend::guiApp->selection();
3317 #include "moc_GuiApplication.cpp"