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"
34 #include "Paragraph.h"
35 #include "WordLangTuple.h"
37 #include "support/debug.h"
38 #include "support/docstring.h"
39 #include "support/docstring_list.h"
40 #include "support/ExceptionMessage.h"
41 #include "support/gettext.h"
42 #include "support/lstrings.h"
43 #include "support/textutils.h"
46 #include <QListWidgetItem>
47 #include <QMessageBox>
49 #include "SpellChecker.h"
51 #include "frontends/alert.h"
54 using namespace lyx::support;
60 struct SpellcheckerWidget::Private
62 Private(SpellcheckerWidget * parent, DockView * dv, GuiView * gv)
63 : p(parent), dv_(dv), gv_(gv), incheck_(false), wrap_around_(false) {}
64 /// update from controller
65 void updateSuggestions(docstring_list & words);
66 /// move to next position after current word
68 /// check text until next misspelled/unknown word
70 /// close the spell checker dialog
72 /// make/restore a selection between from and to
73 void setSelection(DocIterator const & from, DocIterator const & to) const;
74 /// if no selection was checked:
75 /// ask the user if the check should start over
76 bool continueFromBeginning();
77 /// set the given language in language chooser
78 void setLanguage(Language const * lang);
79 /// test and set guard flag
86 void canCheck() { incheck_ = false; }
87 /// check for wrap around
88 void wrapAround(bool flag) {
94 /// test for existing association with a document buffer
95 /// and test for already active check
97 return gv_->documentBufferView() == 0 || inCheck();
99 /// the cursor position of the buffer view
100 DocIterator const cursor() const;
102 bool isCurrentBuffer(DocIterator const & cursor) const;
103 bool isWrapAround(DocIterator const & cursor) const;
104 bool isWrapAround() const { return wrap_around_; }
105 bool atLastPos(DocIterator const & cursor) const;
106 /// validate the cached doc iterators
107 /// The spell checker dialog is not modal.
108 /// The user may change the buffer being checked and break the iterators.
109 void fixPositionsIfBroken();
111 Ui::SpellcheckerUi ui;
113 SpellcheckerWidget * p;
118 /// current word being checked and lang code
120 /// cursor position where spell checking starts
122 /// range to spell check
123 /// for selection both are non-empty
124 /// after wrap around the start position becomes the end
134 SpellcheckerWidget::SpellcheckerWidget(GuiView * gv, DockView * dv, QWidget * parent)
135 : QTabWidget(parent), d(new Private(this, dv, gv))
139 connect(d->ui.suggestionsLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
140 this, SLOT(on_replacePB_clicked()));
143 QAbstractItemModel * language_model = guiApp->languageModel();
144 // FIXME: it would be nice if sorting was enabled/disabled via a checkbox.
145 language_model->sort(0);
146 d->ui.languageCO->setModel(language_model);
147 d->ui.languageCO->setModelColumn(1);
149 d->ui.wordED->setReadOnly(true);
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()
210 BufferView * bv = d->gv_->documentBufferView();
211 // we need a buffer view and the buffer has to be writable
212 bool const enabled = bv != 0 && !bv->buffer().isReadonly();
214 if (enabled && hasFocus()) {
215 Cursor const & cursor = bv->cursor();
216 if (d->start_.empty() || !d->isCurrentBuffer(cursor)) {
217 if (cursor.selection()) {
218 d->begin_ = cursor.selectionBegin();
219 d->end_ = cursor.selectionEnd();
220 d->start_ = d->begin_;
221 bv->cursor().setCursor(d->start_);
223 d->begin_ = DocIterator();
224 d->end_ = DocIterator();
227 d->wrapAround(false);
233 DocIterator const SpellcheckerWidget::Private::cursor() const
235 BufferView * bv = gv_->documentBufferView();
236 return bv ? bv->cursor() : DocIterator();
239 bool SpellcheckerWidget::Private::continueFromBeginning()
241 DocIterator const current_ = cursor();
242 if (isCurrentBuffer(current_) && !begin_.empty()) {
243 // selection was checked
244 // start over from beginning makes no sense
245 fixPositionsIfBroken();
247 if (current_ == start_) {
248 // no errors found... tell the user the good news
249 // so there is some feedback
250 QMessageBox::information(p,
251 qt_("Spell Checker"),
252 qt_("Spell check of the selection done, "
253 "did not find any errors."));
257 QMessageBox::StandardButton const answer = QMessageBox::question(p,
258 qt_("Spell Checker"),
259 qt_("We reached the end of the document, would you like to "
260 "continue from the beginning?"),
261 QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
262 if (answer == QMessageBox::No) {
263 fixPositionsIfBroken();
267 // there is no selection, start over from the beginning now
269 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
273 bool SpellcheckerWidget::Private::isCurrentBuffer(DocIterator const & cursor) const
275 return start_.buffer() == cursor.buffer();
278 bool SpellcheckerWidget::Private::atLastPos(DocIterator const & cursor) const
280 bool const valid_end = !end_.empty();
281 return cursor.depth() <= 1 && (
283 (valid_end && isCurrentBuffer(cursor) && cursor >= end_));
286 bool SpellcheckerWidget::Private::isWrapAround(DocIterator const & cursor) const
288 return wrap_around_ && isCurrentBuffer(cursor) && start_ < cursor;
291 void SpellcheckerWidget::Private::fixPositionsIfBroken()
293 DocIterator const current_ = cursor();
294 if (!isCurrentBuffer(current_)) {
295 LYXERR(Debug::GUI, "wrong document of current cursor position " << start_);
297 begin_ = DocIterator();
298 end_ = DocIterator();
300 if (start_.fixIfBroken())
301 LYXERR(Debug::GUI, "broken start position fixed " << start_);
302 if (begin_.fixIfBroken()) {
303 LYXERR(Debug::GUI, "broken selection begin position fixed " << begin_);
304 begin_ = DocIterator();
305 end_ = DocIterator();
307 if (end_.fixIfBroken())
308 LYXERR(Debug::GUI, "broken selection end position fixed " << end_);
311 void SpellcheckerWidget::Private::hide() const
313 BufferView * bv = gv_->documentBufferView();
314 Cursor & bvcur = bv->cursor();
316 if (isCurrentBuffer(bvcur)) {
317 if (!begin_.empty() && !end_.empty()) {
318 // restore previous selection
319 setSelection(begin_, end_);
321 // restore cursor position
322 bvcur.setCursor(start_);
323 bvcur.clearSelection();
324 bv->processUpdateFlags(Update::Force | Update::FitCursor);
329 void SpellcheckerWidget::Private::setSelection(
330 DocIterator const & from, DocIterator const & to) const
332 BufferView * bv = gv_->documentBufferView();
333 DocIterator end = to;
335 if (from.pit() != end.pit()) {
336 // there are multiple paragraphs in selection
337 Cursor & bvcur = bv->cursor();
338 bvcur.setCursor(from);
339 bvcur.clearSelection();
340 bvcur.selection(true);
341 bvcur.setCursor(end);
342 bvcur.selection(true);
345 // If we used a LFUN, dispatch would do all of this for us
346 int const size = end.pos() - from.pos();
347 bv->putSelectionAt(from, size, false);
349 bv->processUpdateFlags(Update::Force | Update::FitCursor);
352 void SpellcheckerWidget::Private::forward()
354 DocIterator const from = cursor();
356 dispatch(FuncRequest(LFUN_ESCAPE));
357 fixPositionsIfBroken();
358 if (!atLastPos(cursor())) {
359 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
361 if (atLastPos(cursor())) {
364 if (from == cursor()) {
365 //FIXME we must be at the end of a cell
366 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
368 if (isWrapAround(cursor())) {
374 void SpellcheckerWidget::on_languageCO_activated(int index)
377 fromqstr(d->ui.languageCO->itemData(index).toString());
378 if (!d->word_.lang() || d->word_.lang()->lang() == lang)
381 dispatch(FuncRequest(LFUN_LANGUAGE, lang));
386 bool SpellcheckerWidget::initialiseParams(std::string const &)
388 BufferView * bv = d->gv_->documentBufferView();
391 std::set<Language const *> languages =
392 bv->buffer().masterBuffer()->getLanguages();
393 if (!languages.empty())
394 d->setLanguage(*languages.begin());
395 d->start_ = DocIterator();
396 d->wrapAround(false);
402 void SpellcheckerWidget::on_ignoreAllPB_clicked()
404 /// ignore all occurrences of word
407 LYXERR(Debug::GUI, "Spellchecker: ignore all button");
408 if (d->word_.lang() && !d->word_.word().empty())
409 theSpellChecker()->accept(d->word_);
416 void SpellcheckerWidget::on_addPB_clicked()
418 /// insert word in personal dictionary
421 LYXERR(Debug::GUI, "Spellchecker: add word button");
422 theSpellChecker()->insert(d->word_);
429 void SpellcheckerWidget::on_ignorePB_clicked()
431 /// ignore this occurrence of word
434 LYXERR(Debug::GUI, "Spellchecker: ignore button");
441 void SpellcheckerWidget::on_findNextPB_clicked()
445 docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
446 docstring const datastring = find2string(textfield,
448 LYXERR(Debug::GUI, "Spellchecker: find next (" << textfield << ")");
449 dispatch(FuncRequest(LFUN_WORD_FIND, datastring));
454 void SpellcheckerWidget::on_replacePB_clicked()
458 docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
459 docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
460 docstring const datastring =
461 replace2string(replacement, textfield,
462 true, // case sensitive
468 LYXERR(Debug::GUI, "Replace (" << replacement << ")");
469 dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
476 void SpellcheckerWidget::on_replaceAllPB_clicked()
480 docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
481 docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
482 docstring const datastring =
483 replace2string(replacement, textfield,
484 true, // case sensitive
490 LYXERR(Debug::GUI, "Replace all (" << replacement << ")");
491 dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
493 // replace all wraps around
495 d->check(); // continue spellchecking
500 void SpellcheckerWidget::Private::updateSuggestions(docstring_list & words)
502 QString const suggestion = toqstr(word_.word());
503 ui.wordED->setText(suggestion);
504 QListWidget * lw = ui.suggestionsLW;
508 p->on_suggestionsLW_itemClicked(new QListWidgetItem(suggestion));
511 for (size_t i = 0; i != words.size(); ++i)
512 lw->addItem(toqstr(words[i]));
514 p->on_suggestionsLW_itemClicked(lw->item(0));
515 lw->setCurrentRow(0);
519 void SpellcheckerWidget::Private::setLanguage(Language const * lang)
521 int const pos = ui.languageCO->findData(toqstr(lang->lang()));
523 ui.languageCO->setCurrentIndex(pos);
527 void SpellcheckerWidget::Private::check()
529 BufferView * bv = gv_->documentBufferView();
530 if (!bv || bv->buffer().text().empty())
533 fixPositionsIfBroken();
535 SpellChecker * speller = theSpellChecker();
536 if (speller && !speller->hasDictionary(bv->buffer().language())) {
537 int dsize = speller->numDictionaries();
540 QMessageBox::information(p,
541 qt_("Spell Checker"),
542 qt_("Spell checker has no dictionaries."));
547 DocIterator from = bv->cursor();
548 DocIterator to = isCurrentBuffer(from) ? end_ : doc_iterator_end(&bv->buffer());
549 WordLangTuple word_lang;
550 docstring_list suggestions;
552 LYXERR(Debug::GUI, "Spellchecker: start check at " << from);
554 bv->buffer().spellCheck(from, to, word_lang, suggestions);
555 } catch (ExceptionMessage const & message) {
556 if (message.type_ == WarningException) {
557 Alert::warning(message.title_, message.details_);
563 // end of document or selection?
564 if (atLastPos(from)) {
565 if (isWrapAround()) {
569 if (continueFromBeginning())
574 if (isWrapAround(from)) {
582 updateSuggestions(suggestions);
584 if (!word_lang.lang())
586 setLanguage(word_lang.lang());
587 // mark misspelled word
588 setSelection(from, to);
592 GuiSpellchecker::GuiSpellchecker(GuiView & parent,
593 Qt::DockWidgetArea area, Qt::WindowFlags flags)
594 : DockView(parent, "spellchecker", qt_("Spellchecker"),
597 widget_ = new SpellcheckerWidget(&parent, this);
599 setFocusProxy(widget_);
603 GuiSpellchecker::~GuiSpellchecker()
610 void GuiSpellchecker::updateView()
612 widget_->updateView();
616 Dialog * createGuiSpellchecker(GuiView & lv)
618 GuiSpellchecker * gui = new GuiSpellchecker(lv, Qt::RightDockWidgetArea);
620 gui->setFloating(true);
626 } // namespace frontend
629 #include "moc_GuiSpellchecker.cpp"