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>
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 Cursor & cursor = bv->cursor();
1107 Buffer & buf = bv->buffer();
1110 // This check out to be done somewhere else. It got moved here
1111 // from TextMetrics.cpp, where it definitely didn't need to be.
1112 // Actually, this test ought not to be done at all, since the
1113 // whole InsetBibitem business is a mess. But that is a different
1116 if (cursor.inTexted()) {
1117 moveCursor = cursor.paragraph().checkBiblio(buf);
1119 cursor.posForward();
1120 else if (moveCursor < 0 && cursor.pos() >= -moveCursor)
1121 cursor.posBackward();
1123 if (moveCursor != 0 || dr.needBufferUpdate()) {
1124 cursor.clearBufferUpdate();
1127 // BufferView::update() updates the ViewMetricsInfo and
1128 // also initializes the position cache for all insets in
1129 // (at least partially) visible top-level paragraphs.
1130 // We will redraw the screen only if needed.
1131 bv->processUpdateFlags(dr.screenUpdate());
1133 // Do we have a selection?
1134 theSelection().haveSelection(bv->cursor().selection());
1137 current_view_->restartCursor();
1139 if (dr.needMessageUpdate()) {
1140 // Some messages may already be translated, so we cannot use _()
1141 current_view_->message(makeDispatchMessage(
1142 translateIfPossible(dr.message()), cmd));
1147 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1148 bool switchToBuffer)
1150 if (!theSession().bookmarks().isValid(idx))
1152 BookmarksSection::Bookmark const & bm =
1153 theSession().bookmarks().bookmark(idx);
1154 LASSERT(!bm.filename.empty(), /**/);
1155 string const file = bm.filename.absFileName();
1156 // if the file is not opened, open it.
1157 if (!theBufferList().exists(bm.filename)) {
1159 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1163 // open may fail, so we need to test it again
1164 if (!theBufferList().exists(bm.filename))
1167 // bm can be changed when saving
1168 BookmarksSection::Bookmark tmp = bm;
1170 // Special case idx == 0 used for back-from-back jump navigation
1172 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1174 // if the current buffer is not that one, switch to it.
1175 BufferView * doc_bv = current_view_ ?
1176 current_view_->documentBufferView() : 0;
1177 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1178 if (switchToBuffer) {
1179 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1182 doc_bv = current_view_->documentBufferView();
1187 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1188 if (!doc_bv->moveToPosition(
1189 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1196 // Cursor jump succeeded!
1197 Cursor const & cur = doc_bv->cursor();
1198 pit_type new_pit = cur.pit();
1199 pos_type new_pos = cur.pos();
1200 int new_id = cur.paragraph().id();
1202 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1203 // see http://www.lyx.org/trac/ticket/3092
1204 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1205 || bm.top_id != new_id) {
1206 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1207 new_pit, new_pos, new_id);
1211 // This function runs "configure" and then rereads lyx.defaults to
1212 // reconfigure the automatic settings.
1213 void GuiApplication::reconfigure(string const & option)
1215 // emit message signal.
1217 current_view_->message(_("Running configure..."));
1219 // Run configure in user lyx directory
1220 PathChanger p(package().user_support());
1221 string configure_command = package().configure_command();
1222 configure_command += option;
1224 int ret = one.startscript(Systemcall::Wait, configure_command);
1226 // emit message signal.
1228 current_view_->message(_("Reloading configuration..."));
1229 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1230 // Re-read packages.lst
1231 LaTeXFeatures::getAvailable();
1234 Alert::information(_("System reconfiguration failed"),
1235 _("The system reconfiguration has failed.\n"
1236 "Default textclass is used but LyX may "
1237 "not be able to work properly.\n"
1238 "Please reconfigure again if needed."));
1240 Alert::information(_("System reconfigured"),
1241 _("The system has been reconfigured.\n"
1242 "You need to restart LyX to make use of any\n"
1243 "updated document class specifications."));
1246 void GuiApplication::validateCurrentView()
1248 if (!d->views_.empty() && !current_view_) {
1249 // currently at least one view exists but no view has the focus.
1250 // choose the last view to make it current.
1251 // a view without any open document is preferred.
1252 GuiView * candidate = 0;
1253 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1254 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1255 for (; it != end; ++it) {
1257 if (!candidate->documentBufferView())
1260 setCurrentView(candidate);
1264 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1266 string const argument = to_utf8(cmd.argument());
1267 FuncCode const action = cmd.action();
1269 LYXERR(Debug::ACTION, "cmd: " << cmd);
1271 // we have not done anything wrong yet.
1274 FuncStatus const flag = getStatus(cmd);
1275 if (!flag.enabled()) {
1276 // We cannot use this function here
1277 LYXERR(Debug::ACTION, "action "
1278 << lyxaction.getActionName(action)
1279 << " [" << action << "] is disabled at this location");
1280 dr.setMessage(flag.message());
1282 dr.dispatched(false);
1283 dr.screenUpdate(Update::None);
1284 dr.clearBufferUpdate();
1288 // Assumes that the action will be dispatched.
1289 dr.dispatched(true);
1291 switch (cmd.action()) {
1293 case LFUN_WINDOW_NEW:
1294 createView(toqstr(cmd.argument()));
1297 case LFUN_WINDOW_CLOSE:
1298 // update bookmark pit of the current buffer before window close
1299 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1300 gotoBookmark(i+1, false, false);
1301 // clear the last opened list, because
1302 // maybe this will end the session
1303 theSession().lastOpened().clear();
1304 // check for valid current_view_
1305 validateCurrentView();
1307 current_view_->closeScheduled();
1311 // quitting is triggered by the gui code
1312 // (leaving the event loop).
1314 current_view_->message(from_utf8(N_("Exiting.")));
1315 if (closeAllViews())
1319 case LFUN_SCREEN_FONT_UPDATE: {
1320 // handle the screen font changes.
1321 d->font_loader_.update();
1322 // Backup current_view_
1323 GuiView * view = current_view_;
1324 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1325 // to skip the refresh.
1327 theBufferList().changed(false);
1328 // Restore current_view_
1329 current_view_ = view;
1333 case LFUN_BUFFER_NEW:
1334 validateCurrentView();
1335 if (d->views_.empty()
1336 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1337 createView(QString(), false); // keep hidden
1338 current_view_->newDocument(to_utf8(cmd.argument()), false);
1339 current_view_->show();
1340 setActiveWindow(current_view_);
1342 current_view_->newDocument(to_utf8(cmd.argument()), false);
1346 case LFUN_BUFFER_NEW_TEMPLATE:
1347 validateCurrentView();
1348 if (d->views_.empty()
1349 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1351 current_view_->newDocument(to_utf8(cmd.argument()), true);
1352 if (!current_view_->documentBufferView())
1353 current_view_->close();
1355 current_view_->newDocument(to_utf8(cmd.argument()), true);
1359 case LFUN_FILE_OPEN: {
1360 validateCurrentView();
1361 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1362 string const fname = to_utf8(cmd.argument());
1363 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1364 && current_view_->documentBufferView() != 0)) {
1365 // We want the ui session to be saved per document and not per
1366 // window number. The filename crc is a good enough identifier.
1367 boost::crc_32_type crc;
1368 crc = for_each(fname.begin(), fname.end(), crc);
1369 createView(crc.checksum());
1370 current_view_->openDocument(fname);
1371 if (current_view_ && !current_view_->documentBufferView())
1372 current_view_->close();
1374 current_view_->openDocument(fname);
1378 case LFUN_HELP_OPEN: {
1379 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1380 if (current_view_ == 0)
1382 string const arg = to_utf8(cmd.argument());
1384 current_view_->message(_("Missing argument"));
1387 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1389 fname = i18nLibFileSearch("examples", arg, "lyx");
1391 if (fname.empty()) {
1392 lyxerr << "LyX: unable to find documentation file `"
1393 << arg << "'. Bad installation?" << endl;
1396 current_view_->message(bformat(_("Opening help file %1$s..."),
1397 makeDisplayPath(fname.absFileName())));
1398 Buffer * buf = current_view_->loadDocument(fname, false);
1400 #ifndef DEVEL_VERSION
1402 buf->setReadonly(true);
1409 case LFUN_SET_COLOR: {
1411 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1412 if (lyx_name.empty() || x11_name.empty()) {
1414 current_view_->message(
1415 _("Syntax: set-color <lyx_name> <x11_name>"));
1420 // FIXME: The graphics cache no longer has a changeDisplay method.
1421 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1422 bool const graphicsbg_changed =
1423 lyx_name == graphicsbg && x11_name != graphicsbg;
1424 if (graphicsbg_changed)
1425 graphics::GCache::get().changeDisplay(true);
1428 if (!lcolor.setColor(lyx_name, x11_name)) {
1430 current_view_->message(
1431 bformat(_("Set-color \"%1$s\" failed "
1432 "- color is undefined or "
1433 "may not be redefined"),
1434 from_utf8(lyx_name)));
1437 // Make sure we don't keep old colors in cache.
1438 d->color_cache_.clear();
1442 case LFUN_LYXRC_APPLY: {
1443 // reset active key sequences, since the bindings
1444 // are updated (bug 6064)
1446 LyXRC const lyxrc_orig = lyxrc;
1448 istringstream ss(to_utf8(cmd.argument()));
1449 bool const success = lyxrc.read(ss);
1452 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1453 << "Unable to read lyxrc data"
1458 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1465 case LFUN_COMMAND_PREFIX:
1466 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1471 d->meta_fake_bit = NoModifier;
1472 GuiView * gv = currentView();
1473 if (gv && gv->currentBufferView())
1474 // cancel any selection
1475 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1476 dr.setMessage(from_ascii(N_("Cancel")));
1479 case LFUN_META_PREFIX:
1480 d->meta_fake_bit = AltModifier;
1481 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1484 // --- Menus -----------------------------------------------
1485 case LFUN_RECONFIGURE:
1486 // argument is any additional parameter to the configure.py command
1487 reconfigure(to_utf8(cmd.argument()));
1490 // --- lyxserver commands ----------------------------
1491 case LFUN_SERVER_GET_FILENAME: {
1492 if (current_view_ && current_view_->documentBufferView()) {
1493 docstring const fname = from_utf8(
1494 current_view_->documentBufferView()->buffer().absFileName());
1495 dr.setMessage(fname);
1496 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1498 dr.setMessage(docstring());
1499 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1504 case LFUN_SERVER_NOTIFY: {
1505 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1506 dr.setMessage(dispatch_buffer);
1507 theServer().notifyClient(to_utf8(dispatch_buffer));
1511 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1512 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1518 string rest = split(argument, countstr, ' ');
1519 istringstream is(countstr);
1522 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1523 for (int i = 0; i < count; ++i)
1524 dispatch(lyxaction.lookupFunc(rest));
1528 case LFUN_COMMAND_SEQUENCE: {
1529 // argument contains ';'-terminated commands
1530 string arg = argument;
1531 // FIXME: this LFUN should also work without any view.
1532 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1533 ? &(current_view_->documentBufferView()->buffer()) : 0;
1535 buffer->undo().beginUndoGroup();
1536 while (!arg.empty()) {
1538 arg = split(arg, first, ';');
1539 FuncRequest func(lyxaction.lookupFunc(first));
1540 func.setOrigin(cmd.origin());
1543 // the buffer may have been closed by one action
1544 if (theBufferList().isLoaded(buffer))
1545 buffer->undo().endUndoGroup();
1549 case LFUN_COMMAND_ALTERNATIVES: {
1550 // argument contains ';'-terminated commands
1551 string arg = argument;
1552 while (!arg.empty()) {
1554 arg = split(arg, first, ';');
1555 FuncRequest func(lyxaction.lookupFunc(first));
1556 func.setOrigin(cmd.origin());
1557 FuncStatus const stat = getStatus(func);
1558 if (stat.enabled()) {
1568 if (theTopLevelCmdDef().lock(argument, func)) {
1569 func.setOrigin(cmd.origin());
1571 theTopLevelCmdDef().release(argument);
1573 if (func.action() == LFUN_UNKNOWN_ACTION) {
1574 // unknown command definition
1575 lyxerr << "Warning: unknown command definition `"
1579 // recursion detected
1580 lyxerr << "Warning: Recursion in the command definition `"
1581 << argument << "' detected"
1588 case LFUN_PREFERENCES_SAVE:
1589 lyxrc.write(support::makeAbsPath("preferences",
1590 package().user_support().absFileName()), false);
1593 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1594 string const fname = addName(addPath(package().user_support().absFileName(),
1595 "templates/"), "defaults.lyx");
1596 Buffer defaults(fname);
1598 istringstream ss(argument);
1601 int const unknown_tokens = defaults.readHeader(lex);
1603 if (unknown_tokens != 0) {
1604 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1605 << unknown_tokens << " unknown token"
1606 << (unknown_tokens == 1 ? "" : "s")
1610 if (defaults.writeFile(FileName(defaults.absFileName())))
1611 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1612 makeDisplayPath(fname)));
1615 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1620 case LFUN_BOOKMARK_GOTO:
1621 // go to bookmark, open unopened file and switch to buffer if necessary
1622 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1623 dr.screenUpdate(Update::Force | Update::FitCursor);
1626 case LFUN_BOOKMARK_CLEAR:
1627 theSession().bookmarks().clear();
1630 case LFUN_DEBUG_LEVEL_SET:
1631 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1635 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1638 current_view_->dispatch(cmd, dr);
1644 docstring GuiApplication::viewStatusMessage()
1646 // When meta-fake key is pressed, show the key sequence so far + "M-".
1647 if (d->meta_fake_bit != NoModifier)
1648 return d->keyseq.print(KeySequence::ForGui) + "M-";
1650 // Else, when a non-complete key sequence is pressed,
1651 // show the available options.
1652 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1653 return d->keyseq.printOptions(true);
1659 void GuiApplication::handleKeyFunc(FuncCode action)
1663 if (d->keyseq.length())
1665 GuiView * gv = currentView();
1666 LASSERT(gv && gv->currentBufferView(), return);
1667 BufferView * bv = gv->currentBufferView();
1668 bv->getIntl().getTransManager().deadkey(
1669 c, get_accent(action).accent, bv->cursor().innerText(),
1671 // Need to clear, in case the minibuffer calls these
1674 // copied verbatim from do_accent_char
1675 bv->cursor().resetAnchor();
1679 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1681 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1683 // Do nothing if we have nothing (JMarc)
1684 if (!keysym.isOK()) {
1685 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1687 current_view_->restartCursor();
1691 if (keysym.isModifier()) {
1693 current_view_->restartCursor();
1697 char_type encoded_last_key = keysym.getUCSEncoded();
1699 // Do a one-deep top-level lookup for
1700 // cancel and meta-fake keys. RVDK_PATCH_5
1701 d->cancel_meta_seq.reset();
1703 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1704 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1706 // When not cancel or meta-fake, do the normal lookup.
1707 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1708 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1709 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1710 // remove Caps Lock and Mod2 as a modifiers
1711 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1712 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1715 // Dont remove this unless you know what you are doing.
1716 d->meta_fake_bit = NoModifier;
1718 // Can this happen now ?
1719 if (func.action() == LFUN_NOACTION)
1720 func = FuncRequest(LFUN_COMMAND_PREFIX);
1722 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1723 << d->keyseq.print(KeySequence::Portable) << ']');
1725 // already here we know if it any point in going further
1726 // why not return already here if action == -1 and
1727 // num_bytes == 0? (Lgb)
1729 if (d->keyseq.length() > 1 && current_view_)
1730 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1733 // Maybe user can only reach the key via holding down shift.
1734 // Let's see. But only if shift is the only modifier
1735 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1736 LYXERR(Debug::KEY, "Trying without shift");
1737 func = d->keyseq.addkey(keysym, NoModifier);
1738 LYXERR(Debug::KEY, "Action now " << func.action());
1741 if (func.action() == LFUN_UNKNOWN_ACTION) {
1742 // Hmm, we didn't match any of the keysequences. See
1743 // if it's normal insertable text not already covered
1745 if (keysym.isText() && d->keyseq.length() == 1) {
1746 LYXERR(Debug::KEY, "isText() is true, inserting.");
1747 func = FuncRequest(LFUN_SELF_INSERT,
1748 FuncRequest::KEYBOARD);
1750 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1751 if (current_view_) {
1752 current_view_->message(_("Unknown function."));
1753 current_view_->restartCursor();
1759 if (func.action() == LFUN_SELF_INSERT) {
1760 if (encoded_last_key != 0) {
1761 docstring const arg(1, encoded_last_key);
1762 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
1763 FuncRequest::KEYBOARD));
1764 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1767 processFuncRequest(func);
1771 void GuiApplication::processFuncRequest(FuncRequest const & func)
1773 lyx::dispatch(func);
1777 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
1779 addToFuncRequestQueue(func);
1780 processFuncRequestQueueAsync();
1784 void GuiApplication::processFuncRequestQueue()
1786 while (!d->func_request_queue_.empty()) {
1787 processFuncRequest(d->func_request_queue_.front());
1788 d->func_request_queue_.pop();
1793 void GuiApplication::processFuncRequestQueueAsync()
1795 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
1799 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
1801 d->func_request_queue_.push(func);
1805 void GuiApplication::resetGui()
1807 // Set the language defined by the user.
1811 if (!readUIFile(toqstr(lyxrc.ui_file)))
1812 // Gives some error box here.
1815 if (d->global_menubar_)
1816 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1818 QHash<int, GuiView *>::iterator it;
1819 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1822 gv->setLayoutDirection(layoutDirection());
1826 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1830 void GuiApplication::createView(int view_id)
1832 createView(QString(), true, view_id);
1836 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1839 // release the keyboard which might have been grabed by the global
1840 // menubar on Mac to catch shortcuts even without any GuiView.
1841 if (d->global_menubar_)
1842 d->global_menubar_->releaseKeyboard();
1844 #if QT_VERSION < 0x040700
1845 // the option to disable kerning in rowpainter
1846 // is needed only with Qt4.7.0 or better
1847 lyxrc.force_paint_single_char = false;
1848 system_lyxrc.force_paint_single_char = false;
1853 while (d->views_.find(id) != d->views_.end())
1856 LYXERR(Debug::GUI, "About to create new window with ID " << id);
1857 GuiView * view = new GuiView(id);
1859 d->views_[id] = view;
1863 setActiveWindow(view);
1866 if (!geometry_arg.isEmpty()) {
1870 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1871 re.indexIn(geometry_arg);
1872 w = re.cap(1).toInt();
1873 h = re.cap(2).toInt();
1874 x = re.cap(3).toInt();
1875 y = re.cap(4).toInt();
1876 view->setGeometry(x, y, w, h);
1883 Clipboard & GuiApplication::clipboard()
1885 return d->clipboard_;
1889 Selection & GuiApplication::selection()
1891 return d->selection_;
1895 FontLoader & GuiApplication::fontLoader()
1897 return d->font_loader_;
1901 Toolbars const & GuiApplication::toolbars() const
1903 return d->toolbars_;
1907 Toolbars & GuiApplication::toolbars()
1909 return d->toolbars_;
1913 Menus const & GuiApplication::menus() const
1919 Menus & GuiApplication::menus()
1925 QList<int> GuiApplication::viewIds() const
1927 return d->views_.keys();
1931 ColorCache & GuiApplication::colorCache()
1933 return d->color_cache_;
1937 int GuiApplication::exec()
1939 // asynchronously handle batch commands. This event will be in
1940 // the event queue in front of other asynchronous events. Hence,
1941 // we can assume in the latter that the gui is setup already.
1942 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1944 return QApplication::exec();
1948 void GuiApplication::exit(int status)
1950 QApplication::exit(status);
1954 void GuiApplication::setGuiLanguage()
1956 // Set the language defined by the user.
1959 QString const default_language = toqstr(Messages::defaultLanguage());
1960 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
1961 QLocale const default_locale(default_language);
1962 QLocale::setDefault(default_locale);
1964 // install translation file for Qt built-in dialogs
1965 QString const language_name = QString("qt_") + default_locale.name();
1967 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1968 // Short-named translator can be loaded from a long name, but not the
1969 // opposite. Therefore, long name should be used without truncation.
1970 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1971 if (!d->qt_trans_.load(language_name,
1972 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1973 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1976 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1980 switch (default_locale.language()) {
1981 case QLocale::Arabic :
1982 case QLocale::Hebrew :
1983 case QLocale::Persian :
1984 case QLocale::Urdu :
1985 setLayoutDirection(Qt::RightToLeft);
1988 setLayoutDirection(Qt::LeftToRight);
1993 void GuiApplication::execBatchCommands()
1998 if (!readUIFile(toqstr(lyxrc.ui_file)))
1999 // Gives some error box here.
2003 #if QT_VERSION > 0x040600
2004 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2006 // Create the global default menubar which is shown for the dialogs
2007 // and if no GuiView is visible.
2008 // This must be done after the session was recovered to know the "last files".
2009 d->global_menubar_ = new GlobalMenuBar();
2010 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2013 lyx::execBatchCommands();
2017 QAbstractItemModel * GuiApplication::languageModel()
2019 if (d->language_model_)
2020 return d->language_model_;
2022 QStandardItemModel * lang_model = new QStandardItemModel(this);
2023 lang_model->insertColumns(0, 3);
2025 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2026 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2027 Languages::const_iterator it = lyx::languages.begin();
2028 Languages::const_iterator end = lyx::languages.end();
2029 for (; it != end; ++it) {
2030 current_row = lang_model->rowCount();
2031 lang_model->insertRows(current_row, 1);
2032 QModelIndex pl_item = lang_model->index(current_row, 0);
2033 QModelIndex sp_item = lang_model->index(current_row, 1);
2034 QModelIndex th_item = lang_model->index(current_row, 2);
2035 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2036 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2037 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2038 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2039 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2040 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2041 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2042 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2043 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2044 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2046 d->language_model_ = new QSortFilterProxyModel(this);
2047 d->language_model_->setSourceModel(lang_model);
2048 #if QT_VERSION >= 0x040300
2049 d->language_model_->setSortLocaleAware(true);
2051 return d->language_model_;
2055 void GuiApplication::restoreGuiSession()
2057 if (!lyxrc.load_session)
2060 Session & session = theSession();
2061 LastOpenedSection::LastOpened const & lastopened =
2062 session.lastOpened().getfiles();
2064 validateCurrentView();
2066 FileName active_file;
2067 // do not add to the lastfile list since these files are restored from
2068 // last session, and should be already there (regular files), or should
2069 // not be added at all (help files).
2070 for (size_t i = 0; i < lastopened.size(); ++i) {
2071 FileName const & file_name = lastopened[i].file_name;
2072 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2073 && current_view_->documentBufferView() != 0)) {
2074 boost::crc_32_type crc;
2075 string const & fname = file_name.absFileName();
2076 crc = for_each(fname.begin(), fname.end(), crc);
2077 createView(crc.checksum());
2079 current_view_->loadDocument(file_name, false);
2081 if (lastopened[i].active)
2082 active_file = file_name;
2085 // Restore last active buffer
2086 Buffer * buffer = theBufferList().getBuffer(active_file);
2087 if (buffer && current_view_)
2088 current_view_->setBuffer(buffer);
2090 // clear this list to save a few bytes of RAM
2091 session.lastOpened().clear();
2095 QString const GuiApplication::romanFontName()
2098 font.setKerning(false);
2099 font.setStyleHint(QFont::Serif);
2100 font.setFamily("serif");
2102 return QFontInfo(font).family();
2106 QString const GuiApplication::sansFontName()
2109 font.setKerning(false);
2110 font.setStyleHint(QFont::SansSerif);
2111 font.setFamily("sans");
2113 return QFontInfo(font).family();
2117 QString const GuiApplication::typewriterFontName()
2120 font.setKerning(false);
2121 font.setStyleHint(QFont::TypeWriter);
2122 font.setFamily("monospace");
2124 return QFontInfo(font).family();
2128 void GuiApplication::handleRegularEvents()
2130 ForkedCallsController::handleCompletedProcesses();
2134 bool GuiApplication::event(QEvent * e)
2137 case QEvent::FileOpen: {
2138 // Open a file; this happens only on Mac OS X for now.
2140 // We do this asynchronously because on startup the batch
2141 // commands are not executed here yet and the gui is not ready
2143 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2144 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2145 processFuncRequestAsync(fr);
2150 return QApplication::event(e);
2155 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2158 return QApplication::notify(receiver, event);
2160 catch (ExceptionMessage const & e) {
2162 case ErrorException:
2164 setQuitOnLastWindowClosed(false);
2166 Alert::error(e.title_, e.details_);
2168 // Properly crash in debug mode in order to get a useful backtrace.
2171 // In release mode, try to exit gracefully.
2174 case BufferException: {
2175 if (!current_view_ || !current_view_->documentBufferView())
2177 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2178 docstring details = e.details_ + '\n';
2179 details += buf->emergencyWrite();
2180 theBufferList().release(buf);
2181 details += "\n" + _("The current document was closed.");
2182 Alert::error(e.title_, details);
2185 case WarningException:
2186 Alert::warning(e.title_, e.details_);
2190 catch (exception const & e) {
2191 docstring s = _("LyX has caught an exception, it will now "
2192 "attempt to save all unsaved documents and exit."
2194 s += from_ascii(e.what());
2195 Alert::error(_("Software exception Detected"), s);
2199 docstring s = _("LyX has caught some really weird exception, it will "
2200 "now attempt to save all unsaved documents and exit.");
2201 Alert::error(_("Software exception Detected"), s);
2209 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2211 QColor const & qcol = d->color_cache_.get(col);
2212 if (!qcol.isValid()) {
2218 rgbcol.r = qcol.red();
2219 rgbcol.g = qcol.green();
2220 rgbcol.b = qcol.blue();
2225 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2227 QColor const qcol(lcolor.getX11Name(col).c_str());
2228 if (!qcol.isValid()) {
2234 rgbcol.r = qcol.red();
2235 rgbcol.g = qcol.green();
2236 rgbcol.b = qcol.blue();
2241 string const GuiApplication::hexName(ColorCode col)
2243 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2247 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2249 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2250 d->socket_notifiers_[fd] = sn;
2251 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2255 void GuiApplication::socketDataReceived(int fd)
2257 d->socket_notifiers_[fd]->func_();
2261 void GuiApplication::unregisterSocketCallback(int fd)
2263 d->socket_notifiers_.take(fd)->setEnabled(false);
2267 void GuiApplication::commitData(QSessionManager & sm)
2269 /// The implementation is required to avoid an application exit
2270 /// when session state save is triggered by session manager.
2271 /// The default implementation sends a close event to all
2272 /// visible top level widgets when session managment allows
2274 /// We are changing that to close all wiew one by one.
2275 /// FIXME: verify if the default implementation is enough now.
2276 #ifdef QT_NO_SESSIONMANAGER
2277 #warning Qt is compiled without session manager
2280 if (sm.allowsInteraction() && !closeAllViews())
2286 void GuiApplication::unregisterView(GuiView * gv)
2288 LASSERT(d->views_[gv->id()] == gv, /**/);
2289 d->views_.remove(gv->id());
2290 if (current_view_ == gv)
2295 bool GuiApplication::closeAllViews()
2297 if (d->views_.empty())
2300 // When a view/window was closed before without quitting LyX, there
2301 // are already entries in the lastOpened list.
2302 theSession().lastOpened().clear();
2304 QList<GuiView *> views = d->views_.values();
2305 foreach (GuiView * view, views) {
2306 if (!view->closeScheduled())
2315 GuiView & GuiApplication::view(int id) const
2317 LASSERT(d->views_.contains(id), /**/);
2318 return *d->views_.value(id);
2322 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2324 QList<GuiView *> views = d->views_.values();
2325 foreach (GuiView * view, views)
2326 view->hideDialog(name, inset);
2330 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2332 Buffer const * buffer_ = 0;
2333 QHash<int, GuiView *>::iterator end = d->views_.end();
2334 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2335 if (Buffer const * ptr = (*it)->updateInset(inset))
2342 bool GuiApplication::searchMenu(FuncRequest const & func,
2343 docstring_list & names) const
2345 return d->menus_.searchMenu(func, names);
2349 // Ensure that a file is read only once (prevents include loops)
2350 static QStringList uifiles;
2351 // store which ui files define Toolbars
2352 static QStringList toolbar_uifiles;
2355 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2366 LexerKeyword uitags[] = {
2367 { "format", ui_format },
2368 { "include", ui_include },
2369 { "menuset", ui_menuset },
2370 { "toolbars", ui_toolbars },
2371 { "toolbarset", ui_toolbarset }
2375 lex.setFile(ui_path);
2377 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2381 if (lyxerr.debugging(Debug::PARSER))
2382 lex.printTable(lyxerr);
2385 // format before introduction of format tag
2386 unsigned int format = 0;
2387 while (lex.isOK()) {
2388 int const status = lex.lex();
2390 // we have to do this check here, outside the switch,
2391 // because otherwise we would start reading include files,
2392 // e.g., if the first tag we hit was an include tag.
2393 if (status == ui_format)
2395 format = lex.getInteger();
2399 // this will trigger unless the first tag we hit is a format
2400 // tag, with the right format.
2401 if (format != LFUN_FORMAT)
2402 return FormatMismatch;
2405 case Lexer::LEX_FEOF:
2410 QString const file = toqstr(lex.getString());
2411 bool const success = readUIFile(file, true);
2413 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2420 d->menus_.read(lex);
2424 d->toolbars_.readToolbars(lex);
2428 d->toolbars_.readToolbarSettings(lex);
2429 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2433 if (!rtrim(lex.getString()).empty())
2434 lex.printError("LyX::ReadUIFile: "
2435 "Unknown menu tag: `$$Token'");
2437 LYXERR0("Error with status: " << status);
2443 return (error ? ReadError : ReadOK);
2447 bool GuiApplication::readUIFile(QString const & name, bool include)
2449 LYXERR(Debug::INIT, "About to read " << name << "...");
2453 ui_path = libFileSearch("ui", name, "inc");
2454 if (ui_path.empty())
2455 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2457 ui_path = libFileSearch("ui", name, "ui");
2460 if (ui_path.empty()) {
2461 static const QString defaultUIFile = "default";
2462 LYXERR(Debug::INIT, "Could not find " << name);
2464 Alert::warning(_("Could not find UI definition file"),
2465 bformat(_("Error while reading the included file\n%1$s\n"
2466 "Please check your installation."), qstring_to_ucs4(name)));
2469 if (name == defaultUIFile) {
2470 LYXERR(Debug::INIT, "Could not find default UI file!!");
2471 Alert::warning(_("Could not find default UI file"),
2472 _("LyX could not find the default UI file!\n"
2473 "Please check your installation."));
2476 Alert::warning(_("Could not find UI definition file"),
2477 bformat(_("Error while reading the configuration file\n%1$s\n"
2478 "Falling back to default.\n"
2479 "Please look under Tools>Preferences>User Interface and\n"
2480 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2481 return readUIFile(defaultUIFile, false);
2484 QString const uifile = toqstr(ui_path.absFileName());
2485 if (uifiles.contains(uifile)) {
2487 // We are reading again the top uifile so reset the safeguard:
2490 d->toolbars_.reset();
2492 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2493 << "Is this an include loop?");
2497 uifiles.push_back(uifile);
2499 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2501 ReturnValues retval = readUIFile(ui_path);
2503 if (retval == FormatMismatch) {
2504 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2505 FileName const tempfile = FileName::tempName("convert_ui");
2506 bool const success = prefs2prefs(ui_path, tempfile, true);
2508 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2509 " to format " << LFUN_FORMAT << ".");
2511 retval = readUIFile(tempfile);
2512 tempfile.removeFile();
2516 if (retval != ReadOK) {
2517 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2525 settings.beginGroup("ui_files");
2526 bool touched = false;
2527 for (int i = 0; i != uifiles.size(); ++i) {
2528 QFileInfo fi(uifiles[i]);
2529 QDateTime const date_value = fi.lastModified();
2530 QString const name_key = QString::number(i);
2531 // if an ui file which defines Toolbars has changed,
2532 // we have to reset the settings
2533 if (toolbar_uifiles.contains(uifiles[i])
2534 && (!settings.contains(name_key)
2535 || settings.value(name_key).toString() != uifiles[i]
2536 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2538 settings.setValue(name_key, uifiles[i]);
2539 settings.setValue(name_key + "/date", date_value);
2542 settings.endGroup();
2544 settings.remove("views");
2550 void GuiApplication::onLastWindowClosed()
2552 if (d->global_menubar_)
2553 d->global_menubar_->grabKeyboard();
2557 ////////////////////////////////////////////////////////////////////////
2559 // X11 specific stuff goes here...
2562 bool GuiApplication::x11EventFilter(XEvent * xev)
2567 switch (xev->type) {
2568 case SelectionRequest: {
2569 if (xev->xselectionrequest.selection != XA_PRIMARY)
2571 LYXERR(Debug::SELECTION, "X requested selection.");
2572 BufferView * bv = current_view_->currentBufferView();
2574 docstring const sel = bv->requestSelection();
2576 d->selection_.put(sel);
2580 case SelectionClear: {
2581 if (xev->xselectionclear.selection != XA_PRIMARY)
2583 LYXERR(Debug::SELECTION, "Lost selection.");
2584 BufferView * bv = current_view_->currentBufferView();
2586 bv->clearSelection();
2594 } // namespace frontend
2597 void hideDialogs(std::string const & name, Inset * inset)
2600 frontend::guiApp->hideDialogs(name, inset);
2604 ////////////////////////////////////////////////////////////////////
2608 ////////////////////////////////////////////////////////////////////
2610 frontend::FontLoader & theFontLoader()
2612 LASSERT(frontend::guiApp, /**/);
2613 return frontend::guiApp->fontLoader();
2617 frontend::FontMetrics const & theFontMetrics(Font const & f)
2619 return theFontMetrics(f.fontInfo());
2623 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2625 LASSERT(frontend::guiApp, /**/);
2626 return frontend::guiApp->fontLoader().metrics(f);
2630 ////////////////////////////////////////////////////////////////////
2634 ////////////////////////////////////////////////////////////////////
2636 frontend::Clipboard & theClipboard()
2638 LASSERT(frontend::guiApp, /**/);
2639 return frontend::guiApp->clipboard();
2643 frontend::Selection & theSelection()
2645 LASSERT(frontend::guiApp, /**/);
2646 return frontend::guiApp->selection();
2652 #include "moc_GuiApplication.cpp"