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