2 * \file GuiSpellchecker.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 "GuiSpellchecker.h"
16 #include "GuiApplication.h"
18 #include "qt_helpers.h"
20 #include "ui_SpellcheckerUi.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
25 #include "buffer_funcs.h"
28 #include "CutAndPaste.h"
29 #include "FuncRequest.h"
35 #include "Paragraph.h"
36 #include "WordLangTuple.h"
38 #include "support/debug.h"
39 #include "support/docstring.h"
40 #include "support/docstring_list.h"
41 #include "support/ExceptionMessage.h"
42 #include "support/gettext.h"
43 #include "support/lstrings.h"
44 #include "support/textutils.h"
47 #include <QListWidgetItem>
48 #include <QMessageBox>
50 #include "SpellChecker.h"
52 #include "frontends/alert.h"
55 using namespace lyx::support;
61 struct SpellcheckerWidget::Private
63 Private(SpellcheckerWidget * parent, DockView * dv, GuiView * gv)
64 : p(parent), dv_(dv), gv_(gv), incheck_(false), wrap_around_(false) {}
67 /// update from controller
68 void updateSuggestions(docstring_list & words);
69 /// move to next position after current word
71 /// check text until next misspelled/unknown word
73 /// close the spell checker dialog
75 /// make/restore a selection between from and to
76 void setSelection(DocIterator const & from, DocIterator const & to) const;
77 /// if no selection was checked:
78 /// ask the user if the check should start over
79 bool continueFromBeginning();
80 /// set the given language in language chooser
81 void setLanguage(Language const * lang);
82 /// test and set guard flag
89 void canCheck() { incheck_ = false; }
90 /// set if checking already started from the beginning
91 void wrapAround(bool flag) {
97 /// test for existing association with a document buffer
98 /// and test for already active check
100 return gv_->documentBufferView() == nullptr || inCheck();
102 /// the cursor position of the buffer view
103 DocIterator const cursor() const;
105 bool isCurrentBuffer(DocIterator const & cursor) const;
106 /// return true if we ended a complete cycle
107 bool isWrapAround(DocIterator const & cursor) const;
108 /// returns true if we did already start from the beginning
109 bool isWrapAround() const { return wrap_around_; }
110 bool atLastPos(DocIterator const & cursor) const;
111 /// validate the cached doc iterators
112 /// The spell checker dialog is not modal.
113 /// The user may change the buffer being checked and break the iterators.
114 void fixPositionsIfBroken();
116 Ui::SpellcheckerUi ui;
118 SpellcheckerWidget * p;
123 /// current word being checked and lang code
125 /// cursor position where spell checking starts
127 /// range to spell check
128 /// for selection both are non-empty
129 /// after wrap around the start position becomes the end
134 /// Did we already start from the beginning?
139 SpellcheckerWidget::SpellcheckerWidget(GuiView * gv, DockView * dv, QWidget * parent)
140 : QTabWidget(parent), d(new Private(this, dv, gv))
144 connect(d->ui.suggestionsLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
145 this, SLOT(on_replacePB_clicked()));
148 QAbstractItemModel * language_model = guiApp->languageModel();
149 // FIXME: it would be nice if sorting was enabled/disabled via a checkbox.
150 language_model->sort(0);
151 d->ui.languageCO->setModel(language_model);
152 d->ui.languageCO->setModelColumn(1);
153 d->ui.suggestionsLW->installEventFilter(this);
157 SpellcheckerWidget::~SpellcheckerWidget()
163 bool SpellcheckerWidget::eventFilter(QObject *obj, QEvent *event)
165 if (obj == d->ui.suggestionsLW && event->type() == QEvent::KeyPress) {
166 QKeyEvent *e = static_cast<QKeyEvent *> (event);
167 if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) {
168 if (d->ui.suggestionsLW->currentItem()) {
169 on_suggestionsLW_itemClicked(d->ui.suggestionsLW->currentItem());
170 on_replacePB_clicked();
173 } else if (e->key() == Qt::Key_Right) {
174 if (d->ui.suggestionsLW->currentItem())
175 on_suggestionsLW_itemClicked(d->ui.suggestionsLW->currentItem());
179 // standard event processing
180 return QWidget::eventFilter(obj, event);
184 void SpellcheckerWidget::on_suggestionsLW_itemClicked(QListWidgetItem * item)
186 if (d->ui.replaceCO->count() != 0)
187 d->ui.replaceCO->setItemText(0, item->text());
189 d->ui.replaceCO->addItem(item->text());
191 d->ui.replaceCO->setCurrentIndex(0);
195 void SpellcheckerWidget::on_replaceCO_highlighted(int index)
197 QString const str = d->ui.replaceCO->itemText(index);
198 QListWidget * lw = d->ui.suggestionsLW;
199 if (lw->currentItem() && lw->currentItem()->text() == str)
202 for (int i = 0; i != lw->count(); ++i) {
203 if (lw->item(i)->text() == str) {
204 lw->setCurrentRow(i);
211 void SpellcheckerWidget::updateView()
217 void SpellcheckerWidget::Private::updateView()
219 BufferView * bv = gv_->documentBufferView();
220 bool const enabled = bv != nullptr;
221 // Check cursor position
222 if (enabled && p->hasFocus()) {
223 Cursor const & cur = bv->cursor();
224 if (start_.empty() || !isCurrentBuffer(cur)) {
225 if (cur.selection()) {
226 begin_ = cur.selectionBegin();
227 end_ = cur.selectionEnd();
229 bv->cursor().setCursor(start_);
231 begin_ = DocIterator();
232 end_ = DocIterator();
240 // Enable widgets as needed.
241 bool const has_word = enabled && !ui.wordED->text().isEmpty();
242 bool const can_replace = has_word && !bv->buffer().isReadonly();
243 ui.TextLabel3->setEnabled(enabled);
244 ui.wordED->setEnabled(enabled);
245 ui.ignorePB->setEnabled(has_word);
246 ui.ignoreAllPB->setEnabled(has_word);
247 ui.addPB->setEnabled(has_word);
248 ui.TextLabel1->setEnabled(can_replace);
249 ui.replaceCO->setEnabled(can_replace);
250 ui.TextLabel2->setEnabled(has_word);
251 ui.suggestionsLW->setEnabled(has_word);
252 ui.replacePB->setEnabled(can_replace);
253 ui.replaceAllPB->setEnabled(can_replace);
256 DocIterator const SpellcheckerWidget::Private::cursor() const
258 BufferView * bv = gv_->documentBufferView();
259 return bv ? bv->cursor() : DocIterator();
262 bool SpellcheckerWidget::Private::continueFromBeginning()
264 DocIterator const current_ = cursor();
265 if (isCurrentBuffer(current_) && !begin_.empty()) {
266 // selection was checked
267 // start over from beginning makes no sense
268 fixPositionsIfBroken();
270 if (current_ == start_) {
271 // no errors found... tell the user the good news
272 // so there is some feedback
273 QMessageBox::information(p,
274 qt_("Spell Checker"),
275 qt_("Spell check of the selection done, "
276 "did not find any errors."));
280 QMessageBox::StandardButton const answer = QMessageBox::question(p,
281 qt_("Spell Checker"),
282 qt_("We reached the end of the document, would you like to "
283 "continue from the beginning?"),
284 QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
285 if (answer == QMessageBox::No) {
286 fixPositionsIfBroken();
290 // there is no selection, start over from the beginning now
292 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
296 bool SpellcheckerWidget::Private::isCurrentBuffer(DocIterator const & cursor) const
298 return start_.buffer() == cursor.buffer();
301 bool SpellcheckerWidget::Private::atLastPos(DocIterator const & cursor) const
303 bool const valid_end = !end_.empty();
304 return cursor.depth() <= 1 && (
306 (valid_end && isCurrentBuffer(cursor) && cursor >= end_));
309 bool SpellcheckerWidget::Private::isWrapAround(DocIterator const & cursor) const
311 return wrap_around_ && isCurrentBuffer(cursor) && start_ < cursor;
314 void SpellcheckerWidget::Private::fixPositionsIfBroken()
316 DocIterator const current_ = cursor();
317 if (!isCurrentBuffer(current_)) {
318 LYXERR(Debug::GUI, "wrong document of current cursor position " << start_);
320 begin_ = DocIterator();
321 end_ = DocIterator();
323 if (start_.fixIfBroken())
324 LYXERR(Debug::GUI, "broken start position fixed " << start_);
325 if (begin_.fixIfBroken()) {
326 LYXERR(Debug::GUI, "broken selection begin position fixed " << begin_);
327 begin_ = DocIterator();
328 end_ = DocIterator();
330 if (end_.fixIfBroken())
331 LYXERR(Debug::GUI, "broken selection end position fixed " << end_);
334 void SpellcheckerWidget::Private::hide() const
336 BufferView * bv = gv_->documentBufferView();
337 Cursor & bvcur = bv->cursor();
339 if (isCurrentBuffer(bvcur)) {
340 if (!begin_.empty() && !end_.empty()) {
341 // restore previous selection
342 setSelection(begin_, end_);
344 // restore cursor position
345 bvcur.setCursor(start_);
346 bvcur.clearSelection();
347 bv->processUpdateFlags(Update::Force | Update::FitCursor);
352 void SpellcheckerWidget::Private::setSelection(
353 DocIterator const & from, DocIterator const & to) const
355 BufferView * bv = gv_->documentBufferView();
356 DocIterator end = to;
358 if (from.pit() != end.pit()) {
359 // there are multiple paragraphs in selection
360 Cursor & bvcur = bv->cursor();
361 bvcur.setCursor(from);
362 bvcur.clearSelection();
363 bvcur.selection(true);
364 bvcur.setCursor(end);
365 bvcur.selection(true);
368 // If we used a LFUN, dispatch would do all of this for us
369 int const size = end.pos() - from.pos();
370 bv->putSelectionAt(from, size, false);
372 bv->processUpdateFlags(Update::Force | Update::FitCursor);
375 void SpellcheckerWidget::Private::forward()
377 DocIterator const from = cursor();
379 dispatch(FuncRequest(LFUN_ESCAPE));
380 fixPositionsIfBroken();
381 if (!atLastPos(cursor())) {
382 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
384 if (atLastPos(cursor())) {
387 if (from == cursor()) {
388 //FIXME we must be at the end of a cell
389 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
391 if (isWrapAround(cursor())) {
394 // If we reached the end of the document
395 // and have not yet wrapped (which was
396 // checked above), continue from beginning
397 if (cursor().pit() == cursor().lastpit()
398 && cursor().pos() == cursor().lastpos()
399 && cursor().text()->isMainText())
400 continueFromBeginning();
404 void SpellcheckerWidget::on_languageCO_activated(int index)
407 fromqstr(d->ui.languageCO->itemData(index).toString());
408 if (!d->word_.lang() || d->word_.lang()->lang() == lang)
411 dispatch(FuncRequest(LFUN_LANGUAGE, lang));
416 bool SpellcheckerWidget::initialiseParams(std::string const &)
418 BufferView * bv = d->gv_->documentBufferView();
421 std::set<Language const *> langs =
422 bv->buffer().masterBuffer()->getLanguages();
424 d->setLanguage(*langs.begin());
425 d->start_ = DocIterator();
426 d->wrapAround(false);
432 void SpellcheckerWidget::on_skipAllPB_clicked()
434 /// ignore all occurrences of word
437 LYXERR(Debug::GUI, "Spellchecker: skip all button");
438 if (d->word_.lang() && !d->word_.word().empty())
439 theSpellChecker()->accept(d->word_);
446 void SpellcheckerWidget::on_ignoreAllPB_clicked()
448 /// ignore all occurrences of word
451 LYXERR(Debug::GUI, "Spellchecker: ignore all button");
452 if (d->word_.lang() && !d->word_.word().empty())
453 dispatch(FuncRequest(LFUN_SPELLING_ADD_LOCAL,
454 d->word_.word() + " " + from_ascii(d->word_.lang()->lang())));
461 void SpellcheckerWidget::on_addPB_clicked()
463 /// insert word in personal dictionary
466 LYXERR(Debug::GUI, "Spellchecker: add word button");
467 theSpellChecker()->insert(d->word_);
474 void SpellcheckerWidget::on_skipPB_clicked()
476 /// ignore this occurrence of word
479 LYXERR(Debug::GUI, "Spellchecker: skip button");
486 void SpellcheckerWidget::on_ignorePB_clicked()
488 /// ignore this occurrence of word
491 LYXERR(Debug::GUI, "Spellchecker: ignore button");
492 dispatch(FuncRequest(LFUN_FONT_NO_SPELLCHECK));
499 void SpellcheckerWidget::on_replacePB_clicked()
503 docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
504 docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
505 docstring const datastring =
506 replace2string(replacement, textfield,
507 true, // case sensitive
513 false); // only selection
515 LYXERR(Debug::GUI, "Replace (" << replacement << ")");
516 dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
523 void SpellcheckerWidget::on_replaceAllPB_clicked()
527 docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
528 docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
529 docstring const datastring =
530 replace2string(replacement, textfield,
531 true, // case sensitive
537 false); // only selection
539 LYXERR(Debug::GUI, "Replace all (" << replacement << ")");
540 dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
542 d->check(); // continue spellchecking
547 void SpellcheckerWidget::Private::updateSuggestions(docstring_list & words)
549 QString const suggestion = toqstr(word_.word());
550 ui.wordED->setText(suggestion);
551 QListWidget * lw = ui.suggestionsLW;
555 p->on_suggestionsLW_itemClicked(new QListWidgetItem(suggestion));
558 for (size_t i = 0; i != words.size(); ++i)
559 lw->addItem(toqstr(words[i]));
561 p->on_suggestionsLW_itemClicked(lw->item(0));
562 lw->setCurrentRow(0);
566 void SpellcheckerWidget::Private::setLanguage(Language const * lang)
568 int const pos = ui.languageCO->findData(toqstr(lang->lang()));
570 ui.languageCO->setCurrentIndex(pos);
574 void SpellcheckerWidget::Private::check()
576 BufferView * bv = gv_->documentBufferView();
577 if (!bv || bv->buffer().text().empty())
580 fixPositionsIfBroken();
582 SpellChecker * speller = theSpellChecker();
583 if (speller && !speller->hasDictionary(bv->buffer().language())) {
584 int dsize = speller->numDictionaries();
587 QMessageBox::information(p,
588 qt_("Spell Checker"),
589 qt_("Spell checker has no dictionaries."));
594 DocIterator from = bv->cursor();
595 DocIterator to = isCurrentBuffer(from) ? end_ : doc_iterator_end(&bv->buffer());
596 WordLangTuple word_lang;
597 docstring_list suggestions;
599 LYXERR(Debug::GUI, "Spellchecker: start check at " << from);
601 bv->buffer().spellCheck(from, to, word_lang, suggestions);
602 } catch (ExceptionMessage const & message) {
603 if (message.type_ == WarningException) {
604 Alert::warning(message.title_, message.details_);
610 // end of document or selection?
611 if (atLastPos(from)) {
612 if (isWrapAround()) {
616 if (continueFromBeginning())
621 if (isWrapAround(from)) {
629 updateSuggestions(suggestions);
631 if (!word_lang.lang())
633 setLanguage(word_lang.lang());
634 // mark misspelled word
635 setSelection(from, to);
636 // enable relevant widgets
641 GuiSpellchecker::GuiSpellchecker(GuiView & parent,
642 Qt::DockWidgetArea area, Qt::WindowFlags flags)
643 : DockView(parent, "spellchecker", qt_("Spellchecker"),
646 widget_ = new SpellcheckerWidget(&parent, this);
648 setFocusProxy(widget_);
650 // On Mac show and floating
656 GuiSpellchecker::~GuiSpellchecker()
658 setFocusProxy(nullptr);
663 void GuiSpellchecker::updateView()
665 widget_->updateView();
669 } // namespace frontend
672 #include "moc_GuiSpellchecker.cpp"