]> git.lyx.org Git - lyx.git/blobdiff - src/frontends/qt4/GuiSpellchecker.cpp
Don't allow newline characters in preference (#5840).
[lyx.git] / src / frontends / qt4 / GuiSpellchecker.cpp
index 0051aba1401c58da272807323a2058e6014d205b..5e7305e75a9897ffe7409753e6d20b9d33e4290a 100644 (file)
@@ -5,6 +5,7 @@
  *
  * \author John Levon
  * \author Edwin Leuven
+ * \author Abdelrazak Younes
  *
  * Full author contact details are available in file CREDITS.
  */
 #include <config.h>
 
 #include "GuiSpellchecker.h"
+#include "GuiApplication.h"
 
 #include "qt_helpers.h"
 
+#include "ui_SpellcheckerUi.h"
+
 #include "Buffer.h"
 #include "BufferParams.h"
 #include "BufferView.h"
 #include "buffer_funcs.h"
 #include "Cursor.h"
+#include "Text.h"
 #include "CutAndPaste.h"
+#include "FuncRequest.h"
 #include "Language.h"
 #include "LyX.h"
 #include "LyXRC.h"
+#include "lyxfind.h"
 #include "Paragraph.h"
+#include "WordLangTuple.h"
 
 #include "support/debug.h"
 #include "support/docstring.h"
@@ -34,7 +42,9 @@
 #include "support/lstrings.h"
 #include "support/textutils.h"
 
+#include <QKeyEvent>
 #include <QListWidgetItem>
+#include <QMessageBox>
 
 #include "SpellChecker.h"
 
@@ -47,252 +57,406 @@ namespace lyx {
 namespace frontend {
 
 
-GuiSpellchecker::GuiSpellchecker(GuiView & lv)
-       : GuiDialog(lv, "spellchecker", qt_("Spellchecker")), exitEarly_(false),
-         progress_(0), count_(0)
+struct SpellcheckerWidget::Private
 {
-       setupUi(this);
+       Private(SpellcheckerWidget * parent, DockView * dv)
+               : p(parent), dv_(dv), incheck_(false), wrap_around_(false) {}
+       /// update from controller
+       void updateSuggestions(docstring_list & words);
+       /// move to next position after current word
+       void forward();
+       /// check text until next misspelled/unknown word
+       void check();
+       ///
+       bool continueFromBeginning();
+       ///
+       void setLanguage(Language const * lang);
+       /// test and set guard flag
+       bool inCheck() {
+               if (incheck_)
+                       return true;
+               incheck_ = true;
+               return false;
+       }
+       void canCheck() { incheck_ = false; }
+       /// check for wrap around of current position
+       bool isWrapAround(DocIterator cursor) const;
+       ///
+       Ui::SpellcheckerUi ui;
+       ///
+       SpellcheckerWidget * p;
+       ///
+       GuiView * gv_;
+       ///
+       DockView * dv_;
+       /// current word being checked and lang code
+       WordLangTuple word_;
+       ///
+       DocIterator start_;
+       ///
+       bool incheck_;
+       ///
+       bool wrap_around_;
+};
+
+
+SpellcheckerWidget::SpellcheckerWidget(GuiView * gv, DockView * dv, QWidget * parent)
+       : QTabWidget(parent), d(new Private(this, dv))
+{
+       d->ui.setupUi(this);
+       d->gv_ = gv;
 
-       connect(closePB, SIGNAL(clicked()), this, SLOT(slotClose()));
-       connect(replacePB, SIGNAL(clicked()), this, SLOT(replace()));
-       connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
-       connect(replacePB_3, SIGNAL(clicked()), this, SLOT(accept()));
-       connect(addPB, SIGNAL(clicked()), this, SLOT(add()));
+       connect(d->ui.suggestionsLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
+               this, SLOT(on_replacePB_clicked()));
 
-       connect(replaceCO, SIGNAL(highlighted(QString)),
-               this, SLOT(replaceChanged(QString)));
-       connect(suggestionsLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
-               this, SLOT(replace()));
-       connect(suggestionsLW, SIGNAL(itemClicked(QListWidgetItem*)),
-               this, SLOT(suggestionChanged(QListWidgetItem*)));
+       // language
+       QAbstractItemModel * language_model = guiApp->languageModel();
+       // FIXME: it would be nice if sorting was enabled/disabled via a checkbox.
+       language_model->sort(0);
+       d->ui.languageCO->setModel(language_model);
+       d->ui.languageCO->setModelColumn(1);
 
-       wordED->setReadOnly(true);
+       d->ui.wordED->setReadOnly(true);
 
-       bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
-       bc().setCancel(closePB);
+       d->ui.suggestionsLW->installEventFilter(this);
 }
 
 
-void GuiSpellchecker::suggestionChanged(QListWidgetItem * item)
+SpellcheckerWidget::~SpellcheckerWidget()
 {
-       if (replaceCO->count() != 0)
-               replaceCO->setItemText(0, item->text());
+       delete d;
+}
+
+
+bool SpellcheckerWidget::eventFilter(QObject *obj, QEvent *event)
+{
+       if (obj == d->ui.suggestionsLW && event->type() == QEvent::KeyPress) {
+               QKeyEvent *e = static_cast<QKeyEvent *> (event);
+               if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) {
+                       if (d->ui.suggestionsLW->currentItem()) {
+                               on_suggestionsLW_itemClicked(d->ui.suggestionsLW->currentItem());
+                               on_replacePB_clicked();
+                       }
+                       return true;
+               } else if (e->key() == Qt::Key_Right) {
+                       if (d->ui.suggestionsLW->currentItem())
+                               on_suggestionsLW_itemClicked(d->ui.suggestionsLW->currentItem());
+                       return true;
+               }
+       }
+       // standard event processing
+       return QWidget::eventFilter(obj, event);
+}
+
+
+void SpellcheckerWidget::on_suggestionsLW_itemClicked(QListWidgetItem * item)
+{
+       if (d->ui.replaceCO->count() != 0)
+               d->ui.replaceCO->setItemText(0, item->text());
        else
-               replaceCO->addItem(item->text());
+               d->ui.replaceCO->addItem(item->text());
 
-       replaceCO->setCurrentIndex(0);
+       d->ui.replaceCO->setCurrentIndex(0);
 }
 
 
-void GuiSpellchecker::replaceChanged(const QString & str)
+void SpellcheckerWidget::on_replaceCO_highlighted(const QString & str)
 {
-       if (suggestionsLW->currentItem()
-           && suggestionsLW->currentItem()->text() == str)
+       QListWidget * lw = d->ui.suggestionsLW;
+       if (lw->currentItem() && lw->currentItem()->text() == str)
                return;
 
-       for (int i = 0; i != suggestionsLW->count(); ++i) {
-               if (suggestionsLW->item(i)->text() == str) {
-                       suggestionsLW->setCurrentRow(i);
+       for (int i = 0; i != lw->count(); ++i) {
+               if (lw->item(i)->text() == str) {
+                       lw->setCurrentRow(i);
                        break;
                }
        }
 }
 
 
-void GuiSpellchecker::reject()
+void SpellcheckerWidget::updateView()
 {
-       slotClose();
-       QDialog::reject();
+       BufferView * bv = d->gv_->documentBufferView();
+       setEnabled(bv != 0);
+       if (bv && hasFocus() && d->start_.empty()) {
+               d->start_ = bv->cursor();
+               d->check();
+       }
 }
 
 
-void GuiSpellchecker::updateContents()
+bool SpellcheckerWidget::Private::continueFromBeginning()
 {
-       // The clauses below are needed because the spellchecker
-       // has many flaws (see bugs 1950, 2218).
-       // Basically, we have to distinguish the case where a
-       // spellcheck has already been performed for the whole
-       // document (exitEarly() == true, isVisible() == false) 
-       // from the rest (exitEarly() == false, isVisible() == true).
-       // FIXME: rewrite the whole beast!
-       static bool check_after_early_exit;
-       if (exitEarly()) {
-               // a spellcheck has already been performed,
-               check();
-               check_after_early_exit = true;
+       QMessageBox::StandardButton const answer = QMessageBox::question(p,
+               qt_("Spell Checker"),
+               qt_("We reached the end of the document, would you like to "
+                       "continue from the beginning?"),
+               QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+       if (answer == QMessageBox::No) {
+               dv_->hide();
+               return false;
        }
-       else if (isVisible()) {
-               // the above check triggers a second update,
-               // and isVisible() is true then. Prevent a
-               // second check that skips the first word
-               if (check_after_early_exit)
-                       // don't check, but reset the bool.
-                       // business as usual after this.
-                       check_after_early_exit = false;
-               else
-                       // perform spellcheck (default case)
-                       check();
+       dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
+       wrap_around_ = true;
+       return true;
+}
+
+bool SpellcheckerWidget::Private::isWrapAround(DocIterator cursor) const
+{
+       return wrap_around_ && start_.buffer() == cursor.buffer() && start_ < cursor;
+}
+
+
+void SpellcheckerWidget::Private::forward()
+{
+       BufferView * bv = gv_->documentBufferView();
+       DocIterator from = bv->cursor();
+
+       dispatch(FuncRequest(LFUN_ESCAPE));
+       dispatch(FuncRequest(LFUN_CHAR_FORWARD));
+       if (bv->cursor().depth() <= 1 && bv->cursor().atLastPos()) {
+               continueFromBeginning();
+               return;
+       }
+       if (from == bv->cursor()) {
+               //FIXME we must be at the end of a cell
+               dispatch(FuncRequest(LFUN_CHAR_FORWARD));
+       }
+       if (isWrapAround(bv->cursor())) {
+               dv_->hide();
        }
 }
 
 
-void GuiSpellchecker::accept()
+void SpellcheckerWidget::on_languageCO_activated(int index)
+{
+       string const lang =
+               fromqstr(d->ui.languageCO->itemData(index).toString());
+       if (!d->word_.lang() || d->word_.lang()->lang() == lang)
+               // nothing changed
+               return;
+       dispatch(FuncRequest(LFUN_LANGUAGE, lang));
+       d->check();
+}
+
+
+bool SpellcheckerWidget::initialiseParams(std::string const &)
 {
-       theSpellChecker()->accept(word_);
-       check();
+       BufferView * bv = d->gv_->documentBufferView();
+       if (bv == 0)
+               return false;
+       std::set<Language const *> languages = 
+       bv->buffer().masterBuffer()->getLanguages();
+       if (!languages.empty())
+               d->setLanguage(*languages.begin());
+       d->start_ = DocIterator();
+       d->wrap_around_ = false;
+       d->incheck_ = false;
+       return true;
 }
 
 
-void GuiSpellchecker::add()
+void SpellcheckerWidget::on_ignoreAllPB_clicked()
 {
-       theSpellChecker()->insert(word_);
-       check();
+       /// ignore all occurrences of word
+       if (d->inCheck())
+               return;
+       LYXERR(Debug::GUI, "Spellchecker: ignore all button");
+       if (d->word_.lang() && !d->word_.word().empty())
+               theSpellChecker()->accept(d->word_);
+       d->forward();
+       d->check();
+       d->canCheck();
 }
 
 
-void GuiSpellchecker::ignore()
+void SpellcheckerWidget::on_addPB_clicked()
 {
-       check();
+       /// insert word in personal dictionary
+       if (d->inCheck())
+               return;
+       LYXERR(Debug::GUI, "Spellchecker: add word button");
+       theSpellChecker()->insert(d->word_);
+       d->forward();
+       d->check();
+       d->canCheck();
 }
 
 
-void GuiSpellchecker::replace()
+void SpellcheckerWidget::on_ignorePB_clicked()
 {
-       replace(qstring_to_ucs4(replaceCO->currentText()));
+       /// ignore this occurrence of word
+       if (d->inCheck())
+               return;
+       LYXERR(Debug::GUI, "Spellchecker: ignore button");
+       d->forward();
+       d->check();
+       d->canCheck();
 }
 
 
-void GuiSpellchecker::updateSuggestions(docstring_list & words)
+void SpellcheckerWidget::on_findNextPB_clicked()
 {
-       wordED->setText(toqstr(word_.word()));
-       suggestionsLW->clear();
+       if (d->inCheck())
+               return;
+       docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
+       docstring const datastring = find2string(textfield,
+                               true, true, true);
+       LYXERR(Debug::GUI, "Spellchecker: find next (" << textfield << ")");
+       dispatch(FuncRequest(LFUN_WORD_FIND, datastring));
+       d->canCheck();
+}
+
 
-       if (words.empty() == 0) {
-               suggestionChanged(new QListWidgetItem(wordED->text()));
+void SpellcheckerWidget::on_replacePB_clicked()
+{
+       if (d->inCheck())
                return;
-       }
-       for (size_t i = 0; i != words.size(); ++i)
-               suggestionsLW->addItem(toqstr(words[i]));
+       docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
+       docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
+       docstring const datastring = replace2string(replacement, textfield,
+               true, true, false, false);
+
+       LYXERR(Debug::GUI, "Replace (" << replacement << ")");
+       dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
+       d->forward();
+       d->check();
+       d->canCheck();
+}
 
-       suggestionChanged(suggestionsLW->item(0));
-       suggestionsLW->setCurrentRow(0);
+
+void SpellcheckerWidget::on_replaceAllPB_clicked()
+{
+       if (d->inCheck())
+               return;
+       docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
+       docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
+       docstring const datastring = replace2string(replacement, textfield,
+               true, true, true, true);
+
+       LYXERR(Debug::GUI, "Replace all (" << replacement << ")");
+       dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
+       d->forward();
+       d->check(); // continue spellchecking
+       d->canCheck();
 }
 
 
-bool GuiSpellchecker::initialiseParams(string const &)
+void SpellcheckerWidget::Private::updateSuggestions(docstring_list & words)
 {
-       LYXERR(Debug::GUI, "Spellchecker::initialiseParams");
+       QString const suggestion = toqstr(word_.word());
+       ui.wordED->setText(suggestion);
+       QListWidget * lw = ui.suggestionsLW;
+       lw->clear();
 
-       if (!theSpellChecker())
-               return false;
+       if (words.empty()) {
+               p->on_suggestionsLW_itemClicked(new QListWidgetItem(suggestion));
+               return;
+       }
+       for (size_t i = 0; i != words.size(); ++i)
+               lw->addItem(toqstr(words[i]));
 
-       DocIterator const begin = doc_iterator_begin(&buffer());
-       Cursor const & cur = bufferview()->cursor();
-       progress_ = countWords(begin, cur);
-       total_ = progress_ + countWords(cur, doc_iterator_end(&buffer()));
-       count_ = 0;
-       return true;
+       p->on_suggestionsLW_itemClicked(lw->item(0));
+       lw->setCurrentRow(0);
 }
 
 
-void GuiSpellchecker::clearParams()
+void SpellcheckerWidget::Private::setLanguage(Language const * lang)
 {
-       LYXERR(Debug::GUI, "Spellchecker::clearParams");
+       int const pos = ui.languageCO->findData(toqstr(lang->lang()));
+       if (pos != -1)
+               ui.languageCO->setCurrentIndex(pos);
 }
 
 
-void GuiSpellchecker::check()
+void SpellcheckerWidget::Private::check()
 {
-       LYXERR(Debug::GUI, "Check the spelling of a word");
+       BufferView * bv = gv_->documentBufferView();
+       if (!bv || bv->buffer().text().empty())
+               return;
 
-       DocIterator from = bufferview()->cursor();
-       while (from && from.pos() && isLetter(from))
-               from.backwardPos();
+       DocIterator from = bv->cursor();
        DocIterator to;
-       exitEarly_ = false;
        WordLangTuple word_lang;
        docstring_list suggestions;
 
+       LYXERR(Debug::GUI, "Spellchecker: start check at " << from);
        int progress;
        try {
-               progress = buffer().spellCheck(from, to, word_lang, suggestions);
+               progress = bv->buffer().spellCheck(from, to, word_lang, suggestions);
        } catch (ExceptionMessage const & message) {
                if (message.type_ == WarningException) {
                        Alert::warning(message.title_, message.details_);
-                       slotClose();
                        return;
                }
                throw message;
        }
-       LYXERR(Debug::GUI, "Found word \"" << word_lang.word() << "\"");
-       count_ += progress;
-       progress_ += progress;
 
        // end of document
-       if (from == to) {
-               showSummary();
-               exitEarly_ = true;
+       if (from == doc_iterator_end(&bv->buffer())) {
+               if (wrap_around_ || start_ == doc_iterator_begin(&bv->buffer())) {
+                       dv_->hide();
+                       return;
+               }
+               if (continueFromBeginning())
+                       check();
+               return;
+       }
+
+       if (isWrapAround(from)) {
+               dv_->hide();
                return;
        }
+
        word_ = word_lang;
 
-       int const progress_bar = total_
-               ? int(100.0 * float(progress_)/total_) : 100;
-       LYXERR(Debug::GUI, "Updating spell progress.");
-       // set progress bar
-       spellcheckPR->setValue(progress_bar);
        // set suggestions
        updateSuggestions(suggestions);
+       // set language
+       setLanguage(word_lang.lang());
 
-       // FIXME: if we used a lfun like in find/replace, dispatch would do
-       // that for us
+       // FIXME LFUN
+       // If we used a LFUN, dispatch would do all of this for us
        int const size = to.pos() - from.pos();
-       BufferView * bv = const_cast<BufferView *>(bufferview());
        bv->putSelectionAt(from, size, false);
+       bv->processUpdateFlags(Update::Force | Update::FitCursor);      
 }
 
 
-void GuiSpellchecker::showSummary()
+GuiSpellchecker::GuiSpellchecker(GuiView & parent,
+               Qt::DockWidgetArea area, Qt::WindowFlags flags)
+       : DockView(parent, "spellchecker", qt_("Spellchecker"),
+                  area, flags)
 {
-       if (count_ == 0) {
-               slotClose();
-               return;
-       }
-
-       docstring message;
-       if (count_ != 1)
-               message = bformat(_("%1$d words checked."), count_);
-       else
-               message = _("One word checked.");
-
-       slotClose();
-       Alert::information(_("Spelling check completed"), message);
+       widget_ = new SpellcheckerWidget(&parent, this);
+       setWidget(widget_);
+       setFocusProxy(widget_);
 }
 
 
-void GuiSpellchecker::replace(docstring const & replacement)
+GuiSpellchecker::~GuiSpellchecker()
 {
-       LYXERR(Debug::GUI, "GuiSpellchecker::replace("
-                          << to_utf8(replacement) << ")");
-       BufferView * bv = const_cast<BufferView *>(bufferview());
-       cap::replaceSelectionWithString(bv->cursor(), replacement, true);
-       bv->buffer().markDirty();
-       // If we used an LFUN, we would not need that
-       bv->processUpdateFlags(Update::Force | Update::FitCursor);
-       // fix up the count
-       --count_;
-       check();
+       setFocusProxy(0);
+       delete widget_;
 }
 
 
-void GuiSpellchecker::replaceAll(docstring const & replacement)
+void GuiSpellchecker::updateView()
 {
-       // TODO: add to list
-       replace(replacement);
+       widget_->updateView();
 }
 
 
-Dialog * createGuiSpellchecker(GuiView & lv) { return new GuiSpellchecker(lv); }
+Dialog * createGuiSpellchecker(GuiView & lv) 
+{ 
+       GuiSpellchecker * gui = new GuiSpellchecker(lv, Qt::RightDockWidgetArea);
+#ifdef Q_WS_MACX
+       gui->setFloating(true);
+#endif
+       return gui;
+}
+
 
 } // namespace frontend
 } // namespace lyx