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(const QString & str)
197 QListWidget * lw = d->ui.suggestionsLW;
198 if (lw->currentItem() && lw->currentItem()->text() == str)
201 for (int i = 0; i != lw->count(); ++i) {
202 if (lw->item(i)->text() == str) {
203 lw->setCurrentRow(i);
210 void SpellcheckerWidget::updateView()
216 void SpellcheckerWidget::Private::updateView()
218 BufferView * bv = gv_->documentBufferView();
219 bool const enabled = bv != nullptr;
220 // Check cursor position
221 if (enabled && p->hasFocus()) {
222 Cursor const & cur = bv->cursor();
223 if (start_.empty() || !isCurrentBuffer(cur)) {
224 if (cur.selection()) {
225 begin_ = cur.selectionBegin();
226 end_ = cur.selectionEnd();
228 bv->cursor().setCursor(start_);
230 begin_ = DocIterator();
231 end_ = DocIterator();
239 // Enable widgets as needed.
240 bool const has_word = enabled && !ui.wordED->text().isEmpty();
241 bool const can_replace = has_word && !bv->buffer().isReadonly();
242 ui.TextLabel3->setEnabled(enabled);
243 ui.wordED->setEnabled(enabled);
244 ui.ignorePB->setEnabled(has_word);
245 ui.ignoreAllPB->setEnabled(has_word);
246 ui.addPB->setEnabled(has_word);
247 ui.TextLabel1->setEnabled(can_replace);
248 ui.replaceCO->setEnabled(can_replace);
249 ui.TextLabel2->setEnabled(has_word);
250 ui.suggestionsLW->setEnabled(has_word);
251 ui.replacePB->setEnabled(can_replace);
252 ui.replaceAllPB->setEnabled(can_replace);
255 DocIterator const SpellcheckerWidget::Private::cursor() const
257 BufferView * bv = gv_->documentBufferView();
258 return bv ? bv->cursor() : DocIterator();
261 bool SpellcheckerWidget::Private::continueFromBeginning()
263 DocIterator const current_ = cursor();
264 if (isCurrentBuffer(current_) && !begin_.empty()) {
265 // selection was checked
266 // start over from beginning makes no sense
267 fixPositionsIfBroken();
269 if (current_ == start_) {
270 // no errors found... tell the user the good news
271 // so there is some feedback
272 QMessageBox::information(p,
273 qt_("Spell Checker"),
274 qt_("Spell check of the selection done, "
275 "did not find any errors."));
279 QMessageBox::StandardButton const answer = QMessageBox::question(p,
280 qt_("Spell Checker"),
281 qt_("We reached the end of the document, would you like to "
282 "continue from the beginning?"),
283 QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
284 if (answer == QMessageBox::No) {
285 fixPositionsIfBroken();
289 // there is no selection, start over from the beginning now
291 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
295 bool SpellcheckerWidget::Private::isCurrentBuffer(DocIterator const & cursor) const
297 return start_.buffer() == cursor.buffer();
300 bool SpellcheckerWidget::Private::atLastPos(DocIterator const & cursor) const
302 bool const valid_end = !end_.empty();
303 return cursor.depth() <= 1 && (
305 (valid_end && isCurrentBuffer(cursor) && cursor >= end_));
308 bool SpellcheckerWidget::Private::isWrapAround(DocIterator const & cursor) const
310 return wrap_around_ && isCurrentBuffer(cursor) && start_ < cursor;
313 void SpellcheckerWidget::Private::fixPositionsIfBroken()
315 DocIterator const current_ = cursor();
316 if (!isCurrentBuffer(current_)) {
317 LYXERR(Debug::GUI, "wrong document of current cursor position " << start_);
319 begin_ = DocIterator();
320 end_ = DocIterator();
322 if (start_.fixIfBroken())
323 LYXERR(Debug::GUI, "broken start position fixed " << start_);
324 if (begin_.fixIfBroken()) {
325 LYXERR(Debug::GUI, "broken selection begin position fixed " << begin_);
326 begin_ = DocIterator();
327 end_ = DocIterator();
329 if (end_.fixIfBroken())
330 LYXERR(Debug::GUI, "broken selection end position fixed " << end_);
333 void SpellcheckerWidget::Private::hide() const
335 BufferView * bv = gv_->documentBufferView();
336 Cursor & bvcur = bv->cursor();
338 if (isCurrentBuffer(bvcur)) {
339 if (!begin_.empty() && !end_.empty()) {
340 // restore previous selection
341 setSelection(begin_, end_);
343 // restore cursor position
344 bvcur.setCursor(start_);
345 bvcur.clearSelection();
346 bv->processUpdateFlags(Update::Force | Update::FitCursor);
351 void SpellcheckerWidget::Private::setSelection(
352 DocIterator const & from, DocIterator const & to) const
354 BufferView * bv = gv_->documentBufferView();
355 DocIterator end = to;
357 if (from.pit() != end.pit()) {
358 // there are multiple paragraphs in selection
359 Cursor & bvcur = bv->cursor();
360 bvcur.setCursor(from);
361 bvcur.clearSelection();
362 bvcur.selection(true);
363 bvcur.setCursor(end);
364 bvcur.selection(true);
367 // If we used a LFUN, dispatch would do all of this for us
368 int const size = end.pos() - from.pos();
369 bv->putSelectionAt(from, size, false);
371 bv->processUpdateFlags(Update::Force | Update::FitCursor);
374 void SpellcheckerWidget::Private::forward()
376 DocIterator const from = cursor();
378 dispatch(FuncRequest(LFUN_ESCAPE));
379 fixPositionsIfBroken();
380 if (!atLastPos(cursor())) {
381 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
383 if (atLastPos(cursor())) {
386 if (from == cursor()) {
387 //FIXME we must be at the end of a cell
388 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
390 if (isWrapAround(cursor())) {
393 // If we reached the end of the document
394 // and have not yet wrapped (which was
395 // checked above), continue from beginning
396 if (cursor().pit() == cursor().lastpit()
397 && cursor().pos() == cursor().lastpos()
398 && cursor().text()->isMainText())
399 continueFromBeginning();
403 void SpellcheckerWidget::on_languageCO_activated(int index)
406 fromqstr(d->ui.languageCO->itemData(index).toString());
407 if (!d->word_.lang() || d->word_.lang()->lang() == lang)
410 dispatch(FuncRequest(LFUN_LANGUAGE, lang));
415 bool SpellcheckerWidget::initialiseParams(std::string const &)
417 BufferView * bv = d->gv_->documentBufferView();
420 std::set<Language const *> langs =
421 bv->buffer().masterBuffer()->getLanguages();
423 d->setLanguage(*langs.begin());
424 d->start_ = DocIterator();
425 d->wrapAround(false);
431 void SpellcheckerWidget::on_skipAllPB_clicked()
433 /// ignore all occurrences of word
436 LYXERR(Debug::GUI, "Spellchecker: skip all button");
437 if (d->word_.lang() && !d->word_.word().empty())
438 theSpellChecker()->accept(d->word_);
445 void SpellcheckerWidget::on_ignoreAllPB_clicked()
447 /// ignore all occurrences of word
450 LYXERR(Debug::GUI, "Spellchecker: ignore all button");
451 if (d->word_.lang() && !d->word_.word().empty())
452 dispatch(FuncRequest(LFUN_SPELLING_ADD_LOCAL,
453 d->word_.word() + " " + from_ascii(d->word_.lang()->lang())));
460 void SpellcheckerWidget::on_addPB_clicked()
462 /// insert word in personal dictionary
465 LYXERR(Debug::GUI, "Spellchecker: add word button");
466 theSpellChecker()->insert(d->word_);
473 void SpellcheckerWidget::on_skipPB_clicked()
475 /// ignore this occurrence of word
478 LYXERR(Debug::GUI, "Spellchecker: skip button");
485 void SpellcheckerWidget::on_ignorePB_clicked()
487 /// ignore this occurrence of word
490 LYXERR(Debug::GUI, "Spellchecker: ignore button");
491 dispatch(FuncRequest(LFUN_FONT_NO_SPELLCHECK));
498 void SpellcheckerWidget::on_replacePB_clicked()
502 docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
503 docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
504 docstring const datastring =
505 replace2string(replacement, textfield,
506 true, // case sensitive
512 false); // only selection
514 LYXERR(Debug::GUI, "Replace (" << replacement << ")");
515 dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
522 void SpellcheckerWidget::on_replaceAllPB_clicked()
526 docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
527 docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
528 docstring const datastring =
529 replace2string(replacement, textfield,
530 true, // case sensitive
536 false); // only selection
538 LYXERR(Debug::GUI, "Replace all (" << replacement << ")");
539 dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
541 d->check(); // continue spellchecking
546 void SpellcheckerWidget::Private::updateSuggestions(docstring_list & words)
548 QString const suggestion = toqstr(word_.word());
549 ui.wordED->setText(suggestion);
550 QListWidget * lw = ui.suggestionsLW;
554 p->on_suggestionsLW_itemClicked(new QListWidgetItem(suggestion));
557 for (size_t i = 0; i != words.size(); ++i)
558 lw->addItem(toqstr(words[i]));
560 p->on_suggestionsLW_itemClicked(lw->item(0));
561 lw->setCurrentRow(0);
565 void SpellcheckerWidget::Private::setLanguage(Language const * lang)
567 int const pos = ui.languageCO->findData(toqstr(lang->lang()));
569 ui.languageCO->setCurrentIndex(pos);
573 void SpellcheckerWidget::Private::check()
575 BufferView * bv = gv_->documentBufferView();
576 if (!bv || bv->buffer().text().empty())
579 fixPositionsIfBroken();
581 SpellChecker * speller = theSpellChecker();
582 if (speller && !speller->hasDictionary(bv->buffer().language())) {
583 int dsize = speller->numDictionaries();
586 QMessageBox::information(p,
587 qt_("Spell Checker"),
588 qt_("Spell checker has no dictionaries."));
593 DocIterator from = bv->cursor();
594 DocIterator to = isCurrentBuffer(from) ? end_ : doc_iterator_end(&bv->buffer());
595 WordLangTuple word_lang;
596 docstring_list suggestions;
598 LYXERR(Debug::GUI, "Spellchecker: start check at " << from);
600 bv->buffer().spellCheck(from, to, word_lang, suggestions);
601 } catch (ExceptionMessage const & message) {
602 if (message.type_ == WarningException) {
603 Alert::warning(message.title_, message.details_);
609 // end of document or selection?
610 if (atLastPos(from)) {
611 if (isWrapAround()) {
615 if (continueFromBeginning())
620 if (isWrapAround(from)) {
628 updateSuggestions(suggestions);
630 if (!word_lang.lang())
632 setLanguage(word_lang.lang());
633 // mark misspelled word
634 setSelection(from, to);
635 // enable relevant widgets
640 GuiSpellchecker::GuiSpellchecker(GuiView & parent,
641 Qt::DockWidgetArea area, Qt::WindowFlags flags)
642 : DockView(parent, "spellchecker", qt_("Spellchecker"),
645 widget_ = new SpellcheckerWidget(&parent, this);
647 setFocusProxy(widget_);
649 // On Mac show and floating
655 GuiSpellchecker::~GuiSpellchecker()
657 setFocusProxy(nullptr);
662 void GuiSpellchecker::updateView()
664 widget_->updateView();
668 } // namespace frontend
671 #include "moc_GuiSpellchecker.cpp"