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 isWrapAround(DocIterator cursor) const;
94 bool isWrapAround() const { return wrap_around_; }
96 bool atLastPos(DocIterator cursor) const;
98 Ui::SpellcheckerUi ui;
100 SpellcheckerWidget * p;
105 /// current word being checked and lang code
107 /// cursor position when spell checking starts
109 /// range to spell check
110 /// for selection both are non-empty
111 /// after wrap around the start becomes the end
121 SpellcheckerWidget::SpellcheckerWidget(GuiView * gv, DockView * dv, QWidget * parent)
122 : QTabWidget(parent), d(new Private(this, dv))
127 connect(d->ui.suggestionsLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
128 this, SLOT(on_replacePB_clicked()));
131 QAbstractItemModel * language_model = guiApp->languageModel();
132 // FIXME: it would be nice if sorting was enabled/disabled via a checkbox.
133 language_model->sort(0);
134 d->ui.languageCO->setModel(language_model);
135 d->ui.languageCO->setModelColumn(1);
137 d->ui.wordED->setReadOnly(true);
139 d->ui.suggestionsLW->installEventFilter(this);
143 SpellcheckerWidget::~SpellcheckerWidget()
149 bool SpellcheckerWidget::eventFilter(QObject *obj, QEvent *event)
151 if (obj == d->ui.suggestionsLW && event->type() == QEvent::KeyPress) {
152 QKeyEvent *e = static_cast<QKeyEvent *> (event);
153 if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) {
154 if (d->ui.suggestionsLW->currentItem()) {
155 on_suggestionsLW_itemClicked(d->ui.suggestionsLW->currentItem());
156 on_replacePB_clicked();
159 } else if (e->key() == Qt::Key_Right) {
160 if (d->ui.suggestionsLW->currentItem())
161 on_suggestionsLW_itemClicked(d->ui.suggestionsLW->currentItem());
165 // standard event processing
166 return QWidget::eventFilter(obj, event);
170 void SpellcheckerWidget::on_suggestionsLW_itemClicked(QListWidgetItem * item)
172 if (d->ui.replaceCO->count() != 0)
173 d->ui.replaceCO->setItemText(0, item->text());
175 d->ui.replaceCO->addItem(item->text());
177 d->ui.replaceCO->setCurrentIndex(0);
181 void SpellcheckerWidget::on_replaceCO_highlighted(const QString & str)
183 QListWidget * lw = d->ui.suggestionsLW;
184 if (lw->currentItem() && lw->currentItem()->text() == str)
187 for (int i = 0; i != lw->count(); ++i) {
188 if (lw->item(i)->text() == str) {
189 lw->setCurrentRow(i);
196 void SpellcheckerWidget::updateView()
198 BufferView * bv = d->gv_->documentBufferView();
199 // we need a buffer view and the buffer has to be writable
200 bool const enabled = bv != 0 && !bv->buffer().isReadonly();
202 if (enabled && hasFocus()) {
203 Cursor const & cursor = bv->cursor();
204 if (d->start_.empty() || d->start_.buffer() != cursor.buffer()) {
205 if (cursor.selection()) {
206 d->begin_ = cursor.selectionBegin();
207 d->end_ = cursor.selectionEnd();
208 d->start_ = d->begin_;
209 bv->cursor().setCursor(d->start_);
211 d->begin_ = DocIterator();
212 d->end_ = DocIterator();
215 d->wrapAround(false);
222 bool SpellcheckerWidget::Private::continueFromBeginning()
224 BufferView * bv = gv_->documentBufferView();
225 if (!begin_.empty()) {
226 // selection was checked
227 // start over from beginning makes no sense
228 DocIterator current_ = bv->cursor();
230 if (current_ == start_) {
231 // no errors found... tell the user the good news
232 // so there is some feedback
233 QMessageBox::information(p,
234 qt_("Spell Checker"),
235 qt_("Spell check of the selection done, "
236 "did not find any errors."));
240 QMessageBox::StandardButton const answer = QMessageBox::question(p,
241 qt_("Spell Checker"),
242 qt_("We reached the end of the document, would you like to "
243 "continue from the beginning?"),
244 QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
245 if (answer == QMessageBox::No) {
249 // there is no selection, start over from the beginning now
251 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
255 bool SpellcheckerWidget::Private::atLastPos(DocIterator cursor) const
257 bool const valid_end = !end_.empty();
258 return cursor.depth() <= 1 && (
260 (valid_end && cursor >= end_));
263 bool SpellcheckerWidget::Private::isWrapAround(DocIterator cursor) const
265 return wrap_around_ && start_ < cursor;
268 void SpellcheckerWidget::Private::hide() const
271 if (!begin_.empty() && !end_.empty()) {
272 // restore previous selection
273 setSelection(begin_, end_);
275 // restore cursor position
276 BufferView * bv = gv_->documentBufferView();
277 Cursor & bvcur = bv->cursor();
278 bvcur.setCursor(start_);
279 bvcur.clearSelection();
280 bv->processUpdateFlags(Update::Force | Update::FitCursor);
284 void SpellcheckerWidget::Private::setSelection(
285 DocIterator const & from, DocIterator const & to) const
287 BufferView * bv = gv_->documentBufferView();
288 DocIterator end = to;
290 // spell checker corrections may have invalidated the end
293 if (from.pit() != end.pit()) {
294 // there are multiple paragraphs in selection
295 Cursor & bvcur = bv->cursor();
296 bvcur.setCursor(from);
297 bvcur.clearSelection();
298 bvcur.setSelection(true);
299 bvcur.setCursor(end);
300 bvcur.setSelection(true);
303 // If we used a LFUN, dispatch would do all of this for us
304 int const size = end.pos() - from.pos();
305 bv->putSelectionAt(from, size, false);
307 bv->processUpdateFlags(Update::Force | Update::FitCursor);
310 void SpellcheckerWidget::Private::forward()
312 BufferView * bv = gv_->documentBufferView();
313 DocIterator from = bv->cursor();
315 dispatch(FuncRequest(LFUN_ESCAPE));
316 if (!atLastPos(bv->cursor())) {
317 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
319 if (atLastPos(bv->cursor())) {
322 if (from == bv->cursor()) {
323 //FIXME we must be at the end of a cell
324 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
326 if (isWrapAround(bv->cursor())) {
332 void SpellcheckerWidget::on_languageCO_activated(int index)
335 fromqstr(d->ui.languageCO->itemData(index).toString());
336 if (!d->word_.lang() || d->word_.lang()->lang() == lang)
339 dispatch(FuncRequest(LFUN_LANGUAGE, lang));
344 bool SpellcheckerWidget::initialiseParams(std::string const &)
346 BufferView * bv = d->gv_->documentBufferView();
349 std::set<Language const *> languages =
350 bv->buffer().masterBuffer()->getLanguages();
351 if (!languages.empty())
352 d->setLanguage(*languages.begin());
353 d->start_ = DocIterator();
354 d->wrapAround(false);
360 void SpellcheckerWidget::on_ignoreAllPB_clicked()
362 /// ignore all occurrences of word
365 LYXERR(Debug::GUI, "Spellchecker: ignore all button");
366 if (d->word_.lang() && !d->word_.word().empty())
367 theSpellChecker()->accept(d->word_);
374 void SpellcheckerWidget::on_addPB_clicked()
376 /// insert word in personal dictionary
379 LYXERR(Debug::GUI, "Spellchecker: add word button");
380 theSpellChecker()->insert(d->word_);
387 void SpellcheckerWidget::on_ignorePB_clicked()
389 /// ignore this occurrence of word
392 LYXERR(Debug::GUI, "Spellchecker: ignore button");
399 void SpellcheckerWidget::on_findNextPB_clicked()
403 docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
404 docstring const datastring = find2string(textfield,
406 LYXERR(Debug::GUI, "Spellchecker: find next (" << textfield << ")");
407 dispatch(FuncRequest(LFUN_WORD_FIND, datastring));
412 void SpellcheckerWidget::on_replacePB_clicked()
416 docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
417 docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
418 docstring const datastring = replace2string(replacement, textfield,
419 true, true, false, false);
421 LYXERR(Debug::GUI, "Replace (" << replacement << ")");
422 dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
429 void SpellcheckerWidget::on_replaceAllPB_clicked()
433 docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
434 docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
435 docstring const datastring = replace2string(replacement, textfield,
436 true, true, true, true);
438 LYXERR(Debug::GUI, "Replace all (" << replacement << ")");
439 dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
441 d->check(); // continue spellchecking
446 void SpellcheckerWidget::Private::updateSuggestions(docstring_list & words)
448 QString const suggestion = toqstr(word_.word());
449 ui.wordED->setText(suggestion);
450 QListWidget * lw = ui.suggestionsLW;
454 p->on_suggestionsLW_itemClicked(new QListWidgetItem(suggestion));
457 for (size_t i = 0; i != words.size(); ++i)
458 lw->addItem(toqstr(words[i]));
460 p->on_suggestionsLW_itemClicked(lw->item(0));
461 lw->setCurrentRow(0);
465 void SpellcheckerWidget::Private::setLanguage(Language const * lang)
467 int const pos = ui.languageCO->findData(toqstr(lang->lang()));
469 ui.languageCO->setCurrentIndex(pos);
473 void SpellcheckerWidget::Private::check()
475 BufferView * bv = gv_->documentBufferView();
476 if (!bv || bv->buffer().text().empty())
479 DocIterator from = bv->cursor();
480 DocIterator to = end_;
481 WordLangTuple word_lang;
482 docstring_list suggestions;
484 LYXERR(Debug::GUI, "Spellchecker: start check at " << from);
486 bv->buffer().spellCheck(from, to, word_lang, suggestions);
487 } catch (ExceptionMessage const & message) {
488 if (message.type_ == WarningException) {
489 Alert::warning(message.title_, message.details_);
495 // end of document or selection?
496 if (atLastPos(from)) {
497 if (isWrapAround()) {
501 if (continueFromBeginning())
506 if (isWrapAround(from)) {
514 updateSuggestions(suggestions);
516 if (!word_lang.lang())
518 setLanguage(word_lang.lang());
519 // mark misspelled word
520 setSelection(from, to);
524 GuiSpellchecker::GuiSpellchecker(GuiView & parent,
525 Qt::DockWidgetArea area, Qt::WindowFlags flags)
526 : DockView(parent, "spellchecker", qt_("Spellchecker"),
529 widget_ = new SpellcheckerWidget(&parent, this);
531 setFocusProxy(widget_);
535 GuiSpellchecker::~GuiSpellchecker()
542 void GuiSpellchecker::updateView()
544 widget_->updateView();
548 Dialog * createGuiSpellchecker(GuiView & lv)
550 GuiSpellchecker * gui = new GuiSpellchecker(lv, Qt::RightDockWidgetArea);
552 gui->setFloating(true);
558 } // namespace frontend
561 #include "moc_GuiSpellchecker.cpp"