summaryrefslogtreecommitdiffstats
blob: 4ffd32a92e6a18327910f9dc37edd928eed528b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/*
 * Copyright (c) 2010-2016 Isode Limited.
 * All rights reserved.
 * See the COPYING file for more information.
 */

#include <Swift/QtUI/QtTextEdit.h>

#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
#include <boost/tuple/tuple.hpp>

#include <QApplication>
#include <QKeyEvent>
#include <QKeySequence>
#include <QMenu>
#include <QTextDocument>

#include <Swiften/Base/Log.h>
#include <Swiften/Base/foreach.h>

#include <Swift/Controllers/SettingConstants.h>

#include <SwifTools/SpellChecker.h>
#include <SwifTools/SpellCheckerFactory.h>

#include <Swift/QtUI/QtSpellCheckerWindow.h>
#include <Swift/QtUI/QtSwiftUtil.h>
#include <Swift/QtUI/QtUtilities.h>

namespace Swift {

QtTextEdit::QtTextEdit(SettingsProvider* settings, QWidget* parent) : QTextEdit(parent), checker_(nullptr), highlighter_(nullptr) {
    connect(this, SIGNAL(textChanged()), this, SLOT(handleTextChanged()));
    settings_ = settings;
#ifdef HAVE_SPELLCHECKER
    setUpSpellChecker();
#endif
    handleTextChanged();
    QTextOption textOption = document()->defaultTextOption();
    textOption.setWrapMode(QTextOption::WordWrap);
    document()->setDefaultTextOption(textOption);
}

QtTextEdit::~QtTextEdit() {
    delete checker_;
}

void QtTextEdit::keyPressEvent(QKeyEvent* event) {
    int key = event->key();
    Qt::KeyboardModifiers modifiers = event->modifiers();
    if ((key == Qt::Key_Enter || key == Qt::Key_Return)
        && (modifiers == Qt::NoModifier || modifiers == Qt::KeypadModifier)) {
        emit returnPressed();
    }
    else if (((key == Qt::Key_PageUp || key == Qt::Key_PageDown) && modifiers == Qt::ShiftModifier)
               || (key == Qt::Key_C && modifiers == Qt::ControlModifier && textCursor().selectedText().isEmpty())
               || (key == Qt::Key_W && modifiers == Qt::ControlModifier)
               || (key == Qt::Key_PageUp && modifiers == Qt::ControlModifier)
               || (key == Qt::Key_PageDown && modifiers == Qt::ControlModifier)
               || (key == Qt::Key_Tab && modifiers == Qt::ControlModifier)
               || (key == Qt::Key_A && modifiers == Qt::AltModifier)
               || (key == Qt::Key_Tab)
               || (event->matches(QKeySequence::ZoomIn))
               || (event->matches(QKeySequence::ZoomOut))
    ) {
        emit unhandledKeyPressEvent(event);
    }
    else if ((key == Qt::Key_Up)
               || (key == Qt::Key_Down)) {
        emit unhandledKeyPressEvent(event);
        QTextEdit::keyPressEvent(event);
    }
    else if ((key == Qt::Key_K && modifiers == QtUtilities::ctrlHardwareKeyModifier)) {
        QTextCursor cursor = textCursor();
        cursor.setPosition(toPlainText().size(), QTextCursor::KeepAnchor);
        cursor.removeSelectedText();
    }
    else {
        QTextEdit::keyPressEvent(event);
    }
}

void QtTextEdit::focusInEvent(QFocusEvent* event) {
    receivedFocus();
    QTextEdit::focusInEvent(event);
}

void QtTextEdit::focusOutEvent(QFocusEvent* event) {
    lostFocus();
    QTextEdit::focusOutEvent(event);
}

void QtTextEdit::handleTextChanged() {
    QSize previous(maximumSize());
    setMaximumSize(QSize(maximumWidth(), sizeHint().height()));
    if (previous != maximumSize()) {
        updateGeometry();
    }
}

void QtTextEdit::replaceMisspelledWord(const QString& word, int cursorPosition) {
    QTextCursor cursor = textCursor();
    PositionPair wordPosition = getWordFromCursor(cursorPosition);
    cursor.setPosition(boost::get<0>(wordPosition), QTextCursor::MoveAnchor);
    cursor.setPosition(boost::get<1>(wordPosition), QTextCursor::KeepAnchor);
    QTextCharFormat normalFormat;
    cursor.insertText(word, normalFormat);
}

PositionPair QtTextEdit::getWordFromCursor(int cursorPosition) {
    PositionPairList misspelledPositions = highlighter_->getMisspelledPositions();
    for (auto& misspelledPosition : misspelledPositions) {
        if (cursorPosition >= boost::get<0>(misspelledPosition) && cursorPosition <= boost::get<1>(misspelledPosition)) {
            return misspelledPosition;
        }
    }
    return boost::make_tuple(-1,-1);
}

QSize QtTextEdit::sizeHint() const {
    QSize hint = document()->size().toSize();
    QMargins margins = contentsMargins();
    return hint + QSize(margins.left() + margins.right(), margins.top() + margins.bottom());
}

void QtTextEdit::contextMenuEvent(QContextMenuEvent* event) {
    QMenu* menu = createStandardContextMenu();
    QTextCursor cursor = cursorForPosition(event->pos());
#ifdef HAVE_SPELLCHECKER
    QAction* insertPoint = menu->actions().first();
    QAction* settingsAction = new QAction(tr("Spell Checker Options"), menu);
    menu->insertAction(insertPoint, settingsAction);
    menu->insertAction(insertPoint, menu->addSeparator());
    addSuggestions(menu, event);
    QAction* result = menu->exec(event->globalPos());
    if (result == settingsAction) {
        spellCheckerSettingsWindow();
    }
    for (auto& replaceWordAction : replaceWordActions_) {
        if (replaceWordAction == result) {
            replaceMisspelledWord(replaceWordAction->text(), cursor.position());
        }
    }
#else
    menu->exec(event->globalPos());
#endif
    delete menu;
}

void QtTextEdit::addSuggestions(QMenu* menu, QContextMenuEvent* event)
{
    replaceWordActions_.clear();
    if (checker_ && highlighter_) {
        QAction* insertPoint = menu->actions().first();
        QTextCursor cursor = cursorForPosition(event->pos());
        PositionPair wordPosition = getWordFromCursor(cursor.position());
        if (boost::get<0>(wordPosition) < 0) {
            // The click was executed outside a spellable word so no
            // suggestions are necessary
            return;
        }
        cursor.setPosition(boost::get<0>(wordPosition), QTextCursor::MoveAnchor);
        cursor.setPosition(boost::get<1>(wordPosition), QTextCursor::KeepAnchor);
        std::vector<std::string> wordList;
        checker_->getSuggestions(Q2PSTRING(cursor.selectedText()), wordList);
        if (wordList.size() == 0) {
            QAction* noSuggestions = new QAction(tr("No Suggestions"), menu);
            noSuggestions->setDisabled(true);
            menu->insertAction(insertPoint, noSuggestions);
        }
        else {
            for (auto& word : wordList) {
                QAction* wordAction = new QAction(word.c_str(), menu);
                menu->insertAction(insertPoint, wordAction);
                replaceWordActions_.push_back(wordAction);
            }
        }
        menu->insertAction(insertPoint, menu->addSeparator());
    }
}


#ifdef HAVE_SPELLCHECKER
void QtTextEdit::setUpSpellChecker() {
    delete highlighter_;
    highlighter_ = nullptr;
    delete checker_;
    checker_ = nullptr;
    if (settings_->getSetting(SettingConstants::SPELL_CHECKER)) {
        checker_ = SpellCheckerFactory().createSpellChecker();
        if (checker_) {
            if (!checker_->isAutomaticallyDetectingLanguage()) {
                checker_->setActiveLanguage(settings_->getSetting(SettingConstants::SPELL_CHECKER_LANGUAGE));
            }
            highlighter_ = new QtSpellCheckHighlighter(document(), checker_);
        }
        else {
            // Spellchecking is not working, as we did not get a valid checker from the factory. Disable spellchecking.
            SWIFT_LOG(warning) << "Spellchecking is currently misconfigured in Swift (e.g. missing dictionary or broken dictionary file). Disable spellchecking." << std::endl;
            settings_->storeSetting(SettingConstants::SPELL_CHECKER, false);
        }

    }
}
#endif

void QtTextEdit::spellCheckerSettingsWindow() {
    if (!spellCheckerWindow_) {
        spellCheckerWindow_ = new QtSpellCheckerWindow(settings_);
        settings_->onSettingChanged.connect(boost::bind(&QtTextEdit::handleSettingChanged, this, _1));
        spellCheckerWindow_->show();
    }
    else {
        spellCheckerWindow_->show();
        spellCheckerWindow_->raise();
        spellCheckerWindow_->activateWindow();
    }
    if (checker_) {
        spellCheckerWindow_->setAutomaticallyIdentifiesLanguage(checker_->isAutomaticallyDetectingLanguage());
        if (!checker_->isAutomaticallyDetectingLanguage()) {
            spellCheckerWindow_->setSupportedLanguages(checker_->supportedLanguages());
            spellCheckerWindow_->setActiveLanguage(checker_->activeLanguage());
        }
    }
}

void QtTextEdit::handleSettingChanged(const std::string& settings) {
    if (settings == SettingConstants::SPELL_CHECKER.getKey() ||
        settings == SettingConstants::SPELL_CHECKER_LANGUAGE.getKey()) {
#ifdef HAVE_SPELLCHECKER
        setUpSpellChecker();
        if (highlighter_) {
            highlighter_->rehighlight();
        }
#endif
    }
}

}