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