]> git.lyx.org Git - lyx.git/blobdiff - src/frontends/qt4/GuiApplication.cpp
Extend list of accessible menu info
[lyx.git] / src / frontends / qt4 / GuiApplication.cpp
index c27f4c87e3a032147b335bce36fba34158213922..d4b1701758ae248bae8345d66164d0d7d1250441 100644 (file)
 
 #include <queue>
 
-#include <QFontDatabase>
 #include <QByteArray>
-#include <QClipboard>
 #include <QDateTime>
 #include <QDesktopWidget>
 #include <QDir>
 #include <QEvent>
-#include <QEventLoop>
 #include <QFileOpenEvent>
 #include <QFileInfo>
+#include <QFontDatabase>
 #include <QHash>
 #include <QIcon>
 #include <QImageReader>
 #include <QRegExp>
 #include <QSessionManager>
 #include <QSettings>
-#include <QShowEvent>
 #include <QSocketNotifier>
 #include <QSortFilterProxyModel>
 #include <QStandardItemModel>
-#include <QTextCodec>
 #include <QTimer>
 #include <QTranslator>
 #include <QThreadPool>
@@ -188,6 +184,12 @@ frontend::Application * createApplication(int & argc, char * argv[])
                }
        }
 #endif
+
+#if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
+       // On Windows, allow bringing the LyX window to top
+       AllowSetForegroundWindow(ASFW_ANY);
+#endif
+
        frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
        // I'd rather do that in the constructor, but I do not think that
        // the palette is accessible there.
@@ -468,7 +470,7 @@ QString findImg(QString const & name)
        return img_name;
 }
 
-} // namespace anon
+} // namespace
 
 
 QString themeIconName(QString const & action)
@@ -592,7 +594,7 @@ QPixmap getPixmap(QString const & path, QString const & name, QString const & ex
        if (getPixmap(pixmap, fpath)) {
                return pixmap;
        }
-       
+
        QStringList exts = ext.split(",");
        fpath = ":/" + path + name + ".";
        for (int i = 0; i < exts.size(); ++i) {
@@ -662,38 +664,48 @@ public:
 };
 
 
-////////////////////////////////////////////////////////////////////////
-//
-// Mac specific stuff goes here...
-//
-////////////////////////////////////////////////////////////////////////
-
-class MenuTranslator : public QTranslator
+class GuiTranslator : public QTranslator
 {
 public:
-       MenuTranslator(QObject * parent)
+       GuiTranslator(QObject * parent = nullptr)
                : QTranslator(parent)
        {}
 
-#if QT_VERSION >= 0x050000
        virtual QString translate(const char * /* context */,
                const char *sourceText,
+#if QT_VERSION >= 0x050000
                const char * /* disambiguation */ = 0, int /* n */ = -1) const
 #else
-       QString translate(const char * /*context*/,
-         const char * sourceText,
-         const char * /*comment*/ = 0) const
+               const char * /*comment*/ = 0) const
 #endif
        {
-               string const s = sourceText;
-               if (s == N_("About %1") || s == N_("Preferences")
-                               || s == N_("Reconfigure") || s == N_("Quit %1"))
-                       return qt_(s);
-               else
-                       return QString();
+               // Here we declare the strings that need to be translated from Qt own GUI
+               // This is needed to include these strings to po files
+               _("About %1");
+               _("Preferences");
+               _("Reconfigure");
+               _("Quit %1");
+               _("&OK");
+               // Already in po: "Cancel", "&Cancel"
+               _("Apply"); // Already in po: "&Apply"
+               _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
+
+               docstring s = getGuiMessages().getIfFound(sourceText);
+               // This test should eventually be removed when translations are updated
+               if (s.empty())
+                       LYXERR(Debug::LOCALE, "Missing translation for `"
+                              << string(sourceText) << "'");
+               return toqstr(s);
        }
 };
 
+
+////////////////////////////////////////////////////////////////////////
+//
+// Mac specific stuff goes here...
+//
+////////////////////////////////////////////////////////////////////////
+
 #ifdef Q_OS_MAC
 // QMacPasteboardMimeGraphics can only be compiled on Mac.
 
@@ -942,8 +954,10 @@ struct GuiApplication::Private
        FontLoader font_loader_;
        ///
        ColorCache color_cache_;
-       ///
+       /// the built-in Qt translation mechanism
        QTranslator qt_trans_;
+       /// LyX gettext-based translation for Qt elements
+       GuiTranslator gui_trans_;
        ///
        QHash<int, SocketNotifier *> socket_notifiers_;
        ///
@@ -1023,7 +1037,9 @@ GuiApplication::GuiApplication(int & argc, char ** argv)
 
        qsrand(QDateTime::currentDateTime().toTime_t());
 
-       // Install translator for GUI elements.
+       // Install LyX translator for missing Qt translations
+       installTranslator(&d->gui_trans_);
+       // Install Qt native translator for GUI elements.
        installTranslator(&d->qt_trans_);
 
 #ifdef QPA_XCB
@@ -1042,10 +1058,6 @@ GuiApplication::GuiApplication(int & argc, char ** argv)
        // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
        // seems to be the default case for applications like LyX.
        setQuitOnLastWindowClosed(false);
-       // This allows to translate the strings that appear in the LyX menu.
-       /// A translator suitable for the entries in the LyX menu.
-       /// Only needed with Qt/Mac.
-       installTranslator(new MenuTranslator(this));
        ///
        setupApplescript();
 #endif
@@ -1343,12 +1355,12 @@ bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
 static docstring makeDispatchMessage(docstring const & msg,
                                     FuncRequest const & cmd)
 {
-       const bool verbose = (cmd.origin() == FuncRequest::MENU
+       const bool be_verbose = (cmd.origin() == FuncRequest::MENU
                              || cmd.origin() == FuncRequest::TOOLBAR
                              || cmd.origin() == FuncRequest::COMMANDBUFFER);
 
-       if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
-               LYXERR(Debug::ACTION, "dispatch msg is " << msg);
+       if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
+               LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
                return msg;
        }
 
@@ -1385,25 +1397,31 @@ static docstring makeDispatchMessage(docstring const & msg,
 
 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
 {
+       DispatchResult dr;
+
        Buffer * buffer = 0;
+       if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
+               //setCurrentView(cmd.view_origin); //does not work
+               dr.setError(true);
+               dr.setMessage(_("Wrong focus!"));
+               d->dispatch_result_ = dr;
+               return d->dispatch_result_;
+       }
        if (current_view_ && current_view_->currentBufferView()) {
                current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
                buffer = &current_view_->currentBufferView()->buffer();
-               if (buffer)
-                       buffer->undo().beginUndoGroup();
        }
 
-       DispatchResult dr;
+       dr.screenUpdate(Update::FitCursor);
+       {
+               // This handles undo groups automagically
+               UndoGroupHelper ugh(buffer);
+               dispatch(cmd, dr);
+       }
+
        // redraw the screen at the end (first of the two drawing steps).
        // This is done unless explicitly requested otherwise
-       dr.screenUpdate(Update::FitCursor);
-       dispatch(cmd, dr);
        updateCurrentView(cmd, dr);
-
-       // the buffer may have been closed by one action
-       if (theBufferList().isLoaded(buffer))
-               buffer->undo().endUndoGroup();
-
        d->dispatch_result_ = dr;
        return d->dispatch_result_;
 }
@@ -1433,7 +1451,7 @@ void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult &
                theSelection().haveSelection(bv->cursor().selection());
 
                // update gui
-               current_view_->restartCursor();
+               current_view_->restartCaret();
        }
        if (dr.needMessageUpdate()) {
                // Some messages may already be translated, so we cannot use _()
@@ -1627,20 +1645,13 @@ void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
        case LFUN_SCREEN_FONT_UPDATE: {
                // handle the screen font changes.
                d->font_loader_.update();
-               // Backup current_view_
-               GuiView * view = current_view_;
-               // Set current_view_ to zero to forbid GuiWorkArea::redraw()
-               // to skip the refresh.
-               current_view_ = 0;
-               theBufferList().changed(false);
-               // Restore current_view_
-               current_view_ = view;
+               dr.screenUpdate(Update::Force | Update::FitCursor);
                break;
        }
 
        case LFUN_BUFFER_NEW:
                validateCurrentView();
-               if (d->views_.empty()
+               if (!current_view_
                   || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
                        createView(QString(), false); // keep hidden
                        current_view_->newDocument(to_utf8(cmd.argument()), false);
@@ -1653,7 +1664,7 @@ void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
 
        case LFUN_BUFFER_NEW_TEMPLATE:
                validateCurrentView();
-               if (d->views_.empty()
+               if (!current_view_
                   || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
                        createView();
                        current_view_->newDocument(to_utf8(cmd.argument()), true);
@@ -1665,12 +1676,14 @@ void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
                break;
 
        case LFUN_FILE_OPEN: {
+               // FIXME: normally the code below is not needed, since getStatus makes sure that
+               //   current_view_ is not null.
                validateCurrentView();
                // FIXME: create a new method shared with LFUN_HELP_OPEN.
                string const fname = to_utf8(cmd.argument());
                bool const is_open = FileName::isAbsolute(fname)
                        && theBufferList().getBuffer(FileName(fname));
-               if (d->views_.empty()
+               if (!current_view_
                    || (!lyxrc.open_buffers_in_tabs
                        && current_view_->documentBufferView() != 0
                        && !is_open)) {
@@ -1679,9 +1692,6 @@ void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
                        boost::crc_32_type crc;
                        crc = for_each(fname.begin(), fname.end(), crc);
                        createView(crc.checksum());
-                       // we know current_view_ is non-null, because createView sets it.
-                       // but let's make sure
-                       LASSERT(current_view_, break);
                        current_view_->openDocument(fname);
                        if (!current_view_->documentBufferView())
                                current_view_->close();
@@ -1691,9 +1701,6 @@ void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
                                current_view_->showNormal();
                        }
                } else {
-                       // we know !d->views.empty(), so this should be ok
-                       // but let's make sure
-                       LASSERT(current_view_, break);
                        current_view_->openDocument(fname);
                        if (cmd.origin() == FuncRequest::LYXSERVER) {
                                current_view_->raise();
@@ -1725,13 +1732,8 @@ void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
                current_view_->message(bformat(_("Opening help file %1$s..."),
                                               makeDisplayPath(fname.absFileName())));
                Buffer * buf = current_view_->loadDocument(fname, false);
-
-#ifndef DEVEL_VERSION
                if (buf)
-                       buf->setReadonly(true);
-#else
-               (void) buf;
-#endif
+                       buf->setReadonly(!current_view_->develMode());
                break;
        }
 
@@ -1800,6 +1802,7 @@ void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
                //   UI, then, nothing would happen. This seems fairly unlikely, but
                //   it definitely is a bug.
 
+               dr.forceBufferUpdate();
                break;
        }
 
@@ -1858,8 +1861,18 @@ void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
                string countstr;
                string rest = split(argument, countstr, ' ');
                int const count = convert<int>(countstr);
-               for (int i = 0; i < count; ++i)
-                       dispatch(lyxaction.lookupFunc(rest));
+               // an arbitrary number to limit number of iterations
+               int const max_iter = 10000;
+               if (count > max_iter) {
+                       dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
+                       dr.setError(true);
+               } else {
+                       for (int i = 0; i < count; ++i) {
+                               FuncRequest lfun = lyxaction.lookupFunc(rest);
+                               lfun.allowAsync(false);
+                               dispatch(lfun);
+                       }
+               }
                break;
        }
 
@@ -1869,23 +1882,22 @@ void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
                // FIXME: this LFUN should also work without any view.
                Buffer * buffer = (current_view_ && current_view_->documentBufferView())
                                  ? &(current_view_->documentBufferView()->buffer()) : 0;
-               if (buffer)
-                       buffer->undo().beginUndoGroup();
+               // This handles undo groups automagically
+               UndoGroupHelper ugh(buffer);
                while (!arg.empty()) {
                        string first;
                        arg = split(arg, first, ';');
                        FuncRequest func(lyxaction.lookupFunc(first));
+                       func.allowAsync(false);
                        func.setOrigin(cmd.origin());
                        dispatch(func);
                }
-               // the buffer may have been closed by one action
-               if (theBufferList().isLoaded(buffer))
-                       buffer->undo().endUndoGroup();
                break;
        }
 
        case LFUN_BUFFER_FORALL: {
-               FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
+               FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
+               funcToRun.allowAsync(false);
 
                map<Buffer *, GuiView *> views_lVisible;
                map<GuiView *, Buffer *> activeBuffers;
@@ -2066,9 +2078,8 @@ void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
                        if (current_view_ == 0)
                                createView();
                }
-               // fall through
        }
-
+       // fall through
        default:
                // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
                // let's try that:
@@ -2155,7 +2166,7 @@ void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
                if (!keysym.isOK())
                        LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
                if (current_view_)
-                       current_view_->restartCursor();
+                       current_view_->restartCaret();
                return;
        }
 
@@ -2215,7 +2226,7 @@ void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
                        if (!isPrintable(encoded_last_key)) {
                                LYXERR(Debug::KEY, "Non-printable character! Omitting.");
                                if (current_view_)
-                                       current_view_->restartCursor();
+                                       current_view_->restartCaret();
                                return;
                        }
                        // The following modifier check is not needed on Mac.
@@ -2237,7 +2248,7 @@ void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
                        {
                                if (current_view_) {
                                        current_view_->message(_("Unknown function."));
-                                       current_view_->restartCursor();
+                                       current_view_->restartCaret();
                                }
                                return;
                        }
@@ -2252,7 +2263,7 @@ void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
                        LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
                        if (current_view_) {
                                current_view_->message(_("Unknown function."));
-                               current_view_->restartCursor();
+                               current_view_->restartCaret();
                        }
                        return;
                }
@@ -2286,8 +2297,12 @@ void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
 void GuiApplication::processFuncRequestQueue()
 {
        while (!d->func_request_queue_.empty()) {
-               processFuncRequest(d->func_request_queue_.front());
+               // take the item from the stack _before_ processing the
+               // request in order to avoid race conditions from nested
+               // or parallel requests (see #10406)
+               FuncRequest const fr(d->func_request_queue_.front());
                d->func_request_queue_.pop();
+               processFuncRequest(fr);
        }
 }
 
@@ -2350,6 +2365,8 @@ void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
 
        LYXERR(Debug::GUI, "About to create new window with ID " << id);
        GuiView * view = new GuiView(id);
+       // `view' is the new current_view_. Tell coverity that is is not 0.
+       LATTEST(current_view_);
        // register view
        d->views_[id] = view;
 
@@ -2399,6 +2416,15 @@ void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
 }
 
 
+bool GuiApplication::unhide(Buffer * buf)
+{
+       if (!currentView())
+               return false;
+       currentView()->setBuffer(buf, false);
+       return true;
+}
+
+
 Clipboard & GuiApplication::clipboard()
 {
        return d->clipboard_;
@@ -2581,7 +2607,7 @@ void GuiApplication::restoreGuiSession()
        // not be added at all (help files).
        for (size_t i = 0; i < lastopened.size(); ++i) {
                FileName const & file_name = lastopened[i].file_name;
-               if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
+               if (!current_view_ || (!lyxrc.open_buffers_in_tabs
                          && current_view_->documentBufferView() != 0)) {
                        boost::crc_32_type crc;
                        string const & fname = file_name.absFileName();
@@ -2637,7 +2663,7 @@ namespace {
                const QFontInfo fi(font);
                return fi.fixedPitch();
        }
-}
+} // namespace
 
 
 QFont const GuiApplication::typewriterSystemFont()
@@ -2709,7 +2735,8 @@ bool GuiApplication::notify(QObject * receiver, QEvent * event)
 #endif
                        // In release mode, try to exit gracefully.
                        this->exit(1);
-
+                       // FIXME: GCC 7 thinks we can fall through here. Can we?
+                       // fall through
                case BufferException: {
                        if (!current_view_ || !current_view_->documentBufferView())
                                return false;
@@ -2908,7 +2935,16 @@ Buffer const * GuiApplication::updateInset(Inset const * inset) const
 bool GuiApplication::searchMenu(FuncRequest const & func,
        docstring_list & names) const
 {
-       return d->menus_.searchMenu(func, names);
+       BufferView * bv = 0;
+       if (current_view_)
+               bv = current_view_->currentBufferView();
+       return d->menus_.searchMenu(func, names, bv);
+}
+
+
+bool GuiApplication::hasBufferView() const
+{
+       return (current_view_ && current_view_->currentBufferView());
 }