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 FileName fname = libFileSearch("images/" + path, name1, "png");
372 return toqstr(fname.absFileName());
374 fname = libFileSearch("images/" + path, name2, "png");
376 return toqstr(fname.absFileName());
378 path = ":/images/" + path;
381 LYXERR0("Directory " << path << " not found in resource!");
385 if (res.exists(name1))
389 if (res.exists(name2))
392 LYXERR(Debug::GUI, "Cannot find icon with filename "
393 << "\"" << name1 << "\""
395 << "\"" << name2 << "\""
397 << lyxaction.getActionName(f.action())
398 << '(' << to_utf8(f.argument()) << ")\"");
401 fname = libFileSearch(QString("images/"), "unknown", "png");
403 return toqstr(fname.absFileName());
404 return QString(":/images/unknown.png");
410 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
413 FileName fname = libFileSearch(path, name, ext);
414 QString path1 = toqstr(fname.absFileName());
415 QString path2 = ":/" + path + name + "." + ext;
417 if (pixmap.load(path1)) {
420 else if (pixmap.load(path2)) {
424 LYXERR0("Cannot load pixmap \""
425 << path << name << '.' << ext
426 << "\", please verify resource system!");
431 QIcon getIcon(FuncRequest const & f, bool unknown)
433 QString icon = iconName(f, unknown);
437 //LYXERR(Debug::GUI, "Found icon: " << icon);
439 if (!pm.load(icon)) {
440 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
448 ////////////////////////////////////////////////////////////////////////
450 // LyX server support code.
452 ////////////////////////////////////////////////////////////////////////
454 class SocketNotifier : public QSocketNotifier
457 /// connect a connection notification from the LyXServerSocket
458 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
459 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
463 /// The callback function
464 Application::SocketCallback func_;
468 ////////////////////////////////////////////////////////////////////////
470 // Mac specific stuff goes here...
472 ////////////////////////////////////////////////////////////////////////
474 class MenuTranslator : public QTranslator
477 MenuTranslator(QObject * parent)
478 : QTranslator(parent)
481 QString translate(const char * /*context*/,
482 const char * sourceText,
483 const char * /*comment*/ = 0)
485 string const s = sourceText;
486 if (s == N_("About %1") || s == N_("Preferences")
487 || s == N_("Reconfigure") || s == N_("Quit %1"))
494 class GlobalMenuBar : public QMenuBar
498 GlobalMenuBar() : QMenuBar(0) {}
501 bool event(QEvent * e)
503 if (e->type() == QEvent::ShortcutOverride) {
504 // && activeWindow() == 0) {
505 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
507 setKeySymbol(&sym, ke);
508 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
517 // QMacPasteboardMimeGraphics can only be compiled on Mac.
519 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
522 QMacPasteboardMimeGraphics()
523 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
526 QString convertorName() { return "Graphics"; }
528 QString flavorFor(QString const & mime)
530 LYXERR(Debug::ACTION, "flavorFor " << mime);
531 if (mime == pdfMimeType())
532 return QLatin1String("com.adobe.pdf");
536 QString mimeFor(QString flav)
538 LYXERR(Debug::ACTION, "mimeFor " << flav);
539 if (flav == QLatin1String("com.adobe.pdf"))
540 return pdfMimeType();
544 bool canConvert(QString const & mime, QString flav)
546 return mimeFor(flav) == mime;
549 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
553 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
557 QList<QByteArray> convertFromMime(QString const & /*mime*/,
558 QVariant data, QString /*flav*/)
560 QList<QByteArray> ret;
561 ret.append(data.toByteArray());
567 ///////////////////////////////////////////////////////////////
569 // You can find more platform specific stuff at the end of this file...
571 ///////////////////////////////////////////////////////////////
573 ////////////////////////////////////////////////////////////////////////
574 // Windows specific stuff goes here...
577 // QWindowsMimeMetafile can only be compiled on Windows.
579 static FORMATETC cfFromMime(QString const & mimetype)
582 if (mimetype == emfMimeType()) {
583 formatetc.cfFormat = CF_ENHMETAFILE;
584 formatetc.tymed = TYMED_ENHMF;
585 } else if (mimetype == wmfMimeType()) {
586 formatetc.cfFormat = CF_METAFILEPICT;
587 formatetc.tymed = TYMED_MFPICT;
590 formatetc.dwAspect = DVASPECT_CONTENT;
591 formatetc.lindex = -1;
596 class QWindowsMimeMetafile : public QWindowsMime {
598 QWindowsMimeMetafile() {}
600 bool canConvertFromMime(FORMATETC const & formatetc,
601 QMimeData const * mimedata) const
606 bool canConvertToMime(QString const & mimetype,
607 IDataObject * pDataObj) const
609 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
611 FORMATETC formatetc = cfFromMime(mimetype);
612 return pDataObj->QueryGetData(&formatetc) == S_OK;
615 bool convertFromMime(FORMATETC const & formatetc,
616 const QMimeData * mimedata, STGMEDIUM * pmedium) const
621 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
622 QVariant::Type preferredType) const
625 if (!canConvertToMime(mimetype, pDataObj))
628 FORMATETC formatetc = cfFromMime(mimetype);
630 if (pDataObj->GetData(&formatetc, &s) != S_OK)
634 if (s.tymed == TYMED_ENHMF) {
635 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
636 data.resize(dataSize);
637 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
638 (LPBYTE)data.data());
639 } else if (s.tymed == TYMED_MFPICT) {
640 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
641 data.resize(dataSize);
642 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
643 (LPBYTE)data.data());
646 ReleaseStgMedium(&s);
652 QVector<FORMATETC> formatsForMime(QString const & mimetype,
653 QMimeData const * mimedata) const
655 QVector<FORMATETC> formats;
656 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
657 formats += cfFromMime(mimetype);
661 QString mimeForFormat(FORMATETC const & formatetc) const
663 switch (formatetc.cfFormat) {
665 return emfMimeType();
666 case CF_METAFILEPICT:
667 return wmfMimeType();
675 ////////////////////////////////////////////////////////////////////////
676 // GuiApplication::Private definition and implementation.
677 ////////////////////////////////////////////////////////////////////////
679 struct GuiApplication::Private
681 Private(): language_model_(0), meta_fake_bit(NoModifier),
685 /// WMF Mime handler for Windows clipboard.
686 wmf_mime_ = new QWindowsMimeMetafile();
688 initKeySequences(&theTopLevelKeymap());
691 void initKeySequences(KeyMap * kb)
693 keyseq = KeySequence(kb, kb);
694 cancel_meta_seq = KeySequence(kb, kb);
698 QSortFilterProxyModel * language_model_;
700 GuiClipboard clipboard_;
702 GuiSelection selection_;
704 FontLoader font_loader_;
706 ColorCache color_cache_;
708 QTranslator qt_trans_;
710 QHash<int, SocketNotifier *> socket_notifiers_;
714 /// The global instance
717 /// this timer is used for any regular events one wants to
718 /// perform. at present it is used to check if forked processes
720 QTimer general_timer_;
722 /// delayed FuncRequests
723 std::queue<FuncRequest> func_request_queue_;
728 KeySequence cancel_meta_seq;
730 KeyModifier meta_fake_bit;
732 /// Multiple views container.
734 * Warning: This must not be a smart pointer as the destruction of the
735 * object is handled by Qt when the view is closed
736 * \sa Qt::WA_DeleteOnClose attribute.
738 QHash<int, GuiView *> views_;
740 /// Only used on mac.
741 GlobalMenuBar * global_menubar_;
744 /// Linkback mime handler for MacOSX.
745 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
749 /// WMF Mime handler for Windows clipboard.
750 QWindowsMimeMetafile * wmf_mime_;
755 GuiApplication * guiApp;
757 GuiApplication::~GuiApplication()
760 closeAllLinkBackLinks();
766 GuiApplication::GuiApplication(int & argc, char ** argv)
767 : QApplication(argc, argv), current_view_(0),
768 d(new GuiApplication::Private)
770 QString app_name = "LyX";
771 QCoreApplication::setOrganizationName(app_name);
772 QCoreApplication::setOrganizationDomain("lyx.org");
773 QCoreApplication::setApplicationName(lyx_package);
775 // Install translator for GUI elements.
776 installTranslator(&d->qt_trans_);
778 // FIXME: quitOnLastWindowClosed is true by default. We should have a
779 // lyxrc setting for this in order to let the application stay resident.
780 // But then we need some kind of dock icon, at least on Windows.
782 if (lyxrc.quit_on_last_window_closed)
783 setQuitOnLastWindowClosed(false);
786 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
787 // seems to be the default case for applications like LyX.
788 setQuitOnLastWindowClosed(false);
789 // This allows to translate the strings that appear in the LyX menu.
790 /// A translator suitable for the entries in the LyX menu.
791 /// Only needed with Qt/Mac.
792 installTranslator(new MenuTranslator(this));
796 // doubleClickInterval() is 400 ms on X11 which is just too long.
797 // On Windows and Mac OS X, the operating system's value is used.
798 // On Microsoft Windows, calling this function sets the double
799 // click interval for all applications. So we don't!
800 QApplication::setDoubleClickInterval(300);
803 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
805 // needs to be done before reading lyxrc
807 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
811 // Set the cache to 5120 kilobytes which corresponds to screen size of
812 // 1280 by 1024 pixels with a color depth of 32 bits.
813 QPixmapCache::setCacheLimit(5120);
815 // Initialize RC Fonts
816 if (lyxrc.roman_font_name.empty())
817 lyxrc.roman_font_name = fromqstr(romanFontName());
819 if (lyxrc.sans_font_name.empty())
820 lyxrc.sans_font_name = fromqstr(sansFontName());
822 if (lyxrc.typewriter_font_name.empty())
823 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
825 d->general_timer_.setInterval(500);
826 connect(&d->general_timer_, SIGNAL(timeout()),
827 this, SLOT(handleRegularEvents()));
828 d->general_timer_.start();
830 #if QT_VERSION >= 0x040400
831 // maxThreadCount() defaults in general to 2 on single or dual-processor.
832 // This is clearly not enough in a time where we use threads for
833 // document preview and/or export. 20 should be OK.
834 QThreadPool::globalInstance()->setMaxThreadCount(20);
839 GuiApplication * theGuiApp()
841 return dynamic_cast<GuiApplication *>(theApp());
845 void GuiApplication::clearSession()
852 docstring Application::iconName(FuncRequest const & f, bool unknown)
854 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
858 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
863 BufferView * doc_bv = 0;
865 if (cmd.action() == LFUN_NOACTION) {
866 status.message(from_utf8(N_("Nothing to do")));
867 status.setEnabled(false);
870 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
871 status.setUnknown(true);
872 status.message(from_utf8(N_("Unknown action")));
873 status.setEnabled(false);
876 // Does the GuiApplication know something?
877 else if (getStatus(cmd, status)) { }
879 // If we do not have a GuiView, then other functions are disabled
880 else if (!current_view_)
881 status.setEnabled(false);
883 // Does the GuiView know something?
884 else if (current_view_->getStatus(cmd, status)) { }
886 // In LyX/Mac, when a dialog is open, the menus of the
887 // application can still be accessed without giving focus to
888 // the main window. In this case, we want to disable the menu
889 // entries that are buffer or view-related.
890 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
892 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
893 status.setEnabled(false);
896 // If we do not have a BufferView, then other functions are disabled
897 else if (!(bv = current_view_->currentBufferView()))
898 status.setEnabled(false);
900 // Does the current BufferView know something?
901 else if (bv->getStatus(cmd, status)) { }
903 // Does the current Buffer know something?
904 else if (bv->buffer().getStatus(cmd, status)) { }
906 // If we do not have a document BufferView, different from the
907 // current BufferView, then other functions are disabled
908 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
909 status.setEnabled(false);
911 // Does the document Buffer know something?
912 else if (doc_bv->buffer().getStatus(cmd, status)) { }
915 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
916 status.message(from_utf8(N_("Command not handled")));
917 status.setEnabled(false);
920 // the default error message if we disable the command
921 if (!status.enabled() && status.message().empty())
922 status.message(from_utf8(N_("Command disabled")));
928 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
930 // I would really like to avoid having this switch and rather try to
931 // encode this in the function itself.
932 // -- And I'd rather let an inset decide which LFUNs it is willing
933 // to handle (Andre')
935 switch (cmd.action()) {
937 // This could be used for the no-GUI version. The GUI version is handled in
938 // GuiView::getStatus(). See above.
940 case LFUN_BUFFER_WRITE:
941 case LFUN_BUFFER_WRITE_AS: {
942 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
943 enable = b && (b->isUnnamed() || !b->isClean());
948 case LFUN_BOOKMARK_GOTO: {
949 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
950 enable = theSession().bookmarks().isValid(num);
954 case LFUN_BOOKMARK_CLEAR:
955 enable = theSession().bookmarks().hasValid();
958 // this one is difficult to get right. As a half-baked
959 // solution, we consider only the first action of the sequence
960 case LFUN_COMMAND_SEQUENCE: {
961 // argument contains ';'-terminated commands
962 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
963 FuncRequest func(lyxaction.lookupFunc(firstcmd));
964 func.setOrigin(cmd.origin());
965 flag = getStatus(func);
969 // we want to check if at least one of these is enabled
970 case LFUN_COMMAND_ALTERNATIVES: {
971 // argument contains ';'-terminated commands
972 string arg = to_utf8(cmd.argument());
973 while (!arg.empty()) {
975 arg = split(arg, first, ';');
976 FuncRequest func(lyxaction.lookupFunc(first));
977 func.setOrigin(cmd.origin());
978 flag = getStatus(func);
979 // if this one is enabled, the whole thing is
988 string name = to_utf8(cmd.argument());
989 if (theTopLevelCmdDef().lock(name, func)) {
990 func.setOrigin(cmd.origin());
991 flag = getStatus(func);
992 theTopLevelCmdDef().release(name);
994 // catch recursion or unknown command
995 // definition. all operations until the
996 // recursion or unknown command definition
997 // occurs are performed, so set the state to
1004 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1006 case LFUN_PREFERENCES_SAVE:
1007 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1008 case LFUN_DEBUG_LEVEL_SET:
1009 // these are handled in our dispatch()
1012 case LFUN_WINDOW_CLOSE:
1013 enable = d->views_.size() > 0;
1016 case LFUN_BUFFER_NEW:
1017 case LFUN_BUFFER_NEW_TEMPLATE:
1018 case LFUN_FILE_OPEN:
1019 case LFUN_HELP_OPEN:
1020 case LFUN_SCREEN_FONT_UPDATE:
1021 case LFUN_SET_COLOR:
1022 case LFUN_WINDOW_NEW:
1024 case LFUN_LYXRC_APPLY:
1025 case LFUN_COMMAND_PREFIX:
1027 case LFUN_META_PREFIX:
1028 case LFUN_RECONFIGURE:
1029 case LFUN_SERVER_GET_FILENAME:
1030 case LFUN_SERVER_NOTIFY:
1039 flag.setEnabled(false);
1043 /// make a post-dispatch status message
1044 static docstring makeDispatchMessage(docstring const & msg,
1045 FuncRequest const & cmd)
1047 const bool verbose = (cmd.origin() == FuncRequest::MENU
1048 || cmd.origin() == FuncRequest::TOOLBAR
1049 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1051 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1052 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1056 docstring dispatch_msg = msg;
1057 if (!dispatch_msg.empty())
1058 dispatch_msg += ' ';
1060 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1062 bool argsadded = false;
1064 if (!cmd.argument().empty()) {
1065 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1066 comname += ' ' + cmd.argument();
1070 docstring const shortcuts = theTopLevelKeymap().
1071 printBindings(cmd, KeySequence::ForGui);
1073 if (!shortcuts.empty())
1074 comname += ": " + shortcuts;
1075 else if (!argsadded && !cmd.argument().empty())
1076 comname += ' ' + cmd.argument();
1078 if (!comname.empty()) {
1079 comname = rtrim(comname);
1080 dispatch_msg += '(' + rtrim(comname) + ')';
1082 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1083 return dispatch_msg;
1087 void GuiApplication::dispatch(FuncRequest const & cmd)
1089 if (current_view_ && current_view_->currentBufferView())
1090 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1093 // redraw the screen at the end (first of the two drawing steps).
1094 // This is done unless explicitly requested otherwise
1095 dr.screenUpdate(Update::FitCursor);
1101 BufferView * bv = current_view_->currentBufferView();
1103 Cursor & cursor = bv->cursor();
1104 Buffer & buf = bv->buffer();
1107 // This check out to be done somewhere else. It got moved here
1108 // from TextMetrics.cpp, where it definitely didn't need to be.
1109 // Actually, this test ought not to be done at all, since the
1110 // whole InsetBibitem business is a mess. But that is a different
1113 if (cursor.inTexted()) {
1114 moveCursor = cursor.paragraph().checkBiblio(buf);
1116 cursor.posForward();
1117 else if (moveCursor < 0 && cursor.pos() >= -moveCursor)
1118 cursor.posBackward();
1120 if (moveCursor != 0 || dr.needBufferUpdate()) {
1121 cursor.clearBufferUpdate();
1124 // BufferView::update() updates the ViewMetricsInfo and
1125 // also initializes the position cache for all insets in
1126 // (at least partially) visible top-level paragraphs.
1127 // We will redraw the screen only if needed.
1128 bv->processUpdateFlags(dr.screenUpdate());
1130 // Do we have a selection?
1131 theSelection().haveSelection(bv->cursor().selection());
1134 current_view_->restartCursor();
1136 if (dr.needMessageUpdate()) {
1137 // Some messages may already be translated, so we cannot use _()
1138 current_view_->message(makeDispatchMessage(
1139 translateIfPossible(dr.message()), cmd));
1144 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1145 bool switchToBuffer)
1147 if (!theSession().bookmarks().isValid(idx))
1149 BookmarksSection::Bookmark const & bm =
1150 theSession().bookmarks().bookmark(idx);
1151 LASSERT(!bm.filename.empty(), /**/);
1152 string const file = bm.filename.absFileName();
1153 // if the file is not opened, open it.
1154 if (!theBufferList().exists(bm.filename)) {
1156 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1160 // open may fail, so we need to test it again
1161 if (!theBufferList().exists(bm.filename))
1164 // bm can be changed when saving
1165 BookmarksSection::Bookmark tmp = bm;
1167 // Special case idx == 0 used for back-from-back jump navigation
1169 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1171 // if the current buffer is not that one, switch to it.
1172 BufferView * doc_bv = current_view_->documentBufferView();
1173 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1174 if (switchToBuffer) {
1175 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1176 doc_bv = current_view_->documentBufferView();
1181 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1182 if (!doc_bv->moveToPosition(
1183 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1190 // Cursor jump succeeded!
1191 Cursor const & cur = doc_bv->cursor();
1192 pit_type new_pit = cur.pit();
1193 pos_type new_pos = cur.pos();
1194 int new_id = cur.paragraph().id();
1196 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1197 // see http://www.lyx.org/trac/ticket/3092
1198 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1199 || bm.top_id != new_id) {
1200 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1201 new_pit, new_pos, new_id);
1205 // This function runs "configure" and then rereads lyx.defaults to
1206 // reconfigure the automatic settings.
1207 void GuiApplication::reconfigure(string const & option)
1209 // emit message signal.
1211 current_view_->message(_("Running configure..."));
1213 // Run configure in user lyx directory
1214 PathChanger p(package().user_support());
1215 string configure_command = package().configure_command();
1216 configure_command += option;
1218 int ret = one.startscript(Systemcall::Wait, configure_command);
1220 // emit message signal.
1222 current_view_->message(_("Reloading configuration..."));
1223 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1224 // Re-read packages.lst
1225 LaTeXFeatures::getAvailable();
1228 Alert::information(_("System reconfiguration failed"),
1229 _("The system reconfiguration has failed.\n"
1230 "Default textclass is used but LyX may "
1231 "not be able to work properly.\n"
1232 "Please reconfigure again if needed."));
1234 Alert::information(_("System reconfigured"),
1235 _("The system has been reconfigured.\n"
1236 "You need to restart LyX to make use of any\n"
1237 "updated document class specifications."));
1240 void GuiApplication::validateCurrentView()
1242 if (!d->views_.empty() && !current_view_) {
1243 // currently at least one view exists but no view has the focus.
1244 // choose a view to open the document in it.
1245 // a view without any open document is preferred.
1246 GuiView * candidate = 0;
1247 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1248 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1249 for (; it != end; ++it) {
1251 if (!candidate->documentBufferView())
1254 setCurrentView(candidate);
1258 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1260 string const argument = to_utf8(cmd.argument());
1261 FuncCode const action = cmd.action();
1263 LYXERR(Debug::ACTION, "cmd: " << cmd);
1265 // we have not done anything wrong yet.
1268 FuncStatus const flag = getStatus(cmd);
1269 if (!flag.enabled()) {
1270 // We cannot use this function here
1271 LYXERR(Debug::ACTION, "action "
1272 << lyxaction.getActionName(action)
1273 << " [" << action << "] is disabled at this location");
1275 current_view_->restartCursor();
1276 dr.setMessage(flag.message());
1278 dr.dispatched(false);
1279 dr.screenUpdate(Update::None);
1280 dr.clearBufferUpdate();
1284 // Assumes that the action will be dispatched.
1285 dr.dispatched(true);
1287 switch (cmd.action()) {
1289 case LFUN_WINDOW_NEW:
1290 createView(toqstr(cmd.argument()));
1293 case LFUN_WINDOW_CLOSE:
1294 // update bookmark pit of the current buffer before window close
1295 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1296 gotoBookmark(i+1, false, false);
1297 // clear the last opened list, because
1298 // maybe this will end the session
1299 theSession().lastOpened().clear();
1300 current_view_->closeScheduled();
1304 // quitting is triggered by the gui code
1305 // (leaving the event loop).
1307 current_view_->message(from_utf8(N_("Exiting.")));
1308 if (closeAllViews())
1312 case LFUN_SCREEN_FONT_UPDATE: {
1313 // handle the screen font changes.
1314 d->font_loader_.update();
1315 // Backup current_view_
1316 GuiView * view = current_view_;
1317 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1318 // to skip the refresh.
1320 theBufferList().changed(false);
1321 // Restore current_view_
1322 current_view_ = view;
1326 case LFUN_BUFFER_NEW:
1327 validateCurrentView();
1328 if (d->views_.empty()
1329 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1330 createView(QString(), false); // keep hidden
1331 current_view_->newDocument(to_utf8(cmd.argument()), false);
1332 current_view_->show();
1333 setActiveWindow(current_view_);
1335 current_view_->newDocument(to_utf8(cmd.argument()), false);
1339 case LFUN_BUFFER_NEW_TEMPLATE:
1340 validateCurrentView();
1341 if (d->views_.empty()
1342 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1344 current_view_->newDocument(to_utf8(cmd.argument()), true);
1345 if (!current_view_->documentBufferView())
1346 current_view_->close();
1348 current_view_->newDocument(to_utf8(cmd.argument()), true);
1352 case LFUN_FILE_OPEN: {
1353 validateCurrentView();
1354 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1355 string const fname = to_utf8(cmd.argument());
1356 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1357 && current_view_->documentBufferView() != 0)) {
1358 // We want the ui session to be saved per document and not per
1359 // window number. The filename crc is a good enough identifier.
1360 boost::crc_32_type crc;
1361 crc = for_each(fname.begin(), fname.end(), crc);
1362 createView(crc.checksum());
1363 current_view_->openDocument(fname);
1364 if (current_view_ && !current_view_->documentBufferView())
1365 current_view_->close();
1367 current_view_->openDocument(fname);
1371 case LFUN_HELP_OPEN: {
1372 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1373 if (current_view_ == 0)
1375 string const arg = to_utf8(cmd.argument());
1377 current_view_->message(_("Missing argument"));
1380 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1382 fname = i18nLibFileSearch("examples", arg, "lyx");
1384 if (fname.empty()) {
1385 lyxerr << "LyX: unable to find documentation file `"
1386 << arg << "'. Bad installation?" << endl;
1389 current_view_->message(bformat(_("Opening help file %1$s..."),
1390 makeDisplayPath(fname.absFileName())));
1391 Buffer * buf = current_view_->loadDocument(fname, false);
1393 #ifndef DEVEL_VERSION
1395 buf->setReadonly(true);
1402 case LFUN_SET_COLOR: {
1404 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1405 if (lyx_name.empty() || x11_name.empty()) {
1407 current_view_->message(
1408 _("Syntax: set-color <lyx_name> <x11_name>"));
1412 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1413 bool const graphicsbg_changed =
1414 lyx_name == graphicsbg && x11_name != graphicsbg;
1415 if (graphicsbg_changed) {
1416 // FIXME: The graphics cache no longer has a changeDisplay method.
1418 graphics::GCache::get().changeDisplay(true);
1422 if (!lcolor.setColor(lyx_name, x11_name)) {
1423 current_view_->message(
1424 bformat(_("Set-color \"%1$s\" failed "
1425 "- color is undefined or "
1426 "may not be redefined"),
1427 from_utf8(lyx_name)));
1430 // Make sure we don't keep old colors in cache.
1431 d->color_cache_.clear();
1435 case LFUN_LYXRC_APPLY: {
1436 // reset active key sequences, since the bindings
1437 // are updated (bug 6064)
1439 LyXRC const lyxrc_orig = lyxrc;
1441 istringstream ss(to_utf8(cmd.argument()));
1442 bool const success = lyxrc.read(ss);
1445 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1446 << "Unable to read lyxrc data"
1451 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1458 case LFUN_COMMAND_PREFIX:
1459 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1464 d->meta_fake_bit = NoModifier;
1465 GuiView * gv = currentView();
1466 if (gv && gv->currentBufferView())
1467 // cancel any selection
1468 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1469 dr.setMessage(from_ascii(N_("Cancel")));
1472 case LFUN_META_PREFIX:
1473 d->meta_fake_bit = AltModifier;
1474 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1477 // --- Menus -----------------------------------------------
1478 case LFUN_RECONFIGURE:
1479 // argument is any additional parameter to the configure.py command
1480 reconfigure(to_utf8(cmd.argument()));
1483 // --- lyxserver commands ----------------------------
1484 case LFUN_SERVER_GET_FILENAME: {
1485 LASSERT(current_view_ && current_view_->documentBufferView(), return);
1486 docstring const fname = from_utf8(
1487 current_view_->documentBufferView()->buffer().absFileName());
1488 dr.setMessage(fname);
1489 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1492 case LFUN_SERVER_NOTIFY: {
1493 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1494 dr.setMessage(dispatch_buffer);
1495 theServer().notifyClient(to_utf8(dispatch_buffer));
1499 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1500 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1506 string rest = split(argument, countstr, ' ');
1507 istringstream is(countstr);
1510 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1511 for (int i = 0; i < count; ++i)
1512 dispatch(lyxaction.lookupFunc(rest));
1516 case LFUN_COMMAND_SEQUENCE: {
1517 // argument contains ';'-terminated commands
1518 string arg = argument;
1519 // FIXME: this LFUN should also work without any view.
1520 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1521 ? &(current_view_->documentBufferView()->buffer()) : 0;
1523 buffer->undo().beginUndoGroup();
1524 while (!arg.empty()) {
1526 arg = split(arg, first, ';');
1527 FuncRequest func(lyxaction.lookupFunc(first));
1528 func.setOrigin(cmd.origin());
1531 // the buffer may have been closed by one action
1532 if (theBufferList().isLoaded(buffer))
1533 buffer->undo().endUndoGroup();
1537 case LFUN_COMMAND_ALTERNATIVES: {
1538 // argument contains ';'-terminated commands
1539 string arg = argument;
1540 while (!arg.empty()) {
1542 arg = split(arg, first, ';');
1543 FuncRequest func(lyxaction.lookupFunc(first));
1544 func.setOrigin(cmd.origin());
1545 FuncStatus const stat = getStatus(func);
1546 if (stat.enabled()) {
1556 if (theTopLevelCmdDef().lock(argument, func)) {
1557 func.setOrigin(cmd.origin());
1559 theTopLevelCmdDef().release(argument);
1561 if (func.action() == LFUN_UNKNOWN_ACTION) {
1562 // unknown command definition
1563 lyxerr << "Warning: unknown command definition `"
1567 // recursion detected
1568 lyxerr << "Warning: Recursion in the command definition `"
1569 << argument << "' detected"
1576 case LFUN_PREFERENCES_SAVE:
1577 lyxrc.write(support::makeAbsPath("preferences",
1578 package().user_support().absFileName()), false);
1581 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1582 string const fname = addName(addPath(package().user_support().absFileName(),
1583 "templates/"), "defaults.lyx");
1584 Buffer defaults(fname);
1586 istringstream ss(argument);
1589 int const unknown_tokens = defaults.readHeader(lex);
1591 if (unknown_tokens != 0) {
1592 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1593 << unknown_tokens << " unknown token"
1594 << (unknown_tokens == 1 ? "" : "s")
1598 if (defaults.writeFile(FileName(defaults.absFileName())))
1599 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1600 makeDisplayPath(fname)));
1603 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1608 case LFUN_BOOKMARK_GOTO:
1609 // go to bookmark, open unopened file and switch to buffer if necessary
1610 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1611 dr.screenUpdate(Update::Force | Update::FitCursor);
1614 case LFUN_BOOKMARK_CLEAR:
1615 theSession().bookmarks().clear();
1618 case LFUN_DEBUG_LEVEL_SET:
1619 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1623 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1626 current_view_->dispatch(cmd, dr);
1632 docstring GuiApplication::viewStatusMessage()
1634 // When meta-fake key is pressed, show the key sequence so far + "M-".
1635 if (d->meta_fake_bit != NoModifier)
1636 return d->keyseq.print(KeySequence::ForGui) + "M-";
1638 // Else, when a non-complete key sequence is pressed,
1639 // show the available options.
1640 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1641 return d->keyseq.printOptions(true);
1647 void GuiApplication::handleKeyFunc(FuncCode action)
1651 if (d->keyseq.length())
1653 GuiView * gv = currentView();
1654 LASSERT(gv && gv->currentBufferView(), return);
1655 BufferView * bv = gv->currentBufferView();
1656 bv->getIntl().getTransManager().deadkey(
1657 c, get_accent(action).accent, bv->cursor().innerText(),
1659 // Need to clear, in case the minibuffer calls these
1662 // copied verbatim from do_accent_char
1663 bv->cursor().resetAnchor();
1667 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1669 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1671 // Do nothing if we have nothing (JMarc)
1672 if (!keysym.isOK()) {
1673 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1675 current_view_->restartCursor();
1679 if (keysym.isModifier()) {
1680 LYXERR(Debug::KEY, "isModifier true");
1682 current_view_->restartCursor();
1686 char_type encoded_last_key = keysym.getUCSEncoded();
1688 // Do a one-deep top-level lookup for
1689 // cancel and meta-fake keys. RVDK_PATCH_5
1690 d->cancel_meta_seq.reset();
1692 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1693 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1695 // When not cancel or meta-fake, do the normal lookup.
1696 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1697 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1698 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1699 // remove Caps Lock and Mod2 as a modifiers
1700 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1701 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1704 // Dont remove this unless you know what you are doing.
1705 d->meta_fake_bit = NoModifier;
1707 // Can this happen now ?
1708 if (func.action() == LFUN_NOACTION)
1709 func = FuncRequest(LFUN_COMMAND_PREFIX);
1711 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1712 << d->keyseq.print(KeySequence::Portable) << ']');
1714 // already here we know if it any point in going further
1715 // why not return already here if action == -1 and
1716 // num_bytes == 0? (Lgb)
1718 if (d->keyseq.length() > 1 && current_view_)
1719 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1722 // Maybe user can only reach the key via holding down shift.
1723 // Let's see. But only if shift is the only modifier
1724 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1725 LYXERR(Debug::KEY, "Trying without shift");
1726 func = d->keyseq.addkey(keysym, NoModifier);
1727 LYXERR(Debug::KEY, "Action now " << func.action());
1730 if (func.action() == LFUN_UNKNOWN_ACTION) {
1731 // Hmm, we didn't match any of the keysequences. See
1732 // if it's normal insertable text not already covered
1734 if (keysym.isText() && d->keyseq.length() == 1) {
1735 LYXERR(Debug::KEY, "isText() is true, inserting.");
1736 func = FuncRequest(LFUN_SELF_INSERT,
1737 FuncRequest::KEYBOARD);
1739 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1740 if (current_view_) {
1741 current_view_->message(_("Unknown function."));
1742 current_view_->restartCursor();
1748 if (func.action() == LFUN_SELF_INSERT) {
1749 if (encoded_last_key != 0) {
1750 docstring const arg(1, encoded_last_key);
1751 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
1752 FuncRequest::KEYBOARD));
1753 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1756 processFuncRequest(func);
1760 void GuiApplication::processFuncRequest(FuncRequest const & func)
1762 lyx::dispatch(func);
1766 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
1768 addToFuncRequestQueue(func);
1769 processFuncRequestQueueAsync();
1773 void GuiApplication::processFuncRequestQueue()
1775 while (!d->func_request_queue_.empty()) {
1776 processFuncRequest(d->func_request_queue_.front());
1777 d->func_request_queue_.pop();
1782 void GuiApplication::processFuncRequestQueueAsync()
1784 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
1788 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
1790 d->func_request_queue_.push(func);
1794 void GuiApplication::resetGui()
1796 // Set the language defined by the user.
1800 if (!readUIFile(toqstr(lyxrc.ui_file)))
1801 // Gives some error box here.
1804 if (d->global_menubar_)
1805 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1807 QHash<int, GuiView *>::iterator it;
1808 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1811 gv->setLayoutDirection(layoutDirection());
1815 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1819 void GuiApplication::createView(int view_id)
1821 createView(QString(), true, view_id);
1825 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1828 // release the keyboard which might have been grabed by the global
1829 // menubar on Mac to catch shortcuts even without any GuiView.
1830 if (d->global_menubar_)
1831 d->global_menubar_->releaseKeyboard();
1835 while (d->views_.find(id) != d->views_.end())
1838 LYXERR(Debug::GUI, "About to create new window with ID " << id);
1839 GuiView * view = new GuiView(id);
1841 d->views_[id] = view;
1845 setActiveWindow(view);
1848 if (!geometry_arg.isEmpty()) {
1852 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1853 re.indexIn(geometry_arg);
1854 w = re.cap(1).toInt();
1855 h = re.cap(2).toInt();
1856 x = re.cap(3).toInt();
1857 y = re.cap(4).toInt();
1858 view->setGeometry(x, y, w, h);
1865 Clipboard & GuiApplication::clipboard()
1867 return d->clipboard_;
1871 Selection & GuiApplication::selection()
1873 return d->selection_;
1877 FontLoader & GuiApplication::fontLoader()
1879 return d->font_loader_;
1883 Toolbars const & GuiApplication::toolbars() const
1885 return d->toolbars_;
1889 Toolbars & GuiApplication::toolbars()
1891 return d->toolbars_;
1895 Menus const & GuiApplication::menus() const
1901 Menus & GuiApplication::menus()
1907 QList<int> GuiApplication::viewIds() const
1909 return d->views_.keys();
1913 ColorCache & GuiApplication::colorCache()
1915 return d->color_cache_;
1919 int GuiApplication::exec()
1921 // asynchronously handle batch commands. This event will be in
1922 // the event queue in front of other asynchronous events. Hence,
1923 // we can assume in the latter that the gui is setup already.
1924 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1926 return QApplication::exec();
1930 void GuiApplication::exit(int status)
1932 QApplication::exit(status);
1936 void GuiApplication::setGuiLanguage()
1938 // Set the language defined by the user.
1941 QString const default_language = toqstr(Messages::defaultLanguage());
1942 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
1943 QLocale const default_locale(default_language);
1944 QLocale::setDefault(default_locale);
1946 // install translation file for Qt built-in dialogs
1947 QString const language_name = QString("qt_") + default_locale.name();
1949 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1950 // Short-named translator can be loaded from a long name, but not the
1951 // opposite. Therefore, long name should be used without truncation.
1952 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1953 if (!d->qt_trans_.load(language_name,
1954 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1955 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1958 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1962 switch (default_locale.language()) {
1963 case QLocale::Arabic :
1964 case QLocale::Hebrew :
1965 case QLocale::Persian :
1966 case QLocale::Urdu :
1967 setLayoutDirection(Qt::RightToLeft);
1970 setLayoutDirection(Qt::LeftToRight);
1975 void GuiApplication::execBatchCommands()
1980 if (!readUIFile(toqstr(lyxrc.ui_file)))
1981 // Gives some error box here.
1985 #if QT_VERSION > 0x040600
1986 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
1988 // Create the global default menubar which is shown for the dialogs
1989 // and if no GuiView is visible.
1990 // This must be done after the session was recovered to know the "last files".
1991 d->global_menubar_ = new GlobalMenuBar();
1992 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1995 lyx::execBatchCommands();
1999 QAbstractItemModel * GuiApplication::languageModel()
2001 if (d->language_model_)
2002 return d->language_model_;
2004 QStandardItemModel * lang_model = new QStandardItemModel(this);
2005 lang_model->insertColumns(0, 3);
2007 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2008 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2009 Languages::const_iterator it = lyx::languages.begin();
2010 Languages::const_iterator end = lyx::languages.end();
2011 for (; it != end; ++it) {
2012 current_row = lang_model->rowCount();
2013 lang_model->insertRows(current_row, 1);
2014 QModelIndex pl_item = lang_model->index(current_row, 0);
2015 QModelIndex sp_item = lang_model->index(current_row, 1);
2016 QModelIndex th_item = lang_model->index(current_row, 2);
2017 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2018 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2019 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2020 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2021 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2022 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2023 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2024 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2025 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2026 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2028 d->language_model_ = new QSortFilterProxyModel(this);
2029 d->language_model_->setSourceModel(lang_model);
2030 #if QT_VERSION >= 0x040300
2031 d->language_model_->setSortLocaleAware(true);
2033 return d->language_model_;
2037 void GuiApplication::restoreGuiSession()
2039 if (!lyxrc.load_session)
2042 Session & session = theSession();
2043 LastOpenedSection::LastOpened const & lastopened =
2044 session.lastOpened().getfiles();
2046 FileName active_file;
2047 // do not add to the lastfile list since these files are restored from
2048 // last session, and should be already there (regular files), or should
2049 // not be added at all (help files).
2050 for (size_t i = 0; i < lastopened.size(); ++i) {
2051 FileName const & file_name = lastopened[i].file_name;
2052 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2053 && current_view_->documentBufferView() != 0)) {
2054 boost::crc_32_type crc;
2055 string const & fname = file_name.absFileName();
2056 crc = for_each(fname.begin(), fname.end(), crc);
2057 createView(crc.checksum());
2059 current_view_->loadDocument(file_name, false);
2061 if (lastopened[i].active)
2062 active_file = file_name;
2065 // Restore last active buffer
2066 Buffer * buffer = theBufferList().getBuffer(active_file);
2068 current_view_->setBuffer(buffer);
2070 // clear this list to save a few bytes of RAM
2071 session.lastOpened().clear();
2075 QString const GuiApplication::romanFontName()
2078 font.setKerning(false);
2079 font.setStyleHint(QFont::Serif);
2080 font.setFamily("serif");
2082 return QFontInfo(font).family();
2086 QString const GuiApplication::sansFontName()
2089 font.setKerning(false);
2090 font.setStyleHint(QFont::SansSerif);
2091 font.setFamily("sans");
2093 return QFontInfo(font).family();
2097 QString const GuiApplication::typewriterFontName()
2100 font.setKerning(false);
2101 font.setStyleHint(QFont::TypeWriter);
2102 font.setFamily("monospace");
2104 return QFontInfo(font).family();
2108 void GuiApplication::handleRegularEvents()
2110 ForkedCallsController::handleCompletedProcesses();
2114 bool GuiApplication::event(QEvent * e)
2117 case QEvent::FileOpen: {
2118 // Open a file; this happens only on Mac OS X for now.
2120 // We do this asynchronously because on startup the batch
2121 // commands are not executed here yet and the gui is not ready
2123 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2124 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2125 processFuncRequestAsync(fr);
2130 return QApplication::event(e);
2135 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2138 return QApplication::notify(receiver, event);
2140 catch (ExceptionMessage const & e) {
2142 case ErrorException:
2144 setQuitOnLastWindowClosed(false);
2146 Alert::error(e.title_, e.details_);
2148 // Properly crash in debug mode in order to get a useful backtrace.
2151 // In release mode, try to exit gracefully.
2154 case BufferException: {
2155 if (!current_view_->documentBufferView())
2157 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2158 docstring details = e.details_ + '\n';
2159 details += buf->emergencyWrite();
2160 theBufferList().release(buf);
2161 details += "\n" + _("The current document was closed.");
2162 Alert::error(e.title_, details);
2165 case WarningException:
2166 Alert::warning(e.title_, e.details_);
2170 catch (exception const & e) {
2171 docstring s = _("LyX has caught an exception, it will now "
2172 "attempt to save all unsaved documents and exit."
2174 s += from_ascii(e.what());
2175 Alert::error(_("Software exception Detected"), s);
2179 docstring s = _("LyX has caught some really weird exception, it will "
2180 "now attempt to save all unsaved documents and exit.");
2181 Alert::error(_("Software exception Detected"), s);
2189 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2191 QColor const & qcol = d->color_cache_.get(col);
2192 if (!qcol.isValid()) {
2198 rgbcol.r = qcol.red();
2199 rgbcol.g = qcol.green();
2200 rgbcol.b = qcol.blue();
2205 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2207 QColor const qcol(lcolor.getX11Name(col).c_str());
2208 if (!qcol.isValid()) {
2214 rgbcol.r = qcol.red();
2215 rgbcol.g = qcol.green();
2216 rgbcol.b = qcol.blue();
2221 string const GuiApplication::hexName(ColorCode col)
2223 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2227 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2229 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2230 d->socket_notifiers_[fd] = sn;
2231 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2235 void GuiApplication::socketDataReceived(int fd)
2237 d->socket_notifiers_[fd]->func_();
2241 void GuiApplication::unregisterSocketCallback(int fd)
2243 d->socket_notifiers_.take(fd)->setEnabled(false);
2247 void GuiApplication::commitData(QSessionManager & sm)
2249 /// The implementation is required to avoid an application exit
2250 /// when session state save is triggered by session manager.
2251 /// The default implementation sends a close event to all
2252 /// visible top level widgets when session managment allows
2254 /// We are changing that to close all wiew one by one.
2255 /// FIXME: verify if the default implementation is enough now.
2256 #ifdef QT_NO_SESSIONMANAGER
2257 #warning Qt is compiled without session manager
2260 if (sm.allowsInteraction() && !closeAllViews())
2266 void GuiApplication::unregisterView(GuiView * gv)
2268 LASSERT(d->views_[gv->id()] == gv, /**/);
2269 d->views_.remove(gv->id());
2270 if (current_view_ == gv)
2275 bool GuiApplication::closeAllViews()
2277 if (d->views_.empty())
2280 // When a view/window was closed before without quitting LyX, there
2281 // are already entries in the lastOpened list.
2282 theSession().lastOpened().clear();
2284 QList<GuiView *> views = d->views_.values();
2285 foreach (GuiView * view, views) {
2286 if (!view->closeScheduled())
2295 GuiView & GuiApplication::view(int id) const
2297 LASSERT(d->views_.contains(id), /**/);
2298 return *d->views_.value(id);
2302 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2304 QList<GuiView *> views = d->views_.values();
2305 foreach (GuiView * view, views)
2306 view->hideDialog(name, inset);
2310 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2312 Buffer const * buffer_ = 0;
2313 QHash<int, GuiView *>::iterator end = d->views_.end();
2314 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2315 if (Buffer const * ptr = (*it)->updateInset(inset))
2322 bool GuiApplication::searchMenu(FuncRequest const & func,
2323 docstring_list & names) const
2325 return d->menus_.searchMenu(func, names);
2329 // Ensure that a file is read only once (prevents include loops)
2330 static QStringList uifiles;
2331 // store which ui files define Toolbars
2332 static QStringList toolbar_uifiles;
2335 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2346 LexerKeyword uitags[] = {
2347 { "format", ui_format },
2348 { "include", ui_include },
2349 { "menuset", ui_menuset },
2350 { "toolbars", ui_toolbars },
2351 { "toolbarset", ui_toolbarset }
2355 lex.setFile(ui_path);
2357 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2361 if (lyxerr.debugging(Debug::PARSER))
2362 lex.printTable(lyxerr);
2365 // format before introduction of format tag
2366 unsigned int format = 0;
2367 while (lex.isOK()) {
2368 int const status = lex.lex();
2370 // we have to do this check here, outside the switch,
2371 // because otherwise we would start reading include files,
2372 // e.g., if the first tag we hit was an include tag.
2373 if (status == ui_format)
2375 format = lex.getInteger();
2379 // this will trigger unless the first tag we hit is a format
2380 // tag, with the right format.
2381 if (format != LFUN_FORMAT)
2382 return FormatMismatch;
2385 case Lexer::LEX_FEOF:
2390 QString const file = toqstr(lex.getString());
2391 bool const success = readUIFile(file, true);
2393 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2400 d->menus_.read(lex);
2404 d->toolbars_.readToolbars(lex);
2408 d->toolbars_.readToolbarSettings(lex);
2409 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2413 if (!rtrim(lex.getString()).empty())
2414 lex.printError("LyX::ReadUIFile: "
2415 "Unknown menu tag: `$$Token'");
2417 LYXERR0("Error with status: " << status);
2423 return (error ? ReadError : ReadOK);
2427 bool GuiApplication::readUIFile(QString const & name, bool include)
2429 LYXERR(Debug::INIT, "About to read " << name << "...");
2433 ui_path = libFileSearch("ui", name, "inc");
2434 if (ui_path.empty())
2435 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2437 ui_path = libFileSearch("ui", name, "ui");
2440 if (ui_path.empty()) {
2441 static const QString defaultUIFile = "default";
2442 LYXERR(Debug::INIT, "Could not find " << name);
2444 Alert::warning(_("Could not find UI definition file"),
2445 bformat(_("Error while reading the included file\n%1$s\n"
2446 "Please check your installation."), qstring_to_ucs4(name)));
2449 if (name == defaultUIFile) {
2450 LYXERR(Debug::INIT, "Could not find default UI file!!");
2451 Alert::warning(_("Could not find default UI file"),
2452 _("LyX could not find the default UI file!\n"
2453 "Please check your installation."));
2456 Alert::warning(_("Could not find UI definition file"),
2457 bformat(_("Error while reading the configuration file\n%1$s\n"
2458 "Falling back to default.\n"
2459 "Please look under Tools>Preferences>User Interface and\n"
2460 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2461 return readUIFile(defaultUIFile, false);
2464 QString const uifile = toqstr(ui_path.absFileName());
2465 if (uifiles.contains(uifile)) {
2467 // We are reading again the top uifile so reset the safeguard:
2470 d->toolbars_.reset();
2472 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2473 << "Is this an include loop?");
2477 uifiles.push_back(uifile);
2479 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2481 ReturnValues retval = readUIFile(ui_path);
2483 if (retval == FormatMismatch) {
2484 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2485 FileName const tempfile = FileName::tempName("convert_ui");
2486 bool const success = prefs2prefs(ui_path, tempfile, true);
2488 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2489 " to format " << LFUN_FORMAT << ".");
2491 retval = readUIFile(tempfile);
2492 tempfile.removeFile();
2496 if (retval != ReadOK) {
2497 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2505 settings.beginGroup("ui_files");
2506 bool touched = false;
2507 for (int i = 0; i != uifiles.size(); ++i) {
2508 QFileInfo fi(uifiles[i]);
2509 QDateTime const date_value = fi.lastModified();
2510 QString const name_key = QString::number(i);
2511 // if an ui file which defines Toolbars has changed,
2512 // we have to reset the settings
2513 if (toolbar_uifiles.contains(uifiles[i])
2514 && (!settings.contains(name_key)
2515 || settings.value(name_key).toString() != uifiles[i]
2516 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2518 settings.setValue(name_key, uifiles[i]);
2519 settings.setValue(name_key + "/date", date_value);
2522 settings.endGroup();
2524 settings.remove("views");
2530 void GuiApplication::onLastWindowClosed()
2532 if (d->global_menubar_)
2533 d->global_menubar_->grabKeyboard();
2537 ////////////////////////////////////////////////////////////////////////
2539 // X11 specific stuff goes here...
2542 bool GuiApplication::x11EventFilter(XEvent * xev)
2547 switch (xev->type) {
2548 case SelectionRequest: {
2549 if (xev->xselectionrequest.selection != XA_PRIMARY)
2551 LYXERR(Debug::SELECTION, "X requested selection.");
2552 BufferView * bv = current_view_->currentBufferView();
2554 docstring const sel = bv->requestSelection();
2556 d->selection_.put(sel);
2560 case SelectionClear: {
2561 if (xev->xselectionclear.selection != XA_PRIMARY)
2563 LYXERR(Debug::SELECTION, "Lost selection.");
2564 BufferView * bv = current_view_->currentBufferView();
2566 bv->clearSelection();
2574 } // namespace frontend
2577 void hideDialogs(std::string const & name, Inset * inset)
2580 frontend::guiApp->hideDialogs(name, inset);
2584 ////////////////////////////////////////////////////////////////////
2588 ////////////////////////////////////////////////////////////////////
2590 frontend::FontLoader & theFontLoader()
2592 LASSERT(frontend::guiApp, /**/);
2593 return frontend::guiApp->fontLoader();
2597 frontend::FontMetrics const & theFontMetrics(Font const & f)
2599 return theFontMetrics(f.fontInfo());
2603 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2605 LASSERT(frontend::guiApp, /**/);
2606 return frontend::guiApp->fontLoader().metrics(f);
2610 ////////////////////////////////////////////////////////////////////
2614 ////////////////////////////////////////////////////////////////////
2616 frontend::Clipboard & theClipboard()
2618 LASSERT(frontend::guiApp, /**/);
2619 return frontend::guiApp->clipboard();
2623 frontend::Selection & theSelection()
2625 LASSERT(frontend::guiApp, /**/);
2626 return frontend::guiApp->selection();
2632 #include "moc_GuiApplication.cpp"