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