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"
21 #include "GuiKeySymbol.h"
22 #include "GuiSelection.h"
25 #include "qt_helpers.h"
28 #include "frontends/alert.h"
29 #include "frontends/Application.h"
30 #include "frontends/FontLoader.h"
31 #include "frontends/FontMetrics.h"
34 #include "BufferList.h"
35 #include "BufferView.h"
39 #include "FuncRequest.h"
40 #include "FuncStatus.h"
44 #include "LaTeXPackages.h"
47 #include "LyXAction.h"
49 #include "Paragraph.h"
52 #include "SpellChecker.h"
53 #include "Thesaurus.h"
56 #include "support/convert.h"
57 #include "support/debug.h"
58 #include "support/ExceptionMessage.h"
59 #include "support/FileName.h"
60 #include "support/filetools.h"
61 #include "support/foreach.h"
62 #include "support/ForkedCalls.h"
63 #include "support/gettext.h"
64 #include "support/lassert.h"
65 #include "support/lstrings.h"
66 #include "support/lyxalgo.h" // sorted
67 #include "support/Messages.h"
68 #include "support/os.h"
69 #include "support/Package.h"
70 #include "support/Path.h"
71 #include "support/Systemcall.h"
74 #include "support/linkback/LinkBackProxy.h"
84 #include <QFileOpenEvent>
88 #include <QImageReader>
90 #include <QLibraryInfo>
92 #include <QMacPasteboardMime>
97 #include <QPixmapCache>
99 #include <QSessionManager>
101 #include <QSocketNotifier>
102 #include <QSortFilterProxyModel>
103 #include <QStandardItemModel>
104 #include <QTextCodec>
106 #include <QTranslator>
107 #if QT_VERSION >= 0x040400
108 #include <QThreadPool>
113 #include <X11/Xatom.h>
114 #include <X11/Xlib.h>
120 #include <QWindowsMime>
127 #include "support/bind.h"
128 #include <boost/crc.hpp>
135 using namespace lyx::support;
138 static void initializeResources()
140 static bool initialized = false;
142 Q_INIT_RESOURCE(Resources);
150 frontend::Application * createApplication(int & argc, char * argv[])
153 // prune -geometry argument(s) by shifting
154 // the following ones 2 places down.
155 for (int i = 0 ; i < argc ; ++i) {
156 if (strcmp(argv[i], "-geometry") == 0) {
157 int const remove = (i+1) < argc ? 2 : 1;
159 for (int j = i; j < argc; ++j)
160 argv[j] = argv[j + remove];
165 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
166 // I'd rather do that in the constructor, but I do not think that
167 // the palette is accessible there.
168 guiApp->colorCache().setPalette(guiApp->palette());
175 /// Return the list of loadable formats.
176 vector<string> loadableImageFormats()
180 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
182 LYXERR(Debug::GRAPHICS,
183 "\nThe image loader can load the following directly:\n");
185 if (qt_formats.empty())
186 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
188 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
190 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
192 string ext = ascii_lowercase((const char *) *it);
203 ////////////////////////////////////////////////////////////////////////
205 // Icon loading support code
207 ////////////////////////////////////////////////////////////////////////
217 bool operator<(PngMap const & lhs, PngMap const & rhs)
219 return lhs.key < rhs.key;
225 CompareKey(QString const & name) : name_(name) {}
226 bool operator()(PngMap const & other) const { return other.key == name_; }
232 // this must be sorted alphabetically
233 // Upper case comes before lower case
234 PngMap sorted_png_map[] = {
235 { "Bumpeq", "bumpeq2" },
238 { "Delta", "delta2" },
239 { "Diamond", "diamond2" },
240 { "Downarrow", "downarrow2" },
241 { "Gamma", "gamma2" },
242 { "Lambda", "lambda2" },
243 { "Leftarrow", "leftarrow2" },
244 { "Leftrightarrow", "leftrightarrow2" },
245 { "Longleftarrow", "longleftarrow2" },
246 { "Longleftrightarrow", "longleftrightarrow2" },
247 { "Longrightarrow", "longrightarrow2" },
248 { "Omega", "omega2" },
252 { "Rightarrow", "rightarrow2" },
253 { "Sigma", "sigma2" },
254 { "Subset", "subset2" },
255 { "Supset", "supset2" },
256 { "Theta", "theta2" },
257 { "Uparrow", "uparrow2" },
258 { "Updownarrow", "updownarrow2" },
259 { "Upsilon", "upsilon2" },
260 { "Vdash", "vdash3" },
263 { "nLeftarrow", "nleftarrow2" },
264 { "nLeftrightarrow", "nleftrightarrow2" },
265 { "nRightarrow", "nrightarrow2" },
266 { "nVDash", "nvdash3" },
267 { "nvDash", "nvdash2" },
268 { "textrm \\AA", "textrm_AA"},
269 { "textrm \\O", "textrm_O"},
270 { "vDash", "vdash2" }
273 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
276 QString findPng(QString const & name)
278 PngMap const * const begin = sorted_png_map;
279 PngMap const * const end = begin + nr_sorted_png_map;
280 LASSERT(sorted(begin, end), /**/);
282 PngMap const * const it = find_if(begin, end, CompareKey(name));
286 png_name = it->value;
289 png_name.replace('_', "underscore");
290 png_name.replace(' ', '_');
292 // This way we can have "math-delim { }" on the toolbar.
293 png_name.replace('(', "lparen");
294 png_name.replace(')', "rparen");
295 png_name.replace('[', "lbracket");
296 png_name.replace(']', "rbracket");
297 png_name.replace('{', "lbrace");
298 png_name.replace('}', "rbrace");
299 png_name.replace('|', "bars");
300 png_name.replace(',', "thinspace");
301 png_name.replace(':', "mediumspace");
302 png_name.replace(';', "thickspace");
303 png_name.replace('!', "negthinspace");
306 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
307 << "Looking for math PNG called \"" << png_name << '"');
314 QString iconName(FuncRequest const & f, bool unknown)
316 initializeResources();
320 switch (f.action()) {
321 case LFUN_MATH_INSERT:
322 if (!f.argument().empty()) {
324 name1 = findPng(toqstr(f.argument()).mid(1));
327 case LFUN_MATH_DELIM:
328 case LFUN_MATH_BIGDELIM:
330 name1 = findPng(toqstr(f.argument()));
334 name1 = toqstr(f.argument());
336 case LFUN_COMMAND_ALTERNATIVES: {
337 // use the first of the alternative commands
339 docstring dummy = split(f.argument(), firstcom, ';');
340 name1 = toqstr(firstcom);
341 // FIXME: we should rename the icons to tabular-xxx instead of
342 // "tabular-feature-xxx"
343 name1.replace("inset-modify tabular", "tabular-feature");
344 name1.replace(' ', '_');
347 case LFUN_INSET_MODIFY: {
348 // FIXME: we should rename the icons to tabular-xxx instead of
349 // "tabular-feature-xxx" and generalize this naming to all
350 // insets, not to tabular using ones.
352 string const command = split(to_utf8(f.argument()), inset_name, ' ');
353 if (insetCode(inset_name) == TABULAR_CODE) {
354 name1 = "tabular-feature "+ toqstr(command);
355 name1.replace(' ', '_');
360 name2 = toqstr(lyxaction.getActionName(f.action()));
363 if (!f.argument().empty()) {
364 name1 = name2 + ' ' + toqstr(f.argument());
365 name1.replace(' ', '_');
366 name1.replace('\\', "backslash");
370 QString imagedir = "images/" + path;
371 FileName fname = imageLibFileSearch(imagedir, name1, "png");
373 return toqstr(fname.absFileName());
375 fname = imageLibFileSearch(imagedir, name2, "png");
377 return toqstr(fname.absFileName());
379 path = ":/images/" + path;
382 LYXERR0("Directory " << path << " not found in resource!");
386 if (res.exists(name1))
390 if (res.exists(name2))
393 LYXERR(Debug::GUI, "Cannot find icon with filename "
394 << "\"" << name1 << "\""
396 << "\"" << name2 << "\""
398 << lyxaction.getActionName(f.action())
399 << '(' << to_utf8(f.argument()) << ")\"");
402 imagedir = "images/";
403 fname = imageLibFileSearch(imagedir, "unknown", "png");
405 return toqstr(fname.absFileName());
406 return QString(":/images/unknown.png");
412 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
415 QString imagedir = path;
416 FileName fname = imageLibFileSearch(imagedir, name, ext);
417 QString path1 = toqstr(fname.absFileName());
418 QString path2 = ":/" + path + name + "." + ext;
420 if (pixmap.load(path1)) {
423 else if (pixmap.load(path2)) {
427 LYXERR0("Cannot load pixmap \""
428 << path << name << '.' << ext
429 << "\", please verify resource system!");
434 QIcon getIcon(FuncRequest const & f, bool unknown)
436 QString icon = iconName(f, unknown);
440 //LYXERR(Debug::GUI, "Found icon: " << icon);
442 if (!pm.load(icon)) {
443 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
451 ////////////////////////////////////////////////////////////////////////
453 // LyX server support code.
455 ////////////////////////////////////////////////////////////////////////
457 class SocketNotifier : public QSocketNotifier
460 /// connect a connection notification from the LyXServerSocket
461 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
462 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
466 /// The callback function
467 Application::SocketCallback func_;
471 ////////////////////////////////////////////////////////////////////////
473 // Mac specific stuff goes here...
475 ////////////////////////////////////////////////////////////////////////
477 class MenuTranslator : public QTranslator
480 MenuTranslator(QObject * parent)
481 : QTranslator(parent)
484 QString translate(const char * /*context*/,
485 const char * sourceText,
486 const char * /*comment*/ = 0)
488 string const s = sourceText;
489 if (s == N_("About %1") || s == N_("Preferences")
490 || s == N_("Reconfigure") || s == N_("Quit %1"))
497 class GlobalMenuBar : public QMenuBar
501 GlobalMenuBar() : QMenuBar(0) {}
504 bool event(QEvent * e)
506 if (e->type() == QEvent::ShortcutOverride) {
507 // && activeWindow() == 0) {
508 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
510 setKeySymbol(&sym, ke);
511 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
520 // QMacPasteboardMimeGraphics can only be compiled on Mac.
522 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
525 QMacPasteboardMimeGraphics()
526 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
529 QString convertorName() { return "Graphics"; }
531 QString flavorFor(QString const & mime)
533 LYXERR(Debug::ACTION, "flavorFor " << mime);
534 if (mime == pdfMimeType())
535 return QLatin1String("com.adobe.pdf");
539 QString mimeFor(QString flav)
541 LYXERR(Debug::ACTION, "mimeFor " << flav);
542 if (flav == QLatin1String("com.adobe.pdf"))
543 return pdfMimeType();
547 bool canConvert(QString const & mime, QString flav)
549 return mimeFor(flav) == mime;
552 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
556 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
560 QList<QByteArray> convertFromMime(QString const & /*mime*/,
561 QVariant data, QString /*flav*/)
563 QList<QByteArray> ret;
564 ret.append(data.toByteArray());
570 ///////////////////////////////////////////////////////////////
572 // You can find more platform specific stuff at the end of this file...
574 ///////////////////////////////////////////////////////////////
576 ////////////////////////////////////////////////////////////////////////
577 // Windows specific stuff goes here...
580 // QWindowsMimeMetafile can only be compiled on Windows.
582 static FORMATETC cfFromMime(QString const & mimetype)
585 if (mimetype == emfMimeType()) {
586 formatetc.cfFormat = CF_ENHMETAFILE;
587 formatetc.tymed = TYMED_ENHMF;
588 } else if (mimetype == wmfMimeType()) {
589 formatetc.cfFormat = CF_METAFILEPICT;
590 formatetc.tymed = TYMED_MFPICT;
593 formatetc.dwAspect = DVASPECT_CONTENT;
594 formatetc.lindex = -1;
599 class QWindowsMimeMetafile : public QWindowsMime {
601 QWindowsMimeMetafile() {}
603 bool canConvertFromMime(FORMATETC const & formatetc,
604 QMimeData const * mimedata) const
609 bool canConvertToMime(QString const & mimetype,
610 IDataObject * pDataObj) const
612 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
614 FORMATETC formatetc = cfFromMime(mimetype);
615 return pDataObj->QueryGetData(&formatetc) == S_OK;
618 bool convertFromMime(FORMATETC const & formatetc,
619 const QMimeData * mimedata, STGMEDIUM * pmedium) const
624 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
625 QVariant::Type preferredType) const
628 if (!canConvertToMime(mimetype, pDataObj))
631 FORMATETC formatetc = cfFromMime(mimetype);
633 if (pDataObj->GetData(&formatetc, &s) != S_OK)
637 if (s.tymed == TYMED_ENHMF) {
638 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
639 data.resize(dataSize);
640 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
641 (LPBYTE)data.data());
642 } else if (s.tymed == TYMED_MFPICT) {
643 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
644 data.resize(dataSize);
645 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
646 (LPBYTE)data.data());
649 ReleaseStgMedium(&s);
655 QVector<FORMATETC> formatsForMime(QString const & mimetype,
656 QMimeData const * mimedata) const
658 QVector<FORMATETC> formats;
659 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
660 formats += cfFromMime(mimetype);
664 QString mimeForFormat(FORMATETC const & formatetc) const
666 switch (formatetc.cfFormat) {
668 return emfMimeType();
669 case CF_METAFILEPICT:
670 return wmfMimeType();
678 ////////////////////////////////////////////////////////////////////////
679 // GuiApplication::Private definition and implementation.
680 ////////////////////////////////////////////////////////////////////////
682 struct GuiApplication::Private
684 Private(): language_model_(0), meta_fake_bit(NoModifier),
688 /// WMF Mime handler for Windows clipboard.
689 wmf_mime_ = new QWindowsMimeMetafile();
691 initKeySequences(&theTopLevelKeymap());
694 void initKeySequences(KeyMap * kb)
696 keyseq = KeySequence(kb, kb);
697 cancel_meta_seq = KeySequence(kb, kb);
701 QSortFilterProxyModel * language_model_;
703 GuiClipboard clipboard_;
705 GuiSelection selection_;
707 FontLoader font_loader_;
709 ColorCache color_cache_;
711 QTranslator qt_trans_;
713 QHash<int, SocketNotifier *> socket_notifiers_;
717 /// The global instance
720 /// this timer is used for any regular events one wants to
721 /// perform. at present it is used to check if forked processes
723 QTimer general_timer_;
725 /// delayed FuncRequests
726 std::queue<FuncRequest> func_request_queue_;
731 KeySequence cancel_meta_seq;
733 KeyModifier meta_fake_bit;
735 /// Multiple views container.
737 * Warning: This must not be a smart pointer as the destruction of the
738 * object is handled by Qt when the view is closed
739 * \sa Qt::WA_DeleteOnClose attribute.
741 QHash<int, GuiView *> views_;
743 /// Only used on mac.
744 GlobalMenuBar * global_menubar_;
747 /// Linkback mime handler for MacOSX.
748 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
752 /// WMF Mime handler for Windows clipboard.
753 QWindowsMimeMetafile * wmf_mime_;
758 GuiApplication * guiApp;
760 GuiApplication::~GuiApplication()
763 closeAllLinkBackLinks();
769 GuiApplication::GuiApplication(int & argc, char ** argv)
770 : QApplication(argc, argv), current_view_(0),
771 d(new GuiApplication::Private)
773 QString app_name = "LyX";
774 QCoreApplication::setOrganizationName(app_name);
775 QCoreApplication::setOrganizationDomain("lyx.org");
776 QCoreApplication::setApplicationName(lyx_package);
778 // Install translator for GUI elements.
779 installTranslator(&d->qt_trans_);
781 // FIXME: quitOnLastWindowClosed is true by default. We should have a
782 // lyxrc setting for this in order to let the application stay resident.
783 // But then we need some kind of dock icon, at least on Windows.
785 if (lyxrc.quit_on_last_window_closed)
786 setQuitOnLastWindowClosed(false);
789 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
790 // seems to be the default case for applications like LyX.
791 setQuitOnLastWindowClosed(false);
792 // This allows to translate the strings that appear in the LyX menu.
793 /// A translator suitable for the entries in the LyX menu.
794 /// Only needed with Qt/Mac.
795 installTranslator(new MenuTranslator(this));
799 // doubleClickInterval() is 400 ms on X11 which is just too long.
800 // On Windows and Mac OS X, the operating system's value is used.
801 // On Microsoft Windows, calling this function sets the double
802 // click interval for all applications. So we don't!
803 QApplication::setDoubleClickInterval(300);
806 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
808 // needs to be done before reading lyxrc
810 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
814 // Set the cache to 5120 kilobytes which corresponds to screen size of
815 // 1280 by 1024 pixels with a color depth of 32 bits.
816 QPixmapCache::setCacheLimit(5120);
818 // Initialize RC Fonts
819 if (lyxrc.roman_font_name.empty())
820 lyxrc.roman_font_name = fromqstr(romanFontName());
822 if (lyxrc.sans_font_name.empty())
823 lyxrc.sans_font_name = fromqstr(sansFontName());
825 if (lyxrc.typewriter_font_name.empty())
826 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
828 d->general_timer_.setInterval(500);
829 connect(&d->general_timer_, SIGNAL(timeout()),
830 this, SLOT(handleRegularEvents()));
831 d->general_timer_.start();
833 #if QT_VERSION >= 0x040400
834 // maxThreadCount() defaults in general to 2 on single or dual-processor.
835 // This is clearly not enough in a time where we use threads for
836 // document preview and/or export. 20 should be OK.
837 QThreadPool::globalInstance()->setMaxThreadCount(20);
842 GuiApplication * theGuiApp()
844 return dynamic_cast<GuiApplication *>(theApp());
848 void GuiApplication::clearSession()
855 docstring Application::iconName(FuncRequest const & f, bool unknown)
857 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
861 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
866 BufferView * doc_bv = 0;
868 if (cmd.action() == LFUN_NOACTION) {
869 status.message(from_utf8(N_("Nothing to do")));
870 status.setEnabled(false);
873 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
874 status.setUnknown(true);
875 status.message(from_utf8(N_("Unknown action")));
876 status.setEnabled(false);
879 // Does the GuiApplication know something?
880 else if (getStatus(cmd, status)) { }
882 // If we do not have a GuiView, then other functions are disabled
883 else if (!current_view_)
884 status.setEnabled(false);
886 // Does the GuiView know something?
887 else if (current_view_->getStatus(cmd, status)) { }
889 // In LyX/Mac, when a dialog is open, the menus of the
890 // application can still be accessed without giving focus to
891 // the main window. In this case, we want to disable the menu
892 // entries that are buffer or view-related.
893 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
895 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
896 status.setEnabled(false);
899 // If we do not have a BufferView, then other functions are disabled
900 else if (!(bv = current_view_->currentBufferView()))
901 status.setEnabled(false);
903 // Does the current BufferView know something?
904 else if (bv->getStatus(cmd, status)) { }
906 // Does the current Buffer know something?
907 else if (bv->buffer().getStatus(cmd, status)) { }
909 // If we do not have a document BufferView, different from the
910 // current BufferView, then other functions are disabled
911 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
912 status.setEnabled(false);
914 // Does the document Buffer know something?
915 else if (doc_bv->buffer().getStatus(cmd, status)) { }
918 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
919 status.message(from_utf8(N_("Command not handled")));
920 status.setEnabled(false);
923 // the default error message if we disable the command
924 if (!status.enabled() && status.message().empty())
925 status.message(from_utf8(N_("Command disabled")));
931 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
933 // I would really like to avoid having this switch and rather try to
934 // encode this in the function itself.
935 // -- And I'd rather let an inset decide which LFUNs it is willing
936 // to handle (Andre')
938 switch (cmd.action()) {
940 // This could be used for the no-GUI version. The GUI version is handled in
941 // GuiView::getStatus(). See above.
943 case LFUN_BUFFER_WRITE:
944 case LFUN_BUFFER_WRITE_AS: {
945 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
946 enable = b && (b->isUnnamed() || !b->isClean());
951 case LFUN_BOOKMARK_GOTO: {
952 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
953 enable = theSession().bookmarks().isValid(num);
957 case LFUN_BOOKMARK_CLEAR:
958 enable = theSession().bookmarks().hasValid();
961 // this one is difficult to get right. As a half-baked
962 // solution, we consider only the first action of the sequence
963 case LFUN_COMMAND_SEQUENCE: {
964 // argument contains ';'-terminated commands
965 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
966 FuncRequest func(lyxaction.lookupFunc(firstcmd));
967 func.setOrigin(cmd.origin());
968 flag = getStatus(func);
972 // we want to check if at least one of these is enabled
973 case LFUN_COMMAND_ALTERNATIVES: {
974 // argument contains ';'-terminated commands
975 string arg = to_utf8(cmd.argument());
976 while (!arg.empty()) {
978 arg = split(arg, first, ';');
979 FuncRequest func(lyxaction.lookupFunc(first));
980 func.setOrigin(cmd.origin());
981 flag = getStatus(func);
982 // if this one is enabled, the whole thing is
991 string name = to_utf8(cmd.argument());
992 if (theTopLevelCmdDef().lock(name, func)) {
993 func.setOrigin(cmd.origin());
994 flag = getStatus(func);
995 theTopLevelCmdDef().release(name);
997 // catch recursion or unknown command
998 // definition. all operations until the
999 // recursion or unknown command definition
1000 // occurs are performed, so set the state to
1007 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1009 case LFUN_PREFERENCES_SAVE:
1010 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1011 case LFUN_DEBUG_LEVEL_SET:
1012 // these are handled in our dispatch()
1015 case LFUN_WINDOW_CLOSE:
1016 enable = d->views_.size() > 0;
1019 case LFUN_BUFFER_NEW:
1020 case LFUN_BUFFER_NEW_TEMPLATE:
1021 case LFUN_FILE_OPEN:
1022 case LFUN_HELP_OPEN:
1023 case LFUN_SCREEN_FONT_UPDATE:
1024 case LFUN_SET_COLOR:
1025 case LFUN_WINDOW_NEW:
1027 case LFUN_LYXRC_APPLY:
1028 case LFUN_COMMAND_PREFIX:
1030 case LFUN_META_PREFIX:
1031 case LFUN_RECONFIGURE:
1032 case LFUN_SERVER_GET_FILENAME:
1033 case LFUN_SERVER_NOTIFY:
1042 flag.setEnabled(false);
1046 /// make a post-dispatch status message
1047 static docstring makeDispatchMessage(docstring const & msg,
1048 FuncRequest const & cmd)
1050 const bool verbose = (cmd.origin() == FuncRequest::MENU
1051 || cmd.origin() == FuncRequest::TOOLBAR
1052 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1054 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1055 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1059 docstring dispatch_msg = msg;
1060 if (!dispatch_msg.empty())
1061 dispatch_msg += ' ';
1063 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1065 bool argsadded = false;
1067 if (!cmd.argument().empty()) {
1068 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1069 comname += ' ' + cmd.argument();
1073 docstring const shortcuts = theTopLevelKeymap().
1074 printBindings(cmd, KeySequence::ForGui);
1076 if (!shortcuts.empty())
1077 comname += ": " + shortcuts;
1078 else if (!argsadded && !cmd.argument().empty())
1079 comname += ' ' + cmd.argument();
1081 if (!comname.empty()) {
1082 comname = rtrim(comname);
1083 dispatch_msg += '(' + rtrim(comname) + ')';
1085 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1086 return dispatch_msg;
1090 void GuiApplication::dispatch(FuncRequest const & cmd)
1092 if (current_view_ && current_view_->currentBufferView())
1093 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1096 // redraw the screen at the end (first of the two drawing steps).
1097 // This is done unless explicitly requested otherwise
1098 dr.screenUpdate(Update::FitCursor);
1104 BufferView * bv = current_view_->currentBufferView();
1106 if (dr.needBufferUpdate()) {
1107 bv->cursor().clearBufferUpdate();
1108 bv->buffer().updateBuffer();
1110 // BufferView::update() updates the ViewMetricsInfo and
1111 // also initializes the position cache for all insets in
1112 // (at least partially) visible top-level paragraphs.
1113 // We will redraw the screen only if needed.
1114 bv->processUpdateFlags(dr.screenUpdate());
1116 // Do we have a selection?
1117 theSelection().haveSelection(bv->cursor().selection());
1120 current_view_->restartCursor();
1122 if (dr.needMessageUpdate()) {
1123 // Some messages may already be translated, so we cannot use _()
1124 current_view_->message(makeDispatchMessage(
1125 translateIfPossible(dr.message()), cmd));
1130 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1131 bool switchToBuffer)
1133 if (!theSession().bookmarks().isValid(idx))
1135 BookmarksSection::Bookmark const & bm =
1136 theSession().bookmarks().bookmark(idx);
1137 LASSERT(!bm.filename.empty(), /**/);
1138 string const file = bm.filename.absFileName();
1139 // if the file is not opened, open it.
1140 if (!theBufferList().exists(bm.filename)) {
1142 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1146 // open may fail, so we need to test it again
1147 if (!theBufferList().exists(bm.filename))
1150 // bm can be changed when saving
1151 BookmarksSection::Bookmark tmp = bm;
1153 // Special case idx == 0 used for back-from-back jump navigation
1155 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1157 // if the current buffer is not that one, switch to it.
1158 BufferView * doc_bv = current_view_ ?
1159 current_view_->documentBufferView() : 0;
1160 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1161 if (switchToBuffer) {
1162 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1165 doc_bv = current_view_->documentBufferView();
1170 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1171 if (!doc_bv->moveToPosition(
1172 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1179 // Cursor jump succeeded!
1180 Cursor const & cur = doc_bv->cursor();
1181 pit_type new_pit = cur.pit();
1182 pos_type new_pos = cur.pos();
1183 int new_id = cur.paragraph().id();
1185 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1186 // see http://www.lyx.org/trac/ticket/3092
1187 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1188 || bm.top_id != new_id) {
1189 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1190 new_pit, new_pos, new_id);
1194 // This function runs "configure" and then rereads lyx.defaults to
1195 // reconfigure the automatic settings.
1196 void GuiApplication::reconfigure(string const & option)
1198 // emit message signal.
1200 current_view_->message(_("Running configure..."));
1202 // Run configure in user lyx directory
1203 PathChanger p(package().user_support());
1204 string configure_command = package().configure_command();
1205 configure_command += option;
1207 int ret = one.startscript(Systemcall::Wait, configure_command);
1209 // emit message signal.
1211 current_view_->message(_("Reloading configuration..."));
1212 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1213 // Re-read packages.lst
1214 LaTeXPackages::getAvailable();
1217 Alert::information(_("System reconfiguration failed"),
1218 _("The system reconfiguration has failed.\n"
1219 "Default textclass is used but LyX may "
1220 "not be able to work properly.\n"
1221 "Please reconfigure again if needed."));
1223 Alert::information(_("System reconfigured"),
1224 _("The system has been reconfigured.\n"
1225 "You need to restart LyX to make use of any\n"
1226 "updated document class specifications."));
1229 void GuiApplication::validateCurrentView()
1231 if (!d->views_.empty() && !current_view_) {
1232 // currently at least one view exists but no view has the focus.
1233 // choose the last view to make it current.
1234 // a view without any open document is preferred.
1235 GuiView * candidate = 0;
1236 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1237 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1238 for (; it != end; ++it) {
1240 if (!candidate->documentBufferView())
1243 setCurrentView(candidate);
1247 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1249 string const argument = to_utf8(cmd.argument());
1250 FuncCode const action = cmd.action();
1252 LYXERR(Debug::ACTION, "cmd: " << cmd);
1254 // we have not done anything wrong yet.
1257 FuncStatus const flag = getStatus(cmd);
1258 if (!flag.enabled()) {
1259 // We cannot use this function here
1260 LYXERR(Debug::ACTION, "action "
1261 << lyxaction.getActionName(action)
1262 << " [" << action << "] is disabled at this location");
1263 dr.setMessage(flag.message());
1265 dr.dispatched(false);
1266 dr.screenUpdate(Update::None);
1267 dr.clearBufferUpdate();
1271 // Assumes that the action will be dispatched.
1272 dr.dispatched(true);
1274 switch (cmd.action()) {
1276 case LFUN_WINDOW_NEW:
1277 createView(toqstr(cmd.argument()));
1280 case LFUN_WINDOW_CLOSE:
1281 // update bookmark pit of the current buffer before window close
1282 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1283 gotoBookmark(i+1, false, false);
1284 // clear the last opened list, because
1285 // maybe this will end the session
1286 theSession().lastOpened().clear();
1287 // check for valid current_view_
1288 validateCurrentView();
1290 current_view_->closeScheduled();
1294 // quitting is triggered by the gui code
1295 // (leaving the event loop).
1297 current_view_->message(from_utf8(N_("Exiting.")));
1298 if (closeAllViews())
1302 case LFUN_SCREEN_FONT_UPDATE: {
1303 // handle the screen font changes.
1304 d->font_loader_.update();
1305 // Backup current_view_
1306 GuiView * view = current_view_;
1307 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1308 // to skip the refresh.
1310 theBufferList().changed(false);
1311 // Restore current_view_
1312 current_view_ = view;
1316 case LFUN_BUFFER_NEW:
1317 validateCurrentView();
1318 if (d->views_.empty()
1319 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1320 createView(QString(), false); // keep hidden
1321 current_view_->newDocument(to_utf8(cmd.argument()), false);
1322 current_view_->show();
1323 setActiveWindow(current_view_);
1325 current_view_->newDocument(to_utf8(cmd.argument()), false);
1329 case LFUN_BUFFER_NEW_TEMPLATE:
1330 validateCurrentView();
1331 if (d->views_.empty()
1332 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1334 current_view_->newDocument(to_utf8(cmd.argument()), true);
1335 if (!current_view_->documentBufferView())
1336 current_view_->close();
1338 current_view_->newDocument(to_utf8(cmd.argument()), true);
1342 case LFUN_FILE_OPEN: {
1343 validateCurrentView();
1344 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1345 string const fname = to_utf8(cmd.argument());
1346 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1347 && current_view_->documentBufferView() != 0)) {
1348 // We want the ui session to be saved per document and not per
1349 // window number. The filename crc is a good enough identifier.
1350 boost::crc_32_type crc;
1351 crc = for_each(fname.begin(), fname.end(), crc);
1352 createView(crc.checksum());
1353 current_view_->openDocument(fname);
1354 if (current_view_ && !current_view_->documentBufferView())
1355 current_view_->close();
1357 current_view_->openDocument(fname);
1361 case LFUN_HELP_OPEN: {
1362 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1363 if (current_view_ == 0)
1365 string const arg = to_utf8(cmd.argument());
1367 current_view_->message(_("Missing argument"));
1370 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1372 fname = i18nLibFileSearch("examples", arg, "lyx");
1374 if (fname.empty()) {
1375 lyxerr << "LyX: unable to find documentation file `"
1376 << arg << "'. Bad installation?" << endl;
1379 current_view_->message(bformat(_("Opening help file %1$s..."),
1380 makeDisplayPath(fname.absFileName())));
1381 Buffer * buf = current_view_->loadDocument(fname, false);
1383 #ifndef DEVEL_VERSION
1385 buf->setReadonly(true);
1392 case LFUN_SET_COLOR: {
1394 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1395 if (lyx_name.empty() || x11_name.empty()) {
1397 current_view_->message(
1398 _("Syntax: set-color <lyx_name> <x11_name>"));
1403 // FIXME: The graphics cache no longer has a changeDisplay method.
1404 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1405 bool const graphicsbg_changed =
1406 lyx_name == graphicsbg && x11_name != graphicsbg;
1407 if (graphicsbg_changed)
1408 graphics::GCache::get().changeDisplay(true);
1411 if (!lcolor.setColor(lyx_name, x11_name)) {
1413 current_view_->message(
1414 bformat(_("Set-color \"%1$s\" failed "
1415 "- color is undefined or "
1416 "may not be redefined"),
1417 from_utf8(lyx_name)));
1420 // Make sure we don't keep old colors in cache.
1421 d->color_cache_.clear();
1425 case LFUN_LYXRC_APPLY: {
1426 // reset active key sequences, since the bindings
1427 // are updated (bug 6064)
1429 LyXRC const lyxrc_orig = lyxrc;
1431 istringstream ss(to_utf8(cmd.argument()));
1432 bool const success = lyxrc.read(ss);
1435 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1436 << "Unable to read lyxrc data"
1441 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1447 case LFUN_COMMAND_PREFIX:
1448 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1453 d->meta_fake_bit = NoModifier;
1454 GuiView * gv = currentView();
1455 if (gv && gv->currentBufferView())
1456 // cancel any selection
1457 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1458 dr.setMessage(from_ascii(N_("Cancel")));
1461 case LFUN_META_PREFIX:
1462 d->meta_fake_bit = AltModifier;
1463 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1466 // --- Menus -----------------------------------------------
1467 case LFUN_RECONFIGURE:
1468 // argument is any additional parameter to the configure.py command
1469 reconfigure(to_utf8(cmd.argument()));
1472 // --- lyxserver commands ----------------------------
1473 case LFUN_SERVER_GET_FILENAME: {
1474 if (current_view_ && current_view_->documentBufferView()) {
1475 docstring const fname = from_utf8(
1476 current_view_->documentBufferView()->buffer().absFileName());
1477 dr.setMessage(fname);
1478 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1480 dr.setMessage(docstring());
1481 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1486 case LFUN_SERVER_NOTIFY: {
1487 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1488 dr.setMessage(dispatch_buffer);
1489 theServer().notifyClient(to_utf8(dispatch_buffer));
1493 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1494 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1500 string rest = split(argument, countstr, ' ');
1501 istringstream is(countstr);
1504 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1505 for (int i = 0; i < count; ++i)
1506 dispatch(lyxaction.lookupFunc(rest));
1510 case LFUN_COMMAND_SEQUENCE: {
1511 // argument contains ';'-terminated commands
1512 string arg = argument;
1513 // FIXME: this LFUN should also work without any view.
1514 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1515 ? &(current_view_->documentBufferView()->buffer()) : 0;
1517 buffer->undo().beginUndoGroup();
1518 while (!arg.empty()) {
1520 arg = split(arg, first, ';');
1521 FuncRequest func(lyxaction.lookupFunc(first));
1522 func.setOrigin(cmd.origin());
1525 // the buffer may have been closed by one action
1526 if (theBufferList().isLoaded(buffer))
1527 buffer->undo().endUndoGroup();
1531 case LFUN_COMMAND_ALTERNATIVES: {
1532 // argument contains ';'-terminated commands
1533 string arg = argument;
1534 while (!arg.empty()) {
1536 arg = split(arg, first, ';');
1537 FuncRequest func(lyxaction.lookupFunc(first));
1538 func.setOrigin(cmd.origin());
1539 FuncStatus const stat = getStatus(func);
1540 if (stat.enabled()) {
1550 if (theTopLevelCmdDef().lock(argument, func)) {
1551 func.setOrigin(cmd.origin());
1553 theTopLevelCmdDef().release(argument);
1555 if (func.action() == LFUN_UNKNOWN_ACTION) {
1556 // unknown command definition
1557 lyxerr << "Warning: unknown command definition `"
1561 // recursion detected
1562 lyxerr << "Warning: Recursion in the command definition `"
1563 << argument << "' detected"
1570 case LFUN_PREFERENCES_SAVE:
1571 lyxrc.write(support::makeAbsPath("preferences",
1572 package().user_support().absFileName()), false);
1575 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1576 string const fname = addName(addPath(package().user_support().absFileName(),
1577 "templates/"), "defaults.lyx");
1578 Buffer defaults(fname);
1580 istringstream ss(argument);
1583 int const unknown_tokens = defaults.readHeader(lex);
1585 if (unknown_tokens != 0) {
1586 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1587 << unknown_tokens << " unknown token"
1588 << (unknown_tokens == 1 ? "" : "s")
1592 if (defaults.writeFile(FileName(defaults.absFileName())))
1593 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1594 makeDisplayPath(fname)));
1597 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1602 case LFUN_BOOKMARK_GOTO:
1603 // go to bookmark, open unopened file and switch to buffer if necessary
1604 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1605 dr.screenUpdate(Update::Force | Update::FitCursor);
1608 case LFUN_BOOKMARK_CLEAR:
1609 theSession().bookmarks().clear();
1612 case LFUN_DEBUG_LEVEL_SET:
1613 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1617 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1620 current_view_->dispatch(cmd, dr);
1626 docstring GuiApplication::viewStatusMessage()
1628 // When meta-fake key is pressed, show the key sequence so far + "M-".
1629 if (d->meta_fake_bit != NoModifier)
1630 return d->keyseq.print(KeySequence::ForGui) + "M-";
1632 // Else, when a non-complete key sequence is pressed,
1633 // show the available options.
1634 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1635 return d->keyseq.printOptions(true);
1641 void GuiApplication::handleKeyFunc(FuncCode action)
1645 if (d->keyseq.length())
1647 GuiView * gv = currentView();
1648 LASSERT(gv && gv->currentBufferView(), return);
1649 BufferView * bv = gv->currentBufferView();
1650 bv->getIntl().getTransManager().deadkey(
1651 c, get_accent(action).accent, bv->cursor().innerText(),
1653 // Need to clear, in case the minibuffer calls these
1656 // copied verbatim from do_accent_char
1657 bv->cursor().resetAnchor();
1661 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1663 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1665 // Do nothing if we have nothing (JMarc)
1666 if (!keysym.isOK()) {
1667 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1669 current_view_->restartCursor();
1673 if (keysym.isModifier()) {
1675 current_view_->restartCursor();
1679 char_type encoded_last_key = keysym.getUCSEncoded();
1681 // Do a one-deep top-level lookup for
1682 // cancel and meta-fake keys. RVDK_PATCH_5
1683 d->cancel_meta_seq.reset();
1685 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1686 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1688 // When not cancel or meta-fake, do the normal lookup.
1689 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1690 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1691 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1692 // remove Caps Lock and Mod2 as a modifiers
1693 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1694 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1697 // Dont remove this unless you know what you are doing.
1698 d->meta_fake_bit = NoModifier;
1700 // Can this happen now ?
1701 if (func.action() == LFUN_NOACTION)
1702 func = FuncRequest(LFUN_COMMAND_PREFIX);
1704 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1705 << d->keyseq.print(KeySequence::Portable) << ']');
1707 // already here we know if it any point in going further
1708 // why not return already here if action == -1 and
1709 // num_bytes == 0? (Lgb)
1711 if (d->keyseq.length() > 1 && current_view_)
1712 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1715 // Maybe user can only reach the key via holding down shift.
1716 // Let's see. But only if shift is the only modifier
1717 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1718 LYXERR(Debug::KEY, "Trying without shift");
1719 func = d->keyseq.addkey(keysym, NoModifier);
1720 LYXERR(Debug::KEY, "Action now " << func.action());
1723 if (func.action() == LFUN_UNKNOWN_ACTION) {
1724 // Hmm, we didn't match any of the keysequences. See
1725 // if it's normal insertable text not already covered
1727 if (keysym.isText() && d->keyseq.length() == 1) {
1728 LYXERR(Debug::KEY, "isText() is true, inserting.");
1729 func = FuncRequest(LFUN_SELF_INSERT,
1730 FuncRequest::KEYBOARD);
1732 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1733 if (current_view_) {
1734 current_view_->message(_("Unknown function."));
1735 current_view_->restartCursor();
1741 if (func.action() == LFUN_SELF_INSERT) {
1742 if (encoded_last_key != 0) {
1743 docstring const arg(1, encoded_last_key);
1744 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
1745 FuncRequest::KEYBOARD));
1746 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1749 processFuncRequest(func);
1753 void GuiApplication::processFuncRequest(FuncRequest const & func)
1755 lyx::dispatch(func);
1759 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
1761 addToFuncRequestQueue(func);
1762 processFuncRequestQueueAsync();
1766 void GuiApplication::processFuncRequestQueue()
1768 while (!d->func_request_queue_.empty()) {
1769 processFuncRequest(d->func_request_queue_.front());
1770 d->func_request_queue_.pop();
1775 void GuiApplication::processFuncRequestQueueAsync()
1777 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
1781 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
1783 d->func_request_queue_.push(func);
1787 void GuiApplication::resetGui()
1789 // Set the language defined by the user.
1793 if (!readUIFile(toqstr(lyxrc.ui_file)))
1794 // Gives some error box here.
1797 if (d->global_menubar_)
1798 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1800 QHash<int, GuiView *>::iterator it;
1801 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1804 gv->setLayoutDirection(layoutDirection());
1808 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1812 void GuiApplication::createView(int view_id)
1814 createView(QString(), true, view_id);
1818 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1821 // release the keyboard which might have been grabed by the global
1822 // menubar on Mac to catch shortcuts even without any GuiView.
1823 if (d->global_menubar_)
1824 d->global_menubar_->releaseKeyboard();
1828 while (d->views_.find(id) != d->views_.end())
1831 LYXERR(Debug::GUI, "About to create new window with ID " << id);
1832 GuiView * view = new GuiView(id);
1834 d->views_[id] = view;
1838 setActiveWindow(view);
1841 if (!geometry_arg.isEmpty()) {
1845 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1846 re.indexIn(geometry_arg);
1847 w = re.cap(1).toInt();
1848 h = re.cap(2).toInt();
1849 x = re.cap(3).toInt();
1850 y = re.cap(4).toInt();
1851 view->setGeometry(x, y, w, h);
1858 Clipboard & GuiApplication::clipboard()
1860 return d->clipboard_;
1864 Selection & GuiApplication::selection()
1866 return d->selection_;
1870 FontLoader & GuiApplication::fontLoader()
1872 return d->font_loader_;
1876 Toolbars const & GuiApplication::toolbars() const
1878 return d->toolbars_;
1882 Toolbars & GuiApplication::toolbars()
1884 return d->toolbars_;
1888 Menus const & GuiApplication::menus() const
1894 Menus & GuiApplication::menus()
1900 QList<int> GuiApplication::viewIds() const
1902 return d->views_.keys();
1906 ColorCache & GuiApplication::colorCache()
1908 return d->color_cache_;
1912 int GuiApplication::exec()
1914 // asynchronously handle batch commands. This event will be in
1915 // the event queue in front of other asynchronous events. Hence,
1916 // we can assume in the latter that the gui is setup already.
1917 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1919 return QApplication::exec();
1923 void GuiApplication::exit(int status)
1925 QApplication::exit(status);
1929 void GuiApplication::setGuiLanguage()
1931 // Set the language defined by the user.
1934 QString const default_language = toqstr(Messages::defaultLanguage());
1935 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
1936 QLocale const default_locale(default_language);
1937 QLocale::setDefault(default_locale);
1939 // install translation file for Qt built-in dialogs
1940 QString const language_name = QString("qt_") + default_locale.name();
1942 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1943 // Short-named translator can be loaded from a long name, but not the
1944 // opposite. Therefore, long name should be used without truncation.
1945 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1946 if (!d->qt_trans_.load(language_name,
1947 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1948 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1951 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1955 switch (default_locale.language()) {
1956 case QLocale::Arabic :
1957 case QLocale::Hebrew :
1958 case QLocale::Persian :
1959 case QLocale::Urdu :
1960 setLayoutDirection(Qt::RightToLeft);
1963 setLayoutDirection(Qt::LeftToRight);
1968 void GuiApplication::execBatchCommands()
1973 if (!readUIFile(toqstr(lyxrc.ui_file)))
1974 // Gives some error box here.
1978 #if QT_VERSION > 0x040600
1979 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
1981 // Create the global default menubar which is shown for the dialogs
1982 // and if no GuiView is visible.
1983 // This must be done after the session was recovered to know the "last files".
1984 d->global_menubar_ = new GlobalMenuBar();
1985 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1988 lyx::execBatchCommands();
1992 QAbstractItemModel * GuiApplication::languageModel()
1994 if (d->language_model_)
1995 return d->language_model_;
1997 QStandardItemModel * lang_model = new QStandardItemModel(this);
1998 lang_model->insertColumns(0, 3);
2000 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2001 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2002 Languages::const_iterator it = lyx::languages.begin();
2003 Languages::const_iterator end = lyx::languages.end();
2004 for (; it != end; ++it) {
2005 current_row = lang_model->rowCount();
2006 lang_model->insertRows(current_row, 1);
2007 QModelIndex pl_item = lang_model->index(current_row, 0);
2008 QModelIndex sp_item = lang_model->index(current_row, 1);
2009 QModelIndex th_item = lang_model->index(current_row, 2);
2010 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2011 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2012 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2013 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2014 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2015 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2016 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2017 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2018 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2019 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2021 d->language_model_ = new QSortFilterProxyModel(this);
2022 d->language_model_->setSourceModel(lang_model);
2023 #if QT_VERSION >= 0x040300
2024 d->language_model_->setSortLocaleAware(true);
2026 return d->language_model_;
2030 void GuiApplication::restoreGuiSession()
2032 if (!lyxrc.load_session)
2035 Session & session = theSession();
2036 LastOpenedSection::LastOpened const & lastopened =
2037 session.lastOpened().getfiles();
2039 validateCurrentView();
2041 FileName active_file;
2042 // do not add to the lastfile list since these files are restored from
2043 // last session, and should be already there (regular files), or should
2044 // not be added at all (help files).
2045 for (size_t i = 0; i < lastopened.size(); ++i) {
2046 FileName const & file_name = lastopened[i].file_name;
2047 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2048 && current_view_->documentBufferView() != 0)) {
2049 boost::crc_32_type crc;
2050 string const & fname = file_name.absFileName();
2051 crc = for_each(fname.begin(), fname.end(), crc);
2052 createView(crc.checksum());
2054 current_view_->loadDocument(file_name, false);
2056 if (lastopened[i].active)
2057 active_file = file_name;
2060 // Restore last active buffer
2061 Buffer * buffer = theBufferList().getBuffer(active_file);
2062 if (buffer && current_view_)
2063 current_view_->setBuffer(buffer);
2065 // clear this list to save a few bytes of RAM
2066 session.lastOpened().clear();
2070 QString const GuiApplication::romanFontName()
2073 font.setKerning(false);
2074 font.setStyleHint(QFont::Serif);
2075 font.setFamily("serif");
2077 return QFontInfo(font).family();
2081 QString const GuiApplication::sansFontName()
2084 font.setKerning(false);
2085 font.setStyleHint(QFont::SansSerif);
2086 font.setFamily("sans");
2088 return QFontInfo(font).family();
2092 QString const GuiApplication::typewriterFontName()
2095 font.setKerning(false);
2096 font.setStyleHint(QFont::TypeWriter);
2097 font.setFamily("monospace");
2099 return QFontInfo(font).family();
2103 void GuiApplication::handleRegularEvents()
2105 ForkedCallsController::handleCompletedProcesses();
2109 bool GuiApplication::event(QEvent * e)
2112 case QEvent::FileOpen: {
2113 // Open a file; this happens only on Mac OS X for now.
2115 // We do this asynchronously because on startup the batch
2116 // commands are not executed here yet and the gui is not ready
2118 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2119 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2120 processFuncRequestAsync(fr);
2125 return QApplication::event(e);
2130 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2133 return QApplication::notify(receiver, event);
2135 catch (ExceptionMessage const & e) {
2137 case ErrorException:
2139 setQuitOnLastWindowClosed(false);
2141 Alert::error(e.title_, e.details_);
2143 // Properly crash in debug mode in order to get a useful backtrace.
2146 // In release mode, try to exit gracefully.
2149 case BufferException: {
2150 if (!current_view_ || !current_view_->documentBufferView())
2152 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2153 docstring details = e.details_ + '\n';
2154 details += buf->emergencyWrite();
2155 theBufferList().release(buf);
2156 details += "\n" + _("The current document was closed.");
2157 Alert::error(e.title_, details);
2160 case WarningException:
2161 Alert::warning(e.title_, e.details_);
2165 catch (exception const & e) {
2166 docstring s = _("LyX has caught an exception, it will now "
2167 "attempt to save all unsaved documents and exit."
2169 s += from_ascii(e.what());
2170 Alert::error(_("Software exception Detected"), s);
2174 docstring s = _("LyX has caught some really weird exception, it will "
2175 "now attempt to save all unsaved documents and exit.");
2176 Alert::error(_("Software exception Detected"), s);
2184 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2186 QColor const & qcol = d->color_cache_.get(col);
2187 if (!qcol.isValid()) {
2193 rgbcol.r = qcol.red();
2194 rgbcol.g = qcol.green();
2195 rgbcol.b = qcol.blue();
2200 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2202 QColor const qcol(lcolor.getX11Name(col).c_str());
2203 if (!qcol.isValid()) {
2209 rgbcol.r = qcol.red();
2210 rgbcol.g = qcol.green();
2211 rgbcol.b = qcol.blue();
2216 string const GuiApplication::hexName(ColorCode col)
2218 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2222 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2224 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2225 d->socket_notifiers_[fd] = sn;
2226 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2230 void GuiApplication::socketDataReceived(int fd)
2232 d->socket_notifiers_[fd]->func_();
2236 void GuiApplication::unregisterSocketCallback(int fd)
2238 d->socket_notifiers_.take(fd)->setEnabled(false);
2242 void GuiApplication::commitData(QSessionManager & sm)
2244 /// The implementation is required to avoid an application exit
2245 /// when session state save is triggered by session manager.
2246 /// The default implementation sends a close event to all
2247 /// visible top level widgets when session managment allows
2249 /// We are changing that to close all wiew one by one.
2250 /// FIXME: verify if the default implementation is enough now.
2251 #ifdef QT_NO_SESSIONMANAGER
2252 #warning Qt is compiled without session manager
2255 if (sm.allowsInteraction() && !closeAllViews())
2261 void GuiApplication::unregisterView(GuiView * gv)
2263 LASSERT(d->views_[gv->id()] == gv, /**/);
2264 d->views_.remove(gv->id());
2265 if (current_view_ == gv)
2270 bool GuiApplication::closeAllViews()
2272 if (d->views_.empty())
2275 // When a view/window was closed before without quitting LyX, there
2276 // are already entries in the lastOpened list.
2277 theSession().lastOpened().clear();
2279 QList<GuiView *> views = d->views_.values();
2280 foreach (GuiView * view, views) {
2281 if (!view->closeScheduled())
2290 GuiView & GuiApplication::view(int id) const
2292 LASSERT(d->views_.contains(id), /**/);
2293 return *d->views_.value(id);
2297 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2299 QList<GuiView *> views = d->views_.values();
2300 foreach (GuiView * view, views)
2301 view->hideDialog(name, inset);
2305 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2307 Buffer const * buffer_ = 0;
2308 QHash<int, GuiView *>::iterator end = d->views_.end();
2309 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2310 if (Buffer const * ptr = (*it)->updateInset(inset))
2317 bool GuiApplication::searchMenu(FuncRequest const & func,
2318 docstring_list & names) const
2320 return d->menus_.searchMenu(func, names);
2324 // Ensure that a file is read only once (prevents include loops)
2325 static QStringList uifiles;
2326 // store which ui files define Toolbars
2327 static QStringList toolbar_uifiles;
2330 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2341 LexerKeyword uitags[] = {
2342 { "format", ui_format },
2343 { "include", ui_include },
2344 { "menuset", ui_menuset },
2345 { "toolbars", ui_toolbars },
2346 { "toolbarset", ui_toolbarset }
2350 lex.setFile(ui_path);
2352 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2356 if (lyxerr.debugging(Debug::PARSER))
2357 lex.printTable(lyxerr);
2360 // format before introduction of format tag
2361 unsigned int format = 0;
2362 while (lex.isOK()) {
2363 int const status = lex.lex();
2365 // we have to do this check here, outside the switch,
2366 // because otherwise we would start reading include files,
2367 // e.g., if the first tag we hit was an include tag.
2368 if (status == ui_format)
2370 format = lex.getInteger();
2374 // this will trigger unless the first tag we hit is a format
2375 // tag, with the right format.
2376 if (format != LFUN_FORMAT)
2377 return FormatMismatch;
2380 case Lexer::LEX_FEOF:
2385 QString const file = toqstr(lex.getString());
2386 bool const success = readUIFile(file, true);
2388 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2395 d->menus_.read(lex);
2399 d->toolbars_.readToolbars(lex);
2403 d->toolbars_.readToolbarSettings(lex);
2404 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2408 if (!rtrim(lex.getString()).empty())
2409 lex.printError("LyX::ReadUIFile: "
2410 "Unknown menu tag: `$$Token'");
2412 LYXERR0("Error with status: " << status);
2418 return (error ? ReadError : ReadOK);
2422 bool GuiApplication::readUIFile(QString const & name, bool include)
2424 LYXERR(Debug::INIT, "About to read " << name << "...");
2428 ui_path = libFileSearch("ui", name, "inc");
2429 if (ui_path.empty())
2430 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2432 ui_path = libFileSearch("ui", name, "ui");
2435 if (ui_path.empty()) {
2436 static const QString defaultUIFile = "default";
2437 LYXERR(Debug::INIT, "Could not find " << name);
2439 Alert::warning(_("Could not find UI definition file"),
2440 bformat(_("Error while reading the included file\n%1$s\n"
2441 "Please check your installation."), qstring_to_ucs4(name)));
2444 if (name == defaultUIFile) {
2445 LYXERR(Debug::INIT, "Could not find default UI file!!");
2446 Alert::warning(_("Could not find default UI file"),
2447 _("LyX could not find the default UI file!\n"
2448 "Please check your installation."));
2451 Alert::warning(_("Could not find UI definition file"),
2452 bformat(_("Error while reading the configuration file\n%1$s\n"
2453 "Falling back to default.\n"
2454 "Please look under Tools>Preferences>User Interface and\n"
2455 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2456 return readUIFile(defaultUIFile, false);
2459 QString const uifile = toqstr(ui_path.absFileName());
2460 if (uifiles.contains(uifile)) {
2462 // We are reading again the top uifile so reset the safeguard:
2465 d->toolbars_.reset();
2467 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2468 << "Is this an include loop?");
2472 uifiles.push_back(uifile);
2474 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2476 ReturnValues retval = readUIFile(ui_path);
2478 if (retval == FormatMismatch) {
2479 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2480 FileName const tempfile = FileName::tempName("convert_ui");
2481 bool const success = prefs2prefs(ui_path, tempfile, true);
2483 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2484 " to format " << LFUN_FORMAT << ".");
2486 retval = readUIFile(tempfile);
2487 tempfile.removeFile();
2491 if (retval != ReadOK) {
2492 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2500 settings.beginGroup("ui_files");
2501 bool touched = false;
2502 for (int i = 0; i != uifiles.size(); ++i) {
2503 QFileInfo fi(uifiles[i]);
2504 QDateTime const date_value = fi.lastModified();
2505 QString const name_key = QString::number(i);
2506 // if an ui file which defines Toolbars has changed,
2507 // we have to reset the settings
2508 if (toolbar_uifiles.contains(uifiles[i])
2509 && (!settings.contains(name_key)
2510 || settings.value(name_key).toString() != uifiles[i]
2511 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2513 settings.setValue(name_key, uifiles[i]);
2514 settings.setValue(name_key + "/date", date_value);
2517 settings.endGroup();
2519 settings.remove("views");
2525 void GuiApplication::onLastWindowClosed()
2527 if (d->global_menubar_)
2528 d->global_menubar_->grabKeyboard();
2532 ////////////////////////////////////////////////////////////////////////
2534 // X11 specific stuff goes here...
2537 bool GuiApplication::x11EventFilter(XEvent * xev)
2542 switch (xev->type) {
2543 case SelectionRequest: {
2544 if (xev->xselectionrequest.selection != XA_PRIMARY)
2546 LYXERR(Debug::SELECTION, "X requested selection.");
2547 BufferView * bv = current_view_->currentBufferView();
2549 docstring const sel = bv->requestSelection();
2551 d->selection_.put(sel);
2555 case SelectionClear: {
2556 if (xev->xselectionclear.selection != XA_PRIMARY)
2558 LYXERR(Debug::SELECTION, "Lost selection.");
2559 BufferView * bv = current_view_->currentBufferView();
2561 bv->clearSelection();
2569 } // namespace frontend
2572 void hideDialogs(std::string const & name, Inset * inset)
2575 frontend::guiApp->hideDialogs(name, inset);
2579 ////////////////////////////////////////////////////////////////////
2583 ////////////////////////////////////////////////////////////////////
2585 frontend::FontLoader & theFontLoader()
2587 LASSERT(frontend::guiApp, /**/);
2588 return frontend::guiApp->fontLoader();
2592 frontend::FontMetrics const & theFontMetrics(Font const & f)
2594 return theFontMetrics(f.fontInfo());
2598 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2600 LASSERT(frontend::guiApp, /**/);
2601 return frontend::guiApp->fontLoader().metrics(f);
2605 ////////////////////////////////////////////////////////////////////
2609 ////////////////////////////////////////////////////////////////////
2611 frontend::Clipboard & theClipboard()
2613 LASSERT(frontend::guiApp, /**/);
2614 return frontend::guiApp->clipboard();
2618 frontend::Selection & theSelection()
2620 LASSERT(frontend::guiApp, /**/);
2621 return frontend::guiApp->selection();
2627 #include "moc_GuiApplication.cpp"