]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiSpellchecker.cpp
* Singleton-ify the used SpellChecker object.
[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 "LyX.h"
25 #include "LyXRC.h"
26 #include "Paragraph.h"
27
28 #include "support/debug.h"
29 #include "support/docstring.h"
30 #include "support/gettext.h"
31 #include "support/lstrings.h"
32 #include "support/textutils.h"
33
34 #include <QListWidgetItem>
35
36 #if defined(USE_ASPELL)
37 # include "ASpell_local.h"
38 #endif
39
40 #include "SpellChecker.h"
41
42 #include "frontends/alert.h"
43
44 using namespace std;
45 using namespace lyx::support;
46
47 namespace lyx {
48 namespace frontend {
49
50
51 GuiSpellchecker::GuiSpellchecker(GuiView & lv)
52         : GuiDialog(lv, "spellchecker", qt_("Spellchecker")), exitEarly_(false),
53           oldval_(0), newvalue_(0), count_(0), speller_(0)
54 {
55         setupUi(this);
56
57         connect(closePB, SIGNAL(clicked()), this, SLOT(slotClose()));
58         connect(replacePB, SIGNAL(clicked()), this, SLOT(replace()));
59         connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
60         connect(replacePB_3, SIGNAL(clicked()), this, SLOT(accept()));
61         connect(addPB, SIGNAL(clicked()), this, SLOT(add()));
62
63         connect(replaceCO, SIGNAL(highlighted(QString)),
64                 this, SLOT(replaceChanged(QString)));
65         connect(suggestionsLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
66                 this, SLOT(replace()));
67         connect(suggestionsLW, SIGNAL(itemClicked(QListWidgetItem*)),
68                 this, SLOT(suggestionChanged(QListWidgetItem*)));
69
70         wordED->setReadOnly(true);
71
72         bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
73         bc().setCancel(closePB);
74 }
75
76
77 GuiSpellchecker::~GuiSpellchecker()
78 {
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()
96             && suggestionsLW->currentItem()->text() == str)
97                 return;
98
99         for (int i = 0; i != suggestionsLW->count(); ++i) {
100                 if (suggestionsLW->item(i)->text() == str) {
101                         suggestionsLW->setCurrentRow(i);
102                         break;
103                 }
104         }
105 }
106
107
108 void GuiSpellchecker::reject()
109 {
110         slotClose();
111         QDialog::reject();
112 }
113
114
115 void GuiSpellchecker::updateContents()
116 {
117         // The clauses below are needed because the spellchecker
118         // has many flaws (see bugs 1950, 2218).
119         // Basically, we have to distinguish the case where a
120         // spellcheck has already been performed for the whole
121         // document (exitEarly() == true, isVisible() == false) 
122         // from the rest (exitEarly() == false, isVisible() == true).
123         // FIXME: rewrite the whole beast!
124         static bool check_after_early_exit;
125         if (exitEarly()) {
126                 // a spellcheck has already been performed,
127                 check();
128                 check_after_early_exit = true;
129         }
130         else if (isVisible()) {
131                 // the above check triggers a second update,
132                 // and isVisible() is true then. Prevent a
133                 // second check that skips the first word
134                 if (check_after_early_exit)
135                         // don't check, but reset the bool.
136                         // business as usual after this.
137                         check_after_early_exit = false;
138                 else
139                         // perform spellcheck (default case)
140                         check();
141         }
142 }
143
144
145 void GuiSpellchecker::accept()
146 {
147         ignoreAll();
148 }
149
150
151 void GuiSpellchecker::add()
152 {
153         insert();
154 }
155
156
157 void GuiSpellchecker::ignore()
158 {
159         check();
160 }
161
162
163 void GuiSpellchecker::replace()
164 {
165         replace(qstring_to_ucs4(replaceCO->currentText()));
166 }
167
168
169 void GuiSpellchecker::partialUpdate(int state)
170 {
171         switch (state) {
172                 case SPELL_PROGRESSED:
173                         spellcheckPR->setValue(getProgress());
174                         break;
175
176                 case SPELL_FOUND_WORD: {
177                         wordED->setText(toqstr(getWord()));
178                         suggestionsLW->clear();
179
180                         docstring w;
181                         while (!(w = getSuggestion()).empty())
182                                 suggestionsLW->addItem(toqstr(w));
183
184                         if (suggestionsLW->count() == 0)
185                                 suggestionChanged(new QListWidgetItem(wordED->text()));
186                         else
187                                 suggestionChanged(suggestionsLW->item(0));
188
189                         suggestionsLW->setCurrentRow(0);
190                         break;
191                 }
192         }
193 }
194
195
196 bool GuiSpellchecker::initialiseParams(string const &)
197 {
198         LYXERR(Debug::GUI, "Spellchecker::initialiseParams");
199
200         speller_ = theSpellChecker();
201         if (!speller_)
202                 return false;
203
204         // reset values to initial
205         oldval_ = 0;
206         newvalue_ = 0;
207         count_ = 0;
208
209         bool const success = speller_->error().empty();
210
211         if (!success) {
212                 Alert::error(_("Spellchecker error"),
213                              _("The spellchecker could not be started\n")
214                              + speller_->error());
215                 speller_ = 0;
216         }
217
218         return success;
219 }
220
221
222 void GuiSpellchecker::clearParams()
223 {
224         LYXERR(Debug::GUI, "Spellchecker::clearParams");
225         speller_ = 0;
226 }
227
228
229 static WordLangTuple nextWord(Cursor & cur, ptrdiff_t & progress)
230 {
231         Buffer const & buf = cur.bv().buffer();
232         cur.resetAnchor();
233         docstring word;
234         DocIterator from = cur;
235         DocIterator to;
236         if (!buf.nextWord(from, to, word))
237                 return WordLangTuple(docstring(), string());
238
239         cur.setCursor(from);
240         cur.resetAnchor();
241         cur.setCursor(to);
242         cur.setSelection();
243         string lang_code = lyxrc.spellchecker_use_alt_lang
244                       ? lyxrc.spellchecker_alt_lang
245                       : from.paragraph().getFontSettings(buf.params(), cur.pos()).language()->code();
246         ++progress;
247         return WordLangTuple(word, lang_code);
248 }
249
250
251 void GuiSpellchecker::check()
252 {
253         LYXERR(Debug::GUI, "Check the spelling of a word");
254
255         SpellChecker::Result res = SpellChecker::OK;
256
257         Cursor cur = bufferview()->cursor();
258         while (cur && cur.pos() && isLetter(cur))
259                 cur.backwardPos();
260
261         ptrdiff_t start = 0;
262         ptrdiff_t total = 0;
263         DocIterator it = doc_iterator_begin(&buffer());
264         for (start = 1; it != cur; it.forwardPos())
265                 ++start;
266
267         for (total = start; it; it.forwardPos())
268                 ++total;
269
270         exitEarly_ = false;
271
272         while (res == SpellChecker::OK || res == SpellChecker::IGNORED_WORD) {
273                 word_ = nextWord(cur, start);
274
275                 // end of document
276                 if (getWord().empty()) {
277                         showSummary();
278                         exitEarly_ = true;
279                         return;
280                 }
281
282                 ++count_;
283
284                 // Update slider if and only if value has changed
285                 float progress = total ? float(start)/total : 1;
286                 newvalue_ = int(100.0 * progress);
287                 if (newvalue_!= oldval_) {
288                         LYXERR(Debug::GUI, "Updating spell progress.");
289                         oldval_ = newvalue_;
290                         // set progress bar
291                         partialUpdate(SPELL_PROGRESSED);
292                 }
293
294                 res = speller_->check(word_);
295
296                 // ... just bail out if the spellchecker reports an error.
297                 if (!speller_->error().empty()) {
298                         docstring const message =
299                                 _("The spellchecker has failed.\n") + speller_->error();
300                         slotClose();
301                         return;
302                 }       
303         }
304
305         LYXERR(Debug::GUI, "Found word \"" << to_utf8(getWord()) << "\"");
306
307         int const size = cur.selEnd().pos() - cur.selBegin().pos();
308         cur.pos() -= size;
309         BufferView * bv = const_cast<BufferView *>(bufferview());
310         bv->putSelectionAt(cur, size, false);
311         // FIXME: if we used a lfun like in find/replace, dispatch would do
312         // that for us
313         // FIXME: this Controller is very badly designed...
314         bv->processUpdateFlags(Update::Force | Update::FitCursor);
315
316         // set suggestions
317         if (res != SpellChecker::OK && res != SpellChecker::IGNORED_WORD) {
318                 LYXERR(Debug::GUI, "Found a word needing checking.");
319                 partialUpdate(SPELL_FOUND_WORD);
320         }
321 }
322
323
324 void GuiSpellchecker::showSummary()
325 {
326         if (count_ == 0) {
327                 slotClose();
328                 return;
329         }
330
331         docstring message;
332         if (count_ != 1)
333                 message = bformat(_("%1$d words checked."), count_);
334         else
335                 message = _("One word checked.");
336
337         slotClose();
338         Alert::information(_("Spelling check completed"), message);
339 }
340
341
342 void GuiSpellchecker::replace(docstring const & replacement)
343 {
344         LYXERR(Debug::GUI, "GuiSpellchecker::replace("
345                            << to_utf8(replacement) << ")");
346         BufferView * bv = const_cast<BufferView *>(bufferview());
347         cap::replaceSelectionWithString(bv->cursor(), replacement, true);
348         bv->buffer().markDirty();
349         // If we used an LFUN, we would not need that
350         bv->processUpdateFlags(Update::Force | Update::FitCursor);
351         // fix up the count
352         --count_;
353         check();
354 }
355
356
357 void GuiSpellchecker::replaceAll(docstring const & replacement)
358 {
359         // TODO: add to list
360         replace(replacement);
361 }
362
363
364 void GuiSpellchecker::insert()
365 {
366         speller_->insert(word_);
367         check();
368 }
369
370
371 docstring GuiSpellchecker::getSuggestion() const
372 {
373         return speller_->nextMiss();
374 }
375
376
377 docstring GuiSpellchecker::getWord() const
378 {
379         return word_.word();
380 }
381
382
383 void GuiSpellchecker::ignoreAll()
384 {
385         speller_->accept(word_);
386         check();
387 }
388
389
390 Dialog * createGuiSpellchecker(GuiView & lv) { return new GuiSpellchecker(lv); }
391
392 } // namespace frontend
393 } // namespace lyx
394
395 #include "moc_GuiSpellchecker.cpp"