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 "LaTeXFeatures.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>
110 #include <X11/Xatom.h>
111 #include <X11/Xlib.h>
117 #include <QWindowsMime>
124 #include <boost/bind.hpp>
125 #include <boost/crc.hpp>
132 using namespace lyx::support;
135 static void initializeResources()
137 static bool initialized = false;
139 Q_INIT_RESOURCE(Resources);
147 frontend::Application * createApplication(int & argc, char * argv[])
150 // prune -geometry argument(s) by shifting
151 // the following ones 2 places down.
152 for (int i = 0 ; i < argc ; ++i) {
153 if (strcmp(argv[i], "-geometry") == 0) {
154 int const remove = (i+1) < argc ? 2 : 1;
156 for (int j = i; j < argc; ++j)
157 argv[j] = argv[j + remove];
162 return new frontend::GuiApplication(argc, argv);
168 /// Return the list of loadable formats.
169 vector<string> loadableImageFormats()
173 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
175 LYXERR(Debug::GRAPHICS,
176 "\nThe image loader can load the following directly:\n");
178 if (qt_formats.empty())
179 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
181 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
183 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
185 string ext = ascii_lowercase((const char *) *it);
196 ////////////////////////////////////////////////////////////////////////
198 // Icon loading support code
200 ////////////////////////////////////////////////////////////////////////
210 bool operator<(PngMap const & lhs, PngMap const & rhs)
212 return lhs.key < rhs.key;
218 CompareKey(QString const & name) : name_(name) {}
219 bool operator()(PngMap const & other) const { return other.key == name_; }
225 // this must be sorted alphabetically
226 // Upper case comes before lower case
227 PngMap sorted_png_map[] = {
228 { "Bumpeq", "bumpeq2" },
231 { "Delta", "delta2" },
232 { "Diamond", "diamond2" },
233 { "Downarrow", "downarrow2" },
234 { "Gamma", "gamma2" },
235 { "Lambda", "lambda2" },
236 { "Leftarrow", "leftarrow2" },
237 { "Leftrightarrow", "leftrightarrow2" },
238 { "Longleftarrow", "longleftarrow2" },
239 { "Longleftrightarrow", "longleftrightarrow2" },
240 { "Longrightarrow", "longrightarrow2" },
241 { "Omega", "omega2" },
245 { "Rightarrow", "rightarrow2" },
246 { "Sigma", "sigma2" },
247 { "Subset", "subset2" },
248 { "Supset", "supset2" },
249 { "Theta", "theta2" },
250 { "Uparrow", "uparrow2" },
251 { "Updownarrow", "updownarrow2" },
252 { "Upsilon", "upsilon2" },
253 { "Vdash", "vdash3" },
256 { "nLeftarrow", "nleftarrow2" },
257 { "nLeftrightarrow", "nleftrightarrow2" },
258 { "nRightarrow", "nrightarrow2" },
259 { "nVDash", "nvdash3" },
260 { "nvDash", "nvdash2" },
261 { "textrm \\AA", "textrm_AA"},
262 { "textrm \\O", "textrm_O"},
263 { "vDash", "vdash2" }
266 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
269 QString findPng(QString const & name)
271 PngMap const * const begin = sorted_png_map;
272 PngMap const * const end = begin + nr_sorted_png_map;
273 LASSERT(sorted(begin, end), /**/);
275 PngMap const * const it = find_if(begin, end, CompareKey(name));
279 png_name = it->value;
282 png_name.replace('_', "underscore");
283 png_name.replace(' ', '_');
285 // This way we can have "math-delim { }" on the toolbar.
286 png_name.replace('(', "lparen");
287 png_name.replace(')', "rparen");
288 png_name.replace('[', "lbracket");
289 png_name.replace(']', "rbracket");
290 png_name.replace('{', "lbrace");
291 png_name.replace('}', "rbrace");
292 png_name.replace('|', "bars");
293 png_name.replace(',', "thinspace");
294 png_name.replace(':', "mediumspace");
295 png_name.replace(';', "thickspace");
296 png_name.replace('!', "negthinspace");
299 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
300 << "Looking for math PNG called \"" << png_name << '"');
307 QString iconName(FuncRequest const & f, bool unknown)
309 initializeResources();
314 case LFUN_MATH_INSERT:
315 if (!f.argument().empty()) {
317 name1 = findPng(toqstr(f.argument()).mid(1));
320 case LFUN_MATH_DELIM:
321 case LFUN_MATH_BIGDELIM:
323 name1 = findPng(toqstr(f.argument()));
327 name1 = toqstr(f.argument());
329 case LFUN_COMMAND_ALTERNATIVES: {
330 // use the first of the alternative commands
332 docstring dummy = split(f.argument(), firstcom, ';');
333 name1 = toqstr(firstcom);
334 // FIXME: we should rename the icons to tabular-xxx instead of
335 // "tabular-feature-xxx"
336 name1.replace("inset-modify tabular", "tabular-feature");
337 name1.replace(' ', '_');
340 case LFUN_INSET_MODIFY: {
341 // FIXME: we should rename the icons to tabular-xxx instead of
342 // "tabular-feature-xxx" and generalize this naming to all
343 // insets, not to tabular using ones.
345 string const command = split(to_utf8(f.argument()), inset_name, ' ');
346 if (insetCode(inset_name) == TABULAR_CODE) {
347 name1 = "tabular-feature "+ toqstr(command);
348 name1.replace(' ', '_');
353 name2 = toqstr(lyxaction.getActionName(f.action));
356 if (!f.argument().empty()) {
357 name1 = name2 + ' ' + toqstr(f.argument());
358 name1.replace(' ', '_');
359 name1.replace('\\', "backslash");
363 FileName fname = libFileSearch("images/" + path, name1, "png");
365 return toqstr(fname.absFilename());
367 fname = libFileSearch("images/" + path, name2, "png");
369 return toqstr(fname.absFilename());
371 path = ":/images/" + path;
374 LYXERR0("Directory " << path << " not found in resource!");
378 if (res.exists(name1))
382 if (res.exists(name2))
385 LYXERR(Debug::GUI, "Cannot find icon with filename "
386 << "\"" << name1 << "\""
388 << "\"" << name2 << "\""
390 << lyxaction.getActionName(f.action)
391 << '(' << to_utf8(f.argument()) << ")\"");
394 fname = libFileSearch(QString("images/"), "unknown", "png");
396 return toqstr(fname.absFilename());
397 return QString(":/images/unknown.png");
403 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
406 FileName fname = libFileSearch(path, name, ext);
407 QString path1 = toqstr(fname.absFilename());
408 QString path2 = ":/" + path + name + "." + ext;
410 if (pixmap.load(path1)) {
413 else if (pixmap.load(path2)) {
417 LYXERR0("Cannot load pixmap \""
418 << path << name << '.' << ext
419 << "\", please verify resource system!");
424 QIcon getIcon(FuncRequest const & f, bool unknown)
426 QString icon = iconName(f, unknown);
430 //LYXERR(Debug::GUI, "Found icon: " << icon);
432 if (!pm.load(icon)) {
433 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
441 ////////////////////////////////////////////////////////////////////////
443 // LyX server support code.
445 ////////////////////////////////////////////////////////////////////////
447 class SocketNotifier : public QSocketNotifier
450 /// connect a connection notification from the LyXServerSocket
451 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
452 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
456 /// The callback function
457 Application::SocketCallback func_;
461 ////////////////////////////////////////////////////////////////////////
463 // Mac specific stuff goes here...
465 ////////////////////////////////////////////////////////////////////////
467 class MenuTranslator : public QTranslator
470 MenuTranslator(QObject * parent)
471 : QTranslator(parent)
474 QString translate(const char * /*context*/,
475 const char * sourceText,
476 const char * /*comment*/ = 0)
478 string const s = sourceText;
479 if (s == N_("About %1") || s == N_("Preferences")
480 || s == N_("Reconfigure") || s == N_("Quit %1"))
487 class GlobalMenuBar : public QMenuBar
491 GlobalMenuBar() : QMenuBar(0) {}
494 bool event(QEvent * e)
496 if (e->type() == QEvent::ShortcutOverride) {
497 // && activeWindow() == 0) {
498 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
500 setKeySymbol(&sym, ke);
501 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
510 // QMacPasteboardMimeGraphics can only be compiled on Mac.
512 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
515 QMacPasteboardMimeGraphics()
516 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
519 QString convertorName() { return "Graphics"; }
521 QString flavorFor(QString const & mime)
523 LYXERR(Debug::ACTION, "flavorFor " << mime);
524 if (mime == pdfMimeType())
525 return QLatin1String("com.adobe.pdf");
529 QString mimeFor(QString flav)
531 LYXERR(Debug::ACTION, "mimeFor " << flav);
532 if (flav == QLatin1String("com.adobe.pdf"))
533 return pdfMimeType();
537 bool canConvert(QString const & mime, QString flav)
539 return mimeFor(flav) == mime;
542 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
546 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
550 QList<QByteArray> convertFromMime(QString const & /*mime*/,
551 QVariant data, QString /*flav*/)
553 QList<QByteArray> ret;
554 ret.append(data.toByteArray());
560 ///////////////////////////////////////////////////////////////
562 // You can find more platform specific stuff at the end of this file...
564 ///////////////////////////////////////////////////////////////
566 ////////////////////////////////////////////////////////////////////////
567 // Windows specific stuff goes here...
570 // QWindowsMimeMetafile can only be compiled on Windows.
572 static FORMATETC cfFromMime(QString const & mimetype)
575 if (mimetype == emfMimeType()) {
576 formatetc.cfFormat = CF_ENHMETAFILE;
577 formatetc.tymed = TYMED_ENHMF;
578 } else if (mimetype == wmfMimeType()) {
579 formatetc.cfFormat = CF_METAFILEPICT;
580 formatetc.tymed = TYMED_MFPICT;
583 formatetc.dwAspect = DVASPECT_CONTENT;
584 formatetc.lindex = -1;
589 class QWindowsMimeMetafile : public QWindowsMime {
591 QWindowsMimeMetafile() {}
593 bool canConvertFromMime(FORMATETC const & formatetc,
594 QMimeData const * mimedata) const
599 bool canConvertToMime(QString const & mimetype,
600 IDataObject * pDataObj) const
602 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
604 FORMATETC formatetc = cfFromMime(mimetype);
605 return pDataObj->QueryGetData(&formatetc) == S_OK;
608 bool convertFromMime(FORMATETC const & formatetc,
609 const QMimeData * mimedata, STGMEDIUM * pmedium) const
614 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
615 QVariant::Type preferredType) const
618 if (!canConvertToMime(mimetype, pDataObj))
621 FORMATETC formatetc = cfFromMime(mimetype);
623 if (pDataObj->GetData(&formatetc, &s) != S_OK)
627 if (s.tymed == TYMED_ENHMF) {
628 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
629 data.resize(dataSize);
630 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
631 (LPBYTE)data.data());
632 } else if (s.tymed == TYMED_MFPICT) {
633 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
634 data.resize(dataSize);
635 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
636 (LPBYTE)data.data());
639 ReleaseStgMedium(&s);
645 QVector<FORMATETC> formatsForMime(QString const & mimetype,
646 QMimeData const * mimedata) const
648 QVector<FORMATETC> formats;
649 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
650 formats += cfFromMime(mimetype);
654 QString mimeForFormat(FORMATETC const & formatetc) const
656 switch (formatetc.cfFormat) {
658 return emfMimeType();
659 case CF_METAFILEPICT:
660 return wmfMimeType();
668 ////////////////////////////////////////////////////////////////////////
669 // GuiApplication::Private definition and implementation.
670 ////////////////////////////////////////////////////////////////////////
672 struct GuiApplication::Private
674 Private(): language_model_(0), meta_fake_bit(NoModifier),
678 /// WMF Mime handler for Windows clipboard.
679 wmf_mime_ = new QWindowsMimeMetafile();
681 initKeySequences(&theTopLevelKeymap());
684 void initKeySequences(KeyMap * kb)
686 keyseq = KeySequence(kb, kb);
687 cancel_meta_seq = KeySequence(kb, kb);
691 QSortFilterProxyModel * language_model_;
693 GuiClipboard clipboard_;
695 GuiSelection selection_;
697 FontLoader font_loader_;
699 ColorCache color_cache_;
701 QTranslator qt_trans_;
703 QHash<int, SocketNotifier *> socket_notifiers_;
707 /// The global instance
710 /// this timer is used for any regular events one wants to
711 /// perform. at present it is used to check if forked processes
713 QTimer general_timer_;
715 /// delayed FuncRequests
716 std::queue<FuncRequest> func_request_queue_;
721 KeySequence cancel_meta_seq;
723 KeyModifier meta_fake_bit;
725 /// Multiple views container.
727 * Warning: This must not be a smart pointer as the destruction of the
728 * object is handled by Qt when the view is closed
729 * \sa Qt::WA_DeleteOnClose attribute.
731 QHash<int, GuiView *> views_;
733 /// Only used on mac.
734 GlobalMenuBar * global_menubar_;
737 /// Linkback mime handler for MacOSX.
738 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
742 /// WMF Mime handler for Windows clipboard.
743 QWindowsMimeMetafile * wmf_mime_;
748 GuiApplication * guiApp;
750 GuiApplication::~GuiApplication()
753 closeAllLinkBackLinks();
759 GuiApplication::GuiApplication(int & argc, char ** argv)
760 : QApplication(argc, argv), current_view_(0),
761 d(new GuiApplication::Private)
763 QString app_name = "LyX";
764 QCoreApplication::setOrganizationName(app_name);
765 QCoreApplication::setOrganizationDomain("lyx.org");
766 QCoreApplication::setApplicationName(lyx_package);
768 // Install translator for GUI elements.
769 installTranslator(&d->qt_trans_);
771 // FIXME: quitOnLastWindowClosed is true by default. We should have a
772 // lyxrc setting for this in order to let the application stay resident.
773 // But then we need some kind of dock icon, at least on Windows.
775 if (lyxrc.quit_on_last_window_closed)
776 setQuitOnLastWindowClosed(false);
779 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
780 // seems to be the default case for applications like LyX.
781 setQuitOnLastWindowClosed(false);
783 // This allows to translate the strings that appear in the LyX menu.
784 /// A translator suitable for the entries in the LyX menu.
785 /// Only needed with Qt/Mac.
786 installTranslator(new MenuTranslator(this));
790 // doubleClickInterval() is 400 ms on X11 which is just too long.
791 // On Windows and Mac OS X, the operating system's value is used.
792 // On Microsoft Windows, calling this function sets the double
793 // click interval for all applications. So we don't!
794 QApplication::setDoubleClickInterval(300);
797 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
799 // needs to be done before reading lyxrc
801 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
805 // Set the cache to 5120 kilobytes which corresponds to screen size of
806 // 1280 by 1024 pixels with a color depth of 32 bits.
807 QPixmapCache::setCacheLimit(5120);
809 // Initialize RC Fonts
810 if (lyxrc.roman_font_name.empty())
811 lyxrc.roman_font_name = fromqstr(romanFontName());
813 if (lyxrc.sans_font_name.empty())
814 lyxrc.sans_font_name = fromqstr(sansFontName());
816 if (lyxrc.typewriter_font_name.empty())
817 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
819 d->general_timer_.setInterval(500);
820 connect(&d->general_timer_, SIGNAL(timeout()),
821 this, SLOT(handleRegularEvents()));
822 d->general_timer_.start();
826 GuiApplication * theGuiApp()
828 return dynamic_cast<GuiApplication *>(theApp());
832 void GuiApplication::clearSession()
839 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
841 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
845 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
849 if (cmd.action == LFUN_NOACTION) {
850 flag.message(from_utf8(N_("Nothing to do")));
851 flag.setEnabled(false);
855 if (cmd.action == LFUN_UNKNOWN_ACTION) {
857 flag.setEnabled(false);
858 flag.message(from_utf8(N_("Unknown action")));
862 // I would really like to avoid having this switch and rather try to
863 // encode this in the function itself.
864 // -- And I'd rather let an inset decide which LFUNs it is willing
865 // to handle (Andre')
867 switch (cmd.action) {
869 // This could be used for the no-GUI version. The GUI version is handled in
870 // GuiView::getStatus(). See above.
872 case LFUN_BUFFER_WRITE:
873 case LFUN_BUFFER_WRITE_AS: {
874 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
875 enable = b && (b->isUnnamed() || !b->isClean());
880 case LFUN_BOOKMARK_GOTO: {
881 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
882 enable = theSession().bookmarks().isValid(num);
886 case LFUN_BOOKMARK_CLEAR:
887 enable = theSession().bookmarks().hasValid();
890 // this one is difficult to get right. As a half-baked
891 // solution, we consider only the first action of the sequence
892 case LFUN_COMMAND_SEQUENCE: {
893 // argument contains ';'-terminated commands
894 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
895 FuncRequest func(lyxaction.lookupFunc(firstcmd));
896 func.origin = cmd.origin;
897 flag = getStatus(func);
901 // we want to check if at least one of these is enabled
902 case LFUN_COMMAND_ALTERNATIVES: {
903 // argument contains ';'-terminated commands
904 string arg = to_utf8(cmd.argument());
905 while (!arg.empty()) {
907 arg = split(arg, first, ';');
908 FuncRequest func(lyxaction.lookupFunc(first));
909 func.origin = cmd.origin;
910 flag = getStatus(func);
911 // if this one is enabled, the whole thing is
920 string name = to_utf8(cmd.argument());
921 if (theTopLevelCmdDef().lock(name, func)) {
922 func.origin = cmd.origin;
923 flag = getStatus(func);
924 theTopLevelCmdDef().release(name);
926 // catch recursion or unknown command
927 // definition. all operations until the
928 // recursion or unknown command definition
929 // occurs are performed, so set the state to
936 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
938 case LFUN_PREFERENCES_SAVE:
939 case LFUN_BUFFER_SAVE_AS_DEFAULT:
940 case LFUN_DEBUG_LEVEL_SET:
941 // these are handled in our dispatch()
944 case LFUN_WINDOW_CLOSE:
945 enable = d->views_.size() > 0;
948 case LFUN_BUFFER_NEW:
949 case LFUN_BUFFER_NEW_TEMPLATE:
952 case LFUN_SCREEN_FONT_UPDATE:
954 case LFUN_WINDOW_NEW:
956 case LFUN_LYXRC_APPLY:
957 case LFUN_COMMAND_PREFIX:
959 case LFUN_META_PREFIX:
960 case LFUN_RECONFIGURE:
961 case LFUN_SERVER_GET_FILENAME:
962 case LFUN_SERVER_NOTIFY:
967 // Does the view know something?
968 if (!current_view_) {
973 if (current_view_->getStatus(cmd, flag))
976 // In LyX/Mac, when a dialog is open, the menus of the
977 // application can still be accessed without giving focus to
978 // the main window. In this case, we want to disable the menu
979 // entries that are buffer or view-related.
980 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
982 if (cmd.origin == FuncRequest::MENU && !current_view_->hasFocus()) {
988 BufferView * bv = current_view_->currentBufferView();
989 BufferView * doc_bv = current_view_->documentBufferView();
990 // If we do not have a BufferView, then other functions are disabled
995 // try the BufferView
996 bool decided = bv->getStatus(cmd, flag);
999 decided = bv->buffer().getStatus(cmd, flag);
1000 if (!decided && doc_bv)
1001 // try the Document Buffer
1002 decided = doc_bv->buffer().getStatus(cmd, flag);
1006 flag.setEnabled(false);
1008 // the default error message if we disable the command
1009 if (!flag.enabled() && flag.message().empty())
1010 flag.message(from_utf8(N_("Command disabled")));
1015 /// make a post-dispatch status message
1016 static docstring makeDispatchMessage(docstring const & msg,
1017 FuncRequest const & cmd)
1019 const bool verbose = (cmd.origin == FuncRequest::MENU
1020 || cmd.origin == FuncRequest::TOOLBAR
1021 || cmd.origin == FuncRequest::COMMANDBUFFER);
1023 if (cmd.action == LFUN_SELF_INSERT || !verbose) {
1024 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1028 docstring dispatch_msg = msg;
1029 if (!dispatch_msg.empty())
1030 dispatch_msg += ' ';
1032 docstring comname = from_utf8(lyxaction.getActionName(cmd.action));
1034 bool argsadded = false;
1036 if (!cmd.argument().empty()) {
1037 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1038 comname += ' ' + cmd.argument();
1042 docstring const shortcuts = theTopLevelKeymap().
1043 printBindings(cmd, KeySequence::ForGui);
1045 if (!shortcuts.empty())
1046 comname += ": " + shortcuts;
1047 else if (!argsadded && !cmd.argument().empty())
1048 comname += ' ' + cmd.argument();
1050 if (!comname.empty()) {
1051 comname = rtrim(comname);
1052 dispatch_msg += '(' + rtrim(comname) + ')';
1054 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1055 return dispatch_msg;
1059 void GuiApplication::dispatch(FuncRequest const & cmd)
1061 if (current_view_ && current_view_->currentBufferView())
1062 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1065 // redraw the screen at the end (first of the two drawing steps).
1066 //This is done unless explicitly requested otherwise
1067 dr.update(Update::FitCursor);
1073 BufferView * bv = current_view_->currentBufferView();
1075 // BufferView::update() updates the ViewMetricsInfo and
1076 // also initializes the position cache for all insets in
1077 // (at least partially) visible top-level paragraphs.
1078 // We will redraw the screen only if needed.
1079 bv->processUpdateFlags(dr.update());
1081 // Do we have a selection?
1082 theSelection().haveSelection(bv->cursor().selection());
1085 current_view_->restartCursor();
1087 // Some messages may already be translated, so we cannot use _()
1088 current_view_->message(makeDispatchMessage(
1089 translateIfPossible(dr.message()), cmd));
1093 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile, bool switchToBuffer)
1095 GuiView * lv = current_view_;
1097 if (!theSession().bookmarks().isValid(idx))
1099 BookmarksSection::Bookmark const & bm = theSession().bookmarks().bookmark(idx);
1100 LASSERT(!bm.filename.empty(), /**/);
1101 string const file = bm.filename.absFilename();
1102 // if the file is not opened, open it.
1103 if (!theBufferList().exists(bm.filename)) {
1105 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1109 // open may fail, so we need to test it again
1110 if (!theBufferList().exists(bm.filename))
1113 // bm can be changed when saving
1114 BookmarksSection::Bookmark tmp = bm;
1116 // Special case idx == 0 used for back-from-back jump navigation
1118 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1120 // if the current buffer is not that one, switch to it.
1121 if (!lv->documentBufferView()
1122 || lv->documentBufferView()->buffer().fileName() != tmp.filename) {
1123 if (!switchToBuffer)
1125 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1128 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1129 if (!lv->documentBufferView()->moveToPosition(
1130 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1137 // Cursor jump succeeded!
1138 Cursor const & cur = lv->documentBufferView()->cursor();
1139 pit_type new_pit = cur.pit();
1140 pos_type new_pos = cur.pos();
1141 int new_id = cur.paragraph().id();
1143 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1144 // see http://www.lyx.org/trac/ticket/3092
1145 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1146 || bm.top_id != new_id) {
1147 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1148 new_pit, new_pos, new_id);
1152 // This function runs "configure" and then rereads lyx.defaults to
1153 // reconfigure the automatic settings.
1154 static void reconfigure(GuiView * lv, string const & option)
1156 // emit message signal.
1158 lv->message(_("Running configure..."));
1160 // Run configure in user lyx directory
1161 PathChanger p(package().user_support());
1162 string configure_command = package().configure_command();
1163 configure_command += option;
1165 int ret = one.startscript(Systemcall::Wait, configure_command);
1167 // emit message signal.
1169 lv->message(_("Reloading configuration..."));
1170 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"));
1171 // Re-read packages.lst
1172 LaTeXFeatures::getAvailable();
1175 Alert::information(_("System reconfiguration failed"),
1176 _("The system reconfiguration has failed.\n"
1177 "Default textclass is used but LyX may "
1178 "not be able to work properly.\n"
1179 "Please reconfigure again if needed."));
1182 Alert::information(_("System reconfigured"),
1183 _("The system has been reconfigured.\n"
1184 "You need to restart LyX to make use of any\n"
1185 "updated document class specifications."));
1190 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1192 string const argument = to_utf8(cmd.argument());
1193 FuncCode const action = cmd.action;
1195 LYXERR(Debug::ACTION, "cmd: " << cmd);
1197 // we have not done anything wrong yet.
1200 FuncStatus const flag = getStatus(cmd);
1201 if (!flag.enabled()) {
1202 // We cannot use this function here
1203 LYXERR(Debug::ACTION, "action "
1204 << lyxaction.getActionName(action)
1205 << " [" << action << "] is disabled at this location");
1207 current_view_->restartCursor();
1208 dr.setMessage(flag.message());
1210 dr.dispatched(false);
1211 dr.update(Update::None);
1215 // Assumes that the action will be dispatched.
1216 dr.dispatched(true);
1218 switch (cmd.action) {
1220 case LFUN_WINDOW_NEW:
1221 createView(toqstr(cmd.argument()));
1224 case LFUN_WINDOW_CLOSE:
1225 // update bookmark pit of the current buffer before window close
1226 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1227 gotoBookmark(i+1, false, false);
1228 // clear the last opened list, because
1229 // maybe this will end the session
1230 theSession().lastOpened().clear();
1231 current_view_->close();
1235 // quitting is triggered by the gui code
1236 // (leaving the event loop).
1238 current_view_->message(from_utf8(N_("Exiting.")));
1239 if (closeAllViews())
1243 case LFUN_SCREEN_FONT_UPDATE: {
1244 // handle the screen font changes.
1245 d->font_loader_.update();
1246 // Backup current_view_
1247 GuiView * view = current_view_;
1248 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1249 // to skip the refresh.
1251 theBufferList().changed(false);
1252 // Restore current_view_
1253 current_view_ = view;
1257 case LFUN_BUFFER_NEW:
1258 if (d->views_.empty()
1259 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1260 createView(QString(), false); // keep hidden
1261 current_view_->newDocument(to_utf8(cmd.argument()), false);
1262 current_view_->show();
1263 setActiveWindow(current_view_);
1265 current_view_->newDocument(to_utf8(cmd.argument()), false);
1269 case LFUN_BUFFER_NEW_TEMPLATE:
1270 if (d->views_.empty()
1271 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1273 current_view_->newDocument(to_utf8(cmd.argument()), true);
1274 if (!current_view_->documentBufferView())
1275 current_view_->close();
1277 current_view_->newDocument(to_utf8(cmd.argument()), true);
1281 case LFUN_FILE_OPEN:
1282 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1283 if (d->views_.empty()
1284 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1285 string const fname = to_utf8(cmd.argument());
1286 // We want the ui session to be saved per document and not per
1287 // window number. The filename crc is a good enough identifier.
1288 boost::crc_32_type crc;
1289 crc = for_each(fname.begin(), fname.end(), crc);
1290 createView(crc.checksum());
1291 current_view_->openDocument(fname);
1292 if (current_view_ && !current_view_->documentBufferView())
1293 current_view_->close();
1295 current_view_->openDocument(to_utf8(cmd.argument()));
1298 case LFUN_HELP_OPEN: {
1299 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1300 if (current_view_ == 0)
1302 string const arg = to_utf8(cmd.argument());
1304 current_view_->message(_("Missing argument"));
1307 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1309 fname = i18nLibFileSearch("examples", arg, "lyx");
1311 if (fname.empty()) {
1312 lyxerr << "LyX: unable to find documentation file `"
1313 << arg << "'. Bad installation?" << endl;
1316 current_view_->message(bformat(_("Opening help file %1$s..."),
1317 makeDisplayPath(fname.absFilename())));
1318 Buffer * buf = current_view_->loadDocument(fname, false);
1320 current_view_->setBuffer(buf);
1321 #ifndef DEVEL_VERSION
1322 buf->setReadonly(true);
1324 buf->updateLabels();
1325 buf->errors("Parse");
1330 case LFUN_SET_COLOR: {
1332 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1333 if (lyx_name.empty() || x11_name.empty()) {
1334 current_view_->message(
1335 _("Syntax: set-color <lyx_name> <x11_name>"));
1339 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1340 bool const graphicsbg_changed =
1341 lyx_name == graphicsbg && x11_name != graphicsbg;
1342 if (graphicsbg_changed) {
1343 // FIXME: The graphics cache no longer has a changeDisplay method.
1345 graphics::GCache::get().changeDisplay(true);
1349 if (!lcolor.setColor(lyx_name, x11_name)) {
1350 current_view_->message(
1351 bformat(_("Set-color \"%1$s\" failed "
1352 "- color is undefined or "
1353 "may not be redefined"),
1354 from_utf8(lyx_name)));
1357 // Make sure we don't keep old colors in cache.
1358 d->color_cache_.clear();
1362 case LFUN_LYXRC_APPLY: {
1363 // reset active key sequences, since the bindings
1364 // are updated (bug 6064)
1366 LyXRC const lyxrc_orig = lyxrc;
1368 istringstream ss(to_utf8(cmd.argument()));
1369 bool const success = lyxrc.read(ss) == 0;
1372 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1373 << "Unable to read lyxrc data"
1378 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1385 case LFUN_COMMAND_PREFIX:
1386 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1391 d->meta_fake_bit = NoModifier;
1392 GuiView * gv = currentView();
1393 if (gv && gv->currentBufferView())
1394 // cancel any selection
1395 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1396 dr.setMessage(from_ascii(N_("Cancel")));
1399 case LFUN_META_PREFIX:
1400 d->meta_fake_bit = AltModifier;
1401 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1404 // --- Menus -----------------------------------------------
1405 case LFUN_RECONFIGURE:
1406 // argument is any additional parameter to the configure.py command
1407 reconfigure(currentView(), to_utf8(cmd.argument()));
1410 // --- lyxserver commands ----------------------------
1411 case LFUN_SERVER_GET_FILENAME: {
1412 GuiView * lv = currentView();
1413 LASSERT(lv && lv->documentBufferView(), return);
1414 docstring const fname = from_utf8(
1415 lv->documentBufferView()->buffer().absFileName());
1416 dr.setMessage(fname);
1417 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1420 case LFUN_SERVER_NOTIFY: {
1421 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1422 dr.setMessage(dispatch_buffer);
1423 theServer().notifyClient(to_utf8(dispatch_buffer));
1427 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1428 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1434 string rest = split(argument, countstr, ' ');
1435 istringstream is(countstr);
1438 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1439 for (int i = 0; i < count; ++i)
1440 dispatch(lyxaction.lookupFunc(rest));
1444 case LFUN_COMMAND_SEQUENCE: {
1445 // argument contains ';'-terminated commands
1446 string arg = argument;
1447 // FIXME: this LFUN should also work without any view.
1448 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1449 ? &(current_view_->documentBufferView()->buffer()) : 0;
1451 buffer->undo().beginUndoGroup();
1452 while (!arg.empty()) {
1454 arg = split(arg, first, ';');
1455 FuncRequest func(lyxaction.lookupFunc(first));
1456 func.origin = cmd.origin;
1459 // the buffer may have been closed by one action
1460 if (theBufferList().isLoaded(buffer))
1461 buffer->undo().endUndoGroup();
1465 case LFUN_COMMAND_ALTERNATIVES: {
1466 // argument contains ';'-terminated commands
1467 string arg = argument;
1468 while (!arg.empty()) {
1470 arg = split(arg, first, ';');
1471 FuncRequest func(lyxaction.lookupFunc(first));
1472 func.origin = cmd.origin;
1473 FuncStatus stat = getStatus(func);
1474 if (stat.enabled()) {
1484 if (theTopLevelCmdDef().lock(argument, func)) {
1485 func.origin = cmd.origin;
1487 theTopLevelCmdDef().release(argument);
1489 if (func.action == LFUN_UNKNOWN_ACTION) {
1490 // unknown command definition
1491 lyxerr << "Warning: unknown command definition `"
1495 // recursion detected
1496 lyxerr << "Warning: Recursion in the command definition `"
1497 << argument << "' detected"
1504 case LFUN_PREFERENCES_SAVE:
1505 lyxrc.write(support::makeAbsPath("preferences",
1506 package().user_support().absFilename()), false);
1509 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1510 string const fname = addName(addPath(package().user_support().absFilename(),
1511 "templates/"), "defaults.lyx");
1512 Buffer defaults(fname);
1514 istringstream ss(argument);
1517 int const unknown_tokens = defaults.readHeader(lex);
1519 if (unknown_tokens != 0) {
1520 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1521 << unknown_tokens << " unknown token"
1522 << (unknown_tokens == 1 ? "" : "s")
1526 if (defaults.writeFile(FileName(defaults.absFileName())))
1527 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1528 makeDisplayPath(fname)));
1531 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1536 case LFUN_BOOKMARK_GOTO:
1537 // go to bookmark, open unopened file and switch to buffer if necessary
1538 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1539 dr.update(Update::FitCursor);
1542 case LFUN_BOOKMARK_CLEAR:
1543 theSession().bookmarks().clear();
1546 case LFUN_DEBUG_LEVEL_SET:
1547 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1551 // Notify the caller that the action has not been dispatched.
1552 dr.dispatched(false);
1556 // The action has been dispatched in this method, nothing more to do.
1557 if (dr.dispatched())
1560 GuiView * lv = current_view_;
1562 // Everything below is only for active window
1566 // Let the current GuiView dispatch its own actions.
1567 lv->dispatch(cmd, dr);
1568 if (dr.dispatched() && lv )
1571 BufferView * bv = lv->currentBufferView();
1574 // Let the current BufferView dispatch its own actions.
1575 bv->dispatch(cmd, dr);
1576 if (dr.dispatched())
1579 BufferView * doc_bv = lv->documentBufferView();
1580 // Try with the document BufferView dispatch if any.
1582 doc_bv->dispatch(cmd, dr);
1583 if (dr.dispatched())
1587 // OK, so try the current Buffer itself...
1588 bv->buffer().dispatch(cmd, dr);
1589 if (dr.dispatched())
1592 // and with the document Buffer.
1594 doc_bv->buffer().dispatch(cmd, dr);
1595 if (dr.dispatched())
1599 // Let the current Cursor dispatch its own actions.
1600 Cursor old = bv->cursor();
1601 bv->cursor().dispatch(cmd);
1603 // notify insets we just left
1604 if (bv->cursor() != old) {
1606 bool badcursor = notifyCursorLeavesOrEnters(old, bv->cursor());
1608 bv->cursor().fixIfBroken();
1611 // update completion. We do it here and not in
1612 // processKeySym to avoid another redraw just for a
1613 // changed inline completion
1614 if (cmd.origin == FuncRequest::KEYBOARD) {
1615 if (cmd.action == LFUN_SELF_INSERT
1616 || (cmd.action == LFUN_ERT_INSERT && bv->cursor().inMathed()))
1617 lv->updateCompletion(bv->cursor(), true, true);
1618 else if (cmd.action == LFUN_CHAR_DELETE_BACKWARD)
1619 lv->updateCompletion(bv->cursor(), false, true);
1621 lv->updateCompletion(bv->cursor(), false, false);
1624 dr = bv->cursor().result();
1626 // if we executed a mutating lfun, mark the buffer as dirty
1627 Buffer * doc_buffer = (lv && lv->documentBufferView())
1628 ? &(lv->documentBufferView()->buffer()) : 0;
1629 if (doc_buffer && theBufferList().isLoaded(doc_buffer)
1631 && !lyxaction.funcHasFlag(action, LyXAction::NoBuffer)
1632 && !lyxaction.funcHasFlag(action, LyXAction::ReadOnly))
1633 lv->currentBufferView()->buffer().markDirty();
1637 docstring GuiApplication::viewStatusMessage()
1639 // When meta-fake key is pressed, show the key sequence so far + "M-".
1640 if (d->meta_fake_bit != NoModifier)
1641 return d->keyseq.print(KeySequence::ForGui) + "M-";
1643 // Else, when a non-complete key sequence is pressed,
1644 // show the available options.
1645 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1646 return d->keyseq.printOptions(true);
1652 void GuiApplication::handleKeyFunc(FuncCode action)
1656 if (d->keyseq.length())
1658 GuiView * gv = currentView();
1659 LASSERT(gv && gv->currentBufferView(), return);
1660 BufferView * bv = gv->currentBufferView();
1661 bv->getIntl().getTransManager().deadkey(
1662 c, get_accent(action).accent, bv->cursor().innerText(),
1664 // Need to clear, in case the minibuffer calls these
1667 // copied verbatim from do_accent_char
1668 bv->cursor().resetAnchor();
1669 bv->processUpdateFlags(Update::FitCursor);
1673 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1675 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1677 GuiView * lv = currentView();
1679 // Do nothing if we have nothing (JMarc)
1680 if (!keysym.isOK()) {
1681 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1682 lv->restartCursor();
1686 if (keysym.isModifier()) {
1687 LYXERR(Debug::KEY, "isModifier true");
1689 lv->restartCursor();
1693 char_type encoded_last_key = keysym.getUCSEncoded();
1695 // Do a one-deep top-level lookup for
1696 // cancel and meta-fake keys. RVDK_PATCH_5
1697 d->cancel_meta_seq.reset();
1699 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1700 LYXERR(Debug::KEY, "action first set to [" << func.action << ']');
1702 // When not cancel or meta-fake, do the normal lookup.
1703 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1704 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1705 if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_PREFIX)) {
1706 // remove Caps Lock and Mod2 as a modifiers
1707 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1708 LYXERR(Debug::KEY, "action now set to [" << func.action << ']');
1711 // Dont remove this unless you know what you are doing.
1712 d->meta_fake_bit = NoModifier;
1714 // Can this happen now ?
1715 if (func.action == LFUN_NOACTION)
1716 func = FuncRequest(LFUN_COMMAND_PREFIX);
1718 LYXERR(Debug::KEY, " Key [action=" << func.action << "]["
1719 << d->keyseq.print(KeySequence::Portable) << ']');
1721 // already here we know if it any point in going further
1722 // why not return already here if action == -1 and
1723 // num_bytes == 0? (Lgb)
1725 if (d->keyseq.length() > 1)
1726 lv->message(d->keyseq.print(KeySequence::ForGui));
1729 // Maybe user can only reach the key via holding down shift.
1730 // Let's see. But only if shift is the only modifier
1731 if (func.action == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1732 LYXERR(Debug::KEY, "Trying without shift");
1733 func = d->keyseq.addkey(keysym, NoModifier);
1734 LYXERR(Debug::KEY, "Action now " << func.action);
1737 if (func.action == LFUN_UNKNOWN_ACTION) {
1738 // Hmm, we didn't match any of the keysequences. See
1739 // if it's normal insertable text not already covered
1741 if (keysym.isText() && d->keyseq.length() == 1) {
1742 LYXERR(Debug::KEY, "isText() is true, inserting.");
1743 func = FuncRequest(LFUN_SELF_INSERT,
1744 FuncRequest::KEYBOARD);
1746 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1747 lv->message(_("Unknown function."));
1748 lv->restartCursor();
1753 if (func.action == LFUN_SELF_INSERT) {
1754 if (encoded_last_key != 0) {
1755 docstring const arg(1, encoded_last_key);
1756 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, arg,
1757 FuncRequest::KEYBOARD));
1758 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1761 lyx::dispatch(func);
1768 void GuiApplication::dispatchDelayed(FuncRequest const & func)
1770 d->func_request_queue_.push(func);
1771 QTimer::singleShot(0, this, SLOT(processFuncRequestQueue()));
1775 void GuiApplication::resetGui()
1777 // Set the language defined by the user.
1781 if (!readUIFile(toqstr(lyxrc.ui_file)))
1782 // Gives some error box here.
1785 if (d->global_menubar_)
1786 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1788 QHash<int, GuiView *>::iterator it;
1789 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1792 gv->setLayoutDirection(layoutDirection());
1796 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1800 void GuiApplication::createView(int view_id)
1802 createView(QString(), true, view_id);
1806 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1809 // release the keyboard which might have been grabed by the global
1810 // menubar on Mac to catch shortcuts even without any GuiView.
1811 if (d->global_menubar_)
1812 d->global_menubar_->releaseKeyboard();
1816 while (d->views_.find(id) != d->views_.end())
1819 LYXERR(Debug::GUI, "About to create new window with ID " << id);
1820 GuiView * view = new GuiView(id);
1822 d->views_[id] = view;
1826 setActiveWindow(view);
1829 if (!geometry_arg.isEmpty()) {
1833 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1834 re.indexIn(geometry_arg);
1835 w = re.cap(1).toInt();
1836 h = re.cap(2).toInt();
1837 x = re.cap(3).toInt();
1838 y = re.cap(4).toInt();
1839 view->setGeometry(x, y, w, h);
1846 Clipboard & GuiApplication::clipboard()
1848 return d->clipboard_;
1852 Selection & GuiApplication::selection()
1854 return d->selection_;
1858 FontLoader & GuiApplication::fontLoader()
1860 return d->font_loader_;
1864 Toolbars const & GuiApplication::toolbars() const
1866 return d->toolbars_;
1870 Toolbars & GuiApplication::toolbars()
1872 return d->toolbars_;
1876 Menus const & GuiApplication::menus() const
1882 Menus & GuiApplication::menus()
1888 QList<int> GuiApplication::viewIds() const
1890 return d->views_.keys();
1894 ColorCache & GuiApplication::colorCache()
1896 return d->color_cache_;
1900 int GuiApplication::exec()
1902 // asynchronously handle batch commands. This event will be in
1903 // the event queue in front of other asynchronous events. Hence,
1904 // we can assume in the latter that the gui is setup already.
1905 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1907 return QApplication::exec();
1911 void GuiApplication::exit(int status)
1913 QApplication::exit(status);
1917 void GuiApplication::setGuiLanguage()
1919 // Set the language defined by the user.
1922 QString const default_language = toqstr(Messages::defaultLanguage());
1923 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
1924 QLocale const default_locale(default_language);
1925 QLocale::setDefault(default_locale);
1927 // install translation file for Qt built-in dialogs
1928 QString const language_name = QString("qt_") + default_locale.name();
1930 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1931 // Short-named translator can be loaded from a long name, but not the
1932 // opposite. Therefore, long name should be used without truncation.
1933 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1934 if (!d->qt_trans_.load(language_name,
1935 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1936 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1939 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1943 switch (default_locale.language()) {
1944 case QLocale::Arabic :
1945 case QLocale::Hebrew :
1946 case QLocale::Persian :
1947 case QLocale::Urdu :
1948 setLayoutDirection(Qt::RightToLeft);
1951 setLayoutDirection(Qt::LeftToRight);
1956 void GuiApplication::processFuncRequestQueue()
1958 while (!d->func_request_queue_.empty()) {
1959 lyx::dispatch(d->func_request_queue_.back());
1960 d->func_request_queue_.pop();
1965 void GuiApplication::execBatchCommands()
1970 if (!readUIFile(toqstr(lyxrc.ui_file)))
1971 // Gives some error box here.
1975 // Create the global default menubar which is shown for the dialogs
1976 // and if no GuiView is visible.
1977 // This must be done after the session was recovered to know the "last files".
1978 d->global_menubar_ = new GlobalMenuBar();
1979 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1982 lyx::execBatchCommands();
1986 QAbstractItemModel * GuiApplication::languageModel()
1988 if (d->language_model_)
1989 return d->language_model_;
1991 QStandardItemModel * lang_model = new QStandardItemModel(this);
1992 lang_model->insertColumns(0, 3);
1994 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
1995 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
1996 Languages::const_iterator it = lyx::languages.begin();
1997 Languages::const_iterator end = lyx::languages.end();
1998 for (; it != end; ++it) {
1999 current_row = lang_model->rowCount();
2000 lang_model->insertRows(current_row, 1);
2001 QModelIndex pl_item = lang_model->index(current_row, 0);
2002 QModelIndex sp_item = lang_model->index(current_row, 1);
2003 QModelIndex th_item = lang_model->index(current_row, 2);
2004 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2005 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2006 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2007 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2008 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2009 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2010 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2011 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2012 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2013 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2015 d->language_model_ = new QSortFilterProxyModel(this);
2016 d->language_model_->setSourceModel(lang_model);
2017 #if QT_VERSION >= 0x040300
2018 d->language_model_->setSortLocaleAware(true);
2020 return d->language_model_;
2024 void GuiApplication::restoreGuiSession()
2026 if (!lyxrc.load_session)
2029 Session & session = theSession();
2030 LastOpenedSection::LastOpened const & lastopened =
2031 session.lastOpened().getfiles();
2033 FileName active_file;
2034 // do not add to the lastfile list since these files are restored from
2035 // last session, and should be already there (regular files), or should
2036 // not be added at all (help files).
2037 for (size_t i = 0; i < lastopened.size(); ++i) {
2038 FileName const & file_name = lastopened[i].file_name;
2039 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2040 && current_view_->documentBufferView() != 0)) {
2041 boost::crc_32_type crc;
2042 string const & fname = file_name.absFilename();
2043 crc = for_each(fname.begin(), fname.end(), crc);
2044 createView(crc.checksum());
2046 current_view_->loadDocument(file_name, false);
2048 if (lastopened[i].active)
2049 active_file = file_name;
2052 // Restore last active buffer
2053 Buffer * buffer = theBufferList().getBuffer(active_file);
2055 current_view_->setBuffer(buffer);
2057 // clear this list to save a few bytes of RAM
2058 session.lastOpened().clear();
2062 QString const GuiApplication::romanFontName()
2065 font.setKerning(false);
2066 font.setStyleHint(QFont::Serif);
2067 font.setFamily("serif");
2069 return QFontInfo(font).family();
2073 QString const GuiApplication::sansFontName()
2076 font.setKerning(false);
2077 font.setStyleHint(QFont::SansSerif);
2078 font.setFamily("sans");
2080 return QFontInfo(font).family();
2084 QString const GuiApplication::typewriterFontName()
2087 font.setKerning(false);
2088 font.setStyleHint(QFont::TypeWriter);
2089 font.setFamily("monospace");
2091 return QFontInfo(font).family();
2095 void GuiApplication::handleRegularEvents()
2097 ForkedCallsController::handleCompletedProcesses();
2101 bool GuiApplication::event(QEvent * e)
2104 case QEvent::FileOpen: {
2105 // Open a file; this happens only on Mac OS X for now.
2107 // We do this asynchronously because on startup the batch
2108 // commands are not executed here yet and the gui is not ready
2110 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2111 dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file())));
2116 return QApplication::event(e);
2121 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2124 return QApplication::notify(receiver, event);
2126 catch (ExceptionMessage const & e) {
2128 case ErrorException:
2130 setQuitOnLastWindowClosed(false);
2132 Alert::error(e.title_, e.details_);
2134 // Properly crash in debug mode in order to get a useful backtrace.
2137 // In release mode, try to exit gracefully.
2140 case BufferException: {
2141 if (!current_view_->documentBufferView())
2143 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2144 docstring details = e.details_ + '\n';
2145 details += buf->emergencyWrite();
2146 theBufferList().release(buf);
2147 details += "\n" + _("The current document was closed.");
2148 Alert::error(e.title_, details);
2151 case WarningException:
2152 Alert::warning(e.title_, e.details_);
2156 catch (exception const & e) {
2157 docstring s = _("LyX has caught an exception, it will now "
2158 "attempt to save all unsaved documents and exit."
2160 s += from_ascii(e.what());
2161 Alert::error(_("Software exception Detected"), s);
2165 docstring s = _("LyX has caught some really weird exception, it will "
2166 "now attempt to save all unsaved documents and exit.");
2167 Alert::error(_("Software exception Detected"), s);
2175 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2177 QColor const & qcol = d->color_cache_.get(col);
2178 if (!qcol.isValid()) {
2184 rgbcol.r = qcol.red();
2185 rgbcol.g = qcol.green();
2186 rgbcol.b = qcol.blue();
2191 string const GuiApplication::hexName(ColorCode col)
2193 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2197 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2199 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2200 d->socket_notifiers_[fd] = sn;
2201 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2205 void GuiApplication::socketDataReceived(int fd)
2207 d->socket_notifiers_[fd]->func_();
2211 void GuiApplication::unregisterSocketCallback(int fd)
2213 d->socket_notifiers_.take(fd)->setEnabled(false);
2217 void GuiApplication::commitData(QSessionManager & sm)
2219 /// The implementation is required to avoid an application exit
2220 /// when session state save is triggered by session manager.
2221 /// The default implementation sends a close event to all
2222 /// visible top level widgets when session managment allows
2224 /// We are changing that to close all wiew one by one.
2225 /// FIXME: verify if the default implementation is enough now.
2226 if (sm.allowsInteraction() && !closeAllViews())
2231 void GuiApplication::unregisterView(GuiView * gv)
2233 LASSERT(d->views_[gv->id()] == gv, /**/);
2234 d->views_.remove(gv->id());
2235 if (current_view_ == gv)
2240 bool GuiApplication::closeAllViews()
2242 if (d->views_.empty())
2245 // When a view/window was closed before without quitting LyX, there
2246 // are already entries in the lastOpened list.
2247 theSession().lastOpened().clear();
2249 QList<GuiView *> views = d->views_.values();
2250 foreach (GuiView * view, views) {
2260 GuiView & GuiApplication::view(int id) const
2262 LASSERT(d->views_.contains(id), /**/);
2263 return *d->views_.value(id);
2267 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2269 QList<GuiView *> views = d->views_.values();
2270 foreach (GuiView * view, views)
2271 view->hideDialog(name, inset);
2275 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2277 Buffer const * buffer_ = 0;
2278 QHash<int, GuiView *>::iterator end = d->views_.end();
2279 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2280 if (Buffer const * ptr = (*it)->updateInset(inset))
2287 bool GuiApplication::searchMenu(FuncRequest const & func,
2288 docstring_list & names) const
2290 return d->menus_.searchMenu(func, names);
2294 bool GuiApplication::readUIFile(QString const & name, bool include)
2296 LYXERR(Debug::INIT, "About to read " << name << "...");
2300 ui_path = libFileSearch("ui", name, "inc");
2301 if (ui_path.empty())
2302 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2304 ui_path = libFileSearch("ui", name, "ui");
2307 if (ui_path.empty()) {
2308 static const QString defaultUIFile = "default";
2309 LYXERR(Debug::INIT, "Could not find " << name);
2311 Alert::warning(_("Could not find UI definition file"),
2312 bformat(_("Error while reading the included file\n%1$s\n"
2313 "Please check your installation."), qstring_to_ucs4(name)));
2316 if (name == defaultUIFile) {
2317 LYXERR(Debug::INIT, "Could not find default UI file!!");
2318 Alert::warning(_("Could not find default UI file"),
2319 _("LyX could not find the default UI file!\n"
2320 "Please check your installation."));
2323 Alert::warning(_("Could not find UI definition file"),
2324 bformat(_("Error while reading the configuration file\n%1$s\n"
2325 "Falling back to default.\n"
2326 "Please look under Tools>Preferences>User Interface and\n"
2327 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2328 return readUIFile(defaultUIFile, false);
2331 // Ensure that a file is read only once (prevents include loops)
2332 static QStringList uifiles;
2333 QString const uifile = toqstr(ui_path.absFilename());
2334 if (uifiles.contains(uifile)) {
2336 // We are reading again the top uifile so reset the safeguard:
2339 d->toolbars_.reset();
2341 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2342 << "Is this an include loop?");
2346 uifiles.push_back(uifile);
2348 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2358 LexerKeyword uitags[] = {
2359 { "include", ui_include },
2360 { "menuset", ui_menuset },
2361 { "toolbars", ui_toolbars },
2362 { "toolbarset", ui_toolbarset }
2366 lex.setFile(ui_path);
2368 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2372 if (lyxerr.debugging(Debug::PARSER))
2373 lex.printTable(lyxerr);
2375 // store which ui files define Toolbars
2376 static QStringList toolbar_uifiles;
2378 while (lex.isOK()) {
2379 switch (lex.lex()) {
2382 QString const file = toqstr(lex.getString());
2383 if (!readUIFile(file, true))
2388 d->menus_.read(lex);
2392 d->toolbars_.readToolbars(lex);
2396 d->toolbars_.readToolbarSettings(lex);
2397 toolbar_uifiles.push_back(uifile);
2401 if (!rtrim(lex.getString()).empty())
2402 lex.printError("LyX::ReadUIFile: "
2403 "Unknown menu tag: `$$Token'");
2412 settings.beginGroup("ui_files");
2413 bool touched = false;
2414 for (int i = 0; i != uifiles.size(); ++i) {
2415 QFileInfo fi(uifiles[i]);
2416 QDateTime const date_value = fi.lastModified();
2417 QString const name_key = QString::number(i);
2418 // if an ui file which defines Toolbars has changed,
2419 // we have to reset the settings
2420 if (toolbar_uifiles.contains(uifiles[i])
2421 && (!settings.contains(name_key)
2422 || settings.value(name_key).toString() != uifiles[i]
2423 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2425 settings.setValue(name_key, uifiles[i]);
2426 settings.setValue(name_key + "/date", date_value);
2429 settings.endGroup();
2431 settings.remove("views");
2437 void GuiApplication::onLastWindowClosed()
2439 if (d->global_menubar_)
2440 d->global_menubar_->grabKeyboard();
2444 ////////////////////////////////////////////////////////////////////////
2446 // X11 specific stuff goes here...
2449 bool GuiApplication::x11EventFilter(XEvent * xev)
2454 switch (xev->type) {
2455 case SelectionRequest: {
2456 if (xev->xselectionrequest.selection != XA_PRIMARY)
2458 LYXERR(Debug::SELECTION, "X requested selection.");
2459 BufferView * bv = current_view_->currentBufferView();
2461 docstring const sel = bv->requestSelection();
2463 d->selection_.put(sel);
2467 case SelectionClear: {
2468 if (xev->xselectionclear.selection != XA_PRIMARY)
2470 LYXERR(Debug::SELECTION, "Lost selection.");
2471 BufferView * bv = current_view_->currentBufferView();
2473 bv->clearSelection();
2481 } // namespace frontend
2484 void hideDialogs(std::string const & name, Inset * inset)
2487 frontend::guiApp->hideDialogs(name, inset);
2491 ////////////////////////////////////////////////////////////////////
2495 ////////////////////////////////////////////////////////////////////
2497 frontend::FontLoader & theFontLoader()
2499 LASSERT(frontend::guiApp, /**/);
2500 return frontend::guiApp->fontLoader();
2504 frontend::FontMetrics const & theFontMetrics(Font const & f)
2506 return theFontMetrics(f.fontInfo());
2510 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2512 LASSERT(frontend::guiApp, /**/);
2513 return frontend::guiApp->fontLoader().metrics(f);
2517 ////////////////////////////////////////////////////////////////////
2521 ////////////////////////////////////////////////////////////////////
2523 frontend::Clipboard & theClipboard()
2525 LASSERT(frontend::guiApp, /**/);
2526 return frontend::guiApp->clipboard();
2530 frontend::Selection & theSelection()
2532 LASSERT(frontend::guiApp, /**/);
2533 return frontend::guiApp->selection();
2539 #include "moc_GuiApplication.cpp"