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, "svgz,png", mode);
524 return toqstr(fname.absFileName());
526 fname = imageLibFileSearch(imagedir, name2, "svgz,png", mode);
528 return toqstr(fname.absFileName());
531 path = ":/images/" + path;
534 LYXERR0("Directory " << path << " not found in resource!");
537 if (res.exists(name1 + ".svgz"))
538 return path + name1 + ".svgz";
539 else if (res.exists(name1 + ".png"))
540 return path + name1 + ".png";
542 if (res.exists(name2 + ".svgz"))
543 return path + name2 + ".svgz";
544 else if (res.exists(name2 + ".png"))
545 return path + name2 + ".png";
547 LYXERR(Debug::GUI, "Cannot find icon with filename "
548 << "\"" << name1 << ".{svgz,png}\""
550 << "\"" << name2 << ".{svgz,png}\""
552 << lyxaction.getActionName(f.action())
553 << '(' << to_utf8(f.argument()) << ")\"");
556 QString imagedir = "images/";
557 FileName fname = imageLibFileSearch(imagedir, "unknown", "svgz,png", mode);
559 return toqstr(fname.absFileName());
560 return QString(":/images/unknown.png");
566 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
569 QString imagedir = path;
570 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
571 QString fpath = toqstr(fname.absFileName());
573 if (pixmap.load(fpath)) {
576 QStringList exts = ext.split(",");
577 fpath = ":/" + path + name + ".";
578 for (int i = 0; i < exts.size(); ++i) {
579 if (pixmap.load(fpath + exts.at(i)))
584 bool const list = ext.contains(",");
585 LYXERR0("Cannot load pixmap \""
586 << path << name << "." << (list ? "{" : "") << ext
587 << (list ? "}" : "") << "\", please verify resource system!");
592 QIcon getIcon(FuncRequest const & f, bool unknown)
594 #if (QT_VERSION >= 0x040600)
595 if (lyxrc.use_system_theme_icons) {
596 QString action = toqstr(lyxaction.getActionName(f.action()));
597 if (!f.argument().empty())
598 action += " " + toqstr(f.argument());
599 QString const theme_icon = themeIconName(action);
600 if (QIcon::hasThemeIcon(theme_icon))
601 return QIcon::fromTheme(theme_icon);
605 QString icon = iconName(f, unknown);
609 //LYXERR(Debug::GUI, "Found icon: " << icon);
611 if (!pm.load(icon)) {
612 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
620 ////////////////////////////////////////////////////////////////////////
622 // LyX server support code.
624 ////////////////////////////////////////////////////////////////////////
626 class SocketNotifier : public QSocketNotifier
629 /// connect a connection notification from the LyXServerSocket
630 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
631 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
635 /// The callback function
636 Application::SocketCallback func_;
640 ////////////////////////////////////////////////////////////////////////
642 // Mac specific stuff goes here...
644 ////////////////////////////////////////////////////////////////////////
646 class MenuTranslator : public QTranslator
649 MenuTranslator(QObject * parent)
650 : QTranslator(parent)
653 #if QT_VERSION >= 0x050000
654 virtual QString translate(const char * /* context */,
655 const char *sourceText,
656 const char * /* disambiguation */ = 0, int /* n */ = -1) const
658 QString translate(const char * /*context*/,
659 const char * sourceText,
660 const char * /*comment*/ = 0) const
663 string const s = sourceText;
664 if (s == N_("About %1") || s == N_("Preferences")
665 || s == N_("Reconfigure") || s == N_("Quit %1"))
673 // QMacPasteboardMimeGraphics can only be compiled on Mac.
675 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
678 QMacPasteboardMimeGraphics()
679 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
682 QString convertorName() { return "Graphics"; }
684 QString flavorFor(QString const & mime)
686 LYXERR(Debug::ACTION, "flavorFor " << mime);
687 if (mime == pdfMimeType())
688 return QLatin1String("com.adobe.pdf");
692 QString mimeFor(QString flav)
694 LYXERR(Debug::ACTION, "mimeFor " << flav);
695 if (flav == QLatin1String("com.adobe.pdf"))
696 return pdfMimeType();
700 bool canConvert(QString const & mime, QString flav)
702 return mimeFor(flav) == mime;
705 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
709 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
713 QList<QByteArray> convertFromMime(QString const & /*mime*/,
714 QVariant data, QString /*flav*/)
716 QList<QByteArray> ret;
717 ret.append(data.toByteArray());
723 ///////////////////////////////////////////////////////////////
725 // You can find more platform specific stuff at the end of this file...
727 ///////////////////////////////////////////////////////////////
729 ////////////////////////////////////////////////////////////////////////
730 // Windows specific stuff goes here...
732 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
733 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
734 // QWindowsMimeMetafile can only be compiled on Windows.
736 static FORMATETC cfFromMime(QString const & mimetype)
739 if (mimetype == emfMimeType()) {
740 formatetc.cfFormat = CF_ENHMETAFILE;
741 formatetc.tymed = TYMED_ENHMF;
742 } else if (mimetype == wmfMimeType()) {
743 formatetc.cfFormat = CF_METAFILEPICT;
744 formatetc.tymed = TYMED_MFPICT;
747 formatetc.dwAspect = DVASPECT_CONTENT;
748 formatetc.lindex = -1;
753 class QWindowsMimeMetafile : public QWINDOWSMIME {
755 QWindowsMimeMetafile() {}
757 bool canConvertFromMime(FORMATETC const & formatetc,
758 QMimeData const * mimedata) const
763 bool canConvertToMime(QString const & mimetype,
764 IDataObject * pDataObj) const
766 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
768 FORMATETC formatetc = cfFromMime(mimetype);
769 return pDataObj->QueryGetData(&formatetc) == S_OK;
772 bool convertFromMime(FORMATETC const & formatetc,
773 const QMimeData * mimedata, STGMEDIUM * pmedium) const
778 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
779 QVariant::Type preferredType) const
782 if (!canConvertToMime(mimetype, pDataObj))
785 FORMATETC formatetc = cfFromMime(mimetype);
787 if (pDataObj->GetData(&formatetc, &s) != S_OK)
791 if (s.tymed == TYMED_ENHMF) {
792 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
793 data.resize(dataSize);
794 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
795 (LPBYTE)data.data());
796 } else if (s.tymed == TYMED_MFPICT) {
797 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
798 data.resize(dataSize);
799 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
800 (LPBYTE)data.data());
803 ReleaseStgMedium(&s);
809 QVector<FORMATETC> formatsForMime(QString const & mimetype,
810 QMimeData const * mimedata) const
812 QVector<FORMATETC> formats;
813 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
814 formats += cfFromMime(mimetype);
818 QString mimeForFormat(FORMATETC const & formatetc) const
820 switch (formatetc.cfFormat) {
822 return emfMimeType();
823 case CF_METAFILEPICT:
824 return wmfMimeType();
834 /// Allows to check whether ESC was pressed during a long operation
835 class KeyChecker : public QObject {
840 KeyChecker() : pressed_(false), started_(false) {}
843 QCoreApplication::instance()->installEventFilter(this);
848 QCoreApplication::instance()->removeEventFilter(this);
852 QCoreApplication::processEvents();
855 bool started() const {
858 bool eventFilter(QObject *obj, QEvent *event) {
859 LYXERR(Debug::ACTION, "Event Type: " << event->type());
860 switch (event->type()) {
864 case QEvent::UpdateRequest:
865 case QEvent::CursorChange:
866 case QEvent::ActionChanged:
867 case QEvent::EnabledChange:
868 case QEvent::SockAct:
871 case QEvent::ToolTipChange:
872 case QEvent::LayoutRequest:
873 case QEvent::MetaCall:
874 return QObject::eventFilter(obj, event);
876 // FIXME Blocking all these events is a bad idea.
877 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
878 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
886 ////////////////////////////////////////////////////////////////////////
887 // GuiApplication::Private definition and implementation.
888 ////////////////////////////////////////////////////////////////////////
890 struct GuiApplication::Private
892 Private(): language_model_(0), meta_fake_bit(NoModifier),
895 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
896 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
897 /// WMF Mime handler for Windows clipboard.
898 wmf_mime_ = new QWindowsMimeMetafile;
901 initKeySequences(&theTopLevelKeymap());
904 void initKeySequences(KeyMap * kb)
906 keyseq = KeySequence(kb, kb);
907 cancel_meta_seq = KeySequence(kb, kb);
911 QSortFilterProxyModel * language_model_;
913 GuiClipboard clipboard_;
915 GuiSelection selection_;
917 FontLoader font_loader_;
919 ColorCache color_cache_;
921 QTranslator qt_trans_;
923 QHash<int, SocketNotifier *> socket_notifiers_;
927 /// The global instance
930 /// this timer is used for any regular events one wants to
931 /// perform. at present it is used to check if forked processes
933 QTimer general_timer_;
935 /// delayed FuncRequests
936 std::queue<FuncRequest> func_request_queue_;
941 KeySequence cancel_meta_seq;
943 KeyModifier meta_fake_bit;
945 /// Multiple views container.
947 * Warning: This must not be a smart pointer as the destruction of the
948 * object is handled by Qt when the view is closed
949 * \sa Qt::WA_DeleteOnClose attribute.
951 QHash<int, GuiView *> views_;
953 /// Only used on mac.
954 QMenuBar * global_menubar_;
957 /// Linkback mime handler for MacOSX.
958 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
961 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
962 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
963 /// WMF Mime handler for Windows clipboard.
964 QWindowsMimeMetafile * wmf_mime_;
968 /// Allows to check whether ESC was pressed during a long operation
969 KeyChecker key_checker_;
973 GuiApplication * guiApp;
975 GuiApplication::~GuiApplication()
978 closeAllLinkBackLinks();
984 GuiApplication::GuiApplication(int & argc, char ** argv)
985 : QApplication(argc, argv), current_view_(0),
986 d(new GuiApplication::Private)
988 QString app_name = "LyX";
989 QCoreApplication::setOrganizationName(app_name);
990 QCoreApplication::setOrganizationDomain("lyx.org");
991 QCoreApplication::setApplicationName(lyx_package);
993 qsrand(QDateTime::currentDateTime().toTime_t());
995 // Install translator for GUI elements.
996 installTranslator(&d->qt_trans_);
998 // FIXME: quitOnLastWindowClosed is true by default. We should have a
999 // lyxrc setting for this in order to let the application stay resident.
1000 // But then we need some kind of dock icon, at least on Windows.
1002 if (lyxrc.quit_on_last_window_closed)
1003 setQuitOnLastWindowClosed(false);
1006 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1007 // seems to be the default case for applications like LyX.
1008 setQuitOnLastWindowClosed(false);
1009 // This allows to translate the strings that appear in the LyX menu.
1010 /// A translator suitable for the entries in the LyX menu.
1011 /// Only needed with Qt/Mac.
1012 installTranslator(new MenuTranslator(this));
1017 #if defined(Q_WS_X11) || defined(QPA_XCB)
1018 // doubleClickInterval() is 400 ms on X11 which is just too long.
1019 // On Windows and Mac OS X, the operating system's value is used.
1020 // On Microsoft Windows, calling this function sets the double
1021 // click interval for all applications. So we don't!
1022 QApplication::setDoubleClickInterval(300);
1025 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1027 // needs to be done before reading lyxrc
1029 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1033 // Set the cache to 5120 kilobytes which corresponds to screen size of
1034 // 1280 by 1024 pixels with a color depth of 32 bits.
1035 QPixmapCache::setCacheLimit(5120);
1037 // Initialize RC Fonts
1038 if (lyxrc.roman_font_name.empty())
1039 lyxrc.roman_font_name = fromqstr(romanFontName());
1041 if (lyxrc.sans_font_name.empty())
1042 lyxrc.sans_font_name = fromqstr(sansFontName());
1044 if (lyxrc.typewriter_font_name.empty())
1045 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1047 d->general_timer_.setInterval(500);
1048 connect(&d->general_timer_, SIGNAL(timeout()),
1049 this, SLOT(handleRegularEvents()));
1050 d->general_timer_.start();
1052 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1053 // This is clearly not enough in a time where we use threads for
1054 // document preview and/or export. 20 should be OK.
1055 QThreadPool::globalInstance()->setMaxThreadCount(20);
1059 GuiApplication * theGuiApp()
1061 return dynamic_cast<GuiApplication *>(theApp());
1065 double GuiApplication::pixelRatio() const
1067 #if QT_VERSION >= 0x050000
1068 return devicePixelRatio();
1075 void GuiApplication::clearSession()
1082 docstring Application::iconName(FuncRequest const & f, bool unknown)
1084 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1088 docstring Application::mathIcon(docstring const & c)
1090 return qstring_to_ucs4(findPng(toqstr(c)));
1094 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1098 BufferView * bv = 0;
1099 BufferView * doc_bv = 0;
1101 if (cmd.action() == LFUN_NOACTION) {
1102 status.message(from_utf8(N_("Nothing to do")));
1103 status.setEnabled(false);
1106 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1107 status.setUnknown(true);
1108 status.message(from_utf8(N_("Unknown action")));
1109 status.setEnabled(false);
1112 // Does the GuiApplication know something?
1113 else if (getStatus(cmd, status)) { }
1115 // If we do not have a GuiView, then other functions are disabled
1116 else if (!current_view_)
1117 status.setEnabled(false);
1119 // Does the GuiView know something?
1120 else if (current_view_->getStatus(cmd, status)) { }
1122 // In LyX/Mac, when a dialog is open, the menus of the
1123 // application can still be accessed without giving focus to
1124 // the main window. In this case, we want to disable the menu
1125 // entries that are buffer or view-related.
1126 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1128 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1129 status.setEnabled(false);
1132 // If we do not have a BufferView, then other functions are disabled
1133 else if (!(bv = current_view_->currentBufferView()))
1134 status.setEnabled(false);
1136 // Does the current BufferView know something?
1137 else if (bv->getStatus(cmd, status)) { }
1139 // Does the current Buffer know something?
1140 else if (bv->buffer().getStatus(cmd, status)) { }
1142 // If we do not have a document BufferView, different from the
1143 // current BufferView, then other functions are disabled
1144 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1145 status.setEnabled(false);
1147 // Does the document Buffer know something?
1148 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1151 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1152 status.message(from_utf8(N_("Command not handled")));
1153 status.setEnabled(false);
1156 // the default error message if we disable the command
1157 if (!status.enabled() && status.message().empty())
1158 status.message(from_utf8(N_("Command disabled")));
1164 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1166 // I would really like to avoid having this switch and rather try to
1167 // encode this in the function itself.
1168 // -- And I'd rather let an inset decide which LFUNs it is willing
1169 // to handle (Andre')
1171 switch (cmd.action()) {
1173 // This could be used for the no-GUI version. The GUI version is handled in
1174 // GuiView::getStatus(). See above.
1176 case LFUN_BUFFER_WRITE:
1177 case LFUN_BUFFER_WRITE_AS: {
1178 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1179 enable = b && (b->isUnnamed() || !b->isClean());
1184 case LFUN_BOOKMARK_GOTO: {
1185 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1186 enable = theSession().bookmarks().isValid(num);
1190 case LFUN_BOOKMARK_CLEAR:
1191 enable = theSession().bookmarks().hasValid();
1194 // this one is difficult to get right. As a half-baked
1195 // solution, we consider only the first action of the sequence
1196 case LFUN_COMMAND_SEQUENCE: {
1197 // argument contains ';'-terminated commands
1198 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1199 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1200 func.setOrigin(cmd.origin());
1201 flag = getStatus(func);
1205 // we want to check if at least one of these is enabled
1206 case LFUN_COMMAND_ALTERNATIVES: {
1207 // argument contains ';'-terminated commands
1208 string arg = to_utf8(cmd.argument());
1209 while (!arg.empty()) {
1211 arg = split(arg, first, ';');
1212 FuncRequest func(lyxaction.lookupFunc(first));
1213 func.setOrigin(cmd.origin());
1214 flag = getStatus(func);
1215 // if this one is enabled, the whole thing is
1224 string name = to_utf8(cmd.argument());
1225 if (theTopLevelCmdDef().lock(name, func)) {
1226 func.setOrigin(cmd.origin());
1227 flag = getStatus(func);
1228 theTopLevelCmdDef().release(name);
1230 // catch recursion or unknown command
1231 // definition. all operations until the
1232 // recursion or unknown command definition
1233 // occurs are performed, so set the state to
1240 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1242 case LFUN_PREFERENCES_SAVE:
1243 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1244 case LFUN_DEBUG_LEVEL_SET:
1245 // these are handled in our dispatch()
1248 case LFUN_WINDOW_CLOSE:
1249 enable = d->views_.size() > 0;
1252 case LFUN_BUFFER_NEW:
1253 case LFUN_BUFFER_NEW_TEMPLATE:
1254 case LFUN_FILE_OPEN:
1255 case LFUN_HELP_OPEN:
1256 case LFUN_SCREEN_FONT_UPDATE:
1257 case LFUN_SET_COLOR:
1258 case LFUN_WINDOW_NEW:
1260 case LFUN_LYXRC_APPLY:
1261 case LFUN_COMMAND_PREFIX:
1263 case LFUN_META_PREFIX:
1264 case LFUN_RECONFIGURE:
1265 case LFUN_SERVER_GET_FILENAME:
1266 case LFUN_SERVER_NOTIFY:
1270 case LFUN_BUFFER_FORALL: {
1271 if (theBufferList().empty()) {
1272 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1273 flag.setEnabled(false);
1277 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1278 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1279 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1280 flag.setEnabled(false);
1285 case LFUN_DIALOG_SHOW: {
1286 string const name = cmd.getArg(0);
1287 return name == "aboutlyx"
1289 || name == "texinfo"
1290 || name == "progress"
1291 || name == "compare";
1299 flag.setEnabled(false);
1303 /// make a post-dispatch status message
1304 static docstring makeDispatchMessage(docstring const & msg,
1305 FuncRequest const & cmd)
1307 const bool verbose = (cmd.origin() == FuncRequest::MENU
1308 || cmd.origin() == FuncRequest::TOOLBAR
1309 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1311 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1312 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1316 docstring dispatch_msg = msg;
1317 if (!dispatch_msg.empty())
1318 dispatch_msg += ' ';
1320 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1322 bool argsadded = false;
1324 if (!cmd.argument().empty()) {
1325 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1326 comname += ' ' + cmd.argument();
1330 docstring const shortcuts = theTopLevelKeymap().
1331 printBindings(cmd, KeySequence::ForGui);
1333 if (!shortcuts.empty())
1334 comname += ": " + shortcuts;
1335 else if (!argsadded && !cmd.argument().empty())
1336 comname += ' ' + cmd.argument();
1338 if (!comname.empty()) {
1339 comname = rtrim(comname);
1340 dispatch_msg += '(' + rtrim(comname) + ')';
1342 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1343 return dispatch_msg;
1347 void GuiApplication::dispatch(FuncRequest const & cmd)
1349 Buffer * buffer = 0;
1350 if (current_view_ && current_view_->currentBufferView()) {
1351 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1352 buffer = ¤t_view_->currentBufferView()->buffer();
1354 buffer->undo().beginUndoGroup();
1358 // redraw the screen at the end (first of the two drawing steps).
1359 // This is done unless explicitly requested otherwise
1360 dr.screenUpdate(Update::FitCursor);
1362 updateCurrentView(cmd, dr);
1364 // the buffer may have been closed by one action
1365 if (theBufferList().isLoaded(buffer))
1366 buffer->undo().endUndoGroup();
1370 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1375 BufferView * bv = current_view_->currentBufferView();
1377 if (dr.needBufferUpdate()) {
1378 bv->cursor().clearBufferUpdate();
1379 bv->buffer().updateBuffer();
1381 // BufferView::update() updates the ViewMetricsInfo and
1382 // also initializes the position cache for all insets in
1383 // (at least partially) visible top-level paragraphs.
1384 // We will redraw the screen only if needed.
1385 bv->processUpdateFlags(dr.screenUpdate());
1387 // Do we have a selection?
1388 theSelection().haveSelection(bv->cursor().selection());
1391 current_view_->restartCursor();
1393 if (dr.needMessageUpdate()) {
1394 // Some messages may already be translated, so we cannot use _()
1395 current_view_->message(makeDispatchMessage(
1396 translateIfPossible(dr.message()), cmd));
1401 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1402 bool switchToBuffer)
1404 if (!theSession().bookmarks().isValid(idx))
1406 BookmarksSection::Bookmark const & bm =
1407 theSession().bookmarks().bookmark(idx);
1408 LASSERT(!bm.filename.empty(), return);
1409 string const file = bm.filename.absFileName();
1410 // if the file is not opened, open it.
1411 if (!theBufferList().exists(bm.filename)) {
1413 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1417 // open may fail, so we need to test it again
1418 if (!theBufferList().exists(bm.filename))
1421 // bm can be changed when saving
1422 BookmarksSection::Bookmark tmp = bm;
1424 // Special case idx == 0 used for back-from-back jump navigation
1426 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1428 // if the current buffer is not that one, switch to it.
1429 BufferView * doc_bv = current_view_ ?
1430 current_view_->documentBufferView() : 0;
1431 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1432 if (switchToBuffer) {
1433 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1436 doc_bv = current_view_->documentBufferView();
1441 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1442 if (!doc_bv->moveToPosition(
1443 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1450 // Cursor jump succeeded!
1451 Cursor const & cur = doc_bv->cursor();
1452 pit_type new_pit = cur.pit();
1453 pos_type new_pos = cur.pos();
1454 int new_id = cur.paragraph().id();
1456 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1457 // see http://www.lyx.org/trac/ticket/3092
1458 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1459 || bm.top_id != new_id) {
1460 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1461 new_pit, new_pos, new_id);
1465 // This function runs "configure" and then rereads lyx.defaults to
1466 // reconfigure the automatic settings.
1467 void GuiApplication::reconfigure(string const & option)
1469 // emit message signal.
1471 current_view_->message(_("Running configure..."));
1473 // Run configure in user lyx directory
1474 string const lock_file = package().getConfigureLockName();
1475 int fd = fileLock(lock_file.c_str());
1476 int const ret = package().reconfigureUserLyXDir(option);
1477 // emit message signal.
1479 current_view_->message(_("Reloading configuration..."));
1480 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1481 // Re-read packages.lst
1482 LaTeXPackages::getAvailable();
1483 fileUnlock(fd, lock_file.c_str());
1486 Alert::information(_("System reconfiguration failed"),
1487 _("The system reconfiguration has failed.\n"
1488 "Default textclass is used but LyX may\n"
1489 "not be able to work properly.\n"
1490 "Please reconfigure again if needed."));
1492 Alert::information(_("System reconfigured"),
1493 _("The system has been reconfigured.\n"
1494 "You need to restart LyX to make use of any\n"
1495 "updated document class specifications."));
1498 void GuiApplication::validateCurrentView()
1500 if (!d->views_.empty() && !current_view_) {
1501 // currently at least one view exists but no view has the focus.
1502 // choose the last view to make it current.
1503 // a view without any open document is preferred.
1504 GuiView * candidate = 0;
1505 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1506 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1507 for (; it != end; ++it) {
1509 if (!candidate->documentBufferView())
1512 setCurrentView(candidate);
1516 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1518 string const argument = to_utf8(cmd.argument());
1519 FuncCode const action = cmd.action();
1521 LYXERR(Debug::ACTION, "cmd: " << cmd);
1523 // we have not done anything wrong yet.
1526 FuncStatus const flag = getStatus(cmd);
1527 if (!flag.enabled()) {
1528 // We cannot use this function here
1529 LYXERR(Debug::ACTION, "action "
1530 << lyxaction.getActionName(action)
1531 << " [" << action << "] is disabled at this location");
1532 dr.setMessage(flag.message());
1534 dr.dispatched(false);
1535 dr.screenUpdate(Update::None);
1536 dr.clearBufferUpdate();
1540 if (cmd.origin() == FuncRequest::LYXSERVER) {
1541 if (current_view_ && current_view_->currentBufferView())
1542 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1543 // we will also need to redraw the screen at the end
1544 dr.screenUpdate(Update::FitCursor);
1547 // Assumes that the action will be dispatched.
1548 dr.dispatched(true);
1550 switch (cmd.action()) {
1552 case LFUN_WINDOW_NEW:
1553 createView(toqstr(cmd.argument()));
1556 case LFUN_WINDOW_CLOSE:
1557 // update bookmark pit of the current buffer before window close
1558 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1559 gotoBookmark(i+1, false, false);
1560 // clear the last opened list, because
1561 // maybe this will end the session
1562 theSession().lastOpened().clear();
1563 // check for valid current_view_
1564 validateCurrentView();
1566 current_view_->closeScheduled();
1570 // quitting is triggered by the gui code
1571 // (leaving the event loop).
1573 current_view_->message(from_utf8(N_("Exiting.")));
1574 if (closeAllViews())
1578 case LFUN_SCREEN_FONT_UPDATE: {
1579 // handle the screen font changes.
1580 d->font_loader_.update();
1581 // Backup current_view_
1582 GuiView * view = current_view_;
1583 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1584 // to skip the refresh.
1586 theBufferList().changed(false);
1587 // Restore current_view_
1588 current_view_ = view;
1592 case LFUN_BUFFER_NEW:
1593 validateCurrentView();
1594 if (d->views_.empty()
1595 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1596 createView(QString(), false); // keep hidden
1597 current_view_->newDocument(to_utf8(cmd.argument()), false);
1598 current_view_->show();
1599 setActiveWindow(current_view_);
1601 current_view_->newDocument(to_utf8(cmd.argument()), false);
1605 case LFUN_BUFFER_NEW_TEMPLATE:
1606 validateCurrentView();
1607 if (d->views_.empty()
1608 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1610 current_view_->newDocument(to_utf8(cmd.argument()), true);
1611 if (!current_view_->documentBufferView())
1612 current_view_->close();
1614 current_view_->newDocument(to_utf8(cmd.argument()), true);
1618 case LFUN_FILE_OPEN: {
1619 validateCurrentView();
1620 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1621 string const fname = to_utf8(cmd.argument());
1622 bool const is_open = FileName::isAbsolute(fname)
1623 && theBufferList().getBuffer(FileName(fname));
1624 if (d->views_.empty()
1625 || (!lyxrc.open_buffers_in_tabs
1626 && current_view_->documentBufferView() != 0
1628 // We want the ui session to be saved per document and not per
1629 // window number. The filename crc is a good enough identifier.
1630 boost::crc_32_type crc;
1631 crc = for_each(fname.begin(), fname.end(), crc);
1632 createView(crc.checksum());
1633 current_view_->openDocument(fname);
1634 if (current_view_ && !current_view_->documentBufferView())
1635 current_view_->close();
1637 current_view_->openDocument(fname);
1641 case LFUN_HELP_OPEN: {
1642 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1643 if (current_view_ == 0)
1645 string const arg = to_utf8(cmd.argument());
1647 current_view_->message(_("Missing argument"));
1650 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1652 fname = i18nLibFileSearch("examples", arg, "lyx");
1654 if (fname.empty()) {
1655 lyxerr << "LyX: unable to find documentation file `"
1656 << arg << "'. Bad installation?" << endl;
1659 current_view_->message(bformat(_("Opening help file %1$s..."),
1660 makeDisplayPath(fname.absFileName())));
1661 Buffer * buf = current_view_->loadDocument(fname, false);
1663 #ifndef DEVEL_VERSION
1665 buf->setReadonly(true);
1672 case LFUN_SET_COLOR: {
1674 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1675 if (lyx_name.empty() || x11_name.empty()) {
1677 current_view_->message(
1678 _("Syntax: set-color <lyx_name> <x11_name>"));
1683 // FIXME: The graphics cache no longer has a changeDisplay method.
1684 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1685 bool const graphicsbg_changed =
1686 lyx_name == graphicsbg && x11_name != graphicsbg;
1687 if (graphicsbg_changed)
1688 graphics::GCache::get().changeDisplay(true);
1691 if (!lcolor.setColor(lyx_name, x11_name)) {
1693 current_view_->message(
1694 bformat(_("Set-color \"%1$s\" failed "
1695 "- color is undefined or "
1696 "may not be redefined"),
1697 from_utf8(lyx_name)));
1700 // Make sure we don't keep old colors in cache.
1701 d->color_cache_.clear();
1705 case LFUN_LYXRC_APPLY: {
1706 // reset active key sequences, since the bindings
1707 // are updated (bug 6064)
1709 LyXRC const lyxrc_orig = lyxrc;
1711 istringstream ss(to_utf8(cmd.argument()));
1712 bool const success = lyxrc.read(ss);
1715 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1716 << "Unable to read lyxrc data"
1721 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1723 // If the request comes from the minibuffer, then we can't reset
1724 // the GUI, since that would destory the minibuffer itself and
1725 // cause a crash, since we are currently in one of the methods of
1726 // GuiCommandBuffer. See bug #8540.
1727 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1730 // FIXME Unfortunately, that leaves a bug here, since we cannot
1731 // reset the GUI in this case. If the changes to lyxrc affected the
1732 // UI, then, nothing would happen. This seems fairly unlikely, but
1733 // it definitely is a bug.
1738 case LFUN_COMMAND_PREFIX:
1739 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1744 d->meta_fake_bit = NoModifier;
1745 GuiView * gv = currentView();
1746 if (gv && gv->currentBufferView())
1747 // cancel any selection
1748 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1749 dr.setMessage(from_ascii(N_("Cancel")));
1752 case LFUN_META_PREFIX:
1753 d->meta_fake_bit = AltModifier;
1754 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1757 // --- Menus -----------------------------------------------
1758 case LFUN_RECONFIGURE:
1759 // argument is any additional parameter to the configure.py command
1760 reconfigure(to_utf8(cmd.argument()));
1763 // --- lyxserver commands ----------------------------
1764 case LFUN_SERVER_GET_FILENAME: {
1765 if (current_view_ && current_view_->documentBufferView()) {
1766 docstring const fname = from_utf8(
1767 current_view_->documentBufferView()->buffer().absFileName());
1768 dr.setMessage(fname);
1769 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1771 dr.setMessage(docstring());
1772 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1777 case LFUN_SERVER_NOTIFY: {
1778 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1779 dr.setMessage(dispatch_buffer);
1780 theServer().notifyClient(to_utf8(dispatch_buffer));
1784 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1785 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1791 string rest = split(argument, countstr, ' ');
1792 istringstream is(countstr);
1795 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1796 for (int i = 0; i < count; ++i)
1797 dispatch(lyxaction.lookupFunc(rest));
1801 case LFUN_COMMAND_SEQUENCE: {
1802 // argument contains ';'-terminated commands
1803 string arg = argument;
1804 // FIXME: this LFUN should also work without any view.
1805 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1806 ? &(current_view_->documentBufferView()->buffer()) : 0;
1808 buffer->undo().beginUndoGroup();
1809 while (!arg.empty()) {
1811 arg = split(arg, first, ';');
1812 FuncRequest func(lyxaction.lookupFunc(first));
1813 func.setOrigin(cmd.origin());
1816 // the buffer may have been closed by one action
1817 if (theBufferList().isLoaded(buffer))
1818 buffer->undo().endUndoGroup();
1822 case LFUN_BUFFER_FORALL: {
1823 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1825 map<Buffer *, GuiView *> views_lVisible;
1826 map<GuiView *, Buffer *> activeBuffers;
1828 QList<GuiView *> allViews = d->views_.values();
1830 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1831 // and on which buffer is active in each view.
1832 Buffer * const last = theBufferList().last();
1833 foreach (GuiView * view, allViews) {
1834 // all of the buffers might be locally hidden. That is, there is no active buffer.
1835 if (!view || !view->currentBufferView())
1836 activeBuffers[view] = 0;
1838 activeBuffers[view] = &view->currentBufferView()->buffer();
1840 // find out if each is locally visible or locally hidden.
1841 // we don't use a for loop as the buffer list cycles.
1842 Buffer * b = theBufferList().first();
1844 bool const locallyVisible = view && view->workArea(*b);
1845 if (locallyVisible) {
1846 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1847 // only need to overwrite/add if we don't already know a buffer is globally
1848 // visible or we do know but we would prefer to dispatch LFUN from the
1849 // current view because of cursor position issues.
1850 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1851 views_lVisible[b] = view;
1855 b = theBufferList().next(b);
1859 GuiView * const homeView = currentView();
1860 Buffer * b = theBufferList().first();
1861 Buffer * nextBuf = 0;
1862 int numProcessed = 0;
1865 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1867 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1869 // first change to a view where b is locally visible, preferably current_view_.
1870 GuiView * const vLv = views_lVisible[b];
1872 lyx::dispatch(funcToRun);
1880 // put things back to how they were (if possible).
1881 foreach (GuiView * view, allViews) {
1882 Buffer * originalBuf = activeBuffers[view];
1883 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1884 if (theBufferList().isLoaded(originalBuf))
1885 view->setBuffer(originalBuf);
1887 homeView->setFocus();
1889 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1893 case LFUN_COMMAND_ALTERNATIVES: {
1894 // argument contains ';'-terminated commands
1895 string arg = argument;
1896 while (!arg.empty()) {
1898 arg = split(arg, first, ';');
1899 FuncRequest func(lyxaction.lookupFunc(first));
1900 func.setOrigin(cmd.origin());
1901 FuncStatus const stat = getStatus(func);
1902 if (stat.enabled()) {
1912 if (theTopLevelCmdDef().lock(argument, func)) {
1913 func.setOrigin(cmd.origin());
1915 theTopLevelCmdDef().release(argument);
1917 if (func.action() == LFUN_UNKNOWN_ACTION) {
1918 // unknown command definition
1919 lyxerr << "Warning: unknown command definition `"
1923 // recursion detected
1924 lyxerr << "Warning: Recursion in the command definition `"
1925 << argument << "' detected"
1932 case LFUN_PREFERENCES_SAVE:
1933 lyxrc.write(support::makeAbsPath("preferences",
1934 package().user_support().absFileName()), false);
1937 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1938 string const fname = addName(addPath(package().user_support().absFileName(),
1939 "templates/"), "defaults.lyx");
1940 Buffer defaults(fname);
1942 istringstream ss(argument);
1947 // We need to make sure that, after we recreat the DocumentClass,
1948 // which we do in readHeader, we apply it to the document itself.
1949 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
1950 int const unknown_tokens = defaults.readHeader(lex);
1951 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
1953 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
1954 cap::switchBetweenClasses(olddc, newdc, theinset, el);
1956 if (unknown_tokens != 0) {
1957 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1958 << unknown_tokens << " unknown token"
1959 << (unknown_tokens == 1 ? "" : "s")
1963 if (defaults.writeFile(FileName(defaults.absFileName())))
1964 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1965 makeDisplayPath(fname)));
1968 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1973 case LFUN_BOOKMARK_GOTO:
1974 // go to bookmark, open unopened file and switch to buffer if necessary
1975 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1976 dr.screenUpdate(Update::Force | Update::FitCursor);
1979 case LFUN_BOOKMARK_CLEAR:
1980 theSession().bookmarks().clear();
1983 case LFUN_DEBUG_LEVEL_SET:
1984 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1987 case LFUN_DIALOG_SHOW: {
1988 string const name = cmd.getArg(0);
1990 if ( name == "aboutlyx"
1992 || name == "texinfo"
1993 || name == "progress"
1994 || name == "compare")
1996 // work around: on Mac OS the application
1997 // is not terminated when closing the last view.
1998 // Create a new one to be able to dispatch the
1999 // LFUN_DIALOG_SHOW to this view.
2000 if (current_view_ == 0)
2006 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2009 current_view_->dispatch(cmd, dr);
2013 if (cmd.origin() == FuncRequest::LYXSERVER)
2014 updateCurrentView(cmd, dr);
2018 docstring GuiApplication::viewStatusMessage()
2020 // When meta-fake key is pressed, show the key sequence so far + "M-".
2021 if (d->meta_fake_bit != NoModifier)
2022 return d->keyseq.print(KeySequence::ForGui) + "M-";
2024 // Else, when a non-complete key sequence is pressed,
2025 // show the available options.
2026 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2027 return d->keyseq.printOptions(true);
2033 void GuiApplication::handleKeyFunc(FuncCode action)
2037 if (d->keyseq.length())
2039 GuiView * gv = currentView();
2040 LASSERT(gv && gv->currentBufferView(), return);
2041 BufferView * bv = gv->currentBufferView();
2042 bv->getIntl().getTransManager().deadkey(
2043 c, get_accent(action).accent, bv->cursor().innerText(),
2045 // Need to clear, in case the minibuffer calls these
2048 // copied verbatim from do_accent_char
2049 bv->cursor().resetAnchor();
2053 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2055 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2057 // Do nothing if we have nothing (JMarc)
2058 if (!keysym.isOK()) {
2059 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2061 current_view_->restartCursor();
2065 if (keysym.isModifier()) {
2067 current_view_->restartCursor();
2071 char_type encoded_last_key = keysym.getUCSEncoded();
2073 // Do a one-deep top-level lookup for
2074 // cancel and meta-fake keys. RVDK_PATCH_5
2075 d->cancel_meta_seq.reset();
2077 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2078 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2080 // When not cancel or meta-fake, do the normal lookup.
2081 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2082 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2083 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2084 // remove Caps Lock and Mod2 as a modifiers
2085 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2086 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2089 // Dont remove this unless you know what you are doing.
2090 d->meta_fake_bit = NoModifier;
2092 // Can this happen now ?
2093 if (func.action() == LFUN_NOACTION)
2094 func = FuncRequest(LFUN_COMMAND_PREFIX);
2096 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2097 << d->keyseq.print(KeySequence::Portable) << ']');
2099 // already here we know if it any point in going further
2100 // why not return already here if action == -1 and
2101 // num_bytes == 0? (Lgb)
2103 if (d->keyseq.length() > 1 && current_view_)
2104 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2107 // Maybe user can only reach the key via holding down shift.
2108 // Let's see. But only if shift is the only modifier
2109 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2110 LYXERR(Debug::KEY, "Trying without shift");
2111 func = d->keyseq.addkey(keysym, NoModifier);
2112 LYXERR(Debug::KEY, "Action now " << func.action());
2115 if (func.action() == LFUN_UNKNOWN_ACTION) {
2116 // Hmm, we didn't match any of the keysequences. See
2117 // if it's normal insertable text not already covered
2119 if (keysym.isText() && d->keyseq.length() == 1) {
2120 LYXERR(Debug::KEY, "isText() is true, inserting.");
2121 func = FuncRequest(LFUN_SELF_INSERT,
2122 FuncRequest::KEYBOARD);
2124 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
2125 if (current_view_) {
2126 current_view_->message(_("Unknown function."));
2127 current_view_->restartCursor();
2133 if (func.action() == LFUN_SELF_INSERT) {
2134 if (encoded_last_key != 0) {
2135 docstring const arg(1, encoded_last_key);
2136 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2137 FuncRequest::KEYBOARD));
2138 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2141 processFuncRequest(func);
2145 void GuiApplication::processFuncRequest(FuncRequest const & func)
2147 lyx::dispatch(func);
2151 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2153 addToFuncRequestQueue(func);
2154 processFuncRequestQueueAsync();
2158 void GuiApplication::processFuncRequestQueue()
2160 while (!d->func_request_queue_.empty()) {
2161 processFuncRequest(d->func_request_queue_.front());
2162 d->func_request_queue_.pop();
2167 void GuiApplication::processFuncRequestQueueAsync()
2169 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2173 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2175 d->func_request_queue_.push(func);
2179 void GuiApplication::resetGui()
2181 // Set the language defined by the user.
2185 if (!readUIFile(toqstr(lyxrc.ui_file)))
2186 // Gives some error box here.
2189 if (d->global_menubar_)
2190 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2192 QHash<int, GuiView *>::iterator it;
2193 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2196 gv->setLayoutDirection(layoutDirection());
2200 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2204 void GuiApplication::createView(int view_id)
2206 createView(QString(), true, view_id);
2210 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2213 // release the keyboard which might have been grabed by the global
2214 // menubar on Mac to catch shortcuts even without any GuiView.
2215 if (d->global_menubar_)
2216 d->global_menubar_->releaseKeyboard();
2220 while (d->views_.find(id) != d->views_.end())
2223 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2224 GuiView * view = new GuiView(id);
2226 d->views_[id] = view;
2230 setActiveWindow(view);
2233 if (!geometry_arg.isEmpty()) {
2234 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2238 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2239 re.indexIn(geometry_arg);
2240 w = re.cap(1).toInt();
2241 h = re.cap(2).toInt();
2242 x = re.cap(3).toInt();
2243 y = re.cap(4).toInt();
2244 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2245 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2246 // Set initial geometry such that we can get the frame size.
2247 view->setGeometry(x, y, w, h);
2248 int framewidth = view->geometry().x() - view->x();
2249 int titleheight = view->geometry().y() - view->y();
2250 // Negative displacements must be interpreted as distances
2251 // from the right or bottom screen borders.
2252 if (sx == '-' || sy == '-') {
2253 QRect rec = QApplication::desktop()->screenGeometry();
2255 x += rec.width() - w - framewidth;
2257 y += rec.height() - h - titleheight;
2258 view->setGeometry(x, y, w, h);
2260 // Make sure that the left and top frame borders are visible.
2261 if (view->x() < 0 || view->y() < 0) {
2266 view->setGeometry(x, y, w, h);
2274 Clipboard & GuiApplication::clipboard()
2276 return d->clipboard_;
2280 Selection & GuiApplication::selection()
2282 return d->selection_;
2286 FontLoader & GuiApplication::fontLoader()
2288 return d->font_loader_;
2292 Toolbars const & GuiApplication::toolbars() const
2294 return d->toolbars_;
2298 Toolbars & GuiApplication::toolbars()
2300 return d->toolbars_;
2304 Menus const & GuiApplication::menus() const
2310 Menus & GuiApplication::menus()
2316 QList<int> GuiApplication::viewIds() const
2318 return d->views_.keys();
2322 ColorCache & GuiApplication::colorCache()
2324 return d->color_cache_;
2328 int GuiApplication::exec()
2330 // asynchronously handle batch commands. This event will be in
2331 // the event queue in front of other asynchronous events. Hence,
2332 // we can assume in the latter that the gui is setup already.
2333 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2335 return QApplication::exec();
2339 void GuiApplication::exit(int status)
2341 QApplication::exit(status);
2345 void GuiApplication::setGuiLanguage()
2349 // install translation file for Qt built-in dialogs
2350 QString const language_name = QString("qt_") + theLocale.name();
2351 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2352 // Short-named translator can be loaded from a long name, but not the
2353 // opposite. Therefore, long name should be used without truncation.
2354 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2355 if (!d->qt_trans_.load(language_name,
2356 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2357 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2360 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2364 switch (theLocale.language()) {
2365 case QLocale::Arabic :
2366 case QLocale::Hebrew :
2367 case QLocale::Persian :
2368 case QLocale::Urdu :
2369 setLayoutDirection(Qt::RightToLeft);
2372 setLayoutDirection(Qt::LeftToRight);
2377 void GuiApplication::execBatchCommands()
2382 if (!readUIFile(toqstr(lyxrc.ui_file)))
2383 // Gives some error box here.
2387 #if QT_VERSION > 0x040600
2388 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2390 // Create the global default menubar which is shown for the dialogs
2391 // and if no GuiView is visible.
2392 // This must be done after the session was recovered to know the "last files".
2393 d->global_menubar_ = new QMenuBar(0);
2394 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2397 lyx::execBatchCommands();
2401 QAbstractItemModel * GuiApplication::languageModel()
2403 if (d->language_model_)
2404 return d->language_model_;
2406 QStandardItemModel * lang_model = new QStandardItemModel(this);
2407 lang_model->insertColumns(0, 3);
2409 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2410 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2411 Languages::const_iterator it = lyx::languages.begin();
2412 Languages::const_iterator end = lyx::languages.end();
2413 for (; it != end; ++it) {
2414 current_row = lang_model->rowCount();
2415 lang_model->insertRows(current_row, 1);
2416 QModelIndex pl_item = lang_model->index(current_row, 0);
2417 QModelIndex sp_item = lang_model->index(current_row, 1);
2418 QModelIndex th_item = lang_model->index(current_row, 2);
2419 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2420 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2421 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2422 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2423 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2424 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2425 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2426 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2427 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2428 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2430 d->language_model_ = new QSortFilterProxyModel(this);
2431 d->language_model_->setSourceModel(lang_model);
2432 d->language_model_->setSortLocaleAware(true);
2433 return d->language_model_;
2437 void GuiApplication::restoreGuiSession()
2439 if (!lyxrc.load_session)
2442 Session & session = theSession();
2443 LastOpenedSection::LastOpened const & lastopened =
2444 session.lastOpened().getfiles();
2446 validateCurrentView();
2448 FileName active_file;
2449 // do not add to the lastfile list since these files are restored from
2450 // last session, and should be already there (regular files), or should
2451 // not be added at all (help files).
2452 for (size_t i = 0; i < lastopened.size(); ++i) {
2453 FileName const & file_name = lastopened[i].file_name;
2454 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2455 && current_view_->documentBufferView() != 0)) {
2456 boost::crc_32_type crc;
2457 string const & fname = file_name.absFileName();
2458 crc = for_each(fname.begin(), fname.end(), crc);
2459 createView(crc.checksum());
2461 current_view_->loadDocument(file_name, false);
2463 if (lastopened[i].active)
2464 active_file = file_name;
2467 // Restore last active buffer
2468 Buffer * buffer = theBufferList().getBuffer(active_file);
2469 if (buffer && current_view_)
2470 current_view_->setBuffer(buffer);
2472 // clear this list to save a few bytes of RAM
2473 session.lastOpened().clear();
2477 QString const GuiApplication::romanFontName()
2480 font.setStyleHint(QFont::Serif);
2481 font.setFamily("serif");
2483 return QFontInfo(font).family();
2487 QString const GuiApplication::sansFontName()
2490 font.setStyleHint(QFont::SansSerif);
2491 font.setFamily("sans");
2493 return QFontInfo(font).family();
2497 QString const GuiApplication::typewriterFontName()
2500 font.setStyleHint(QFont::TypeWriter);
2501 font.setFamily("monospace");
2503 return QFontInfo(font).family();
2507 void GuiApplication::handleRegularEvents()
2509 ForkedCallsController::handleCompletedProcesses();
2513 bool GuiApplication::event(QEvent * e)
2516 case QEvent::FileOpen: {
2517 // Open a file; this happens only on Mac OS X for now.
2519 // We do this asynchronously because on startup the batch
2520 // commands are not executed here yet and the gui is not ready
2522 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2523 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2524 processFuncRequestAsync(fr);
2529 return QApplication::event(e);
2534 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2537 return QApplication::notify(receiver, event);
2539 catch (ExceptionMessage const & e) {
2541 case ErrorException:
2543 setQuitOnLastWindowClosed(false);
2545 Alert::error(e.title_, e.details_);
2547 // Properly crash in debug mode in order to get a useful backtrace.
2550 // In release mode, try to exit gracefully.
2553 case BufferException: {
2554 if (!current_view_ || !current_view_->documentBufferView())
2556 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2557 docstring details = e.details_ + '\n';
2558 details += buf->emergencyWrite();
2559 theBufferList().release(buf);
2560 details += "\n" + _("The current document was closed.");
2561 Alert::error(e.title_, details);
2564 case WarningException:
2565 Alert::warning(e.title_, e.details_);
2569 catch (exception const & e) {
2570 docstring s = _("LyX has caught an exception, it will now "
2571 "attempt to save all unsaved documents and exit."
2573 s += from_ascii(e.what());
2574 Alert::error(_("Software exception Detected"), s);
2578 docstring s = _("LyX has caught some really weird exception, it will "
2579 "now attempt to save all unsaved documents and exit.");
2580 Alert::error(_("Software exception Detected"), s);
2588 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2590 QColor const & qcol = d->color_cache_.get(col);
2591 if (!qcol.isValid()) {
2597 rgbcol.r = qcol.red();
2598 rgbcol.g = qcol.green();
2599 rgbcol.b = qcol.blue();
2604 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2606 QColor const qcol(lcolor.getX11Name(col).c_str());
2607 if (!qcol.isValid()) {
2613 rgbcol.r = qcol.red();
2614 rgbcol.g = qcol.green();
2615 rgbcol.b = qcol.blue();
2620 string const GuiApplication::hexName(ColorCode col)
2622 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2626 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2628 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2629 d->socket_notifiers_[fd] = sn;
2630 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2634 void GuiApplication::socketDataReceived(int fd)
2636 d->socket_notifiers_[fd]->func_();
2640 void GuiApplication::unregisterSocketCallback(int fd)
2642 d->socket_notifiers_.take(fd)->setEnabled(false);
2646 void GuiApplication::commitData(QSessionManager & sm)
2648 /// The implementation is required to avoid an application exit
2649 /// when session state save is triggered by session manager.
2650 /// The default implementation sends a close event to all
2651 /// visible top level widgets when session managment allows
2653 /// We are changing that to close all wiew one by one.
2654 /// FIXME: verify if the default implementation is enough now.
2655 #ifdef QT_NO_SESSIONMANAGER
2657 #warning Qt is compiled without session manager
2659 #pragma message("warning: Qt is compiled without session manager")
2663 if (sm.allowsInteraction() && !closeAllViews())
2669 void GuiApplication::unregisterView(GuiView * gv)
2671 LAPPERR(d->views_[gv->id()] == gv);
2672 d->views_.remove(gv->id());
2673 if (current_view_ == gv)
2678 bool GuiApplication::closeAllViews()
2680 if (d->views_.empty())
2683 // When a view/window was closed before without quitting LyX, there
2684 // are already entries in the lastOpened list.
2685 theSession().lastOpened().clear();
2687 QList<GuiView *> const views = d->views_.values();
2688 foreach (GuiView * view, views) {
2689 if (!view->closeScheduled())
2698 GuiView & GuiApplication::view(int id) const
2700 LAPPERR(d->views_.contains(id));
2701 return *d->views_.value(id);
2705 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2707 QList<GuiView *> const views = d->views_.values();
2708 foreach (GuiView * view, views)
2709 view->hideDialog(name, inset);
2713 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2715 Buffer const * buffer_ = 0;
2716 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2717 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2718 if (Buffer const * ptr = (*it)->updateInset(inset))
2725 bool GuiApplication::searchMenu(FuncRequest const & func,
2726 docstring_list & names) const
2728 return d->menus_.searchMenu(func, names);
2732 // Ensure that a file is read only once (prevents include loops)
2733 static QStringList uifiles;
2734 // store which ui files define Toolbars
2735 static QStringList toolbar_uifiles;
2738 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2749 LexerKeyword uitags[] = {
2750 { "format", ui_format },
2751 { "include", ui_include },
2752 { "menuset", ui_menuset },
2753 { "toolbars", ui_toolbars },
2754 { "toolbarset", ui_toolbarset }
2758 lex.setFile(ui_path);
2760 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2764 if (lyxerr.debugging(Debug::PARSER))
2765 lex.printTable(lyxerr);
2768 // format before introduction of format tag
2769 unsigned int format = 0;
2770 while (lex.isOK()) {
2771 int const status = lex.lex();
2773 // we have to do this check here, outside the switch,
2774 // because otherwise we would start reading include files,
2775 // e.g., if the first tag we hit was an include tag.
2776 if (status == ui_format)
2778 format = lex.getInteger();
2782 // this will trigger unless the first tag we hit is a format
2783 // tag, with the right format.
2784 if (format != LFUN_FORMAT)
2785 return FormatMismatch;
2788 case Lexer::LEX_FEOF:
2793 QString const file = toqstr(lex.getString());
2794 bool const success = readUIFile(file, true);
2796 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2803 d->menus_.read(lex);
2807 d->toolbars_.readToolbars(lex);
2811 d->toolbars_.readToolbarSettings(lex);
2812 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2816 if (!rtrim(lex.getString()).empty())
2817 lex.printError("LyX::ReadUIFile: "
2818 "Unknown menu tag: `$$Token'");
2820 LYXERR0("Error with status: " << status);
2826 return (error ? ReadError : ReadOK);
2830 bool GuiApplication::readUIFile(QString const & name, bool include)
2832 LYXERR(Debug::INIT, "About to read " << name << "...");
2836 ui_path = libFileSearch("ui", name, "inc");
2837 if (ui_path.empty())
2838 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2840 ui_path = libFileSearch("ui", name, "ui");
2843 if (ui_path.empty()) {
2844 static const QString defaultUIFile = "default";
2845 LYXERR(Debug::INIT, "Could not find " << name);
2847 Alert::warning(_("Could not find UI definition file"),
2848 bformat(_("Error while reading the included file\n%1$s\n"
2849 "Please check your installation."), qstring_to_ucs4(name)));
2852 if (name == defaultUIFile) {
2853 LYXERR(Debug::INIT, "Could not find default UI file!!");
2854 Alert::warning(_("Could not find default UI file"),
2855 _("LyX could not find the default UI file!\n"
2856 "Please check your installation."));
2859 Alert::warning(_("Could not find UI definition file"),
2860 bformat(_("Error while reading the configuration file\n%1$s\n"
2861 "Falling back to default.\n"
2862 "Please look under Tools>Preferences>User Interface and\n"
2863 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2864 return readUIFile(defaultUIFile, false);
2867 QString const uifile = toqstr(ui_path.absFileName());
2868 if (uifiles.contains(uifile)) {
2870 // We are reading again the top uifile so reset the safeguard:
2873 d->toolbars_.reset();
2875 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2876 << "Is this an include loop?");
2880 uifiles.push_back(uifile);
2882 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2884 ReturnValues retval = readUIFile(ui_path);
2886 if (retval == FormatMismatch) {
2887 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2888 TempFile tmp("convertXXXXXX.ui");
2889 FileName const tempfile = tmp.name();
2890 bool const success = prefs2prefs(ui_path, tempfile, true);
2892 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2893 " to format " << LFUN_FORMAT << ".");
2895 retval = readUIFile(tempfile);
2899 if (retval != ReadOK) {
2900 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2908 settings.beginGroup("ui_files");
2909 bool touched = false;
2910 for (int i = 0; i != uifiles.size(); ++i) {
2911 QFileInfo fi(uifiles[i]);
2912 QDateTime const date_value = fi.lastModified();
2913 QString const name_key = QString::number(i);
2914 // if an ui file which defines Toolbars has changed,
2915 // we have to reset the settings
2916 if (toolbar_uifiles.contains(uifiles[i])
2917 && (!settings.contains(name_key)
2918 || settings.value(name_key).toString() != uifiles[i]
2919 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2921 settings.setValue(name_key, uifiles[i]);
2922 settings.setValue(name_key + "/date", date_value);
2925 settings.endGroup();
2927 settings.remove("views");
2933 void GuiApplication::onLastWindowClosed()
2935 if (d->global_menubar_)
2936 d->global_menubar_->grabKeyboard();
2940 void GuiApplication::startLongOperation() {
2941 d->key_checker_.start();
2945 bool GuiApplication::longOperationCancelled() {
2946 return d->key_checker_.pressed();
2950 void GuiApplication::stopLongOperation() {
2951 d->key_checker_.stop();
2955 bool GuiApplication::longOperationStarted() {
2956 return d->key_checker_.started();
2960 ////////////////////////////////////////////////////////////////////////
2962 // X11 specific stuff goes here...
2966 bool GuiApplication::x11EventFilter(XEvent * xev)
2971 switch (xev->type) {
2972 case SelectionRequest: {
2973 if (xev->xselectionrequest.selection != XA_PRIMARY)
2975 LYXERR(Debug::SELECTION, "X requested selection.");
2976 BufferView * bv = current_view_->currentBufferView();
2978 docstring const sel = bv->requestSelection();
2980 d->selection_.put(sel);
2984 case SelectionClear: {
2985 if (xev->xselectionclear.selection != XA_PRIMARY)
2987 LYXERR(Debug::SELECTION, "Lost selection.");
2988 BufferView * bv = current_view_->currentBufferView();
2990 bv->clearSelection();
2998 } // namespace frontend
3001 void hideDialogs(std::string const & name, Inset * inset)
3004 frontend::guiApp->hideDialogs(name, inset);
3008 ////////////////////////////////////////////////////////////////////
3012 ////////////////////////////////////////////////////////////////////
3014 frontend::FontLoader & theFontLoader()
3016 LAPPERR(frontend::guiApp);
3017 return frontend::guiApp->fontLoader();
3021 frontend::FontMetrics const & theFontMetrics(Font const & f)
3023 return theFontMetrics(f.fontInfo());
3027 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3029 LAPPERR(frontend::guiApp);
3030 return frontend::guiApp->fontLoader().metrics(f);
3034 ////////////////////////////////////////////////////////////////////
3038 ////////////////////////////////////////////////////////////////////
3040 frontend::Clipboard & theClipboard()
3042 LAPPERR(frontend::guiApp);
3043 return frontend::guiApp->clipboard();
3047 frontend::Selection & theSelection()
3049 LAPPERR(frontend::guiApp);
3050 return frontend::guiApp->selection();
3056 #include "moc_GuiApplication.cpp"