]> git.lyx.org Git - features.git/blob - src/frontends/qt/GuiSpellchecker.cpp
99bd3c50f87741d0bc1849c31ac22586055a8e16
[features.git] / src / frontends / qt / GuiSpellchecker.cpp
1 /**
2  * \file GuiSpellchecker.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author John Levon
7  * \author Edwin Leuven
8  * \author Abdelrazak Younes
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "GuiSpellchecker.h"
16 #include "GuiApplication.h"
17
18 #include "qt_helpers.h"
19
20 #include "ui_SpellcheckerUi.h"
21
22 #include "Buffer.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
25 #include "buffer_funcs.h"
26 #include "Cursor.h"
27 #include "Text.h"
28 #include "CutAndPaste.h"
29 #include "FuncRequest.h"
30 #include "GuiView.h"
31 #include "Language.h"
32 #include "LyX.h"
33 #include "LyXRC.h"
34 #include "lyxfind.h"
35 #include "Paragraph.h"
36 #include "WordLangTuple.h"
37
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"
45
46 #include <QKeyEvent>
47 #include <QListWidgetItem>
48 #include <QMessageBox>
49
50 #include "SpellChecker.h"
51
52 #include "frontends/alert.h"
53
54 using namespace std;
55 using namespace lyx::support;
56
57 namespace lyx {
58 namespace frontend {
59
60
61 struct SpellcheckerWidget::Private
62 {
63         Private(SpellcheckerWidget * parent, DockView * dv, GuiView * gv)
64                 : p(parent), dv_(dv), gv_(gv), incheck_(false), wrap_around_(false) {}
65         ///
66         void updateView();
67         /// update from controller
68         void updateSuggestions(docstring_list & words);
69         /// move to next position after current word
70         void forward();
71         /// check text until next misspelled/unknown word
72         void check();
73         /// close the spell checker dialog
74         void hide() const;
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
83         bool inCheck() {
84                 if (incheck_)
85                         return true;
86                 incheck_ = true;
87                 return false;
88         }
89         void canCheck() { incheck_ = false; }
90         /// check for wrap around
91         void wrapAround(bool flag) {
92                 wrap_around_ = flag;
93                 if (flag) {
94                         end_ = start_;
95                 }
96         }
97         /// test for existing association with a document buffer
98         /// and test for already active check
99         bool disabled() {
100                 return gv_->documentBufferView() == nullptr || inCheck();
101         }
102         /// the cursor position of the buffer view
103         DocIterator const cursor() const;
104         /// status checks
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();
113         ///
114         Ui::SpellcheckerUi ui;
115         ///
116         SpellcheckerWidget * p;
117         ///
118         DockView * dv_;
119         ///
120         GuiView * gv_;
121         /// current word being checked and lang code
122         WordLangTuple word_;
123         /// cursor position where spell checking starts
124         DocIterator start_;
125         /// range to spell check
126         /// for selection both are non-empty
127         /// after wrap around the start position becomes the end
128         DocIterator begin_;
129         DocIterator end_;
130         ///
131         bool incheck_;
132         ///
133         bool wrap_around_;
134 };
135
136
137 SpellcheckerWidget::SpellcheckerWidget(GuiView * gv, DockView * dv, QWidget * parent)
138         : QTabWidget(parent), d(new Private(this, dv, gv))
139 {
140         d->ui.setupUi(this);
141
142         connect(d->ui.suggestionsLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
143                 this, SLOT(on_replacePB_clicked()));
144
145         // language
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);
152 }
153
154
155 SpellcheckerWidget::~SpellcheckerWidget()
156 {
157         delete d;
158 }
159
160
161 bool SpellcheckerWidget::eventFilter(QObject *obj, QEvent *event)
162 {
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();
169                         }
170                         return true;
171                 } else if (e->key() == Qt::Key_Right) {
172                         if (d->ui.suggestionsLW->currentItem())
173                                 on_suggestionsLW_itemClicked(d->ui.suggestionsLW->currentItem());
174                         return true;
175                 }
176         }
177         // standard event processing
178         return QWidget::eventFilter(obj, event);
179 }
180
181
182 void SpellcheckerWidget::on_suggestionsLW_itemClicked(QListWidgetItem * item)
183 {
184         if (d->ui.replaceCO->count() != 0)
185                 d->ui.replaceCO->setItemText(0, item->text());
186         else
187                 d->ui.replaceCO->addItem(item->text());
188
189         d->ui.replaceCO->setCurrentIndex(0);
190 }
191
192
193 void SpellcheckerWidget::on_replaceCO_highlighted(const QString & str)
194 {
195         QListWidget * lw = d->ui.suggestionsLW;
196         if (lw->currentItem() && lw->currentItem()->text() == str)
197                 return;
198
199         for (int i = 0; i != lw->count(); ++i) {
200                 if (lw->item(i)->text() == str) {
201                         lw->setCurrentRow(i);
202                         break;
203                 }
204         }
205 }
206
207
208 void SpellcheckerWidget::updateView()
209 {
210         d->updateView();
211 }
212
213
214 void SpellcheckerWidget::Private::updateView()
215 {
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();
225                                 start_ = begin_;
226                                 bv->cursor().setCursor(start_);
227                         } else {
228                                 begin_ = DocIterator();
229                                 end_   = DocIterator();
230                                 start_ = cur;
231                         }
232                         wrapAround(false);
233                         check();
234                 }
235         }
236
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);
252 }
253
254 DocIterator const SpellcheckerWidget::Private::cursor() const
255 {
256         BufferView * bv = gv_->documentBufferView();
257         return bv ? bv->cursor() : DocIterator();
258 }
259
260 bool SpellcheckerWidget::Private::continueFromBeginning()
261 {
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();
267                 hide();
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."));
275                 }
276                 return false;
277         }
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();
285                 hide();
286                 return false;
287         }
288         // there is no selection, start over from the beginning now
289         wrapAround(true);
290         dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
291         return true;
292 }
293
294 bool SpellcheckerWidget::Private::isCurrentBuffer(DocIterator const & cursor) const
295 {
296         return start_.buffer() == cursor.buffer();
297 }
298
299 bool SpellcheckerWidget::Private::atLastPos(DocIterator const & cursor) const
300 {
301         bool const valid_end = !end_.empty();
302         return cursor.depth() <= 1 && (
303                 cursor.atEnd() ||
304                 (valid_end && isCurrentBuffer(cursor) && cursor >= end_));
305 }
306
307 bool SpellcheckerWidget::Private::isWrapAround(DocIterator const & cursor) const
308 {
309         return wrap_around_ && isCurrentBuffer(cursor) && start_ < cursor;
310 }
311
312 void SpellcheckerWidget::Private::fixPositionsIfBroken()
313 {
314         DocIterator const current_ = cursor();
315         if (!isCurrentBuffer(current_)) {
316                 LYXERR(Debug::GUI, "wrong document of current cursor position " << start_);
317                 start_ = current_;
318                 begin_ = DocIterator();
319                 end_   = DocIterator();
320         }
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();
327         }
328         if (end_.fixIfBroken())
329                 LYXERR(Debug::GUI, "broken selection end position fixed " << end_);
330 }
331
332 void SpellcheckerWidget::Private::hide() const
333 {
334         BufferView * bv = gv_->documentBufferView();
335         Cursor & bvcur = bv->cursor();
336         dv_->hide();
337         if (isCurrentBuffer(bvcur)) {
338                 if (!begin_.empty() && !end_.empty()) {
339                         // restore previous selection
340                         setSelection(begin_, end_);
341                 } else {
342                         // restore cursor position
343                         bvcur.setCursor(start_);
344                         bvcur.clearSelection();
345                         bv->processUpdateFlags(Update::Force | Update::FitCursor);
346                 }
347         }
348 }
349
350 void SpellcheckerWidget::Private::setSelection(
351         DocIterator const & from, DocIterator const & to) const
352 {
353         BufferView * bv = gv_->documentBufferView();
354         DocIterator end = to;
355
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);
364         } else {
365                 // FIXME LFUN
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);
369         }
370         bv->processUpdateFlags(Update::Force | Update::FitCursor);
371 }
372
373 void SpellcheckerWidget::Private::forward()
374 {
375         DocIterator const from = cursor();
376
377         dispatch(FuncRequest(LFUN_ESCAPE));
378         fixPositionsIfBroken();
379         if (!atLastPos(cursor())) {
380                 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
381         }
382         if (atLastPos(cursor())) {
383                 return;
384         }
385         if (from == cursor()) {
386                 //FIXME we must be at the end of a cell
387                 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
388         }
389         if (isWrapAround(cursor())) {
390                 hide();
391         }
392 }
393
394
395 void SpellcheckerWidget::on_languageCO_activated(int index)
396 {
397         string const lang =
398                 fromqstr(d->ui.languageCO->itemData(index).toString());
399         if (!d->word_.lang() || d->word_.lang()->lang() == lang)
400                 // nothing changed
401                 return;
402         dispatch(FuncRequest(LFUN_LANGUAGE, lang));
403         d->check();
404 }
405
406
407 bool SpellcheckerWidget::initialiseParams(std::string const &)
408 {
409         BufferView * bv = d->gv_->documentBufferView();
410         if (bv == nullptr)
411                 return false;
412         std::set<Language const *> langs =
413                 bv->buffer().masterBuffer()->getLanguages();
414         if (!langs.empty())
415                 d->setLanguage(*langs.begin());
416         d->start_ = DocIterator();
417         d->wrapAround(false);
418         d->canCheck();
419         return true;
420 }
421
422
423 void SpellcheckerWidget::on_ignoreAllPB_clicked()
424 {
425         /// ignore all occurrences of word
426         if (d->disabled())
427                 return;
428         LYXERR(Debug::GUI, "Spellchecker: ignore all button");
429         if (d->word_.lang() && !d->word_.word().empty())
430                 theSpellChecker()->accept(d->word_);
431         d->forward();
432         d->check();
433         d->canCheck();
434 }
435
436
437 void SpellcheckerWidget::on_addPB_clicked()
438 {
439         /// insert word in personal dictionary
440         if (d->disabled())
441                 return;
442         LYXERR(Debug::GUI, "Spellchecker: add word button");
443         theSpellChecker()->insert(d->word_);
444         d->forward();
445         d->check();
446         d->canCheck();
447 }
448
449
450 void SpellcheckerWidget::on_ignorePB_clicked()
451 {
452         /// ignore this occurrence of word
453         if (d->disabled())
454                 return;
455         LYXERR(Debug::GUI, "Spellchecker: ignore button");
456         d->forward();
457         d->check();
458         d->canCheck();
459 }
460
461
462 void SpellcheckerWidget::on_findNextPB_clicked()
463 {
464         if (d->disabled())
465                 return;
466         docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
467         docstring const datastring = find2string(textfield,
468                                 true, true, true);
469         LYXERR(Debug::GUI, "Spellchecker: find next (" << textfield << ")");
470         dispatch(FuncRequest(LFUN_WORD_FIND, datastring));
471         d->canCheck();
472 }
473
474
475 void SpellcheckerWidget::on_replacePB_clicked()
476 {
477         if (d->disabled())
478                 return;
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
484                         true,   // match word
485                         false,  // all words
486                         true,   // forward
487                         false); // find next
488
489         LYXERR(Debug::GUI, "Replace (" << replacement << ")");
490         dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
491         d->forward();
492         d->check();
493         d->canCheck();
494 }
495
496
497 void SpellcheckerWidget::on_replaceAllPB_clicked()
498 {
499         if (d->disabled())
500                 return;
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
506                         true,   // match word
507                         true,   // all words
508                         true,   // forward
509                         false); // find next
510
511         LYXERR(Debug::GUI, "Replace all (" << replacement << ")");
512         dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
513         d->forward();
514         d->check(); // continue spellchecking
515         d->canCheck();
516 }
517
518
519 void SpellcheckerWidget::Private::updateSuggestions(docstring_list & words)
520 {
521         QString const suggestion = toqstr(word_.word());
522         ui.wordED->setText(suggestion);
523         QListWidget * lw = ui.suggestionsLW;
524         lw->clear();
525
526         if (words.empty()) {
527                 p->on_suggestionsLW_itemClicked(new QListWidgetItem(suggestion));
528                 return;
529         }
530         for (size_t i = 0; i != words.size(); ++i)
531                 lw->addItem(toqstr(words[i]));
532
533         p->on_suggestionsLW_itemClicked(lw->item(0));
534         lw->setCurrentRow(0);
535 }
536
537
538 void SpellcheckerWidget::Private::setLanguage(Language const * lang)
539 {
540         int const pos = ui.languageCO->findData(toqstr(lang->lang()));
541         if (pos != -1)
542                 ui.languageCO->setCurrentIndex(pos);
543 }
544
545
546 void SpellcheckerWidget::Private::check()
547 {
548         BufferView * bv = gv_->documentBufferView();
549         if (!bv || bv->buffer().text().empty())
550                 return;
551
552         fixPositionsIfBroken();
553
554         SpellChecker * speller = theSpellChecker();
555         if (speller && !speller->hasDictionary(bv->buffer().language())) {
556                 int dsize = speller->numDictionaries();
557                 if (0 == dsize) {
558                         hide();
559                         QMessageBox::information(p,
560                                 qt_("Spell Checker"),
561                                 qt_("Spell checker has no dictionaries."));
562                         return;
563                 }
564         }
565
566         DocIterator from = bv->cursor();
567         DocIterator to = isCurrentBuffer(from) ? end_ : doc_iterator_end(&bv->buffer());
568         WordLangTuple word_lang;
569         docstring_list suggestions;
570
571         LYXERR(Debug::GUI, "Spellchecker: start check at " << from);
572         try {
573                 bv->buffer().spellCheck(from, to, word_lang, suggestions);
574         } catch (ExceptionMessage const & message) {
575                 if (message.type_ == WarningException) {
576                         Alert::warning(message.title_, message.details_);
577                         return;
578                 }
579                 throw;
580         }
581
582         // end of document or selection?
583         if (atLastPos(from)) {
584                 if (isWrapAround()) {
585                         hide();
586                         return;
587                 }
588                 if (continueFromBeginning())
589                         check();
590                 return;
591         }
592
593         if (isWrapAround(from)) {
594                 hide();
595                 return;
596         }
597
598         word_ = word_lang;
599
600         // set suggestions
601         updateSuggestions(suggestions);
602         // set language
603         if (!word_lang.lang())
604                 return;
605         setLanguage(word_lang.lang());
606         // mark misspelled word
607         setSelection(from, to);
608         // enable relevant widgets
609         updateView();
610 }
611
612
613 GuiSpellchecker::GuiSpellchecker(GuiView & parent,
614                 Qt::DockWidgetArea area, Qt::WindowFlags flags)
615         : DockView(parent, "spellchecker", qt_("Spellchecker"),
616                    area, flags)
617 {
618         widget_ = new SpellcheckerWidget(&parent, this);
619         setWidget(widget_);
620         setFocusProxy(widget_);
621 #ifdef Q_OS_MAC
622         // On Mac show and floating
623         setFloating(true);
624 #endif
625 }
626
627
628 GuiSpellchecker::~GuiSpellchecker()
629 {
630         setFocusProxy(nullptr);
631         delete widget_;
632 }
633
634
635 void GuiSpellchecker::updateView()
636 {
637         widget_->updateView();
638 }
639
640
641 } // namespace frontend
642 } // namespace lyx
643
644 #include "moc_GuiSpellchecker.cpp"