]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiSpellchecker.cpp
Remove profiling.py
[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         /// if no selection was checked:
76         /// ask the user if the check should start over
77         bool continueFromBeginning();
78         /// set the given language in language chooser
79         void setLanguage(Language const * lang);
80         /// test and set guard flag
81         bool inCheck() {
82                 if (incheck_)
83                         return true;
84                 incheck_ = true;
85                 return false;
86         }
87         void canCheck() { incheck_ = false; }
88         /// set if checking already started from the beginning
89         void wrapAround(bool flag) {
90                 wrap_around_ = flag;
91                 if (flag) {
92                         end_ = start_;
93                 }
94         }
95         /// test for existing association with a document buffer
96         /// and test for already active check
97         bool disabled() {
98                 return gv_->documentBufferView() == nullptr || inCheck();
99         }
100         /// the cursor position of the buffer view
101         DocIterator const cursor() const;
102         /// status checks
103         bool isCurrentBuffer(DocIterator const & cursor) const;
104         /// return true if we ended a complete cycle
105         bool isWrapAround(DocIterator const & cursor) const;
106         /// returns true if we did already start from the beginning
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         /// Did we already start from the beginning?
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(int index)
194 {
195         QString const str = d->ui.replaceCO->itemText(index);
196         QListWidget * lw = d->ui.suggestionsLW;
197         if (lw->currentItem() && lw->currentItem()->text() == str)
198                 return;
199
200         for (int i = 0; i != lw->count(); ++i) {
201                 if (lw->item(i)->text() == str) {
202                         lw->setCurrentRow(i);
203                         break;
204                 }
205         }
206 }
207
208
209 void SpellcheckerWidget::updateView()
210 {
211         d->updateView();
212 }
213
214
215 void SpellcheckerWidget::Private::updateView()
216 {
217         BufferView * bv = gv_->documentBufferView();
218         bool const enabled = bv != nullptr;
219         // Check cursor position
220         if (enabled && p->hasFocus()) {
221                 Cursor const & cur = bv->cursor();
222                 if (start_.empty() || !isCurrentBuffer(cur)) {
223                         if (cur.selection()) {
224                                 begin_ = cur.selectionBegin();
225                                 end_   = cur.selectionEnd();
226                                 start_ = begin_;
227                                 bv->cursor().setCursor(start_);
228                         } else {
229                                 begin_ = DocIterator();
230                                 end_   = DocIterator();
231                                 start_ = cur;
232                         }
233                         wrapAround(false);
234                         check();
235                 }
236         }
237
238         // Enable widgets as needed.
239         bool const has_word = enabled && !ui.wordED->text().isEmpty();
240         bool const can_replace = has_word && !bv->buffer().isReadonly();
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                         bv->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::forward()
351 {
352         DocIterator const from = cursor();
353
354         dispatch(FuncRequest(LFUN_ESCAPE));
355         fixPositionsIfBroken();
356         if (!atLastPos(cursor())) {
357                 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
358         }
359         if (atLastPos(cursor())) {
360                 return;
361         }
362         if (from == cursor()) {
363                 //FIXME we must be at the end of a cell
364                 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
365         }
366         if (isWrapAround(cursor())) {
367                 hide();
368         }
369         // If we reached the end of the document
370         // and have not yet wrapped (which was
371         // checked above), continue from beginning
372         if (cursor().pit() == cursor().lastpit()
373             && cursor().pos() == cursor().lastpos()
374             && cursor().text()->isMainText())
375                 continueFromBeginning();
376 }
377
378
379 void SpellcheckerWidget::on_languageCO_activated(int index)
380 {
381         string const lang =
382                 fromqstr(d->ui.languageCO->itemData(index).toString());
383         if (!d->word_.lang() || d->word_.lang()->lang() == lang)
384                 // nothing changed
385                 return;
386         dispatch(FuncRequest(LFUN_LANGUAGE, lang));
387         d->check();
388 }
389
390
391 bool SpellcheckerWidget::initialiseParams(std::string const &)
392 {
393         BufferView * bv = d->gv_->documentBufferView();
394         if (bv == nullptr)
395                 return false;
396         std::set<Language const *> langs =
397                 bv->buffer().masterBuffer()->getLanguages();
398         if (!langs.empty())
399                 d->setLanguage(*langs.begin());
400         d->start_ = DocIterator();
401         d->wrapAround(false);
402         d->canCheck();
403         return true;
404 }
405
406
407 void SpellcheckerWidget::on_skipAllPB_clicked()
408 {
409         /// ignore all occurrences of word
410         if (d->disabled())
411                 return;
412         LYXERR(Debug::GUI, "Spellchecker: skip all button");
413         if (d->word_.lang() && !d->word_.word().empty())
414                 theSpellChecker()->accept(d->word_);
415         d->forward();
416         d->check();
417         d->canCheck();
418 }
419
420
421 void SpellcheckerWidget::on_ignoreAllPB_clicked()
422 {
423         /// ignore all occurrences of word
424         if (d->disabled())
425                 return;
426         LYXERR(Debug::GUI, "Spellchecker: ignore all button");
427         if (d->word_.lang() && !d->word_.word().empty())
428                 dispatch(FuncRequest(LFUN_SPELLING_ADD_LOCAL,
429                                      d->word_.word() + " " + from_ascii(d->word_.lang()->lang())));
430         d->forward();
431         d->check();
432         d->canCheck();
433 }
434
435
436 void SpellcheckerWidget::on_addPB_clicked()
437 {
438         /// insert word in personal dictionary
439         if (d->disabled())
440                 return;
441         LYXERR(Debug::GUI, "Spellchecker: add word button");
442         theSpellChecker()->insert(d->word_);
443         d->forward();
444         d->check();
445         d->canCheck();
446 }
447
448
449 void SpellcheckerWidget::on_skipPB_clicked()
450 {
451         /// ignore this occurrence of word
452         if (d->disabled())
453                 return;
454         LYXERR(Debug::GUI, "Spellchecker: skip button");
455         d->forward();
456         d->check();
457         d->canCheck();
458 }
459
460
461 void SpellcheckerWidget::on_ignorePB_clicked()
462 {
463         /// ignore this occurrence of word
464         if (d->disabled())
465                 return;
466         LYXERR(Debug::GUI, "Spellchecker: ignore button");
467         dispatch(FuncRequest(LFUN_FONT_NO_SPELLCHECK));
468         d->forward();
469         d->check();
470         d->canCheck();
471 }
472
473
474 void SpellcheckerWidget::on_replacePB_clicked()
475 {
476         if (d->disabled())
477                 return;
478         docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
479         docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
480         docstring const datastring =
481                 replace2string(replacement, textfield,
482                         true,   // case sensitive
483                         true,   // match word
484                         false,  // all words
485                         true,   // forward
486                         false,  // find next
487                         false,  // auto-wrap
488                         false); // only selection
489
490         LYXERR(Debug::GUI, "Replace (" << replacement << ")");
491         dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
492         d->forward();
493         d->check();
494         d->canCheck();
495 }
496
497
498 void SpellcheckerWidget::on_replaceAllPB_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                         true,   // all words
509                         true,   // forward
510                         false,  // find next
511                         false,  // auto-wrap
512                         false); // only selection
513
514         LYXERR(Debug::GUI, "Replace all (" << replacement << ")");
515         dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
516         d->forward();
517         d->check(); // continue spellchecking
518         d->canCheck();
519 }
520
521
522 void SpellcheckerWidget::Private::updateSuggestions(docstring_list & words)
523 {
524         QString const suggestion = toqstr(word_.word());
525         ui.wordED->setText(suggestion);
526         QListWidget * lw = ui.suggestionsLW;
527         lw->clear();
528
529         if (words.empty()) {
530                 p->on_suggestionsLW_itemClicked(new QListWidgetItem(suggestion));
531                 return;
532         }
533         for (size_t i = 0; i != words.size(); ++i)
534                 lw->addItem(toqstr(words[i]));
535
536         p->on_suggestionsLW_itemClicked(lw->item(0));
537         lw->setCurrentRow(0);
538 }
539
540
541 void SpellcheckerWidget::Private::setLanguage(Language const * lang)
542 {
543         int const pos = ui.languageCO->findData(toqstr(lang->lang()));
544         if (pos != -1)
545                 ui.languageCO->setCurrentIndex(pos);
546 }
547
548
549 void SpellcheckerWidget::Private::check()
550 {
551         BufferView * bv = gv_->documentBufferView();
552         if (!bv || bv->buffer().text().empty())
553                 return;
554
555         fixPositionsIfBroken();
556
557         SpellChecker * speller = theSpellChecker();
558         if (speller && !speller->hasDictionary(bv->buffer().language())) {
559                 int dsize = speller->numDictionaries();
560                 if (0 == dsize) {
561                         hide();
562                         QMessageBox::information(p,
563                                 qt_("Spell Checker"),
564                                 qt_("Spell checker has no dictionaries."));
565                         return;
566                 }
567         }
568
569         DocIterator from = bv->cursor();
570         DocIterator to = isCurrentBuffer(from) ? end_ : doc_iterator_end(&bv->buffer());
571         WordLangTuple word_lang;
572         docstring_list suggestions;
573
574         LYXERR(Debug::GUI, "Spellchecker: start check at " << from);
575         try {
576                 bv->buffer().spellCheck(from, to, word_lang, suggestions);
577         } catch (ExceptionMessage const & message) {
578                 if (message.type_ == WarningException) {
579                         Alert::warning(message.title_, message.details_);
580                         return;
581                 }
582                 throw;
583         }
584
585         // end of document or selection?
586         if (atLastPos(from)) {
587                 if (isWrapAround()) {
588                         hide();
589                         return;
590                 }
591                 if (continueFromBeginning())
592                         check();
593                 return;
594         }
595
596         if (isWrapAround(from)) {
597                 hide();
598                 return;
599         }
600
601         word_ = word_lang;
602
603         // set suggestions
604         updateSuggestions(suggestions);
605         // set language
606         if (!word_lang.lang())
607                 return;
608         setLanguage(word_lang.lang());
609         // mark misspelled word
610         bv->setSelection(from, to);
611         // enable relevant widgets
612         updateView();
613 }
614
615
616 GuiSpellchecker::GuiSpellchecker(GuiView & parent,
617                 Qt::DockWidgetArea area, Qt::WindowFlags flags)
618         : DockView(parent, "spellchecker", qt_("Spellchecker"),
619                    area, flags)
620 {
621         widget_ = new SpellcheckerWidget(&parent, this);
622         setWidget(widget_);
623         setFocusProxy(widget_);
624 #ifdef Q_OS_MAC
625         // On Mac show and floating
626         setFloating(true);
627 #endif
628 }
629
630
631 GuiSpellchecker::~GuiSpellchecker()
632 {
633         setFocusProxy(nullptr);
634         delete widget_;
635 }
636
637
638 void GuiSpellchecker::updateView()
639 {
640         widget_->updateView();
641 }
642
643
644 } // namespace frontend
645 } // namespace lyx
646
647 #include "moc_GuiSpellchecker.cpp"