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