2 * \file GuiApplication.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * \author Abdelrazak Younes
10 * Full author contact details are available in file CREDITS.
15 #include "GuiApplication.h"
17 #include "ColorCache.h"
19 #include "GuiClipboard.h"
20 #include "GuiKeySymbol.h"
21 #include "GuiSelection.h"
24 #include "qt_helpers.h"
27 #include "frontends/alert.h"
28 #include "frontends/Application.h"
29 #include "frontends/FontLoader.h"
30 #include "frontends/FontMetrics.h"
33 #include "BufferList.h"
34 #include "BufferParams.h"
35 #include "BufferView.h"
38 #include "CutAndPaste.h"
39 #include "ErrorList.h"
41 #include "FuncRequest.h"
42 #include "FuncStatus.h"
43 #include "GuiWorkArea.h"
47 #include "LaTeXPackages.h"
50 #include "LyXAction.h"
52 #include "Paragraph.h"
55 #include "SpellChecker.h"
56 #include "Thesaurus.h"
59 #include "insets/InsetText.h"
61 #include "support/convert.h"
62 #include "support/debug.h"
63 #include "support/ExceptionMessage.h"
64 #include "support/FileName.h"
65 #include "support/filetools.h"
66 #include "support/foreach.h"
67 #include "support/ForkedCalls.h"
68 #include "support/gettext.h"
69 #include "support/lassert.h"
70 #include "support/lstrings.h"
71 #include "support/lyxalgo.h" // sorted
72 #include "support/Messages.h"
73 #include "support/os.h"
74 #include "support/Package.h"
75 #include "support/TempFile.h"
78 #include "support/AppleScript.h"
79 #include "support/linkback/LinkBackProxy.h"
87 #include <QDesktopWidget>
91 #include <QFileOpenEvent>
95 #include <QImageReader>
98 #include <QLibraryInfo>
104 #include <QPixmapCache>
106 #include <QSessionManager>
108 #include <QShowEvent>
109 #include <QSocketNotifier>
110 #include <QSortFilterProxyModel>
111 #include <QStandardItemModel>
112 #include <QTextCodec>
114 #include <QTranslator>
115 #include <QThreadPool>
120 #include <X11/Xatom.h>
121 #include <X11/Xlib.h>
126 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
127 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
128 #if (QT_VERSION < 0x050000)
129 #include <QWindowsMime>
130 #define QWINDOWSMIME QWindowsMime
133 #define QWINDOWSMIME QWinMime
143 #include <QMacPasteboardMime>
146 #include "support/bind.h"
147 #include <boost/crc.hpp>
154 using namespace lyx::support;
157 static void initializeResources()
159 static bool initialized = false;
161 Q_INIT_RESOURCE(Resources);
169 frontend::Application * createApplication(int & argc, char * argv[])
171 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
172 // prune -geometry argument(s) by shifting
173 // the following ones 2 places down.
174 for (int i = 0 ; i < argc ; ++i) {
175 if (strcmp(argv[i], "-geometry") == 0) {
176 int const remove = (i+1) < argc ? 2 : 1;
178 for (int j = i; j < argc; ++j)
179 argv[j] = argv[j + remove];
184 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
185 // I'd rather do that in the constructor, but I do not think that
186 // the palette is accessible there.
187 guiApp->colorCache().setPalette(guiApp->palette());
195 if (lyxrc.gui_language == "auto") {
196 theLocale = QLocale::system();
198 Language const * l = languages.getLanguage(lyxrc.gui_language);
199 string const code = l ? l->code() : string();
200 theLocale = QLocale(toqstr(code));
202 string const code = fromqstr(theLocale.name());
203 // Qt tries to outsmart us and transforms en_US to C.
204 Messages::guiLanguage((code == "C") ? "en_US" : code);
205 QLocale::setDefault(theLocale);
206 setlocale(LC_NUMERIC, "C");
213 /// Return the list of loadable formats.
214 vector<string> loadableImageFormats()
218 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
220 LYXERR(Debug::GRAPHICS,
221 "\nThe image loader can load the following directly:\n");
223 if (qt_formats.empty())
224 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
226 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
228 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
230 string ext = ascii_lowercase((const char *) *it);
241 ////////////////////////////////////////////////////////////////////////
243 // Icon loading support code
245 ////////////////////////////////////////////////////////////////////////
255 bool operator<(PngMap const & lhs, PngMap const & rhs)
257 return lhs.key < rhs.key;
263 CompareKey(QString const & name) : name_(name) {}
264 bool operator()(PngMap const & other) const { return other.key == name_; }
270 // this must be sorted alphabetically
271 // Upper case comes before lower case
272 // Please don't change the formatting, this list is parsed by
273 // development/tools/generate_symbols_images.py.
274 PngMap sorted_png_map[] = {
275 { "Arrownot", "arrownot2"},
276 { "Arrowvert", "arrowvert2"},
277 { "Bowtie", "bowtie2" },
279 { "Bumpeq", "bumpeq2" },
280 { "CIRCLE", "circle3" },
282 { "CheckedBox", "checkedbox2" },
283 { "Circle", "circle2" },
284 { "Colonapprox", "colonapprox2" },
285 { "Coloneq", "coloneq2" },
286 { "Coloneqq", "coloneqq2" },
287 { "Colonsim", "colonsim2" },
289 { "DOWNarrow", "downarrow3" },
290 { "Delta", "delta2" },
291 { "Diamond", "diamond2" },
292 { "Doteq", "doteq2" },
293 { "Downarrow", "downarrow2" },
294 { "Eqcolon", "eqcolon2" },
295 { "Eqqcolon", "eqqcolon2" },
296 { "Gamma", "gamma2" },
298 { "LEFTCIRCLE", "leftcircle3" },
299 { "LEFTarrow", "leftarrow3" },
300 { "LEFTcircle", "leftcircle4" },
302 { "Lambda", "lambda2" },
304 { "Leftarrow", "leftarrow2" },
305 { "Leftcircle", "leftcircle2" },
306 { "Leftrightarrow", "leftrightarrow2" },
307 { "Longarrownot", "longarrownot2"},
308 { "Longleftarrow", "longleftarrow2" },
309 { "Longleftrightarrow", "longleftrightarrow2" },
310 { "Longmapsfrom", "longmapsfrom2"},
311 { "Longmapsto", "longmapsto2"},
312 { "Longrightarrow", "longrightarrow2" },
313 { "Mapsfrom", "mapsfrom2"},
314 { "Mapsfromchar", "mapsfromchar2"},
315 { "Mapsto", "mapsto2"},
316 { "Mapstochar", "mapstochar2"},
317 { "Omega", "omega2" },
322 { "RIGHTCIRCLE", "rightcircle3" },
323 { "RIGHTarrow", "rightarrow3" },
324 { "RIGHTcircle", "rightcircle4" },
326 { "Rightarrow", "rightarrow2" },
327 { "Rightcircle", "rightcircle2" },
328 { "Sigma", "sigma2" },
329 { "Square", "square2" },
330 { "Subset", "subset2" },
331 { "Supset", "supset2" },
332 { "Theta", "theta2" },
333 { "Thorn", "thorn2" },
334 { "UParrow", "uparrow3" },
335 { "Uparrow", "uparrow2" },
336 { "Updownarrow", "updownarrow2" },
337 { "Upsilon", "upsilon2" },
338 { "Vdash", "vdash3" },
343 { "lVert", "vert2" },
345 { "nLeftarrow", "nleftarrow2" },
346 { "nLeftrightarrow", "nleftrightarrow2" },
347 { "nRightarrow", "nrightarrow2" },
348 { "nVDash", "nvdash3" },
349 { "nVdash", "nvdash4" },
350 { "nvDash", "nvdash2" },
351 { "rVert", "vert2" },
353 { "textrm \\AA", "textrm_AA"},
354 { "textrm \\O", "textrm_O"},
355 { "vDash", "vdash2" },
356 { "varDelta", "vardelta2" },
357 { "varGamma", "vargamma2" },
358 { "varLambda", "varlambda2" },
359 { "varOmega", "varomega2" },
360 { "varPhi", "varphi2" },
361 { "varPi", "varpi2" },
362 { "varPsi", "varpsi2" },
363 { "varSigma", "varsigma2" },
364 { "varTheta", "vartheta2" },
365 { "varUpsilon", "varupsilon2" },
366 { "varXi", "varxi2" }
370 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
372 // This list specifies which system's theme icon is related to which lyx
373 // command. It was based on:
374 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
375 // this must be sorted alphabetically
376 // Upper case comes before lower case
377 PngMap sorted_theme_icon_map[] = {
378 { "bookmark-goto 0", "go-jump" },
379 { "buffer-new", "document-new" },
380 { "buffer-print", "document-print" },
381 { "buffer-write", "document-save" },
382 { "buffer-write-as", "document-save-as" },
383 { "buffer-zoom-in", "zoom-in" },
384 { "buffer-zoom-out", "zoom-out" },
385 { "copy", "edit-copy" },
386 { "cut", "edit-cut" },
387 { "depth-decrement", "format-indent-less" },
388 { "depth-increment", "format-indent-more" },
389 { "dialog-show print", "document-print" },
390 { "dialog-show spellchecker", "tools-check-spelling" },
391 { "dialog-show-new-inset graphics", "insert-image" },
392 { "dialog-toggle findreplaceadv", "edit-find-replace" },
393 { "file-open", "document-open" },
394 { "font-bold", "format-text-bold" },
395 { "font-ital", "format-text-italic" },
396 { "font-strikeout", "format-text-strikethrough" },
397 { "font-underline", "format-text-underline" },
398 { "lyx-quit", "application-exit" },
399 { "paste", "edit-paste" },
400 { "redo", "edit-redo" },
401 { "undo", "edit-undo" },
402 { "window-close", "window-close" },
403 { "window-new", "window-new" }
406 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(PngMap);
409 QString findPng(QString const & name)
411 PngMap const * const begin = sorted_png_map;
412 PngMap const * const end = begin + nr_sorted_png_map;
413 LATTEST(sorted(begin, end));
415 PngMap const * const it = find_if(begin, end, CompareKey(name));
419 png_name = it->value;
422 png_name.replace('_', "underscore");
423 png_name.replace(' ', '_');
425 // This way we can have "math-delim { }" on the toolbar.
426 png_name.replace('(', "lparen");
427 png_name.replace(')', "rparen");
428 png_name.replace('[', "lbracket");
429 png_name.replace(']', "rbracket");
430 png_name.replace('{', "lbrace");
431 png_name.replace('}', "rbrace");
432 png_name.replace('|', "bars");
433 png_name.replace(',', "thinspace");
434 png_name.replace(':', "mediumspace");
435 png_name.replace(';', "thickspace");
436 png_name.replace('!', "negthinspace");
439 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
440 << "Looking for math PNG called \"" << png_name << '"');
447 QString themeIconName(QString const & action)
449 PngMap const * const begin = sorted_theme_icon_map;
450 PngMap const * const end = begin + nr_sorted_theme_icon_map;
451 LASSERT(sorted(begin, end), /**/);
453 PngMap const * const it = find_if(begin, end, CompareKey(action));
461 QString iconName(FuncRequest const & f, bool unknown)
463 initializeResources();
467 switch (f.action()) {
468 case LFUN_MATH_INSERT:
469 if (!f.argument().empty()) {
471 name1 = findPng(toqstr(f.argument()).mid(1));
474 case LFUN_MATH_DELIM:
475 case LFUN_MATH_BIGDELIM:
477 name1 = findPng(toqstr(f.argument()));
481 name1 = toqstr(f.argument());
483 case LFUN_COMMAND_ALTERNATIVES: {
484 // use the first of the alternative commands
486 docstring dummy = split(f.argument(), firstcom, ';');
487 name1 = toqstr(firstcom);
488 // FIXME: we should rename the icons to tabular-xxx instead of
489 // "tabular-feature-xxx"
490 name1.replace("inset-modify tabular", "tabular-feature");
491 name1.replace(' ', '_');
494 case LFUN_INSET_MODIFY: {
495 // FIXME: we should rename the icons to tabular-xxx instead of
496 // "tabular-feature-xxx" and generalize this naming to all
497 // insets, not to tabular using ones.
499 string const command = split(to_utf8(f.argument()), inset_name, ' ');
500 if (insetCode(inset_name) == TABULAR_CODE) {
501 name1 = "tabular-feature "+ toqstr(command);
502 name1.replace(' ', '_');
507 name2 = toqstr(lyxaction.getActionName(f.action()));
510 if (!f.argument().empty()) {
511 name1 = name2 + ' ' + toqstr(f.argument());
512 name1.replace(' ', '_');
513 name1.replace('\\', "backslash");
517 QStringList imagedirs;
518 imagedirs << "images/" << "images/ipa/";
519 search_mode mode = theGuiApp()->imageSearchMode();
520 for (int i = 0; i < imagedirs.size(); ++i) {
521 QString imagedir = imagedirs.at(i) + path;
522 FileName fname = imageLibFileSearch(imagedir, name1, "png", mode);
524 return toqstr(fname.absFileName());
526 fname = imageLibFileSearch(imagedir, name2, "png", mode);
528 return toqstr(fname.absFileName());
531 path = ":/images/" + path;
534 LYXERR0("Directory " << path << " not found in resource!");
538 if (res.exists(name1))
542 if (res.exists(name2))
545 LYXERR(Debug::GUI, "Cannot find icon with filename "
546 << "\"" << name1 << "\""
548 << "\"" << name2 << "\""
550 << lyxaction.getActionName(f.action())
551 << '(' << to_utf8(f.argument()) << ")\"");
554 QString imagedir = "images/";
555 FileName fname = imageLibFileSearch(imagedir, "unknown", "png", mode);
557 return toqstr(fname.absFileName());
558 return QString(":/images/unknown.png");
564 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
567 QString imagedir = path;
568 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
569 QString path1 = toqstr(fname.absFileName());
570 QString path2 = ":/" + path + name + "." + ext;
572 if (pixmap.load(path1)) {
575 else if (pixmap.load(path2)) {
579 LYXERR0("Cannot load pixmap \""
580 << path << name << '.' << ext
581 << "\", please verify resource system!");
586 QIcon getIcon(FuncRequest const & f, bool unknown)
588 #if (QT_VERSION >= 0x040600)
589 if (lyxrc.use_system_theme_icons) {
590 QString action = toqstr(lyxaction.getActionName(f.action()));
591 if (!f.argument().empty())
592 action += " " + toqstr(f.argument());
593 QString const theme_icon = themeIconName(action);
594 if (QIcon::hasThemeIcon(theme_icon))
595 return QIcon::fromTheme(theme_icon);
599 QString icon = iconName(f, unknown);
603 //LYXERR(Debug::GUI, "Found icon: " << icon);
605 if (!pm.load(icon)) {
606 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
614 ////////////////////////////////////////////////////////////////////////
616 // LyX server support code.
618 ////////////////////////////////////////////////////////////////////////
620 class SocketNotifier : public QSocketNotifier
623 /// connect a connection notification from the LyXServerSocket
624 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
625 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
629 /// The callback function
630 Application::SocketCallback func_;
634 ////////////////////////////////////////////////////////////////////////
636 // Mac specific stuff goes here...
638 ////////////////////////////////////////////////////////////////////////
640 class MenuTranslator : public QTranslator
643 MenuTranslator(QObject * parent)
644 : QTranslator(parent)
647 #if QT_VERSION >= 0x050000
648 virtual QString translate(const char * /* context */,
649 const char *sourceText,
650 const char * /* disambiguation */ = 0, int /* n */ = -1) const
652 QString translate(const char * /*context*/,
653 const char * sourceText,
654 const char * /*comment*/ = 0) const
657 string const s = sourceText;
658 if (s == N_("About %1") || s == N_("Preferences")
659 || s == N_("Reconfigure") || s == N_("Quit %1"))
667 // QMacPasteboardMimeGraphics can only be compiled on Mac.
669 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
672 QMacPasteboardMimeGraphics()
673 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
676 QString convertorName() { return "Graphics"; }
678 QString flavorFor(QString const & mime)
680 LYXERR(Debug::ACTION, "flavorFor " << mime);
681 if (mime == pdfMimeType())
682 return QLatin1String("com.adobe.pdf");
686 QString mimeFor(QString flav)
688 LYXERR(Debug::ACTION, "mimeFor " << flav);
689 if (flav == QLatin1String("com.adobe.pdf"))
690 return pdfMimeType();
694 bool canConvert(QString const & mime, QString flav)
696 return mimeFor(flav) == mime;
699 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
703 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
707 QList<QByteArray> convertFromMime(QString const & /*mime*/,
708 QVariant data, QString /*flav*/)
710 QList<QByteArray> ret;
711 ret.append(data.toByteArray());
717 ///////////////////////////////////////////////////////////////
719 // You can find more platform specific stuff at the end of this file...
721 ///////////////////////////////////////////////////////////////
723 ////////////////////////////////////////////////////////////////////////
724 // Windows specific stuff goes here...
726 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
727 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
728 // QWindowsMimeMetafile can only be compiled on Windows.
730 static FORMATETC cfFromMime(QString const & mimetype)
733 if (mimetype == emfMimeType()) {
734 formatetc.cfFormat = CF_ENHMETAFILE;
735 formatetc.tymed = TYMED_ENHMF;
736 } else if (mimetype == wmfMimeType()) {
737 formatetc.cfFormat = CF_METAFILEPICT;
738 formatetc.tymed = TYMED_MFPICT;
741 formatetc.dwAspect = DVASPECT_CONTENT;
742 formatetc.lindex = -1;
747 class QWindowsMimeMetafile : public QWINDOWSMIME {
749 QWindowsMimeMetafile() {}
751 bool canConvertFromMime(FORMATETC const & formatetc,
752 QMimeData const * mimedata) const
757 bool canConvertToMime(QString const & mimetype,
758 IDataObject * pDataObj) const
760 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
762 FORMATETC formatetc = cfFromMime(mimetype);
763 return pDataObj->QueryGetData(&formatetc) == S_OK;
766 bool convertFromMime(FORMATETC const & formatetc,
767 const QMimeData * mimedata, STGMEDIUM * pmedium) const
772 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
773 QVariant::Type preferredType) const
776 if (!canConvertToMime(mimetype, pDataObj))
779 FORMATETC formatetc = cfFromMime(mimetype);
781 if (pDataObj->GetData(&formatetc, &s) != S_OK)
785 if (s.tymed == TYMED_ENHMF) {
786 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
787 data.resize(dataSize);
788 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
789 (LPBYTE)data.data());
790 } else if (s.tymed == TYMED_MFPICT) {
791 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
792 data.resize(dataSize);
793 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
794 (LPBYTE)data.data());
797 ReleaseStgMedium(&s);
803 QVector<FORMATETC> formatsForMime(QString const & mimetype,
804 QMimeData const * mimedata) const
806 QVector<FORMATETC> formats;
807 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
808 formats += cfFromMime(mimetype);
812 QString mimeForFormat(FORMATETC const & formatetc) const
814 switch (formatetc.cfFormat) {
816 return emfMimeType();
817 case CF_METAFILEPICT:
818 return wmfMimeType();
828 /// Allows to check whether ESC was pressed during a long operation
829 class KeyChecker : public QObject {
834 KeyChecker() : pressed_(false), started_(false) {}
837 QCoreApplication::instance()->installEventFilter(this);
842 QCoreApplication::instance()->removeEventFilter(this);
846 QCoreApplication::processEvents();
849 bool started() const {
852 bool eventFilter(QObject *obj, QEvent *event) {
853 LYXERR(Debug::ACTION, "Event Type: " << event->type());
854 switch (event->type()) {
858 case QEvent::UpdateRequest:
859 case QEvent::CursorChange:
860 case QEvent::ActionChanged:
861 case QEvent::EnabledChange:
862 case QEvent::SockAct:
865 case QEvent::ToolTipChange:
866 case QEvent::LayoutRequest:
867 case QEvent::MetaCall:
868 return QObject::eventFilter(obj, event);
870 // FIXME Blocking all these events is a bad idea.
871 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
872 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
880 ////////////////////////////////////////////////////////////////////////
881 // GuiApplication::Private definition and implementation.
882 ////////////////////////////////////////////////////////////////////////
884 struct GuiApplication::Private
886 Private(): language_model_(0), meta_fake_bit(NoModifier),
889 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
890 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
891 /// WMF Mime handler for Windows clipboard.
892 wmf_mime_ = new QWindowsMimeMetafile;
895 initKeySequences(&theTopLevelKeymap());
898 void initKeySequences(KeyMap * kb)
900 keyseq = KeySequence(kb, kb);
901 cancel_meta_seq = KeySequence(kb, kb);
905 QSortFilterProxyModel * language_model_;
907 GuiClipboard clipboard_;
909 GuiSelection selection_;
911 FontLoader font_loader_;
913 ColorCache color_cache_;
915 QTranslator qt_trans_;
917 QHash<int, SocketNotifier *> socket_notifiers_;
921 /// The global instance
924 /// this timer is used for any regular events one wants to
925 /// perform. at present it is used to check if forked processes
927 QTimer general_timer_;
929 /// delayed FuncRequests
930 std::queue<FuncRequest> func_request_queue_;
935 KeySequence cancel_meta_seq;
937 KeyModifier meta_fake_bit;
939 /// Multiple views container.
941 * Warning: This must not be a smart pointer as the destruction of the
942 * object is handled by Qt when the view is closed
943 * \sa Qt::WA_DeleteOnClose attribute.
945 QHash<int, GuiView *> views_;
947 /// Only used on mac.
948 QMenuBar * global_menubar_;
951 /// Linkback mime handler for MacOSX.
952 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
955 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
956 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
957 /// WMF Mime handler for Windows clipboard.
958 QWindowsMimeMetafile * wmf_mime_;
962 /// Allows to check whether ESC was pressed during a long operation
963 KeyChecker key_checker_;
967 GuiApplication * guiApp;
969 GuiApplication::~GuiApplication()
972 closeAllLinkBackLinks();
978 GuiApplication::GuiApplication(int & argc, char ** argv)
979 : QApplication(argc, argv), current_view_(0),
980 d(new GuiApplication::Private)
982 QString app_name = "LyX";
983 QCoreApplication::setOrganizationName(app_name);
984 QCoreApplication::setOrganizationDomain("lyx.org");
985 QCoreApplication::setApplicationName(lyx_package);
987 qsrand(QDateTime::currentDateTime().toTime_t());
989 // Install translator for GUI elements.
990 installTranslator(&d->qt_trans_);
992 // FIXME: quitOnLastWindowClosed is true by default. We should have a
993 // lyxrc setting for this in order to let the application stay resident.
994 // But then we need some kind of dock icon, at least on Windows.
996 if (lyxrc.quit_on_last_window_closed)
997 setQuitOnLastWindowClosed(false);
1000 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1001 // seems to be the default case for applications like LyX.
1002 setQuitOnLastWindowClosed(false);
1003 // This allows to translate the strings that appear in the LyX menu.
1004 /// A translator suitable for the entries in the LyX menu.
1005 /// Only needed with Qt/Mac.
1006 installTranslator(new MenuTranslator(this));
1011 #if defined(Q_WS_X11) || defined(QPA_XCB)
1012 // doubleClickInterval() is 400 ms on X11 which is just too long.
1013 // On Windows and Mac OS X, the operating system's value is used.
1014 // On Microsoft Windows, calling this function sets the double
1015 // click interval for all applications. So we don't!
1016 QApplication::setDoubleClickInterval(300);
1019 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1021 // needs to be done before reading lyxrc
1023 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1027 // Set the cache to 5120 kilobytes which corresponds to screen size of
1028 // 1280 by 1024 pixels with a color depth of 32 bits.
1029 QPixmapCache::setCacheLimit(5120);
1031 // Initialize RC Fonts
1032 if (lyxrc.roman_font_name.empty())
1033 lyxrc.roman_font_name = fromqstr(romanFontName());
1035 if (lyxrc.sans_font_name.empty())
1036 lyxrc.sans_font_name = fromqstr(sansFontName());
1038 if (lyxrc.typewriter_font_name.empty())
1039 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1041 d->general_timer_.setInterval(500);
1042 connect(&d->general_timer_, SIGNAL(timeout()),
1043 this, SLOT(handleRegularEvents()));
1044 d->general_timer_.start();
1046 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1047 // This is clearly not enough in a time where we use threads for
1048 // document preview and/or export. 20 should be OK.
1049 QThreadPool::globalInstance()->setMaxThreadCount(20);
1053 GuiApplication * theGuiApp()
1055 return dynamic_cast<GuiApplication *>(theApp());
1059 double GuiApplication::pixelRatio() const
1061 #if QT_VERSION >= 0x050000
1062 return devicePixelRatio();
1069 void GuiApplication::clearSession()
1076 docstring Application::iconName(FuncRequest const & f, bool unknown)
1078 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1082 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1086 BufferView * bv = 0;
1087 BufferView * doc_bv = 0;
1089 if (cmd.action() == LFUN_NOACTION) {
1090 status.message(from_utf8(N_("Nothing to do")));
1091 status.setEnabled(false);
1094 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1095 status.setUnknown(true);
1096 status.message(from_utf8(N_("Unknown action")));
1097 status.setEnabled(false);
1100 // Does the GuiApplication know something?
1101 else if (getStatus(cmd, status)) { }
1103 // If we do not have a GuiView, then other functions are disabled
1104 else if (!current_view_)
1105 status.setEnabled(false);
1107 // Does the GuiView know something?
1108 else if (current_view_->getStatus(cmd, status)) { }
1110 // In LyX/Mac, when a dialog is open, the menus of the
1111 // application can still be accessed without giving focus to
1112 // the main window. In this case, we want to disable the menu
1113 // entries that are buffer or view-related.
1114 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1116 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1117 status.setEnabled(false);
1120 // If we do not have a BufferView, then other functions are disabled
1121 else if (!(bv = current_view_->currentBufferView()))
1122 status.setEnabled(false);
1124 // Does the current BufferView know something?
1125 else if (bv->getStatus(cmd, status)) { }
1127 // Does the current Buffer know something?
1128 else if (bv->buffer().getStatus(cmd, status)) { }
1130 // If we do not have a document BufferView, different from the
1131 // current BufferView, then other functions are disabled
1132 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1133 status.setEnabled(false);
1135 // Does the document Buffer know something?
1136 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1139 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1140 status.message(from_utf8(N_("Command not handled")));
1141 status.setEnabled(false);
1144 // the default error message if we disable the command
1145 if (!status.enabled() && status.message().empty())
1146 status.message(from_utf8(N_("Command disabled")));
1152 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1154 // I would really like to avoid having this switch and rather try to
1155 // encode this in the function itself.
1156 // -- And I'd rather let an inset decide which LFUNs it is willing
1157 // to handle (Andre')
1159 switch (cmd.action()) {
1161 // This could be used for the no-GUI version. The GUI version is handled in
1162 // GuiView::getStatus(). See above.
1164 case LFUN_BUFFER_WRITE:
1165 case LFUN_BUFFER_WRITE_AS: {
1166 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1167 enable = b && (b->isUnnamed() || !b->isClean());
1172 case LFUN_BOOKMARK_GOTO: {
1173 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1174 enable = theSession().bookmarks().isValid(num);
1178 case LFUN_BOOKMARK_CLEAR:
1179 enable = theSession().bookmarks().hasValid();
1182 // this one is difficult to get right. As a half-baked
1183 // solution, we consider only the first action of the sequence
1184 case LFUN_COMMAND_SEQUENCE: {
1185 // argument contains ';'-terminated commands
1186 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1187 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1188 func.setOrigin(cmd.origin());
1189 flag = getStatus(func);
1193 // we want to check if at least one of these is enabled
1194 case LFUN_COMMAND_ALTERNATIVES: {
1195 // argument contains ';'-terminated commands
1196 string arg = to_utf8(cmd.argument());
1197 while (!arg.empty()) {
1199 arg = split(arg, first, ';');
1200 FuncRequest func(lyxaction.lookupFunc(first));
1201 func.setOrigin(cmd.origin());
1202 flag = getStatus(func);
1203 // if this one is enabled, the whole thing is
1212 string name = to_utf8(cmd.argument());
1213 if (theTopLevelCmdDef().lock(name, func)) {
1214 func.setOrigin(cmd.origin());
1215 flag = getStatus(func);
1216 theTopLevelCmdDef().release(name);
1218 // catch recursion or unknown command
1219 // definition. all operations until the
1220 // recursion or unknown command definition
1221 // occurs are performed, so set the state to
1228 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1230 case LFUN_PREFERENCES_SAVE:
1231 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1232 case LFUN_DEBUG_LEVEL_SET:
1233 // these are handled in our dispatch()
1236 case LFUN_WINDOW_CLOSE:
1237 enable = d->views_.size() > 0;
1240 case LFUN_BUFFER_NEW:
1241 case LFUN_BUFFER_NEW_TEMPLATE:
1242 case LFUN_FILE_OPEN:
1243 case LFUN_HELP_OPEN:
1244 case LFUN_SCREEN_FONT_UPDATE:
1245 case LFUN_SET_COLOR:
1246 case LFUN_WINDOW_NEW:
1248 case LFUN_LYXRC_APPLY:
1249 case LFUN_COMMAND_PREFIX:
1251 case LFUN_META_PREFIX:
1252 case LFUN_RECONFIGURE:
1253 case LFUN_SERVER_GET_FILENAME:
1254 case LFUN_SERVER_NOTIFY:
1258 case LFUN_BUFFER_FORALL: {
1259 if (theBufferList().empty()) {
1260 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1261 flag.setEnabled(false);
1265 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1266 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1267 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1268 flag.setEnabled(false);
1273 case LFUN_DIALOG_SHOW: {
1274 string const name = cmd.getArg(0);
1275 return name == "aboutlyx"
1277 || name == "texinfo"
1278 || name == "progress"
1279 || name == "compare";
1287 flag.setEnabled(false);
1291 /// make a post-dispatch status message
1292 static docstring makeDispatchMessage(docstring const & msg,
1293 FuncRequest const & cmd)
1295 const bool verbose = (cmd.origin() == FuncRequest::MENU
1296 || cmd.origin() == FuncRequest::TOOLBAR
1297 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1299 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1300 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1304 docstring dispatch_msg = msg;
1305 if (!dispatch_msg.empty())
1306 dispatch_msg += ' ';
1308 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1310 bool argsadded = false;
1312 if (!cmd.argument().empty()) {
1313 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1314 comname += ' ' + cmd.argument();
1318 docstring const shortcuts = theTopLevelKeymap().
1319 printBindings(cmd, KeySequence::ForGui);
1321 if (!shortcuts.empty())
1322 comname += ": " + shortcuts;
1323 else if (!argsadded && !cmd.argument().empty())
1324 comname += ' ' + cmd.argument();
1326 if (!comname.empty()) {
1327 comname = rtrim(comname);
1328 dispatch_msg += '(' + rtrim(comname) + ')';
1330 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1331 return dispatch_msg;
1335 void GuiApplication::dispatch(FuncRequest const & cmd)
1337 Buffer * buffer = 0;
1338 if (current_view_ && current_view_->currentBufferView()) {
1339 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1340 buffer = ¤t_view_->currentBufferView()->buffer();
1342 buffer->undo().beginUndoGroup();
1346 // redraw the screen at the end (first of the two drawing steps).
1347 // This is done unless explicitly requested otherwise
1348 dr.screenUpdate(Update::FitCursor);
1350 updateCurrentView(cmd, dr);
1352 // the buffer may have been closed by one action
1353 if (theBufferList().isLoaded(buffer))
1354 buffer->undo().endUndoGroup();
1358 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1363 BufferView * bv = current_view_->currentBufferView();
1365 if (dr.needBufferUpdate()) {
1366 bv->cursor().clearBufferUpdate();
1367 bv->buffer().updateBuffer();
1369 // BufferView::update() updates the ViewMetricsInfo and
1370 // also initializes the position cache for all insets in
1371 // (at least partially) visible top-level paragraphs.
1372 // We will redraw the screen only if needed.
1373 bv->processUpdateFlags(dr.screenUpdate());
1375 // Do we have a selection?
1376 theSelection().haveSelection(bv->cursor().selection());
1379 current_view_->restartCursor();
1381 if (dr.needMessageUpdate()) {
1382 // Some messages may already be translated, so we cannot use _()
1383 current_view_->message(makeDispatchMessage(
1384 translateIfPossible(dr.message()), cmd));
1389 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1390 bool switchToBuffer)
1392 if (!theSession().bookmarks().isValid(idx))
1394 BookmarksSection::Bookmark const & bm =
1395 theSession().bookmarks().bookmark(idx);
1396 LASSERT(!bm.filename.empty(), return);
1397 string const file = bm.filename.absFileName();
1398 // if the file is not opened, open it.
1399 if (!theBufferList().exists(bm.filename)) {
1401 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1405 // open may fail, so we need to test it again
1406 if (!theBufferList().exists(bm.filename))
1409 // bm can be changed when saving
1410 BookmarksSection::Bookmark tmp = bm;
1412 // Special case idx == 0 used for back-from-back jump navigation
1414 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1416 // if the current buffer is not that one, switch to it.
1417 BufferView * doc_bv = current_view_ ?
1418 current_view_->documentBufferView() : 0;
1419 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1420 if (switchToBuffer) {
1421 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1424 doc_bv = current_view_->documentBufferView();
1429 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1430 if (!doc_bv->moveToPosition(
1431 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1438 // Cursor jump succeeded!
1439 Cursor const & cur = doc_bv->cursor();
1440 pit_type new_pit = cur.pit();
1441 pos_type new_pos = cur.pos();
1442 int new_id = cur.paragraph().id();
1444 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1445 // see http://www.lyx.org/trac/ticket/3092
1446 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1447 || bm.top_id != new_id) {
1448 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1449 new_pit, new_pos, new_id);
1453 // This function runs "configure" and then rereads lyx.defaults to
1454 // reconfigure the automatic settings.
1455 void GuiApplication::reconfigure(string const & option)
1457 // emit message signal.
1459 current_view_->message(_("Running configure..."));
1461 // Run configure in user lyx directory
1462 string const lock_file = package().getConfigureLockName();
1463 int fd = fileLock(lock_file.c_str());
1464 int const ret = package().reconfigureUserLyXDir(option);
1465 // emit message signal.
1467 current_view_->message(_("Reloading configuration..."));
1468 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1469 // Re-read packages.lst
1470 LaTeXPackages::getAvailable();
1471 fileUnlock(fd, lock_file.c_str());
1474 Alert::information(_("System reconfiguration failed"),
1475 _("The system reconfiguration has failed.\n"
1476 "Default textclass is used but LyX may\n"
1477 "not be able to work properly.\n"
1478 "Please reconfigure again if needed."));
1480 Alert::information(_("System reconfigured"),
1481 _("The system has been reconfigured.\n"
1482 "You need to restart LyX to make use of any\n"
1483 "updated document class specifications."));
1486 void GuiApplication::validateCurrentView()
1488 if (!d->views_.empty() && !current_view_) {
1489 // currently at least one view exists but no view has the focus.
1490 // choose the last view to make it current.
1491 // a view without any open document is preferred.
1492 GuiView * candidate = 0;
1493 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1494 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1495 for (; it != end; ++it) {
1497 if (!candidate->documentBufferView())
1500 setCurrentView(candidate);
1504 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1506 string const argument = to_utf8(cmd.argument());
1507 FuncCode const action = cmd.action();
1509 LYXERR(Debug::ACTION, "cmd: " << cmd);
1511 // we have not done anything wrong yet.
1514 FuncStatus const flag = getStatus(cmd);
1515 if (!flag.enabled()) {
1516 // We cannot use this function here
1517 LYXERR(Debug::ACTION, "action "
1518 << lyxaction.getActionName(action)
1519 << " [" << action << "] is disabled at this location");
1520 dr.setMessage(flag.message());
1522 dr.dispatched(false);
1523 dr.screenUpdate(Update::None);
1524 dr.clearBufferUpdate();
1528 if (cmd.origin() == FuncRequest::LYXSERVER) {
1529 if (current_view_ && current_view_->currentBufferView())
1530 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1531 // we will also need to redraw the screen at the end
1532 dr.screenUpdate(Update::FitCursor);
1535 // Assumes that the action will be dispatched.
1536 dr.dispatched(true);
1538 switch (cmd.action()) {
1540 case LFUN_WINDOW_NEW:
1541 createView(toqstr(cmd.argument()));
1544 case LFUN_WINDOW_CLOSE:
1545 // update bookmark pit of the current buffer before window close
1546 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1547 gotoBookmark(i+1, false, false);
1548 // clear the last opened list, because
1549 // maybe this will end the session
1550 theSession().lastOpened().clear();
1551 // check for valid current_view_
1552 validateCurrentView();
1554 current_view_->closeScheduled();
1558 // quitting is triggered by the gui code
1559 // (leaving the event loop).
1561 current_view_->message(from_utf8(N_("Exiting.")));
1562 if (closeAllViews())
1566 case LFUN_SCREEN_FONT_UPDATE: {
1567 // handle the screen font changes.
1568 d->font_loader_.update();
1569 // Backup current_view_
1570 GuiView * view = current_view_;
1571 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1572 // to skip the refresh.
1574 theBufferList().changed(false);
1575 // Restore current_view_
1576 current_view_ = view;
1580 case LFUN_BUFFER_NEW:
1581 validateCurrentView();
1582 if (d->views_.empty()
1583 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1584 createView(QString(), false); // keep hidden
1585 current_view_->newDocument(to_utf8(cmd.argument()), false);
1586 current_view_->show();
1587 setActiveWindow(current_view_);
1589 current_view_->newDocument(to_utf8(cmd.argument()), false);
1593 case LFUN_BUFFER_NEW_TEMPLATE:
1594 validateCurrentView();
1595 if (d->views_.empty()
1596 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1598 current_view_->newDocument(to_utf8(cmd.argument()), true);
1599 if (!current_view_->documentBufferView())
1600 current_view_->close();
1602 current_view_->newDocument(to_utf8(cmd.argument()), true);
1606 case LFUN_FILE_OPEN: {
1607 validateCurrentView();
1608 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1609 string const fname = to_utf8(cmd.argument());
1610 bool const is_open = FileName::isAbsolute(fname)
1611 && theBufferList().getBuffer(FileName(fname));
1612 if (d->views_.empty()
1613 || (!lyxrc.open_buffers_in_tabs
1614 && current_view_->documentBufferView() != 0
1616 // We want the ui session to be saved per document and not per
1617 // window number. The filename crc is a good enough identifier.
1618 boost::crc_32_type crc;
1619 crc = for_each(fname.begin(), fname.end(), crc);
1620 createView(crc.checksum());
1621 current_view_->openDocument(fname);
1622 if (current_view_ && !current_view_->documentBufferView())
1623 current_view_->close();
1625 current_view_->openDocument(fname);
1629 case LFUN_HELP_OPEN: {
1630 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1631 if (current_view_ == 0)
1633 string const arg = to_utf8(cmd.argument());
1635 current_view_->message(_("Missing argument"));
1638 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1640 fname = i18nLibFileSearch("examples", arg, "lyx");
1642 if (fname.empty()) {
1643 lyxerr << "LyX: unable to find documentation file `"
1644 << arg << "'. Bad installation?" << endl;
1647 current_view_->message(bformat(_("Opening help file %1$s..."),
1648 makeDisplayPath(fname.absFileName())));
1649 Buffer * buf = current_view_->loadDocument(fname, false);
1651 #ifndef DEVEL_VERSION
1653 buf->setReadonly(true);
1660 case LFUN_SET_COLOR: {
1662 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1663 if (lyx_name.empty() || x11_name.empty()) {
1665 current_view_->message(
1666 _("Syntax: set-color <lyx_name> <x11_name>"));
1671 // FIXME: The graphics cache no longer has a changeDisplay method.
1672 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1673 bool const graphicsbg_changed =
1674 lyx_name == graphicsbg && x11_name != graphicsbg;
1675 if (graphicsbg_changed)
1676 graphics::GCache::get().changeDisplay(true);
1679 if (!lcolor.setColor(lyx_name, x11_name)) {
1681 current_view_->message(
1682 bformat(_("Set-color \"%1$s\" failed "
1683 "- color is undefined or "
1684 "may not be redefined"),
1685 from_utf8(lyx_name)));
1688 // Make sure we don't keep old colors in cache.
1689 d->color_cache_.clear();
1693 case LFUN_LYXRC_APPLY: {
1694 // reset active key sequences, since the bindings
1695 // are updated (bug 6064)
1697 LyXRC const lyxrc_orig = lyxrc;
1699 istringstream ss(to_utf8(cmd.argument()));
1700 bool const success = lyxrc.read(ss);
1703 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1704 << "Unable to read lyxrc data"
1709 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1711 // If the request comes from the minibuffer, then we can't reset
1712 // the GUI, since that would destory the minibuffer itself and
1713 // cause a crash, since we are currently in one of the methods of
1714 // GuiCommandBuffer. See bug #8540.
1715 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1718 // FIXME Unfortunately, that leaves a bug here, since we cannot
1719 // reset the GUI in this case. If the changes to lyxrc affected the
1720 // UI, then, nothing would happen. This seems fairly unlikely, but
1721 // it definitely is a bug.
1726 case LFUN_COMMAND_PREFIX:
1727 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1732 d->meta_fake_bit = NoModifier;
1733 GuiView * gv = currentView();
1734 if (gv && gv->currentBufferView())
1735 // cancel any selection
1736 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1737 dr.setMessage(from_ascii(N_("Cancel")));
1740 case LFUN_META_PREFIX:
1741 d->meta_fake_bit = AltModifier;
1742 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1745 // --- Menus -----------------------------------------------
1746 case LFUN_RECONFIGURE:
1747 // argument is any additional parameter to the configure.py command
1748 reconfigure(to_utf8(cmd.argument()));
1751 // --- lyxserver commands ----------------------------
1752 case LFUN_SERVER_GET_FILENAME: {
1753 if (current_view_ && current_view_->documentBufferView()) {
1754 docstring const fname = from_utf8(
1755 current_view_->documentBufferView()->buffer().absFileName());
1756 dr.setMessage(fname);
1757 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1759 dr.setMessage(docstring());
1760 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1765 case LFUN_SERVER_NOTIFY: {
1766 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1767 dr.setMessage(dispatch_buffer);
1768 theServer().notifyClient(to_utf8(dispatch_buffer));
1772 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1773 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1779 string rest = split(argument, countstr, ' ');
1780 istringstream is(countstr);
1783 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1784 for (int i = 0; i < count; ++i)
1785 dispatch(lyxaction.lookupFunc(rest));
1789 case LFUN_COMMAND_SEQUENCE: {
1790 // argument contains ';'-terminated commands
1791 string arg = argument;
1792 // FIXME: this LFUN should also work without any view.
1793 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1794 ? &(current_view_->documentBufferView()->buffer()) : 0;
1796 buffer->undo().beginUndoGroup();
1797 while (!arg.empty()) {
1799 arg = split(arg, first, ';');
1800 FuncRequest func(lyxaction.lookupFunc(first));
1801 func.setOrigin(cmd.origin());
1804 // the buffer may have been closed by one action
1805 if (theBufferList().isLoaded(buffer))
1806 buffer->undo().endUndoGroup();
1810 case LFUN_BUFFER_FORALL: {
1811 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1813 map<Buffer *, GuiView *> views_lVisible;
1814 map<GuiView *, Buffer *> activeBuffers;
1816 QList<GuiView *> allViews = d->views_.values();
1818 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1819 // and on which buffer is active in each view.
1820 Buffer * const last = theBufferList().last();
1821 foreach (GuiView * view, allViews) {
1822 // all of the buffers might be locally hidden. That is, there is no active buffer.
1823 if (!view || !view->currentBufferView())
1824 activeBuffers[view] = 0;
1826 activeBuffers[view] = &view->currentBufferView()->buffer();
1828 // find out if each is locally visible or locally hidden.
1829 // we don't use a for loop as the buffer list cycles.
1830 Buffer * b = theBufferList().first();
1832 bool const locallyVisible = view && view->workArea(*b);
1833 if (locallyVisible) {
1834 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1835 // only need to overwrite/add if we don't already know a buffer is globally
1836 // visible or we do know but we would prefer to dispatch LFUN from the
1837 // current view because of cursor position issues.
1838 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1839 views_lVisible[b] = view;
1843 b = theBufferList().next(b);
1847 GuiView * const homeView = currentView();
1848 Buffer * b = theBufferList().first();
1849 Buffer * nextBuf = 0;
1850 int numProcessed = 0;
1853 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1855 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1857 // first change to a view where b is locally visible, preferably current_view_.
1858 GuiView * const vLv = views_lVisible[b];
1860 lyx::dispatch(funcToRun);
1868 // put things back to how they were (if possible).
1869 foreach (GuiView * view, allViews) {
1870 Buffer * originalBuf = activeBuffers[view];
1871 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1872 if (theBufferList().isLoaded(originalBuf))
1873 view->setBuffer(originalBuf);
1875 homeView->setFocus();
1877 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1881 case LFUN_COMMAND_ALTERNATIVES: {
1882 // argument contains ';'-terminated commands
1883 string arg = argument;
1884 while (!arg.empty()) {
1886 arg = split(arg, first, ';');
1887 FuncRequest func(lyxaction.lookupFunc(first));
1888 func.setOrigin(cmd.origin());
1889 FuncStatus const stat = getStatus(func);
1890 if (stat.enabled()) {
1900 if (theTopLevelCmdDef().lock(argument, func)) {
1901 func.setOrigin(cmd.origin());
1903 theTopLevelCmdDef().release(argument);
1905 if (func.action() == LFUN_UNKNOWN_ACTION) {
1906 // unknown command definition
1907 lyxerr << "Warning: unknown command definition `"
1911 // recursion detected
1912 lyxerr << "Warning: Recursion in the command definition `"
1913 << argument << "' detected"
1920 case LFUN_PREFERENCES_SAVE:
1921 lyxrc.write(support::makeAbsPath("preferences",
1922 package().user_support().absFileName()), false);
1925 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1926 string const fname = addName(addPath(package().user_support().absFileName(),
1927 "templates/"), "defaults.lyx");
1928 Buffer defaults(fname);
1930 istringstream ss(argument);
1935 // We need to make sure that, after we recreat the DocumentClass,
1936 // which we do in readHeader, we apply it to the document itself.
1937 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
1938 int const unknown_tokens = defaults.readHeader(lex);
1939 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
1941 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
1942 cap::switchBetweenClasses(olddc, newdc, theinset, el);
1944 if (unknown_tokens != 0) {
1945 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1946 << unknown_tokens << " unknown token"
1947 << (unknown_tokens == 1 ? "" : "s")
1951 if (defaults.writeFile(FileName(defaults.absFileName())))
1952 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1953 makeDisplayPath(fname)));
1956 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1961 case LFUN_BOOKMARK_GOTO:
1962 // go to bookmark, open unopened file and switch to buffer if necessary
1963 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1964 dr.screenUpdate(Update::Force | Update::FitCursor);
1967 case LFUN_BOOKMARK_CLEAR:
1968 theSession().bookmarks().clear();
1971 case LFUN_DEBUG_LEVEL_SET:
1972 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1975 case LFUN_DIALOG_SHOW: {
1976 string const name = cmd.getArg(0);
1978 if ( name == "aboutlyx"
1980 || name == "texinfo"
1981 || name == "progress"
1982 || name == "compare")
1984 // work around: on Mac OS the application
1985 // is not terminated when closing the last view.
1986 // Create a new one to be able to dispatch the
1987 // LFUN_DIALOG_SHOW to this view.
1988 if (current_view_ == 0)
1994 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1997 current_view_->dispatch(cmd, dr);
2001 if (cmd.origin() == FuncRequest::LYXSERVER)
2002 updateCurrentView(cmd, dr);
2006 docstring GuiApplication::viewStatusMessage()
2008 // When meta-fake key is pressed, show the key sequence so far + "M-".
2009 if (d->meta_fake_bit != NoModifier)
2010 return d->keyseq.print(KeySequence::ForGui) + "M-";
2012 // Else, when a non-complete key sequence is pressed,
2013 // show the available options.
2014 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2015 return d->keyseq.printOptions(true);
2021 void GuiApplication::handleKeyFunc(FuncCode action)
2025 if (d->keyseq.length())
2027 GuiView * gv = currentView();
2028 LASSERT(gv && gv->currentBufferView(), return);
2029 BufferView * bv = gv->currentBufferView();
2030 bv->getIntl().getTransManager().deadkey(
2031 c, get_accent(action).accent, bv->cursor().innerText(),
2033 // Need to clear, in case the minibuffer calls these
2036 // copied verbatim from do_accent_char
2037 bv->cursor().resetAnchor();
2041 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2043 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2045 // Do nothing if we have nothing (JMarc)
2046 if (!keysym.isOK()) {
2047 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2049 current_view_->restartCursor();
2053 if (keysym.isModifier()) {
2055 current_view_->restartCursor();
2059 char_type encoded_last_key = keysym.getUCSEncoded();
2061 // Do a one-deep top-level lookup for
2062 // cancel and meta-fake keys. RVDK_PATCH_5
2063 d->cancel_meta_seq.reset();
2065 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2066 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2068 // When not cancel or meta-fake, do the normal lookup.
2069 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2070 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2071 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2072 // remove Caps Lock and Mod2 as a modifiers
2073 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2074 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2077 // Dont remove this unless you know what you are doing.
2078 d->meta_fake_bit = NoModifier;
2080 // Can this happen now ?
2081 if (func.action() == LFUN_NOACTION)
2082 func = FuncRequest(LFUN_COMMAND_PREFIX);
2084 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2085 << d->keyseq.print(KeySequence::Portable) << ']');
2087 // already here we know if it any point in going further
2088 // why not return already here if action == -1 and
2089 // num_bytes == 0? (Lgb)
2091 if (d->keyseq.length() > 1 && current_view_)
2092 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2095 // Maybe user can only reach the key via holding down shift.
2096 // Let's see. But only if shift is the only modifier
2097 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2098 LYXERR(Debug::KEY, "Trying without shift");
2099 func = d->keyseq.addkey(keysym, NoModifier);
2100 LYXERR(Debug::KEY, "Action now " << func.action());
2103 if (func.action() == LFUN_UNKNOWN_ACTION) {
2104 // Hmm, we didn't match any of the keysequences. See
2105 // if it's normal insertable text not already covered
2107 if (keysym.isText() && d->keyseq.length() == 1) {
2108 LYXERR(Debug::KEY, "isText() is true, inserting.");
2109 func = FuncRequest(LFUN_SELF_INSERT,
2110 FuncRequest::KEYBOARD);
2112 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
2113 if (current_view_) {
2114 current_view_->message(_("Unknown function."));
2115 current_view_->restartCursor();
2121 if (func.action() == LFUN_SELF_INSERT) {
2122 if (encoded_last_key != 0) {
2123 docstring const arg(1, encoded_last_key);
2124 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2125 FuncRequest::KEYBOARD));
2126 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2129 processFuncRequest(func);
2133 void GuiApplication::processFuncRequest(FuncRequest const & func)
2135 lyx::dispatch(func);
2139 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2141 addToFuncRequestQueue(func);
2142 processFuncRequestQueueAsync();
2146 void GuiApplication::processFuncRequestQueue()
2148 while (!d->func_request_queue_.empty()) {
2149 processFuncRequest(d->func_request_queue_.front());
2150 d->func_request_queue_.pop();
2155 void GuiApplication::processFuncRequestQueueAsync()
2157 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2161 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2163 d->func_request_queue_.push(func);
2167 void GuiApplication::resetGui()
2169 // Set the language defined by the user.
2173 if (!readUIFile(toqstr(lyxrc.ui_file)))
2174 // Gives some error box here.
2177 if (d->global_menubar_)
2178 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2180 QHash<int, GuiView *>::iterator it;
2181 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2184 gv->setLayoutDirection(layoutDirection());
2188 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2192 void GuiApplication::createView(int view_id)
2194 createView(QString(), true, view_id);
2198 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2201 // release the keyboard which might have been grabed by the global
2202 // menubar on Mac to catch shortcuts even without any GuiView.
2203 if (d->global_menubar_)
2204 d->global_menubar_->releaseKeyboard();
2208 while (d->views_.find(id) != d->views_.end())
2211 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2212 GuiView * view = new GuiView(id);
2214 d->views_[id] = view;
2218 setActiveWindow(view);
2221 if (!geometry_arg.isEmpty()) {
2222 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2226 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2227 re.indexIn(geometry_arg);
2228 w = re.cap(1).toInt();
2229 h = re.cap(2).toInt();
2230 x = re.cap(3).toInt();
2231 y = re.cap(4).toInt();
2232 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2233 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2234 // Set initial geometry such that we can get the frame size.
2235 view->setGeometry(x, y, w, h);
2236 int framewidth = view->geometry().x() - view->x();
2237 int titleheight = view->geometry().y() - view->y();
2238 // Negative displacements must be interpreted as distances
2239 // from the right or bottom screen borders.
2240 if (sx == '-' || sy == '-') {
2241 QRect rec = QApplication::desktop()->screenGeometry();
2243 x += rec.width() - w - framewidth;
2245 y += rec.height() - h - titleheight;
2246 view->setGeometry(x, y, w, h);
2248 // Make sure that the left and top frame borders are visible.
2249 if (view->x() < 0 || view->y() < 0) {
2254 view->setGeometry(x, y, w, h);
2262 Clipboard & GuiApplication::clipboard()
2264 return d->clipboard_;
2268 Selection & GuiApplication::selection()
2270 return d->selection_;
2274 FontLoader & GuiApplication::fontLoader()
2276 return d->font_loader_;
2280 Toolbars const & GuiApplication::toolbars() const
2282 return d->toolbars_;
2286 Toolbars & GuiApplication::toolbars()
2288 return d->toolbars_;
2292 Menus const & GuiApplication::menus() const
2298 Menus & GuiApplication::menus()
2304 QList<int> GuiApplication::viewIds() const
2306 return d->views_.keys();
2310 ColorCache & GuiApplication::colorCache()
2312 return d->color_cache_;
2316 int GuiApplication::exec()
2318 // asynchronously handle batch commands. This event will be in
2319 // the event queue in front of other asynchronous events. Hence,
2320 // we can assume in the latter that the gui is setup already.
2321 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2323 return QApplication::exec();
2327 void GuiApplication::exit(int status)
2329 QApplication::exit(status);
2333 void GuiApplication::setGuiLanguage()
2337 // install translation file for Qt built-in dialogs
2338 QString const language_name = QString("qt_") + theLocale.name();
2339 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2340 // Short-named translator can be loaded from a long name, but not the
2341 // opposite. Therefore, long name should be used without truncation.
2342 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2343 if (!d->qt_trans_.load(language_name,
2344 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2345 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2348 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2352 switch (theLocale.language()) {
2353 case QLocale::Arabic :
2354 case QLocale::Hebrew :
2355 case QLocale::Persian :
2356 case QLocale::Urdu :
2357 setLayoutDirection(Qt::RightToLeft);
2360 setLayoutDirection(Qt::LeftToRight);
2365 void GuiApplication::execBatchCommands()
2370 if (!readUIFile(toqstr(lyxrc.ui_file)))
2371 // Gives some error box here.
2375 #if QT_VERSION > 0x040600
2376 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2378 // Create the global default menubar which is shown for the dialogs
2379 // and if no GuiView is visible.
2380 // This must be done after the session was recovered to know the "last files".
2381 d->global_menubar_ = new QMenuBar(0);
2382 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2385 lyx::execBatchCommands();
2389 QAbstractItemModel * GuiApplication::languageModel()
2391 if (d->language_model_)
2392 return d->language_model_;
2394 QStandardItemModel * lang_model = new QStandardItemModel(this);
2395 lang_model->insertColumns(0, 3);
2397 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2398 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2399 Languages::const_iterator it = lyx::languages.begin();
2400 Languages::const_iterator end = lyx::languages.end();
2401 for (; it != end; ++it) {
2402 current_row = lang_model->rowCount();
2403 lang_model->insertRows(current_row, 1);
2404 QModelIndex pl_item = lang_model->index(current_row, 0);
2405 QModelIndex sp_item = lang_model->index(current_row, 1);
2406 QModelIndex th_item = lang_model->index(current_row, 2);
2407 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2408 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2409 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2410 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2411 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2412 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2413 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2414 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2415 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2416 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2418 d->language_model_ = new QSortFilterProxyModel(this);
2419 d->language_model_->setSourceModel(lang_model);
2420 d->language_model_->setSortLocaleAware(true);
2421 return d->language_model_;
2425 void GuiApplication::restoreGuiSession()
2427 if (!lyxrc.load_session)
2430 Session & session = theSession();
2431 LastOpenedSection::LastOpened const & lastopened =
2432 session.lastOpened().getfiles();
2434 validateCurrentView();
2436 FileName active_file;
2437 // do not add to the lastfile list since these files are restored from
2438 // last session, and should be already there (regular files), or should
2439 // not be added at all (help files).
2440 for (size_t i = 0; i < lastopened.size(); ++i) {
2441 FileName const & file_name = lastopened[i].file_name;
2442 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2443 && current_view_->documentBufferView() != 0)) {
2444 boost::crc_32_type crc;
2445 string const & fname = file_name.absFileName();
2446 crc = for_each(fname.begin(), fname.end(), crc);
2447 createView(crc.checksum());
2449 current_view_->loadDocument(file_name, false);
2451 if (lastopened[i].active)
2452 active_file = file_name;
2455 // Restore last active buffer
2456 Buffer * buffer = theBufferList().getBuffer(active_file);
2457 if (buffer && current_view_)
2458 current_view_->setBuffer(buffer);
2460 // clear this list to save a few bytes of RAM
2461 session.lastOpened().clear();
2465 QString const GuiApplication::romanFontName()
2468 font.setStyleHint(QFont::Serif);
2469 font.setFamily("serif");
2471 return QFontInfo(font).family();
2475 QString const GuiApplication::sansFontName()
2478 font.setStyleHint(QFont::SansSerif);
2479 font.setFamily("sans");
2481 return QFontInfo(font).family();
2485 QString const GuiApplication::typewriterFontName()
2488 font.setStyleHint(QFont::TypeWriter);
2489 font.setFamily("monospace");
2491 return QFontInfo(font).family();
2495 void GuiApplication::handleRegularEvents()
2497 ForkedCallsController::handleCompletedProcesses();
2501 bool GuiApplication::event(QEvent * e)
2504 case QEvent::FileOpen: {
2505 // Open a file; this happens only on Mac OS X for now.
2507 // We do this asynchronously because on startup the batch
2508 // commands are not executed here yet and the gui is not ready
2510 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2511 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2512 processFuncRequestAsync(fr);
2517 return QApplication::event(e);
2522 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2525 return QApplication::notify(receiver, event);
2527 catch (ExceptionMessage const & e) {
2529 case ErrorException:
2531 setQuitOnLastWindowClosed(false);
2533 Alert::error(e.title_, e.details_);
2535 // Properly crash in debug mode in order to get a useful backtrace.
2538 // In release mode, try to exit gracefully.
2541 case BufferException: {
2542 if (!current_view_ || !current_view_->documentBufferView())
2544 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2545 docstring details = e.details_ + '\n';
2546 details += buf->emergencyWrite();
2547 theBufferList().release(buf);
2548 details += "\n" + _("The current document was closed.");
2549 Alert::error(e.title_, details);
2552 case WarningException:
2553 Alert::warning(e.title_, e.details_);
2557 catch (exception const & e) {
2558 docstring s = _("LyX has caught an exception, it will now "
2559 "attempt to save all unsaved documents and exit."
2561 s += from_ascii(e.what());
2562 Alert::error(_("Software exception Detected"), s);
2566 docstring s = _("LyX has caught some really weird exception, it will "
2567 "now attempt to save all unsaved documents and exit.");
2568 Alert::error(_("Software exception Detected"), s);
2576 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2578 QColor const & qcol = d->color_cache_.get(col);
2579 if (!qcol.isValid()) {
2585 rgbcol.r = qcol.red();
2586 rgbcol.g = qcol.green();
2587 rgbcol.b = qcol.blue();
2592 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2594 QColor const qcol(lcolor.getX11Name(col).c_str());
2595 if (!qcol.isValid()) {
2601 rgbcol.r = qcol.red();
2602 rgbcol.g = qcol.green();
2603 rgbcol.b = qcol.blue();
2608 string const GuiApplication::hexName(ColorCode col)
2610 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2614 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2616 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2617 d->socket_notifiers_[fd] = sn;
2618 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2622 void GuiApplication::socketDataReceived(int fd)
2624 d->socket_notifiers_[fd]->func_();
2628 void GuiApplication::unregisterSocketCallback(int fd)
2630 d->socket_notifiers_.take(fd)->setEnabled(false);
2634 void GuiApplication::commitData(QSessionManager & sm)
2636 /// The implementation is required to avoid an application exit
2637 /// when session state save is triggered by session manager.
2638 /// The default implementation sends a close event to all
2639 /// visible top level widgets when session managment allows
2641 /// We are changing that to close all wiew one by one.
2642 /// FIXME: verify if the default implementation is enough now.
2643 #ifdef QT_NO_SESSIONMANAGER
2645 #warning Qt is compiled without session manager
2647 #pragma message("warning: Qt is compiled without session manager")
2651 if (sm.allowsInteraction() && !closeAllViews())
2657 void GuiApplication::unregisterView(GuiView * gv)
2659 LAPPERR(d->views_[gv->id()] == gv);
2660 d->views_.remove(gv->id());
2661 if (current_view_ == gv)
2666 bool GuiApplication::closeAllViews()
2668 if (d->views_.empty())
2671 // When a view/window was closed before without quitting LyX, there
2672 // are already entries in the lastOpened list.
2673 theSession().lastOpened().clear();
2675 QList<GuiView *> const views = d->views_.values();
2676 foreach (GuiView * view, views) {
2677 if (!view->closeScheduled())
2686 GuiView & GuiApplication::view(int id) const
2688 LAPPERR(d->views_.contains(id));
2689 return *d->views_.value(id);
2693 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2695 QList<GuiView *> const views = d->views_.values();
2696 foreach (GuiView * view, views)
2697 view->hideDialog(name, inset);
2701 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2703 Buffer const * buffer_ = 0;
2704 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2705 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2706 if (Buffer const * ptr = (*it)->updateInset(inset))
2713 bool GuiApplication::searchMenu(FuncRequest const & func,
2714 docstring_list & names) const
2716 return d->menus_.searchMenu(func, names);
2720 // Ensure that a file is read only once (prevents include loops)
2721 static QStringList uifiles;
2722 // store which ui files define Toolbars
2723 static QStringList toolbar_uifiles;
2726 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2737 LexerKeyword uitags[] = {
2738 { "format", ui_format },
2739 { "include", ui_include },
2740 { "menuset", ui_menuset },
2741 { "toolbars", ui_toolbars },
2742 { "toolbarset", ui_toolbarset }
2746 lex.setFile(ui_path);
2748 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2752 if (lyxerr.debugging(Debug::PARSER))
2753 lex.printTable(lyxerr);
2756 // format before introduction of format tag
2757 unsigned int format = 0;
2758 while (lex.isOK()) {
2759 int const status = lex.lex();
2761 // we have to do this check here, outside the switch,
2762 // because otherwise we would start reading include files,
2763 // e.g., if the first tag we hit was an include tag.
2764 if (status == ui_format)
2766 format = lex.getInteger();
2770 // this will trigger unless the first tag we hit is a format
2771 // tag, with the right format.
2772 if (format != LFUN_FORMAT)
2773 return FormatMismatch;
2776 case Lexer::LEX_FEOF:
2781 QString const file = toqstr(lex.getString());
2782 bool const success = readUIFile(file, true);
2784 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2791 d->menus_.read(lex);
2795 d->toolbars_.readToolbars(lex);
2799 d->toolbars_.readToolbarSettings(lex);
2800 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2804 if (!rtrim(lex.getString()).empty())
2805 lex.printError("LyX::ReadUIFile: "
2806 "Unknown menu tag: `$$Token'");
2808 LYXERR0("Error with status: " << status);
2814 return (error ? ReadError : ReadOK);
2818 bool GuiApplication::readUIFile(QString const & name, bool include)
2820 LYXERR(Debug::INIT, "About to read " << name << "...");
2824 ui_path = libFileSearch("ui", name, "inc");
2825 if (ui_path.empty())
2826 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2828 ui_path = libFileSearch("ui", name, "ui");
2831 if (ui_path.empty()) {
2832 static const QString defaultUIFile = "default";
2833 LYXERR(Debug::INIT, "Could not find " << name);
2835 Alert::warning(_("Could not find UI definition file"),
2836 bformat(_("Error while reading the included file\n%1$s\n"
2837 "Please check your installation."), qstring_to_ucs4(name)));
2840 if (name == defaultUIFile) {
2841 LYXERR(Debug::INIT, "Could not find default UI file!!");
2842 Alert::warning(_("Could not find default UI file"),
2843 _("LyX could not find the default UI file!\n"
2844 "Please check your installation."));
2847 Alert::warning(_("Could not find UI definition file"),
2848 bformat(_("Error while reading the configuration file\n%1$s\n"
2849 "Falling back to default.\n"
2850 "Please look under Tools>Preferences>User Interface and\n"
2851 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2852 return readUIFile(defaultUIFile, false);
2855 QString const uifile = toqstr(ui_path.absFileName());
2856 if (uifiles.contains(uifile)) {
2858 // We are reading again the top uifile so reset the safeguard:
2861 d->toolbars_.reset();
2863 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2864 << "Is this an include loop?");
2868 uifiles.push_back(uifile);
2870 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2872 ReturnValues retval = readUIFile(ui_path);
2874 if (retval == FormatMismatch) {
2875 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2876 TempFile tmp("convertXXXXXX.ui");
2877 FileName const tempfile = tmp.name();
2878 bool const success = prefs2prefs(ui_path, tempfile, true);
2880 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2881 " to format " << LFUN_FORMAT << ".");
2883 retval = readUIFile(tempfile);
2887 if (retval != ReadOK) {
2888 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2896 settings.beginGroup("ui_files");
2897 bool touched = false;
2898 for (int i = 0; i != uifiles.size(); ++i) {
2899 QFileInfo fi(uifiles[i]);
2900 QDateTime const date_value = fi.lastModified();
2901 QString const name_key = QString::number(i);
2902 // if an ui file which defines Toolbars has changed,
2903 // we have to reset the settings
2904 if (toolbar_uifiles.contains(uifiles[i])
2905 && (!settings.contains(name_key)
2906 || settings.value(name_key).toString() != uifiles[i]
2907 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2909 settings.setValue(name_key, uifiles[i]);
2910 settings.setValue(name_key + "/date", date_value);
2913 settings.endGroup();
2915 settings.remove("views");
2921 void GuiApplication::onLastWindowClosed()
2923 if (d->global_menubar_)
2924 d->global_menubar_->grabKeyboard();
2928 void GuiApplication::startLongOperation() {
2929 d->key_checker_.start();
2933 bool GuiApplication::longOperationCancelled() {
2934 return d->key_checker_.pressed();
2938 void GuiApplication::stopLongOperation() {
2939 d->key_checker_.stop();
2943 bool GuiApplication::longOperationStarted() {
2944 return d->key_checker_.started();
2948 ////////////////////////////////////////////////////////////////////////
2950 // X11 specific stuff goes here...
2954 bool GuiApplication::x11EventFilter(XEvent * xev)
2959 switch (xev->type) {
2960 case SelectionRequest: {
2961 if (xev->xselectionrequest.selection != XA_PRIMARY)
2963 LYXERR(Debug::SELECTION, "X requested selection.");
2964 BufferView * bv = current_view_->currentBufferView();
2966 docstring const sel = bv->requestSelection();
2968 d->selection_.put(sel);
2972 case SelectionClear: {
2973 if (xev->xselectionclear.selection != XA_PRIMARY)
2975 LYXERR(Debug::SELECTION, "Lost selection.");
2976 BufferView * bv = current_view_->currentBufferView();
2978 bv->clearSelection();
2986 } // namespace frontend
2989 void hideDialogs(std::string const & name, Inset * inset)
2992 frontend::guiApp->hideDialogs(name, inset);
2996 ////////////////////////////////////////////////////////////////////
3000 ////////////////////////////////////////////////////////////////////
3002 frontend::FontLoader & theFontLoader()
3004 LAPPERR(frontend::guiApp);
3005 return frontend::guiApp->fontLoader();
3009 frontend::FontMetrics const & theFontMetrics(Font const & f)
3011 return theFontMetrics(f.fontInfo());
3015 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3017 LAPPERR(frontend::guiApp);
3018 return frontend::guiApp->fontLoader().metrics(f);
3022 ////////////////////////////////////////////////////////////////////
3026 ////////////////////////////////////////////////////////////////////
3028 frontend::Clipboard & theClipboard()
3030 LAPPERR(frontend::guiApp);
3031 return frontend::guiApp->clipboard();
3035 frontend::Selection & theSelection()
3037 LAPPERR(frontend::guiApp);
3038 return frontend::guiApp->selection();
3044 #include "moc_GuiApplication.cpp"