]> git.lyx.org Git - features.git/blob - src/frontends/qt4/GuiSpellchecker.cpp
559ce29dd62cf58684b63ae593a9ff10b29d0308
[features.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  * \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 "Language.h"
31 #include "LyX.h"
32 #include "LyXRC.h"
33 #include "lyxfind.h"
34 #include "Paragraph.h"
35 #include "WordLangTuple.h"
36
37 #include "support/debug.h"
38 #include "support/docstring.h"
39 #include "support/docstring_list.h"
40 #include "support/ExceptionMessage.h"
41 #include "support/gettext.h"
42 #include "support/lstrings.h"
43 #include "support/textutils.h"
44
45 #include <QKeyEvent>
46 #include <QListWidgetItem>
47 #include <QMessageBox>
48
49 #include "SpellChecker.h"
50
51 #include "frontends/alert.h"
52
53 using namespace std;
54 using namespace lyx::support;
55
56 namespace lyx {
57 namespace frontend {
58
59
60 struct SpellcheckerWidget::Private
61 {
62         Private(SpellcheckerWidget * parent, DockView * dv)
63                 : p(parent), dv_(dv), start_(true), incheck_(false) {}
64         /// update from controller
65         void updateSuggestions(docstring_list & words);
66         /// move to next position after current word
67         void forward();
68         /// check text until next misspelled/unknown word
69         void check();
70         ///
71         bool continueFromBeginning();
72         ///
73         void setLanguage(Language const * lang);
74         /// test and set guard flag
75         bool inCheck() {
76                 if (incheck_)
77                         return true;
78                 incheck_ = true;
79                 return false;
80         }
81         void canCheck() { incheck_ = false; }
82         ///
83         Ui::SpellcheckerUi ui;
84         ///
85         SpellcheckerWidget * p;
86         ///
87         GuiView * gv_;
88         ///
89         DockView * dv_;
90         /// current word being checked and lang code
91         WordLangTuple word_;
92         ///
93         bool start_;
94         ///
95         bool incheck_;
96 };
97
98
99 SpellcheckerWidget::SpellcheckerWidget(GuiView * gv, DockView * dv, QWidget * parent)
100         : QTabWidget(parent), d(new Private(this, dv))
101 {
102         d->ui.setupUi(this);
103         d->gv_ = gv;
104
105         connect(d->ui.suggestionsLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
106                 this, SLOT(on_replacePB_clicked()));
107
108         // language
109         QAbstractItemModel * language_model = guiApp->languageModel();
110         // FIXME: it would be nice if sorting was enabled/disabled via a checkbox.
111         language_model->sort(0);
112         d->ui.languageCO->setModel(language_model);
113         d->ui.languageCO->setModelColumn(1);
114
115         d->ui.wordED->setReadOnly(true);
116
117         d->ui.suggestionsLW->installEventFilter(this);
118 }
119
120
121 SpellcheckerWidget::~SpellcheckerWidget()
122 {
123         delete d;
124 }
125
126
127 bool SpellcheckerWidget::eventFilter(QObject *obj, QEvent *event)
128 {
129         if (obj == d->ui.suggestionsLW && event->type() == QEvent::KeyPress) {
130                 QKeyEvent *e = static_cast<QKeyEvent *> (event);
131                 if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) {
132                         if (d->ui.suggestionsLW->currentItem()) {
133                                 on_suggestionsLW_itemClicked(d->ui.suggestionsLW->currentItem());
134                                 on_replacePB_clicked();
135                         }
136                         return true;
137                 } else if (e->key() == Qt::Key_Right) {
138                         if (d->ui.suggestionsLW->currentItem())
139                                 on_suggestionsLW_itemClicked(d->ui.suggestionsLW->currentItem());
140                         return true;
141                 }
142         }
143         // standard event processing
144         return QWidget::eventFilter(obj, event);
145 }
146
147
148 void SpellcheckerWidget::on_suggestionsLW_itemClicked(QListWidgetItem * item)
149 {
150         if (d->ui.replaceCO->count() != 0)
151                 d->ui.replaceCO->setItemText(0, item->text());
152         else
153                 d->ui.replaceCO->addItem(item->text());
154
155         d->ui.replaceCO->setCurrentIndex(0);
156 }
157
158
159 void SpellcheckerWidget::on_replaceCO_highlighted(const QString & str)
160 {
161         QListWidget * lw = d->ui.suggestionsLW;
162         if (lw->currentItem() && lw->currentItem()->text() == str)
163                 return;
164
165         for (int i = 0; i != lw->count(); ++i) {
166                 if (lw->item(i)->text() == str) {
167                         lw->setCurrentRow(i);
168                         break;
169                 }
170         }
171 }
172
173
174 void SpellcheckerWidget::updateView()
175 {
176         BufferView * bv = d->gv_->documentBufferView();
177         setEnabled(bv != 0);
178         if (bv && hasFocus() && d->start_) {
179                 d->start_ = false;
180
181                 BufferView * bv = d->gv_->documentBufferView();
182                 std::set<Language const *> languages = 
183                 bv->buffer().masterBuffer()->getLanguages();
184                 if (!languages.empty())
185                         d->setLanguage(*languages.begin());
186                 
187                 d->check();
188         }
189 }
190
191
192 bool SpellcheckerWidget::Private::continueFromBeginning()
193 {
194                 QMessageBox::StandardButton const answer = QMessageBox::question(p,
195                         qt_("Spell Checker"),
196                         qt_("We reached the end of the document, would you like to "
197                                 "continue from the beginning?"),
198                         QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
199                 if (answer == QMessageBox::No) {
200                         dv_->hide();
201                         return false;
202                 }
203                 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
204                 return true;
205 }
206
207
208 void SpellcheckerWidget::Private::forward()
209 {
210         BufferView * bv = gv_->documentBufferView();
211         DocIterator from = bv->cursor();
212
213         dispatch(FuncRequest(LFUN_ESCAPE));
214         dispatch(FuncRequest(LFUN_CHAR_FORWARD));
215         if (bv->cursor().depth() <= 1 && bv->cursor().atLastPos()) {
216                 continueFromBeginning();
217                 return;
218         }
219         if (from == bv->cursor()) {
220                 //FIXME we must be at the end of a cell
221                 dispatch(FuncRequest(LFUN_CHAR_FORWARD));
222         }
223 }
224
225
226 void SpellcheckerWidget::on_languageCO_activated(int index)
227 {
228         string const lang =
229                 fromqstr(d->ui.languageCO->itemData(index).toString());
230         if (!d->word_.lang() || d->word_.lang()->lang() == lang)
231                 // nothing changed
232                 return;
233         dispatch(FuncRequest(LFUN_LANGUAGE, lang));
234         d->check();
235 }
236
237
238 bool SpellcheckerWidget::initialiseParams(std::string const &)
239 {
240         d->start_ = true;
241         return true;
242 }
243
244
245 void SpellcheckerWidget::on_ignoreAllPB_clicked()
246 {
247         /// ignore all occurrences of word
248         if (d->inCheck())
249                 return;
250         LYXERR(Debug::GUI, "Spellchecker: ignore all button");
251         if (d->word_.lang() && !d->word_.word().empty())
252                 theSpellChecker()->accept(d->word_);
253         d->forward();
254         d->check();
255         d->canCheck();
256 }
257
258
259 void SpellcheckerWidget::on_addPB_clicked()
260 {
261         /// insert word in personal dictionary
262         if (d->inCheck())
263                 return;
264         LYXERR(Debug::GUI, "Spellchecker: add word button");
265         theSpellChecker()->insert(d->word_);
266         d->forward();
267         d->check();
268         d->canCheck();
269 }
270
271
272 void SpellcheckerWidget::on_ignorePB_clicked()
273 {
274         /// ignore this occurrence of word
275         if (d->inCheck())
276                 return;
277         LYXERR(Debug::GUI, "Spellchecker: ignore button");
278         d->forward();
279         d->check();
280         d->canCheck();
281 }
282
283
284 void SpellcheckerWidget::on_findNextPB_clicked()
285 {
286         if (d->inCheck())
287                 return;
288         docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
289         docstring const datastring = find2string(textfield,
290                                 true, true, true);
291         LYXERR(Debug::GUI, "Spellchecker: find next (" << textfield << ")");
292         dispatch(FuncRequest(LFUN_WORD_FIND, datastring));
293         d->canCheck();
294 }
295
296
297 void SpellcheckerWidget::on_replacePB_clicked()
298 {
299         if (d->inCheck())
300                 return;
301         docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
302         docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
303         docstring const datastring = replace2string(replacement, textfield,
304                 true, true, false, false);
305
306         LYXERR(Debug::GUI, "Replace (" << replacement << ")");
307         dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
308         d->forward();
309         d->check();
310         d->canCheck();
311 }
312
313
314 void SpellcheckerWidget::on_replaceAllPB_clicked()
315 {
316         if (d->inCheck())
317                 return;
318         docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
319         docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
320         docstring const datastring = replace2string(replacement, textfield,
321                 true, true, true, true);
322
323         LYXERR(Debug::GUI, "Replace all (" << replacement << ")");
324         dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
325         d->forward();
326         d->check(); // continue spellchecking
327         d->canCheck();
328 }
329
330
331 void SpellcheckerWidget::Private::updateSuggestions(docstring_list & words)
332 {
333         QString const suggestion = toqstr(word_.word());
334         ui.wordED->setText(suggestion);
335         QListWidget * lw = ui.suggestionsLW;
336         lw->clear();
337
338         if (words.empty()) {
339                 p->on_suggestionsLW_itemClicked(new QListWidgetItem(suggestion));
340                 return;
341         }
342         for (size_t i = 0; i != words.size(); ++i)
343                 lw->addItem(toqstr(words[i]));
344
345         p->on_suggestionsLW_itemClicked(lw->item(0));
346         lw->setCurrentRow(0);
347 }
348
349
350 void SpellcheckerWidget::Private::setLanguage(Language const * lang)
351 {
352         int const pos = ui.languageCO->findData(toqstr(lang->lang()));
353         if (pos != -1)
354                 ui.languageCO->setCurrentIndex(pos);
355 }
356
357
358 void SpellcheckerWidget::Private::check()
359 {
360         BufferView * bv = gv_->documentBufferView();
361         if (!bv || bv->buffer().text().empty())
362                 return;
363
364         DocIterator from = bv->cursor();
365         DocIterator to;
366         WordLangTuple word_lang;
367         docstring_list suggestions;
368
369         LYXERR(Debug::GUI, "Spellchecker: start check at " << from);
370         int progress;
371         try {
372                 progress = bv->buffer().spellCheck(from, to, word_lang, suggestions);
373         } catch (ExceptionMessage const & message) {
374                 if (message.type_ == WarningException) {
375                         Alert::warning(message.title_, message.details_);
376                         return;
377                 }
378                 throw message;
379         }
380
381         // end of document
382         if (from == doc_iterator_end(&bv->buffer())) {
383                 if (continueFromBeginning())
384                         check();
385                 return;
386         }
387
388         word_ = word_lang;
389
390         // set suggestions
391         updateSuggestions(suggestions);
392         // set language
393         setLanguage(word_lang.lang());
394
395         // FIXME LFUN
396         // If we used a LFUN, dispatch would do all of this for us
397         int const size = to.pos() - from.pos();
398         bv->putSelectionAt(from, size, false);
399         bv->processUpdateFlags(Update::Force | Update::FitCursor);      
400 }
401
402
403 GuiSpellchecker::GuiSpellchecker(GuiView & parent,
404                 Qt::DockWidgetArea area, Qt::WindowFlags flags)
405         : DockView(parent, "spellchecker", qt_("Spellchecker"),
406                    area, flags)
407 {
408         widget_ = new SpellcheckerWidget(&parent, this);
409         setWidget(widget_);
410         setFocusProxy(widget_);
411 }
412
413
414 GuiSpellchecker::~GuiSpellchecker()
415 {
416         setFocusProxy(0);
417         delete widget_;
418 }
419
420
421 void GuiSpellchecker::updateView()
422 {
423         widget_->updateView();
424 }
425
426
427 Dialog * createGuiSpellchecker(GuiView & lv) 
428
429         GuiSpellchecker * gui = new GuiSpellchecker(lv, Qt::RightDockWidgetArea);
430 #ifdef Q_WS_MACX
431         gui->setFloating(true);
432 #endif
433         return gui;
434 }
435
436
437 } // namespace frontend
438 } // namespace lyx
439
440 #include "moc_GuiSpellchecker.cpp"