]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiSpellchecker.cpp
Make code a bit easier to read
[lyx.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         /// set if checking already started from the beginning
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         /// return true if we ended a complete cycle
107         bool isWrapAround(DocIterator const & cursor) const;
108         /// returns true if we did already start from the beginning
109         bool isWrapAround() const { return wrap_around_; }
110         bool atLastPos(DocIterator const & cursor) const;
111         /// validate the cached doc iterators
112         /// The spell checker dialog is not modal.
113         /// The user may change the buffer being checked and break the iterators.
114         void fixPositionsIfBroken();
115         ///
116         Ui::SpellcheckerUi ui;
117         ///
118         SpellcheckerWidget * p;
119         ///
120         DockView * dv_;
121         ///
122         GuiView * gv_;
123         /// current word being checked and lang code
124         WordLangTuple word_;
125         /// cursor position where spell checking starts
126         DocIterator start_;
127         /// range to spell check
128         /// for selection both are non-empty
129         /// after wrap around the start position becomes the end
130         DocIterator begin_;
131         DocIterator end_;
132         ///
133         bool incheck_;
134         /// Did we already start from the beginning?
135         bool wrap_around_;
136 };
137
138
139 SpellcheckerWidget::SpellcheckerWidget(GuiView * gv, DockView * dv, QWidget * parent)
140         : QTabWidget(parent), d(new Private(this, dv, gv))
141 {
142         d->ui.setupUi(this);
143
144         connect(d->ui.suggestionsLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
145                 this, SLOT(on_replacePB_clicked()));
146
147         // language
148         QAbstractItemModel * language_model = guiApp->languageModel();
149         // FIXME: it would be nice if sorting was enabled/disabled via a checkbox.
150         language_model->sort(0);
151         d->ui.languageCO->setModel(language_model);
152         d->ui.languageCO->setModelColumn(1);
153         d->ui.suggestionsLW->installEventFilter(this);
154 }
155
156
157 SpellcheckerWidget::~SpellcheckerWidget()
158 {
159         delete d;
160 }
161
162
163 bool SpellcheckerWidget::eventFilter(QObject *obj, QEvent *event)
164 {
165         if (obj == d->ui.suggestionsLW && event->type() == QEvent::KeyPress) {
166                 QKeyEvent *e = static_cast<QKeyEvent *> (event);
167                 if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) {
168                         if (d->ui.suggestionsLW->currentItem()) {
169                                 on_suggestionsLW_itemClicked(d->ui.suggestionsLW->currentItem());
170                                 on_replacePB_clicked();
171                         }
172                         return true;
173                 } else if (e->key() == Qt::Key_Right) {
174                         if (d->ui.suggestionsLW->currentItem())
175                                 on_suggestionsLW_itemClicked(d->ui.suggestionsLW->currentItem());
176                         return true;
177                 }
178         }
179         // standard event processing
180         return QWidget::eventFilter(obj, event);
181 }
182
183
184 void SpellcheckerWidget::on_suggestionsLW_itemClicked(QListWidgetItem * item)
185 {
186         if (d->ui.replaceCO->count() != 0)
187                 d->ui.replaceCO->setItemText(0, item->text());
188         else
189                 d->ui.replaceCO->addItem(item->text());
190
191         d->ui.replaceCO->setCurrentIndex(0);
192 }
193
194
195 void SpellcheckerWidget::on_replaceCO_highlighted(int index)
196 {
197         QString const str = d->ui.replaceCO->itemText(index);
198         QListWidget * lw = d->ui.suggestionsLW;
199         if (lw->currentItem() && lw->currentItem()->text() == str)
200                 return;
201
202         for (int i = 0; i != lw->count(); ++i) {
203                 if (lw->item(i)->text() == str) {
204                         lw->setCurrentRow(i);
205                         break;
206                 }
207         }
208 }
209
210
211 void SpellcheckerWidget::updateView()
212 {
213         d->updateView();
214 }
215
216
217 void SpellcheckerWidget::Private::updateView()
218 {
219         BufferView * bv = gv_->documentBufferView();
220         bool const enabled = bv != nullptr;
221         // Check cursor position
222         if (enabled && p->hasFocus()) {
223                 Cursor const & cur = bv->cursor();
224                 if (start_.empty() || !isCurrentBuffer(cur)) {
225                         if (cur.selection()) {
226                                 begin_ = cur.selectionBegin();
227                                 end_   = cur.selectionEnd();
228                                 start_ = begin_;
229                                 bv->cursor().setCursor(start_);
230                         } else {
231                                 begin_ = DocIterator();
232                                 end_   = DocIterator();
233                                 start_ = cur;
234                         }
235                         wrapAround(false);
236                         check();
237                 }
238         }
239
240         // Enable widgets as needed.
241         bool const has_word = enabled && !ui.wordED->text().isEmpty();
242         bool const can_replace = has_word && !bv->buffer().isReadonly();
243         ui.TextLabel3->setEnabled(enabled);
244         ui.wordED->setEnabled(enabled);
245         ui.ignorePB->setEnabled(has_word);
246         ui.ignoreAllPB->setEnabled(has_word);
247         ui.addPB->setEnabled(has_word);
248         ui.TextLabel1->setEnabled(can_replace);
249         ui.replaceCO->setEnabled(can_replace);
250         ui.TextLabel2->setEnabled(has_word);
251         ui.suggestionsLW->setEnabled(has_word);
252         ui.replacePB->setEnabled(can_replace);
253         ui.replaceAllPB->setEnabled(can_replace);
254 }
255
256 DocIterator const SpellcheckerWidget::Private::cursor() const
257 {
258         BufferView * bv = gv_->documentBufferView();
259         return bv ? bv->cursor() : DocIterator();
260 }
261
262 bool SpellcheckerWidget::Private::continueFromBeginning()
263 {
264         DocIterator const current_ = cursor();
265         if (isCurrentBuffer(current_) && !begin_.empty()) {
266                 // selection was checked
267                 // start over from beginning makes no sense
268                 fixPositionsIfBroken();
269                 hide();
270                 if (current_ == start_) {
271                         // no errors found... tell the user the good news
272                         // so there is some feedback
273                         QMessageBox::information(p,
274                                 qt_("Spell Checker"),
275                                 qt_("Spell check of the selection done, "
276                                         "did not find any errors."));
277                 }
278                 return false;
279         }
280         QMessageBox::StandardButton const answer = QMessageBox::question(p,
281                 qt_("Spell Checker"),
282                 qt_("We reached the end of the document, would you like to "
283                         "continue from the beginning?"),
284                 QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
285         if (answer == QMessageBox::No) {
286                 fixPositionsIfBroken();
287                 hide();
288                 return false;
289         }
290         // there is no selection, start over from the beginning now
291         wrapAround(true);
292         dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
293         return true;
294 }
295
296 bool SpellcheckerWidget::Private::isCurrentBuffer(DocIterator const & cursor) const
297 {
298         return start_.buffer() == cursor.buffer();
299 }
300
301 bool SpellcheckerWidget::Private::atLastPos(DocIterator const & cursor) const
302 {
303         bool const valid_end = !end_.empty();
304         return cursor.depth() <= 1 && (
305                 cursor.atEnd() ||
306                 (valid_end && isCurrentBuffer(cursor) && cursor >= end_));
307 }
308
309 bool SpellcheckerWidget::Private::isWrapAround(DocIterator const & cursor) const
310 {
311         return wrap_around_ && isCurrentBuffer(cursor) && start_ < cursor;
312 }
313
314 void SpellcheckerWidget::Private::fixPositionsIfBroken()
315 {
316         DocIterator const current_ = cursor();
317         if (!isCurrentBuffer(current_)) {
318                 LYXERR(Debug::GUI, "wrong document of current cursor position " << start_);
319                 start_ = current_;
320                 begin_ = DocIterator();
321                 end_   = DocIterator();
322         }
323         if (start_.fixIfBroken())
324                 LYXERR(Debug::GUI, "broken start position fixed " << start_);
325         if (begin_.fixIfBroken()) {
326                 LYXERR(Debug::GUI, "broken selection begin position fixed " << begin_);
327                 begin_ = DocIterator();
328                 end_   = DocIterator();
329         }
330         if (end_.fixIfBroken())
331                 LYXERR(Debug::GUI, "broken selection end position fixed " << end_);
332 }
333
334 void SpellcheckerWidget::Private::hide() const
335 {
336         BufferView * bv = gv_->documentBufferView();
337         Cursor & bvcur = bv->cursor();
338         dv_->hide();
339         if (isCurrentBuffer(bvcur)) {
340                 if (!begin_.empty() && !end_.empty()) {
341                         // restore previous selection
342                         setSelection(begin_, end_);
343                 } else {
344                         // restore cursor position
345                         bvcur.setCursor(start_);
346                         bvcur.clearSelection();
347                         bv->processUpdateFlags(Update::Force | Update::FitCursor);
348                 }
349         }
350 }
351
352 void SpellcheckerWidget::Private::setSelection(
353         DocIterator const & from, DocIterator const & to) const
354 {
355         BufferView * bv = gv_->documentBufferView();
356         DocIterator end = to;
357
358         if (from.pit() != end.pit()) {
359                 // there are multiple paragraphs in selection
360                 Cursor & bvcur = bv->cursor();
361                 bvcur.setCursor(from);
362                 bvcur.clearSelection();
363                 bvcur.selection(true);
364                 bvcur.setCursor(end);
365                 bvcur.selection(true);
366         } else {
367                 // FIXME LFUN
368                 // If we used a LFUN, dispatch would do all of this for us
369                 int const size = end.pos() - from.pos();
370                 bv->putSelectionAt(from, size, false);
371         }
372         bv->processUpdateFlags(Update::Force | Update::FitCursor);
373 }
374
375 void SpellcheckerWidget::Private::forward()
376 {
377         DocIterator const from = cursor();
378
379         dispatch(FuncRequest(LFUN_ESCAPE));
380         fixPositionsIfBroken();
381         if (!atLastPos(cursor())) {
382                 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
383         }
384         if (atLastPos(cursor())) {
385                 return;
386         }
387         if (from == cursor()) {
388                 //FIXME we must be at the end of a cell
389                 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
390         }
391         if (isWrapAround(cursor())) {
392                 hide();
393         }
394         // If we reached the end of the document
395         // and have not yet wrapped (which was
396         // checked above), continue from beginning
397         if (cursor().pit() == cursor().lastpit()
398             && cursor().pos() == cursor().lastpos()
399             && cursor().text()->isMainText())
400                 continueFromBeginning();
401 }
402
403
404 void SpellcheckerWidget::on_languageCO_activated(int index)
405 {
406         string const lang =
407                 fromqstr(d->ui.languageCO->itemData(index).toString());
408         if (!d->word_.lang() || d->word_.lang()->lang() == lang)
409                 // nothing changed
410                 return;
411         dispatch(FuncRequest(LFUN_LANGUAGE, lang));
412         d->check();
413 }
414
415
416 bool SpellcheckerWidget::initialiseParams(std::string const &)
417 {
418         BufferView * bv = d->gv_->documentBufferView();
419         if (bv == nullptr)
420                 return false;
421         std::set<Language const *> langs =
422                 bv->buffer().masterBuffer()->getLanguages();
423         if (!langs.empty())
424                 d->setLanguage(*langs.begin());
425         d->start_ = DocIterator();
426         d->wrapAround(false);
427         d->canCheck();
428         return true;
429 }
430
431
432 void SpellcheckerWidget::on_skipAllPB_clicked()
433 {
434         /// ignore all occurrences of word
435         if (d->disabled())
436                 return;
437         LYXERR(Debug::GUI, "Spellchecker: skip all button");
438         if (d->word_.lang() && !d->word_.word().empty())
439                 theSpellChecker()->accept(d->word_);
440         d->forward();
441         d->check();
442         d->canCheck();
443 }
444
445
446 void SpellcheckerWidget::on_ignoreAllPB_clicked()
447 {
448         /// ignore all occurrences of word
449         if (d->disabled())
450                 return;
451         LYXERR(Debug::GUI, "Spellchecker: ignore all button");
452         if (d->word_.lang() && !d->word_.word().empty())
453                 dispatch(FuncRequest(LFUN_SPELLING_ADD_LOCAL,
454                                      d->word_.word() + " " + from_ascii(d->word_.lang()->lang())));
455         d->forward();
456         d->check();
457         d->canCheck();
458 }
459
460
461 void SpellcheckerWidget::on_addPB_clicked()
462 {
463         /// insert word in personal dictionary
464         if (d->disabled())
465                 return;
466         LYXERR(Debug::GUI, "Spellchecker: add word button");
467         theSpellChecker()->insert(d->word_);
468         d->forward();
469         d->check();
470         d->canCheck();
471 }
472
473
474 void SpellcheckerWidget::on_skipPB_clicked()
475 {
476         /// ignore this occurrence of word
477         if (d->disabled())
478                 return;
479         LYXERR(Debug::GUI, "Spellchecker: skip button");
480         d->forward();
481         d->check();
482         d->canCheck();
483 }
484
485
486 void SpellcheckerWidget::on_ignorePB_clicked()
487 {
488         /// ignore this occurrence of word
489         if (d->disabled())
490                 return;
491         LYXERR(Debug::GUI, "Spellchecker: ignore button");
492         dispatch(FuncRequest(LFUN_FONT_NO_SPELLCHECK));
493         d->forward();
494         d->check();
495         d->canCheck();
496 }
497
498
499 void SpellcheckerWidget::on_replacePB_clicked()
500 {
501         if (d->disabled())
502                 return;
503         docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
504         docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
505         docstring const datastring =
506                 replace2string(replacement, textfield,
507                         true,   // case sensitive
508                         true,   // match word
509                         false,  // all words
510                         true,   // forward
511                         false,  // find next
512                         false,  // auto-wrap
513                         false); // only selection
514
515         LYXERR(Debug::GUI, "Replace (" << replacement << ")");
516         dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
517         d->forward();
518         d->check();
519         d->canCheck();
520 }
521
522
523 void SpellcheckerWidget::on_replaceAllPB_clicked()
524 {
525         if (d->disabled())
526                 return;
527         docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
528         docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
529         docstring const datastring =
530                 replace2string(replacement, textfield,
531                         true,   // case sensitive
532                         true,   // match word
533                         true,   // all words
534                         true,   // forward
535                         false,  // find next
536                         false,  // auto-wrap
537                         false); // only selection
538
539         LYXERR(Debug::GUI, "Replace all (" << replacement << ")");
540         dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
541         d->forward();
542         d->check(); // continue spellchecking
543         d->canCheck();
544 }
545
546
547 void SpellcheckerWidget::Private::updateSuggestions(docstring_list & words)
548 {
549         QString const suggestion = toqstr(word_.word());
550         ui.wordED->setText(suggestion);
551         QListWidget * lw = ui.suggestionsLW;
552         lw->clear();
553
554         if (words.empty()) {
555                 p->on_suggestionsLW_itemClicked(new QListWidgetItem(suggestion));
556                 return;
557         }
558         for (size_t i = 0; i != words.size(); ++i)
559                 lw->addItem(toqstr(words[i]));
560
561         p->on_suggestionsLW_itemClicked(lw->item(0));
562         lw->setCurrentRow(0);
563 }
564
565
566 void SpellcheckerWidget::Private::setLanguage(Language const * lang)
567 {
568         int const pos = ui.languageCO->findData(toqstr(lang->lang()));
569         if (pos != -1)
570                 ui.languageCO->setCurrentIndex(pos);
571 }
572
573
574 void SpellcheckerWidget::Private::check()
575 {
576         BufferView * bv = gv_->documentBufferView();
577         if (!bv || bv->buffer().text().empty())
578                 return;
579
580         fixPositionsIfBroken();
581
582         SpellChecker * speller = theSpellChecker();
583         if (speller && !speller->hasDictionary(bv->buffer().language())) {
584                 int dsize = speller->numDictionaries();
585                 if (0 == dsize) {
586                         hide();
587                         QMessageBox::information(p,
588                                 qt_("Spell Checker"),
589                                 qt_("Spell checker has no dictionaries."));
590                         return;
591                 }
592         }
593
594         DocIterator from = bv->cursor();
595         DocIterator to = isCurrentBuffer(from) ? end_ : doc_iterator_end(&bv->buffer());
596         WordLangTuple word_lang;
597         docstring_list suggestions;
598
599         LYXERR(Debug::GUI, "Spellchecker: start check at " << from);
600         try {
601                 bv->buffer().spellCheck(from, to, word_lang, suggestions);
602         } catch (ExceptionMessage const & message) {
603                 if (message.type_ == WarningException) {
604                         Alert::warning(message.title_, message.details_);
605                         return;
606                 }
607                 throw;
608         }
609
610         // end of document or selection?
611         if (atLastPos(from)) {
612                 if (isWrapAround()) {
613                         hide();
614                         return;
615                 }
616                 if (continueFromBeginning())
617                         check();
618                 return;
619         }
620
621         if (isWrapAround(from)) {
622                 hide();
623                 return;
624         }
625
626         word_ = word_lang;
627
628         // set suggestions
629         updateSuggestions(suggestions);
630         // set language
631         if (!word_lang.lang())
632                 return;
633         setLanguage(word_lang.lang());
634         // mark misspelled word
635         setSelection(from, to);
636         // enable relevant widgets
637         updateView();
638 }
639
640
641 GuiSpellchecker::GuiSpellchecker(GuiView & parent,
642                 Qt::DockWidgetArea area, Qt::WindowFlags flags)
643         : DockView(parent, "spellchecker", qt_("Spellchecker"),
644                    area, flags)
645 {
646         widget_ = new SpellcheckerWidget(&parent, this);
647         setWidget(widget_);
648         setFocusProxy(widget_);
649 #ifdef Q_OS_MAC
650         // On Mac show and floating
651         setFloating(true);
652 #endif
653 }
654
655
656 GuiSpellchecker::~GuiSpellchecker()
657 {
658         setFocusProxy(nullptr);
659         delete widget_;
660 }
661
662
663 void GuiSpellchecker::updateView()
664 {
665         widget_->updateView();
666 }
667
668
669 } // namespace frontend
670 } // namespace lyx
671
672 #include "moc_GuiSpellchecker.cpp"