]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiSpellchecker.cpp
add Buffer * member to DocIterator
[lyx.git] / src / frontends / qt4 / 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  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "GuiSpellchecker.h"
15
16 #include "qt_helpers.h"
17
18 #include "Buffer.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "Cursor.h"
22 #include "CutAndPaste.h"
23 #include "Language.h"
24 #include "LyXRC.h"
25 #include "Paragraph.h"
26
27 #include "support/debug.h"
28 #include "support/docstring.h"
29 #include "support/gettext.h"
30 #include "support/lstrings.h"
31 #include "support/textutils.h"
32
33 #include <QListWidgetItem>
34
35 #if defined(USE_ASPELL)
36 # include "ASpell_local.h"
37 #endif
38
39 #include "SpellBase.h"
40
41 #include "frontends/alert.h"
42
43 using namespace std;
44 using namespace lyx::support;
45
46 namespace lyx {
47 namespace frontend {
48
49
50 GuiSpellchecker::GuiSpellchecker(GuiView & lv)
51         : GuiDialog(lv, "spellchecker", qt_("Spellchecker")), exitEarly_(false),
52           oldval_(0), newvalue_(0), count_(0), speller_(0)
53 {
54         setupUi(this);
55
56         connect(closePB, SIGNAL(clicked()), this, SLOT(slotClose()));
57         connect(replacePB, SIGNAL(clicked()), this, SLOT(replace()));
58         connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
59         connect(replacePB_3, SIGNAL(clicked()), this, SLOT(accept()));
60         connect(addPB, SIGNAL(clicked()), this, SLOT(add()));
61
62         connect(replaceCO, SIGNAL(highlighted(QString)),
63                 this, SLOT(replaceChanged(QString)));
64         connect(suggestionsLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
65                 this, SLOT(replace()));
66         connect(suggestionsLW, SIGNAL(itemClicked(QListWidgetItem*)),
67                 this, SLOT(suggestionChanged(QListWidgetItem*)));
68
69         wordED->setReadOnly(true);
70
71         bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
72         bc().setCancel(closePB);
73 }
74
75
76 GuiSpellchecker::~GuiSpellchecker()
77 {
78         delete speller_;
79 }
80
81
82 void GuiSpellchecker::suggestionChanged(QListWidgetItem * item)
83 {
84         if (replaceCO->count() != 0)
85                 replaceCO->setItemText(0, item->text());
86         else
87                 replaceCO->addItem(item->text());
88
89         replaceCO->setCurrentIndex(0);
90 }
91
92
93 void GuiSpellchecker::replaceChanged(const QString & str)
94 {
95         if (suggestionsLW->currentItem()->text() == str)
96                 return;
97
98         for (int i = 0; i != suggestionsLW->count(); ++i) {
99                 if (suggestionsLW->item(i)->text() == str) {
100                         suggestionsLW->setCurrentRow(i);
101                         break;
102                 }
103         }
104 }
105
106
107 void GuiSpellchecker::reject()
108 {
109         slotClose();
110         QDialog::reject();
111 }
112
113
114 void GuiSpellchecker::updateContents()
115 {
116         // The clauses below are needed because the spellchecker
117         // has many flaws (see bugs 1950, 2218).
118         // Basically, we have to distinguish the case where a
119         // spellcheck has already been performed for the whole
120         // document (exitEarly() == true, isVisible() == false) 
121         // from the rest (exitEarly() == false, isVisible() == true).
122         // FIXME: rewrite the whole beast!
123         static bool check_after_early_exit;
124         if (exitEarly()) {
125                 // a spellcheck has already been performed,
126                 check();
127                 check_after_early_exit = true;
128         }
129         else if (isVisible()) {
130                 // the above check triggers a second update,
131                 // and isVisible() is true then. Prevent a
132                 // second check that skips the first word
133                 if (check_after_early_exit)
134                         // don't check, but reset the bool.
135                         // business as usual after this.
136                         check_after_early_exit = false;
137                 else
138                         // perform spellcheck (default case)
139                         check();
140         }
141 }
142
143
144 void GuiSpellchecker::accept()
145 {
146         ignoreAll();
147 }
148
149
150 void GuiSpellchecker::add()
151 {
152         insert();
153 }
154
155
156 void GuiSpellchecker::ignore()
157 {
158         check();
159 }
160
161
162 void GuiSpellchecker::replace()
163 {
164         replace(qstring_to_ucs4(replaceCO->currentText()));
165 }
166
167
168 void GuiSpellchecker::partialUpdate(int state)
169 {
170         switch (state) {
171                 case SPELL_PROGRESSED:
172                         spellcheckPR->setValue(getProgress());
173                         break;
174
175                 case SPELL_FOUND_WORD: {
176                         wordED->setText(toqstr(getWord()));
177                         suggestionsLW->clear();
178
179                         docstring w;
180                         while (!(w = getSuggestion()).empty())
181                                 suggestionsLW->addItem(toqstr(w));
182
183                         if (suggestionsLW->count() == 0)
184                                 suggestionChanged(new QListWidgetItem(wordED->text()));
185                         else
186                                 suggestionChanged(suggestionsLW->item(0));
187
188                         suggestionsLW->setCurrentRow(0);
189                         break;
190                 }
191         }
192 }
193
194
195 static SpellBase * createSpeller(BufferParams const & bp)
196 {
197         string lang = lyxrc.spellchecker_use_alt_lang
198                       ? lyxrc.spellchecker_alt_lang
199                       : bp.language->code();
200
201 #if defined(USE_ASPELL)
202         return new ASpell(bp, lang);
203 #endif
204         return new SpellBase;
205 }
206
207
208 bool GuiSpellchecker::initialiseParams(string const &)
209 {
210         LYXERR(Debug::GUI, "Spellchecker::initialiseParams");
211
212         speller_ = createSpeller(buffer().params());
213         if (!speller_)
214                 return false;
215
216         // reset values to initial
217         oldval_ = 0;
218         newvalue_ = 0;
219         count_ = 0;
220
221         bool const success = speller_->error().empty();
222
223         if (!success) {
224                 Alert::error(_("Spellchecker error"),
225                              _("The spellchecker could not be started\n")
226                              + speller_->error());
227                 delete speller_;
228                 speller_ = 0;
229         }
230
231         return success;
232 }
233
234
235 void GuiSpellchecker::clearParams()
236 {
237         LYXERR(Debug::GUI, "Spellchecker::clearParams");
238         delete speller_;
239         speller_ = 0;
240 }
241
242
243 static bool isLetter(DocIterator const & dit)
244 {
245         return dit.inTexted()
246                 && dit.inset().allowSpellCheck()
247                 && dit.pos() != dit.lastpos()
248                 && (dit.paragraph().isLetter(dit.pos())
249                     // We want to pass the ' and escape chars to ispell
250                     || contains(from_utf8(lyxrc.spellchecker_esc_chars + '\''),
251                                 dit.paragraph().getChar(dit.pos())))
252                 && !dit.paragraph().isDeleted(dit.pos());
253 }
254
255
256 static WordLangTuple nextWord(Cursor & cur, ptrdiff_t & progress)
257 {
258         BufferParams const & bp = cur.bv().buffer().params();
259         bool inword = false;
260         bool ignoreword = false;
261         cur.resetAnchor();
262         docstring word;
263         string lang_code;
264
265         while (cur.depth()) {
266                 if (isLetter(cur)) {
267                         if (!inword) {
268                                 inword = true;
269                                 ignoreword = false;
270                                 cur.resetAnchor();
271                                 word.clear();
272                                 lang_code = cur.paragraph().getFontSettings(bp, cur.pos()).language()->code();
273                         }
274                         // Insets like optional hyphens and ligature
275                         // break are part of a word.
276                         if (!cur.paragraph().isInset(cur.pos())) {
277                                 char_type const c = cur.paragraph().getChar(cur.pos());
278                                 word += c;
279                                 if (isDigit(c))
280                                         ignoreword = true;
281                         }
282                 } else { // !isLetter(cur)
283                         if (inword)
284                                 if (!word.empty() && !ignoreword) {
285                                         cur.setSelection();
286                                         return WordLangTuple(word, lang_code);
287                                 }
288                                 inword = false;
289                 }
290
291                 cur.forwardPos();
292                 ++progress;
293         }
294
295         return WordLangTuple(docstring(), string());
296 }
297
298
299 void GuiSpellchecker::check()
300 {
301         LYXERR(Debug::GUI, "Check the spelling of a word");
302
303         SpellBase::Result res = SpellBase::OK;
304
305         Cursor cur = bufferview()->cursor();
306         while (cur && cur.pos() && isLetter(cur))
307                 cur.backwardPos();
308
309         ptrdiff_t start = 0;
310         ptrdiff_t total = 0;
311         DocIterator it = doc_iterator_begin(&buffer());
312         for (start = 1; it != cur; it.forwardPos())
313                 ++start;
314
315         for (total = start; it; it.forwardPos())
316                 ++total;
317
318         exitEarly_ = false;
319
320         while (res == SpellBase::OK || res == SpellBase::IGNORED_WORD) {
321                 word_ = nextWord(cur, start);
322
323                 // end of document
324                 if (getWord().empty()) {
325                         showSummary();
326                         exitEarly_ = true;
327                         return;
328                 }
329
330                 ++count_;
331
332                 // Update slider if and only if value has changed
333                 float progress = total ? float(start)/total : 1;
334                 newvalue_ = int(100.0 * progress);
335                 if (newvalue_!= oldval_) {
336                         LYXERR(Debug::GUI, "Updating spell progress.");
337                         oldval_ = newvalue_;
338                         // set progress bar
339                         partialUpdate(SPELL_PROGRESSED);
340                 }
341
342                 // speller might be dead ...
343                 if (!checkAlive())
344                         return;
345
346                 res = speller_->check(word_);
347
348                 // ... or it might just be reporting an error
349                 if (!checkAlive())
350                         return;
351         }
352
353         LYXERR(Debug::GUI, "Found word \"" << to_utf8(getWord()) << "\"");
354
355         int const size = cur.selEnd().pos() - cur.selBegin().pos();
356         cur.pos() -= size;
357         BufferView * bv = const_cast<BufferView *>(bufferview());
358         bv->putSelectionAt(cur, size, false);
359         // FIXME: if we used a lfun like in find/replace, dispatch would do
360         // that for us
361         // FIXME: this Controller is very badly designed...
362         bv->processUpdateFlags(Update::Force | Update::FitCursor);
363
364         // set suggestions
365         if (res != SpellBase::OK && res != SpellBase::IGNORED_WORD) {
366                 LYXERR(Debug::GUI, "Found a word needing checking.");
367                 partialUpdate(SPELL_FOUND_WORD);
368         }
369 }
370
371
372 bool GuiSpellchecker::checkAlive()
373 {
374         if (speller_->alive() && speller_->error().empty())
375                 return true;
376
377         docstring message;
378         if (speller_->error().empty())
379                 message = _("The spellchecker has died for some reason.\n"
380                                          "Maybe it has been killed.");
381         else
382                 message = _("The spellchecker has failed.\n") + speller_->error();
383
384         slotClose();
385
386         Alert::error(_("The spellchecker has failed"), message);
387         return false;
388 }
389
390
391 void GuiSpellchecker::showSummary()
392 {
393         if (!checkAlive() || count_ == 0) {
394                 slotClose();
395                 return;
396         }
397
398         docstring message;
399         if (count_ != 1)
400                 message = bformat(_("%1$d words checked."), count_);
401         else
402                 message = _("One word checked.");
403
404         slotClose();
405         Alert::information(_("Spelling check completed"), message);
406 }
407
408
409 void GuiSpellchecker::replace(docstring const & replacement)
410 {
411         LYXERR(Debug::GUI, "GuiSpellchecker::replace("
412                            << to_utf8(replacement) << ")");
413         BufferView * bv = const_cast<BufferView *>(bufferview());
414         cap::replaceSelectionWithString(bv->cursor(), replacement, true);
415         bv->buffer().markDirty();
416         // If we used an LFUN, we would not need that
417         bv->processUpdateFlags(Update::Force | Update::FitCursor);
418         // fix up the count
419         --count_;
420         check();
421 }
422
423
424 void GuiSpellchecker::replaceAll(docstring const & replacement)
425 {
426         // TODO: add to list
427         replace(replacement);
428 }
429
430
431 void GuiSpellchecker::insert()
432 {
433         speller_->insert(word_);
434         check();
435 }
436
437
438 docstring GuiSpellchecker::getSuggestion() const
439 {
440         return speller_->nextMiss();
441 }
442
443
444 docstring GuiSpellchecker::getWord() const
445 {
446         return word_.word();
447 }
448
449
450 void GuiSpellchecker::ignoreAll()
451 {
452         speller_->accept(word_);
453         check();
454 }
455
456
457 Dialog * createGuiSpellchecker(GuiView & lv) { return new GuiSpellchecker(lv); }
458
459 } // namespace frontend
460 } // namespace lyx
461
462 #include "moc_GuiSpellchecker.cpp"