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 /// check for wrap around
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 bool isWrapAround(DocIterator const & cursor) const;
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
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(const QString & str)
195 QListWidget * lw = d->ui.suggestionsLW;
196 if (lw->currentItem() && lw->currentItem()->text() == str)
199 for (int i = 0; i != lw->count(); ++i) {
200 if (lw->item(i)->text() == str) {
201 lw->setCurrentRow(i);
208 void SpellcheckerWidget::updateView()
214 void SpellcheckerWidget::Private::updateView()
216 BufferView * bv = gv_->documentBufferView();
217 bool const enabled = bv != nullptr;
218 // Check cursor position
219 if (enabled && p->hasFocus()) {
220 Cursor const & cur = bv->cursor();
221 if (start_.empty() || !isCurrentBuffer(cur)) {
222 if (cur.selection()) {
223 begin_ = cur.selectionBegin();
224 end_ = cur.selectionEnd();
226 bv->cursor().setCursor(start_);
228 begin_ = DocIterator();
229 end_ = DocIterator();
237 // Enable widgets as needed.
238 bool const has_word = enabled && !ui.wordED->text().isEmpty();
239 bool const can_replace = has_word && !bv->buffer().isReadonly();
240 ui.findNextPB->setEnabled(enabled);
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 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::setSelection(
351 DocIterator const & from, DocIterator const & to) const
353 BufferView * bv = gv_->documentBufferView();
354 DocIterator end = to;
356 if (from.pit() != end.pit()) {
357 // there are multiple paragraphs in selection
358 Cursor & bvcur = bv->cursor();
359 bvcur.setCursor(from);
360 bvcur.clearSelection();
361 bvcur.selection(true);
362 bvcur.setCursor(end);
363 bvcur.selection(true);
366 // If we used a LFUN, dispatch would do all of this for us
367 int const size = end.pos() - from.pos();
368 bv->putSelectionAt(from, size, false);
370 bv->processUpdateFlags(Update::Force | Update::FitCursor);
373 void SpellcheckerWidget::Private::forward()
375 DocIterator const from = cursor();
377 dispatch(FuncRequest(LFUN_ESCAPE));
378 fixPositionsIfBroken();
379 if (!atLastPos(cursor())) {
380 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
382 if (atLastPos(cursor())) {
385 if (from == cursor()) {
386 //FIXME we must be at the end of a cell
387 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
389 if (isWrapAround(cursor())) {
395 void SpellcheckerWidget::on_languageCO_activated(int index)
398 fromqstr(d->ui.languageCO->itemData(index).toString());
399 if (!d->word_.lang() || d->word_.lang()->lang() == lang)
402 dispatch(FuncRequest(LFUN_LANGUAGE, lang));
407 bool SpellcheckerWidget::initialiseParams(std::string const &)
409 BufferView * bv = d->gv_->documentBufferView();
412 std::set<Language const *> langs =
413 bv->buffer().masterBuffer()->getLanguages();
415 d->setLanguage(*langs.begin());
416 d->start_ = DocIterator();
417 d->wrapAround(false);
423 void SpellcheckerWidget::on_ignoreAllPB_clicked()
425 /// ignore all occurrences of word
428 LYXERR(Debug::GUI, "Spellchecker: ignore all button");
429 if (d->word_.lang() && !d->word_.word().empty())
430 theSpellChecker()->accept(d->word_);
437 void SpellcheckerWidget::on_addPB_clicked()
439 /// insert word in personal dictionary
442 LYXERR(Debug::GUI, "Spellchecker: add word button");
443 theSpellChecker()->insert(d->word_);
450 void SpellcheckerWidget::on_ignorePB_clicked()
452 /// ignore this occurrence of word
455 LYXERR(Debug::GUI, "Spellchecker: ignore button");
462 void SpellcheckerWidget::on_findNextPB_clicked()
466 docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
467 docstring const datastring = find2string(textfield,
469 LYXERR(Debug::GUI, "Spellchecker: find next (" << textfield << ")");
470 dispatch(FuncRequest(LFUN_WORD_FIND, datastring));
475 void SpellcheckerWidget::on_replacePB_clicked()
479 docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
480 docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
481 docstring const datastring =
482 replace2string(replacement, textfield,
483 true, // case sensitive
489 LYXERR(Debug::GUI, "Replace (" << replacement << ")");
490 dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
497 void SpellcheckerWidget::on_replaceAllPB_clicked()
501 docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
502 docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
503 docstring const datastring =
504 replace2string(replacement, textfield,
505 true, // case sensitive
511 LYXERR(Debug::GUI, "Replace all (" << replacement << ")");
512 dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
514 // replace all wraps around
516 d->check(); // continue spellchecking
521 void SpellcheckerWidget::Private::updateSuggestions(docstring_list & words)
523 QString const suggestion = toqstr(word_.word());
524 ui.wordED->setText(suggestion);
525 QListWidget * lw = ui.suggestionsLW;
529 p->on_suggestionsLW_itemClicked(new QListWidgetItem(suggestion));
532 for (size_t i = 0; i != words.size(); ++i)
533 lw->addItem(toqstr(words[i]));
535 p->on_suggestionsLW_itemClicked(lw->item(0));
536 lw->setCurrentRow(0);
540 void SpellcheckerWidget::Private::setLanguage(Language const * lang)
542 int const pos = ui.languageCO->findData(toqstr(lang->lang()));
544 ui.languageCO->setCurrentIndex(pos);
548 void SpellcheckerWidget::Private::check()
550 BufferView * bv = gv_->documentBufferView();
551 if (!bv || bv->buffer().text().empty())
554 fixPositionsIfBroken();
556 SpellChecker * speller = theSpellChecker();
557 if (speller && !speller->hasDictionary(bv->buffer().language())) {
558 int dsize = speller->numDictionaries();
561 QMessageBox::information(p,
562 qt_("Spell Checker"),
563 qt_("Spell checker has no dictionaries."));
568 DocIterator from = bv->cursor();
569 DocIterator to = isCurrentBuffer(from) ? end_ : doc_iterator_end(&bv->buffer());
570 WordLangTuple word_lang;
571 docstring_list suggestions;
573 LYXERR(Debug::GUI, "Spellchecker: start check at " << from);
575 bv->buffer().spellCheck(from, to, word_lang, suggestions);
576 } catch (ExceptionMessage const & message) {
577 if (message.type_ == WarningException) {
578 Alert::warning(message.title_, message.details_);
584 // end of document or selection?
585 if (atLastPos(from)) {
586 if (isWrapAround()) {
590 if (continueFromBeginning())
595 if (isWrapAround(from)) {
603 updateSuggestions(suggestions);
605 if (!word_lang.lang())
607 setLanguage(word_lang.lang());
608 // mark misspelled word
609 setSelection(from, to);
610 // enable relevant widgets
615 GuiSpellchecker::GuiSpellchecker(GuiView & parent,
616 Qt::DockWidgetArea area, Qt::WindowFlags flags)
617 : DockView(parent, "spellchecker", qt_("Spellchecker"),
620 widget_ = new SpellcheckerWidget(&parent, this);
622 setFocusProxy(widget_);
624 // On Mac show and floating
630 GuiSpellchecker::~GuiSpellchecker()
632 setFocusProxy(nullptr);
637 void GuiSpellchecker::updateView()
639 widget_->updateView();
643 } // namespace frontend
646 #include "moc_GuiSpellchecker.cpp"