]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiSpellchecker.cpp
FindAdv: Search for 'whole words' with help of modified regex.
[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(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.findNextPB->setEnabled(enabled);
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 }
395
396
397 void SpellcheckerWidget::on_languageCO_activated(int index)
398 {
399         string const lang =
400                 fromqstr(d->ui.languageCO->itemData(index).toString());
401         if (!d->word_.lang() || d->word_.lang()->lang() == lang)
402                 // nothing changed
403                 return;
404         dispatch(FuncRequest(LFUN_LANGUAGE, lang));
405         d->check();
406 }
407
408
409 bool SpellcheckerWidget::initialiseParams(std::string const &)
410 {
411         BufferView * bv = d->gv_->documentBufferView();
412         if (bv == nullptr)
413                 return false;
414         std::set<Language const *> langs =
415                 bv->buffer().masterBuffer()->getLanguages();
416         if (!langs.empty())
417                 d->setLanguage(*langs.begin());
418         d->start_ = DocIterator();
419         d->wrapAround(false);
420         d->canCheck();
421         return true;
422 }
423
424
425 void SpellcheckerWidget::on_ignoreAllPB_clicked()
426 {
427         /// ignore all occurrences of word
428         if (d->disabled())
429                 return;
430         LYXERR(Debug::GUI, "Spellchecker: ignore all button");
431         if (d->word_.lang() && !d->word_.word().empty())
432                 theSpellChecker()->accept(d->word_);
433         d->forward();
434         d->check();
435         d->canCheck();
436 }
437
438
439 void SpellcheckerWidget::on_addPB_clicked()
440 {
441         /// insert word in personal dictionary
442         if (d->disabled())
443                 return;
444         LYXERR(Debug::GUI, "Spellchecker: add word button");
445         theSpellChecker()->insert(d->word_);
446         d->forward();
447         d->check();
448         d->canCheck();
449 }
450
451
452 void SpellcheckerWidget::on_ignorePB_clicked()
453 {
454         /// ignore this occurrence of word
455         if (d->disabled())
456                 return;
457         LYXERR(Debug::GUI, "Spellchecker: ignore button");
458         d->forward();
459         d->check();
460         d->canCheck();
461 }
462
463
464 void SpellcheckerWidget::on_findNextPB_clicked()
465 {
466         if (d->disabled())
467                 return;
468         docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
469         docstring const datastring = find2string(textfield,
470                                 true, true, true);
471         LYXERR(Debug::GUI, "Spellchecker: find next (" << textfield << ")");
472         dispatch(FuncRequest(LFUN_WORD_FIND, datastring));
473         d->canCheck();
474 }
475
476
477 void SpellcheckerWidget::on_replacePB_clicked()
478 {
479         if (d->disabled())
480                 return;
481         docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
482         docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
483         docstring const datastring =
484                 replace2string(replacement, textfield,
485                         true,   // case sensitive
486                         true,   // match word
487                         false,  // all words
488                         true,   // forward
489                         false); // find next
490
491         LYXERR(Debug::GUI, "Replace (" << replacement << ")");
492         dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
493         d->forward();
494         d->check();
495         d->canCheck();
496 }
497
498
499 void SpellcheckerWidget::on_replaceAllPB_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                         true,   // all words
510                         true,   // forward
511                         false); // find next
512
513         LYXERR(Debug::GUI, "Replace all (" << replacement << ")");
514         dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
515         d->forward();
516         d->check(); // continue spellchecking
517         d->canCheck();
518 }
519
520
521 void SpellcheckerWidget::Private::updateSuggestions(docstring_list & words)
522 {
523         QString const suggestion = toqstr(word_.word());
524         ui.wordED->setText(suggestion);
525         QListWidget * lw = ui.suggestionsLW;
526         lw->clear();
527
528         if (words.empty()) {
529                 p->on_suggestionsLW_itemClicked(new QListWidgetItem(suggestion));
530                 return;
531         }
532         for (size_t i = 0; i != words.size(); ++i)
533                 lw->addItem(toqstr(words[i]));
534
535         p->on_suggestionsLW_itemClicked(lw->item(0));
536         lw->setCurrentRow(0);
537 }
538
539
540 void SpellcheckerWidget::Private::setLanguage(Language const * lang)
541 {
542         int const pos = ui.languageCO->findData(toqstr(lang->lang()));
543         if (pos != -1)
544                 ui.languageCO->setCurrentIndex(pos);
545 }
546
547
548 void SpellcheckerWidget::Private::check()
549 {
550         BufferView * bv = gv_->documentBufferView();
551         if (!bv || bv->buffer().text().empty())
552                 return;
553
554         fixPositionsIfBroken();
555
556         SpellChecker * speller = theSpellChecker();
557         if (speller && !speller->hasDictionary(bv->buffer().language())) {
558                 int dsize = speller->numDictionaries();
559                 if (0 == dsize) {
560                         hide();
561                         QMessageBox::information(p,
562                                 qt_("Spell Checker"),
563                                 qt_("Spell checker has no dictionaries."));
564                         return;
565                 }
566         }
567
568         DocIterator from = bv->cursor();
569         DocIterator to = isCurrentBuffer(from) ? end_ : doc_iterator_end(&bv->buffer());
570         WordLangTuple word_lang;
571         docstring_list suggestions;
572
573         LYXERR(Debug::GUI, "Spellchecker: start check at " << from);
574         try {
575                 bv->buffer().spellCheck(from, to, word_lang, suggestions);
576         } catch (ExceptionMessage const & message) {
577                 if (message.type_ == WarningException) {
578                         Alert::warning(message.title_, message.details_);
579                         return;
580                 }
581                 throw;
582         }
583
584         // end of document or selection?
585         if (atLastPos(from)) {
586                 if (isWrapAround()) {
587                         hide();
588                         return;
589                 }
590                 if (continueFromBeginning())
591                         check();
592                 return;
593         }
594
595         if (isWrapAround(from)) {
596                 hide();
597                 return;
598         }
599
600         word_ = word_lang;
601
602         // set suggestions
603         updateSuggestions(suggestions);
604         // set language
605         if (!word_lang.lang())
606                 return;
607         setLanguage(word_lang.lang());
608         // mark misspelled word
609         setSelection(from, to);
610         // enable relevant widgets
611         updateView();
612 }
613
614
615 GuiSpellchecker::GuiSpellchecker(GuiView & parent,
616                 Qt::DockWidgetArea area, Qt::WindowFlags flags)
617         : DockView(parent, "spellchecker", qt_("Spellchecker"),
618                    area, flags)
619 {
620         widget_ = new SpellcheckerWidget(&parent, this);
621         setWidget(widget_);
622         setFocusProxy(widget_);
623 #ifdef Q_OS_MAC
624         // On Mac show and floating
625         setFloating(true);
626 #endif
627 }
628
629
630 GuiSpellchecker::~GuiSpellchecker()
631 {
632         setFocusProxy(nullptr);
633         delete widget_;
634 }
635
636
637 void GuiSpellchecker::updateView()
638 {
639         widget_->updateView();
640 }
641
642
643 } // namespace frontend
644 } // namespace lyx
645
646 #include "moc_GuiSpellchecker.cpp"