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 /// if no selection was checked:
76 /// ask the user if the check should start over
77 bool continueFromBeginning();
78 /// set the given language in language chooser
79 void setLanguage(Language const * lang);
80 /// test and set guard flag
87 void canCheck() { incheck_ = false; }
88 /// set if checking already started from the beginning
89 void wrapAround(bool flag) {
95 /// test for existing association with a document buffer
96 /// and test for already active check
98 return gv_->documentBufferView() == nullptr || inCheck();
100 /// the cursor position of the buffer view
101 DocIterator const cursor() const;
103 bool isCurrentBuffer(DocIterator const & cursor) const;
104 /// return true if we ended a complete cycle
105 bool isWrapAround(DocIterator const & cursor) const;
106 /// returns true if we did already start from the beginning
107 bool isWrapAround() const { return wrap_around_; }
108 bool atLastPos(DocIterator const & cursor) const;
109 /// validate the cached doc iterators
110 /// The spell checker dialog is not modal.
111 /// The user may change the buffer being checked and break the iterators.
112 void fixPositionsIfBroken();
114 Ui::SpellcheckerUi ui;
116 SpellcheckerWidget * p;
121 /// current word being checked and lang code
123 /// cursor position where spell checking starts
125 /// range to spell check
126 /// for selection both are non-empty
127 /// after wrap around the start position becomes the end
132 /// Did we already start from the beginning?
137 SpellcheckerWidget::SpellcheckerWidget(GuiView * gv, DockView * dv, QWidget * parent)
138 : QTabWidget(parent), d(new Private(this, dv, gv))
142 connect(d->ui.suggestionsLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
143 this, SLOT(on_replacePB_clicked()));
146 QAbstractItemModel * language_model = guiApp->languageModel();
147 // FIXME: it would be nice if sorting was enabled/disabled via a checkbox.
148 language_model->sort(0);
149 d->ui.languageCO->setModel(language_model);
150 d->ui.languageCO->setModelColumn(1);
151 d->ui.suggestionsLW->installEventFilter(this);
155 SpellcheckerWidget::~SpellcheckerWidget()
161 bool SpellcheckerWidget::eventFilter(QObject *obj, QEvent *event)
163 if (obj == d->ui.suggestionsLW && event->type() == QEvent::KeyPress) {
164 QKeyEvent *e = static_cast<QKeyEvent *> (event);
165 if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) {
166 if (d->ui.suggestionsLW->currentItem()) {
167 on_suggestionsLW_itemClicked(d->ui.suggestionsLW->currentItem());
168 on_replacePB_clicked();
171 } else if (e->key() == Qt::Key_Right) {
172 if (d->ui.suggestionsLW->currentItem())
173 on_suggestionsLW_itemClicked(d->ui.suggestionsLW->currentItem());
177 // standard event processing
178 return QWidget::eventFilter(obj, event);
182 void SpellcheckerWidget::on_suggestionsLW_itemClicked(QListWidgetItem * item)
184 if (d->ui.replaceCO->count() != 0)
185 d->ui.replaceCO->setItemText(0, item->text());
187 d->ui.replaceCO->addItem(item->text());
189 d->ui.replaceCO->setCurrentIndex(0);
193 void SpellcheckerWidget::on_replaceCO_highlighted(int index)
195 QString const str = d->ui.replaceCO->itemText(index);
196 QListWidget * lw = d->ui.suggestionsLW;
197 if (lw->currentItem() && lw->currentItem()->text() == str)
200 for (int i = 0; i != lw->count(); ++i) {
201 if (lw->item(i)->text() == str) {
202 lw->setCurrentRow(i);
209 void SpellcheckerWidget::updateView()
215 void SpellcheckerWidget::Private::updateView()
217 BufferView * bv = gv_->documentBufferView();
218 bool const enabled = bv != nullptr;
219 // Check cursor position
220 if (enabled && p->hasFocus()) {
221 Cursor const & cur = bv->cursor();
222 if (start_.empty() || !isCurrentBuffer(cur)) {
223 if (cur.selection()) {
224 begin_ = cur.selectionBegin();
225 end_ = cur.selectionEnd();
227 bv->cursor().setCursor(start_);
229 begin_ = DocIterator();
230 end_ = DocIterator();
238 // Enable widgets as needed.
239 bool const has_word = enabled && !ui.wordED->text().isEmpty();
240 bool const can_replace = has_word && !bv->buffer().isReadonly();
241 ui.TextLabel3->setEnabled(enabled);
242 ui.wordED->setEnabled(enabled);
243 ui.ignorePB->setEnabled(has_word);
244 ui.ignoreAllPB->setEnabled(has_word);
245 ui.addPB->setEnabled(has_word);
246 ui.TextLabel1->setEnabled(can_replace);
247 ui.replaceCO->setEnabled(can_replace);
248 ui.TextLabel2->setEnabled(has_word);
249 ui.suggestionsLW->setEnabled(has_word);
250 ui.replacePB->setEnabled(can_replace);
251 ui.replaceAllPB->setEnabled(can_replace);
254 DocIterator const SpellcheckerWidget::Private::cursor() const
256 BufferView * bv = gv_->documentBufferView();
257 return bv ? bv->cursor() : DocIterator();
260 bool SpellcheckerWidget::Private::continueFromBeginning()
262 DocIterator const current_ = cursor();
263 if (isCurrentBuffer(current_) && !begin_.empty()) {
264 // selection was checked
265 // start over from beginning makes no sense
266 fixPositionsIfBroken();
268 if (current_ == start_) {
269 // no errors found... tell the user the good news
270 // so there is some feedback
271 QMessageBox::information(p,
272 qt_("Spell Checker"),
273 qt_("Spell check of the selection done, "
274 "did not find any errors."));
278 QMessageBox::StandardButton const answer = QMessageBox::question(p,
279 qt_("Spell Checker"),
280 qt_("We reached the end of the document, would you like to "
281 "continue from the beginning?"),
282 QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
283 if (answer == QMessageBox::No) {
284 fixPositionsIfBroken();
288 // there is no selection, start over from the beginning now
290 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
294 bool SpellcheckerWidget::Private::isCurrentBuffer(DocIterator const & cursor) const
296 return start_.buffer() == cursor.buffer();
299 bool SpellcheckerWidget::Private::atLastPos(DocIterator const & cursor) const
301 bool const valid_end = !end_.empty();
302 return cursor.depth() <= 1 && (
304 (valid_end && isCurrentBuffer(cursor) && cursor >= end_));
307 bool SpellcheckerWidget::Private::isWrapAround(DocIterator const & cursor) const
309 return wrap_around_ && isCurrentBuffer(cursor) && start_ < cursor;
312 void SpellcheckerWidget::Private::fixPositionsIfBroken()
314 DocIterator const current_ = cursor();
315 if (!isCurrentBuffer(current_)) {
316 LYXERR(Debug::GUI, "wrong document of current cursor position " << start_);
318 begin_ = DocIterator();
319 end_ = DocIterator();
321 if (start_.fixIfBroken())
322 LYXERR(Debug::GUI, "broken start position fixed " << start_);
323 if (begin_.fixIfBroken()) {
324 LYXERR(Debug::GUI, "broken selection begin position fixed " << begin_);
325 begin_ = DocIterator();
326 end_ = DocIterator();
328 if (end_.fixIfBroken())
329 LYXERR(Debug::GUI, "broken selection end position fixed " << end_);
332 void SpellcheckerWidget::Private::hide() const
334 BufferView * bv = gv_->documentBufferView();
335 Cursor & bvcur = bv->cursor();
337 if (isCurrentBuffer(bvcur)) {
338 if (!begin_.empty() && !end_.empty()) {
339 // restore previous selection
340 bv->setSelection(begin_, end_);
342 // restore cursor position
343 bvcur.setCursor(start_);
344 bvcur.clearSelection();
345 bv->processUpdateFlags(Update::Force | Update::FitCursor);
350 void SpellcheckerWidget::Private::forward()
352 DocIterator const from = cursor();
354 dispatch(FuncRequest(LFUN_ESCAPE));
355 fixPositionsIfBroken();
356 if (!atLastPos(cursor())) {
357 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
359 if (atLastPos(cursor())) {
362 if (from == cursor()) {
363 //FIXME we must be at the end of a cell
364 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
366 if (isWrapAround(cursor())) {
369 // If we reached the end of the document
370 // and have not yet wrapped (which was
371 // checked above), continue from beginning
372 if (cursor().pit() == cursor().lastpit()
373 && cursor().pos() == cursor().lastpos()
374 && cursor().text()->isMainText())
375 continueFromBeginning();
379 void SpellcheckerWidget::on_languageCO_activated(int index)
382 fromqstr(d->ui.languageCO->itemData(index).toString());
383 if (!d->word_.lang() || d->word_.lang()->lang() == lang)
386 dispatch(FuncRequest(LFUN_LANGUAGE, lang));
391 bool SpellcheckerWidget::initialiseParams(std::string const &)
393 BufferView * bv = d->gv_->documentBufferView();
396 std::set<Language const *> langs =
397 bv->buffer().masterBuffer()->getLanguages();
399 d->setLanguage(*langs.begin());
400 d->start_ = DocIterator();
401 d->wrapAround(false);
407 void SpellcheckerWidget::on_skipAllPB_clicked()
409 /// ignore all occurrences of word
412 LYXERR(Debug::GUI, "Spellchecker: skip all button");
413 if (d->word_.lang() && !d->word_.word().empty())
414 theSpellChecker()->accept(d->word_);
421 void SpellcheckerWidget::on_ignoreAllPB_clicked()
423 /// ignore all occurrences of word
426 LYXERR(Debug::GUI, "Spellchecker: ignore all button");
427 if (d->word_.lang() && !d->word_.word().empty())
428 dispatch(FuncRequest(LFUN_SPELLING_ADD_LOCAL,
429 d->word_.word() + " " + from_ascii(d->word_.lang()->lang())));
436 void SpellcheckerWidget::on_addPB_clicked()
438 /// insert word in personal dictionary
441 LYXERR(Debug::GUI, "Spellchecker: add word button");
442 theSpellChecker()->insert(d->word_);
449 void SpellcheckerWidget::on_skipPB_clicked()
451 /// ignore this occurrence of word
454 LYXERR(Debug::GUI, "Spellchecker: skip button");
461 void SpellcheckerWidget::on_ignorePB_clicked()
463 /// ignore this occurrence of word
466 LYXERR(Debug::GUI, "Spellchecker: ignore button");
467 dispatch(FuncRequest(LFUN_FONT_NO_SPELLCHECK));
474 void SpellcheckerWidget::on_replacePB_clicked()
478 docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
479 docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
480 docstring const datastring =
481 replace2string(replacement, textfield,
482 true, // case sensitive
488 false); // only selection
490 LYXERR(Debug::GUI, "Replace (" << replacement << ")");
491 dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
498 void SpellcheckerWidget::on_replaceAllPB_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 all (" << replacement << ")");
515 dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
517 d->check(); // continue spellchecking
522 void SpellcheckerWidget::Private::updateSuggestions(docstring_list & words)
524 QString const suggestion = toqstr(word_.word());
525 ui.wordED->setText(suggestion);
526 QListWidget * lw = ui.suggestionsLW;
530 p->on_suggestionsLW_itemClicked(new QListWidgetItem(suggestion));
533 for (size_t i = 0; i != words.size(); ++i)
534 lw->addItem(toqstr(words[i]));
536 p->on_suggestionsLW_itemClicked(lw->item(0));
537 lw->setCurrentRow(0);
541 void SpellcheckerWidget::Private::setLanguage(Language const * lang)
543 int const pos = ui.languageCO->findData(toqstr(lang->lang()));
545 ui.languageCO->setCurrentIndex(pos);
549 void SpellcheckerWidget::Private::check()
551 BufferView * bv = gv_->documentBufferView();
552 if (!bv || bv->buffer().text().empty())
555 fixPositionsIfBroken();
557 SpellChecker * speller = theSpellChecker();
558 if (speller && !speller->hasDictionary(bv->buffer().language())) {
559 int dsize = speller->numDictionaries();
562 QMessageBox::information(p,
563 qt_("Spell Checker"),
564 qt_("Spell checker has no dictionaries."));
569 DocIterator from = bv->cursor();
570 DocIterator to = isCurrentBuffer(from) ? end_ : doc_iterator_end(&bv->buffer());
571 WordLangTuple word_lang;
572 docstring_list suggestions;
574 LYXERR(Debug::GUI, "Spellchecker: start check at " << from);
576 bv->buffer().spellCheck(from, to, word_lang, suggestions);
577 } catch (ExceptionMessage const & message) {
578 if (message.type_ == WarningException) {
579 Alert::warning(message.title_, message.details_);
585 // end of document or selection?
586 if (atLastPos(from)) {
587 if (isWrapAround()) {
591 if (continueFromBeginning())
596 if (isWrapAround(from)) {
604 updateSuggestions(suggestions);
606 if (!word_lang.lang())
608 setLanguage(word_lang.lang());
609 // mark misspelled word
610 bv->setSelection(from, to);
611 // enable relevant widgets
616 GuiSpellchecker::GuiSpellchecker(GuiView & parent,
617 Qt::DockWidgetArea area, Qt::WindowFlags flags)
618 : DockView(parent, "spellchecker", qt_("Spellchecker"),
621 widget_ = new SpellcheckerWidget(&parent, this);
623 setFocusProxy(widget_);
625 // On Mac show and floating
631 GuiSpellchecker::~GuiSpellchecker()
633 setFocusProxy(nullptr);
638 void GuiSpellchecker::updateView()
640 widget_->updateView();
644 } // namespace frontend
647 #include "moc_GuiSpellchecker.cpp"