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)
63 : p(parent), dv_(dv), 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
73 void setSelection(DocIterator const & from, DocIterator const & to) const;
75 bool continueFromBeginning();
77 void setLanguage(Language const * lang);
78 /// test and set guard flag
85 void canCheck() { incheck_ = false; }
86 /// check for wrap around
87 void wrapAround(bool flag) {
93 bool isCurrentBuffer(DocIterator const & cursor) const;
94 bool isWrapAround(DocIterator const & cursor) const;
95 bool isWrapAround() const { return wrap_around_; }
97 bool atLastPos(DocIterator const & cursor) const;
99 Ui::SpellcheckerUi ui;
101 SpellcheckerWidget * p;
106 /// current word being checked and lang code
108 /// cursor position when spell checking starts
110 /// range to spell check
111 /// for selection both are non-empty
112 /// after wrap around the start becomes the end
122 SpellcheckerWidget::SpellcheckerWidget(GuiView * gv, DockView * dv, QWidget * parent)
123 : QTabWidget(parent), d(new Private(this, dv))
128 connect(d->ui.suggestionsLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
129 this, SLOT(on_replacePB_clicked()));
132 QAbstractItemModel * language_model = guiApp->languageModel();
133 // FIXME: it would be nice if sorting was enabled/disabled via a checkbox.
134 language_model->sort(0);
135 d->ui.languageCO->setModel(language_model);
136 d->ui.languageCO->setModelColumn(1);
138 d->ui.wordED->setReadOnly(true);
140 d->ui.suggestionsLW->installEventFilter(this);
144 SpellcheckerWidget::~SpellcheckerWidget()
150 bool SpellcheckerWidget::eventFilter(QObject *obj, QEvent *event)
152 if (obj == d->ui.suggestionsLW && event->type() == QEvent::KeyPress) {
153 QKeyEvent *e = static_cast<QKeyEvent *> (event);
154 if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) {
155 if (d->ui.suggestionsLW->currentItem()) {
156 on_suggestionsLW_itemClicked(d->ui.suggestionsLW->currentItem());
157 on_replacePB_clicked();
160 } else if (e->key() == Qt::Key_Right) {
161 if (d->ui.suggestionsLW->currentItem())
162 on_suggestionsLW_itemClicked(d->ui.suggestionsLW->currentItem());
166 // standard event processing
167 return QWidget::eventFilter(obj, event);
171 void SpellcheckerWidget::on_suggestionsLW_itemClicked(QListWidgetItem * item)
173 if (d->ui.replaceCO->count() != 0)
174 d->ui.replaceCO->setItemText(0, item->text());
176 d->ui.replaceCO->addItem(item->text());
178 d->ui.replaceCO->setCurrentIndex(0);
182 void SpellcheckerWidget::on_replaceCO_highlighted(const QString & str)
184 QListWidget * lw = d->ui.suggestionsLW;
185 if (lw->currentItem() && lw->currentItem()->text() == str)
188 for (int i = 0; i != lw->count(); ++i) {
189 if (lw->item(i)->text() == str) {
190 lw->setCurrentRow(i);
197 void SpellcheckerWidget::updateView()
199 BufferView * bv = d->gv_->documentBufferView();
200 // we need a buffer view and the buffer has to be writable
201 bool const enabled = bv != 0 && !bv->buffer().isReadonly();
203 if (enabled && hasFocus()) {
204 Cursor const & cursor = bv->cursor();
205 if (d->start_.empty() || !d->isCurrentBuffer(cursor)) {
206 if (cursor.selection()) {
207 d->begin_ = cursor.selectionBegin();
208 d->end_ = cursor.selectionEnd();
209 d->start_ = d->begin_;
210 bv->cursor().setCursor(d->start_);
212 d->begin_ = DocIterator();
213 d->end_ = DocIterator();
216 d->wrapAround(false);
223 bool SpellcheckerWidget::Private::continueFromBeginning()
225 BufferView * bv = gv_->documentBufferView();
226 DocIterator const current_ = bv->cursor();
227 if (isCurrentBuffer(current_) && !begin_.empty()) {
228 // selection was checked
229 // start over from beginning makes no sense
231 if (current_ == start_) {
232 // no errors found... tell the user the good news
233 // so there is some feedback
234 QMessageBox::information(p,
235 qt_("Spell Checker"),
236 qt_("Spell check of the selection done, "
237 "did not find any errors."));
241 QMessageBox::StandardButton const answer = QMessageBox::question(p,
242 qt_("Spell Checker"),
243 qt_("We reached the end of the document, would you like to "
244 "continue from the beginning?"),
245 QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
246 if (answer == QMessageBox::No) {
250 // there is no selection, start over from the beginning now
252 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
256 bool SpellcheckerWidget::Private::isCurrentBuffer(DocIterator const & cursor) const
258 return start_.buffer() == cursor.buffer();
261 bool SpellcheckerWidget::Private::atLastPos(DocIterator const & cursor) const
263 bool const valid_end = !end_.empty();
264 return cursor.depth() <= 1 && (
266 (valid_end && isCurrentBuffer(cursor) && cursor >= end_));
269 bool SpellcheckerWidget::Private::isWrapAround(DocIterator const & cursor) const
271 return wrap_around_ && isCurrentBuffer(cursor) && start_ < cursor;
274 void SpellcheckerWidget::Private::hide() const
276 BufferView * bv = gv_->documentBufferView();
277 Cursor & bvcur = bv->cursor();
279 if (isCurrentBuffer(bvcur)) {
280 if (!begin_.empty() && !end_.empty()) {
281 // restore previous selection
282 setSelection(begin_, end_);
284 // restore cursor position
285 bvcur.setCursor(start_);
286 bvcur.clearSelection();
287 // spell checker may have started at (invalid) empty paragraph at end
289 bv->processUpdateFlags(Update::Force | Update::FitCursor);
294 void SpellcheckerWidget::Private::setSelection(
295 DocIterator const & from, DocIterator const & to) const
297 BufferView * bv = gv_->documentBufferView();
298 DocIterator end = to;
300 // spell checker corrections may have invalidated the end
303 if (from.pit() != end.pit()) {
304 // there are multiple paragraphs in selection
305 Cursor & bvcur = bv->cursor();
306 bvcur.setCursor(from);
307 bvcur.clearSelection();
308 bvcur.setSelection(true);
309 bvcur.setCursor(end);
310 bvcur.setSelection(true);
313 // If we used a LFUN, dispatch would do all of this for us
314 int const size = end.pos() - from.pos();
315 bv->putSelectionAt(from, size, false);
317 bv->processUpdateFlags(Update::Force | Update::FitCursor);
320 void SpellcheckerWidget::Private::forward()
322 BufferView * bv = gv_->documentBufferView();
323 DocIterator const from = bv->cursor();
325 dispatch(FuncRequest(LFUN_ESCAPE));
326 if (!atLastPos(bv->cursor())) {
327 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
329 if (atLastPos(bv->cursor())) {
332 if (from == bv->cursor()) {
333 //FIXME we must be at the end of a cell
334 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
336 if (isWrapAround(bv->cursor())) {
342 void SpellcheckerWidget::on_languageCO_activated(int index)
345 fromqstr(d->ui.languageCO->itemData(index).toString());
346 if (!d->word_.lang() || d->word_.lang()->lang() == lang)
349 dispatch(FuncRequest(LFUN_LANGUAGE, lang));
354 bool SpellcheckerWidget::initialiseParams(std::string const &)
356 BufferView * bv = d->gv_->documentBufferView();
359 std::set<Language const *> languages =
360 bv->buffer().masterBuffer()->getLanguages();
361 if (!languages.empty())
362 d->setLanguage(*languages.begin());
363 d->start_ = DocIterator();
364 d->wrapAround(false);
370 void SpellcheckerWidget::on_ignoreAllPB_clicked()
372 /// ignore all occurrences of word
375 LYXERR(Debug::GUI, "Spellchecker: ignore all button");
376 if (d->word_.lang() && !d->word_.word().empty())
377 theSpellChecker()->accept(d->word_);
384 void SpellcheckerWidget::on_addPB_clicked()
386 /// insert word in personal dictionary
389 LYXERR(Debug::GUI, "Spellchecker: add word button");
390 theSpellChecker()->insert(d->word_);
397 void SpellcheckerWidget::on_ignorePB_clicked()
399 /// ignore this occurrence of word
402 LYXERR(Debug::GUI, "Spellchecker: ignore button");
409 void SpellcheckerWidget::on_findNextPB_clicked()
413 docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
414 docstring const datastring = find2string(textfield,
416 LYXERR(Debug::GUI, "Spellchecker: find next (" << textfield << ")");
417 dispatch(FuncRequest(LFUN_WORD_FIND, datastring));
422 void SpellcheckerWidget::on_replacePB_clicked()
426 docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
427 docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
428 docstring const datastring = replace2string(replacement, textfield,
429 true, true, false, false);
431 LYXERR(Debug::GUI, "Replace (" << replacement << ")");
432 dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
439 void SpellcheckerWidget::on_replaceAllPB_clicked()
443 docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
444 docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
445 docstring const datastring = replace2string(replacement, textfield,
446 true, true, true, true);
448 LYXERR(Debug::GUI, "Replace all (" << replacement << ")");
449 dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
451 d->check(); // continue spellchecking
456 void SpellcheckerWidget::Private::updateSuggestions(docstring_list & words)
458 QString const suggestion = toqstr(word_.word());
459 ui.wordED->setText(suggestion);
460 QListWidget * lw = ui.suggestionsLW;
464 p->on_suggestionsLW_itemClicked(new QListWidgetItem(suggestion));
467 for (size_t i = 0; i != words.size(); ++i)
468 lw->addItem(toqstr(words[i]));
470 p->on_suggestionsLW_itemClicked(lw->item(0));
471 lw->setCurrentRow(0);
475 void SpellcheckerWidget::Private::setLanguage(Language const * lang)
477 int const pos = ui.languageCO->findData(toqstr(lang->lang()));
479 ui.languageCO->setCurrentIndex(pos);
483 void SpellcheckerWidget::Private::check()
485 BufferView * bv = gv_->documentBufferView();
486 if (!bv || bv->buffer().text().empty())
488 SpellChecker * speller = theSpellChecker();
489 if (speller && !speller->hasDictionary(bv->buffer().language())) {
490 int dsize = speller->numDictionaries();
493 QMessageBox::information(p,
494 qt_("Spell Checker"),
495 qt_("Spell checker has no dictionaries."));
500 DocIterator from = bv->cursor();
501 DocIterator to = isCurrentBuffer(from) ? end_ : doc_iterator_end(&bv->buffer());
502 WordLangTuple word_lang;
503 docstring_list suggestions;
505 LYXERR(Debug::GUI, "Spellchecker: start check at " << from);
507 bv->buffer().spellCheck(from, to, word_lang, suggestions);
508 } catch (ExceptionMessage const & message) {
509 if (message.type_ == WarningException) {
510 Alert::warning(message.title_, message.details_);
516 // end of document or selection?
517 if (atLastPos(from)) {
518 if (isWrapAround()) {
522 if (continueFromBeginning())
527 if (isWrapAround(from)) {
535 updateSuggestions(suggestions);
537 if (!word_lang.lang())
539 setLanguage(word_lang.lang());
540 // mark misspelled word
541 setSelection(from, to);
545 GuiSpellchecker::GuiSpellchecker(GuiView & parent,
546 Qt::DockWidgetArea area, Qt::WindowFlags flags)
547 : DockView(parent, "spellchecker", qt_("Spellchecker"),
550 widget_ = new SpellcheckerWidget(&parent, this);
552 setFocusProxy(widget_);
556 GuiSpellchecker::~GuiSpellchecker()
563 void GuiSpellchecker::updateView()
565 widget_->updateView();
569 Dialog * createGuiSpellchecker(GuiView & lv)
571 GuiSpellchecker * gui = new GuiSpellchecker(lv, Qt::RightDockWidgetArea);
573 gui->setFloating(true);
579 } // namespace frontend
582 #include "moc_GuiSpellchecker.cpp"