aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/hunspell/hunspellinputmethod/hunspellinputmethod_p.cpp
blob: 4651ac1f96349037125f92b6014bb227ebd3c5f8 (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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt Virtual Keyboard module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 or (at your option) any later version
** approved by the KDE Free Qt Foundation. The licenses are as published by
** the Free Software Foundation and appearing in the file LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtHunspellInputMethod/private/hunspellinputmethod_p_p.h>
#include <QtVirtualKeyboard/qvirtualkeyboardinputcontext.h>
#include <hunspell/hunspell.h>
#include <QStringList>
#include <QDir>
#include <QTextCodec>
#include <QtCore/QLibraryInfo>
#include <QStandardPaths>

QT_BEGIN_NAMESPACE
namespace QtVirtualKeyboard {

const int HunspellInputMethodPrivate::userDictionaryMaxSize = 100;

/*!
    \class QtVirtualKeyboard::HunspellInputMethodPrivate
    \internal
*/

HunspellInputMethodPrivate::HunspellInputMethodPrivate(HunspellInputMethod *q_ptr) :
    q_ptr(q_ptr),
    hunspellWorker(new HunspellWorker()),
    locale(),
    wordCompletionPoint(2),
    ignoreUpdate(false),
    autoSpaceAllowed(false),
    dictionaryState(DictionaryNotLoaded),
    userDictionaryWords(new HunspellWordList(userDictionaryMaxSize)),
    blacklistedWords(new HunspellWordList(userDictionaryMaxSize)),
    wordCandidatesUpdateTag(0)
{
    if (hunspellWorker)
        hunspellWorker->start();
}

HunspellInputMethodPrivate::~HunspellInputMethodPrivate()
{
}

bool HunspellInputMethodPrivate::createHunspell(const QString &locale)
{
    Q_Q(HunspellInputMethod);
    if (!hunspellWorker)
        return false;
    if (this->locale != locale) {
        clearSuggestionsRelatedTasks();
        hunspellWorker->waitForAllTasks();
        QString hunspellDataPath(qEnvironmentVariable("QT_VIRTUALKEYBOARD_HUNSPELL_DATA_PATH"));
        const QString pathListSep(
#if defined(Q_OS_WIN32)
            QStringLiteral(";")
#else
            QStringLiteral(":")
#endif
        );
        QStringList searchPaths(hunspellDataPath.split(pathListSep, QString::SkipEmptyParts));
        const QStringList defaultPaths = QStringList()
                << QDir(QLibraryInfo::location(QLibraryInfo::DataPath) + QStringLiteral("/qtvirtualkeyboard/hunspell")).absolutePath()
#if !defined(Q_OS_WIN32)
                << QStringLiteral("/usr/share/hunspell")
                << QStringLiteral("/usr/share/myspell/dicts")
#endif
                   ;
        for (const QString &defaultPath : defaultPaths) {
            if (!searchPaths.contains(defaultPath))
                searchPaths.append(defaultPath);
        }
        QSharedPointer<HunspellLoadDictionaryTask> loadDictionaryTask(new HunspellLoadDictionaryTask(locale, searchPaths));
        QObject::connect(loadDictionaryTask.data(), &HunspellLoadDictionaryTask::completed, q, &HunspellInputMethod::dictionaryLoadCompleted);
        dictionaryState = HunspellInputMethodPrivate::DictionaryLoading;
        emit q->selectionListsChanged();
        hunspellWorker->addTask(loadDictionaryTask);
        this->locale = locale;

        loadCustomDictionary(userDictionaryWords, QLatin1String("userdictionary"));
        addToHunspell(userDictionaryWords);
        loadCustomDictionary(blacklistedWords, QLatin1String("blacklist"));
        removeFromHunspell(blacklistedWords);
    }
    return true;
}

void HunspellInputMethodPrivate::reset()
{
    if (clearSuggestions(true)) {
        Q_Q(HunspellInputMethod);
        emit q->selectionListChanged(QVirtualKeyboardSelectionListModel::Type::WordCandidateList);
        emit q->selectionListActiveItemChanged(QVirtualKeyboardSelectionListModel::Type::WordCandidateList, wordCandidates.index());
    }
    autoSpaceAllowed = false;
}

bool HunspellInputMethodPrivate::updateSuggestions()
{
    bool wordCandidateListChanged = false;
    QString word = wordCandidates.wordAt(0);
    if (!word.isEmpty() && dictionaryState != HunspellInputMethodPrivate::DictionaryNotLoaded) {
        wordCandidateListChanged = true;
        if (word.length() >= wordCompletionPoint) {
            if (hunspellWorker) {
                QSharedPointer<HunspellWordList> wordList(new HunspellWordList(wordCandidates));

                // Clear obsolete tasks from the worker queue
                clearSuggestionsRelatedTasks();

                // Build suggestions
                QSharedPointer<HunspellBuildSuggestionsTask> buildSuggestionsTask(new HunspellBuildSuggestionsTask());
                buildSuggestionsTask->wordList = wordList;
                buildSuggestionsTask->autoCorrect = false;
                hunspellWorker->addTask(buildSuggestionsTask);

                // Filter out blacklisted word (sometimes Hunspell suggests,
                // e.g. with different text case)
                QSharedPointer<HunspellFilterWordTask> filterWordTask(new HunspellFilterWordTask());
                filterWordTask->wordList = wordList;
                filterWordTask->filterList = blacklistedWords;
                hunspellWorker->addTask(filterWordTask);

                // Boost words from user dictionary
                QSharedPointer<HunspellBoostWordTask> boostWordTask(new HunspellBoostWordTask());
                boostWordTask->wordList = wordList;
                boostWordTask->boostList = userDictionaryWords;
                hunspellWorker->addTask(boostWordTask);

                // Update word candidate list
                QSharedPointer<HunspellUpdateSuggestionsTask> updateSuggestionsTask(new HunspellUpdateSuggestionsTask());
                updateSuggestionsTask->wordList = wordList;
                updateSuggestionsTask->tag = ++wordCandidatesUpdateTag;
                Q_Q(HunspellInputMethod);
                QObject::connect(updateSuggestionsTask.data(), &HunspellUpdateSuggestionsTask::updateSuggestions, q, &HunspellInputMethod::updateSuggestions);
                hunspellWorker->addTask(updateSuggestionsTask);
            }
        }
    } else {
        wordCandidateListChanged = clearSuggestions();
    }
    return wordCandidateListChanged;
}

bool HunspellInputMethodPrivate::clearSuggestions(bool clearInputWord)
{
    clearSuggestionsRelatedTasks();
    return clearInputWord ? wordCandidates.clear() : wordCandidates.clearSuggestions();
}

void HunspellInputMethodPrivate::clearSuggestionsRelatedTasks()
{
    if (hunspellWorker) {
        hunspellWorker->removeAllTasksOfType<HunspellBuildSuggestionsTask>();
        hunspellWorker->removeAllTasksOfType<HunspellFilterWordTask>();
        hunspellWorker->removeAllTasksOfType<HunspellBoostWordTask>();
        hunspellWorker->removeAllTasksOfType<HunspellUpdateSuggestionsTask>();
    }
}

bool HunspellInputMethodPrivate::isAutoSpaceAllowed() const
{
    Q_Q(const HunspellInputMethod);
    if (!autoSpaceAllowed)
        return false;
    if (q->inputEngine()->inputMode() == QVirtualKeyboardInputEngine::InputMode::Numeric)
        return false;
    QVirtualKeyboardInputContext *ic = q->inputContext();
    if (!ic)
        return false;
    Qt::InputMethodHints inputMethodHints = ic->inputMethodHints();
    return !inputMethodHints.testFlag(Qt::ImhUrlCharactersOnly) &&
           !inputMethodHints.testFlag(Qt::ImhEmailCharactersOnly);
}

bool HunspellInputMethodPrivate::isValidInputChar(const QChar &c) const
{
    if (c.isLetterOrNumber())
        return true;
    if (isJoiner(c))
        return true;
    if (c.isMark())
        return true;
    return false;
}

bool HunspellInputMethodPrivate::isJoiner(const QChar &c) const
{
    if (c.isPunct() || c.isSymbol()) {
        Q_Q(const HunspellInputMethod);
        QVirtualKeyboardInputContext *ic = q->inputContext();
        if (ic) {
            Qt::InputMethodHints inputMethodHints = ic->inputMethodHints();
            if (inputMethodHints.testFlag(Qt::ImhUrlCharactersOnly) || inputMethodHints.testFlag(Qt::ImhEmailCharactersOnly))
                return QString(QStringLiteral(":/?#[]@!$&'()*+,;=-_.%")).contains(c);
        }
        ushort unicode = c.unicode();
        if (unicode == Qt::Key_Apostrophe || unicode == Qt::Key_Minus)
            return true;
    }
    return false;
}

QString HunspellInputMethodPrivate::customDictionaryLocation(const QString &dictionaryType) const
{
    if (dictionaryType.isEmpty() || locale.isEmpty())
        return QString();

    QString location = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation);
    if (location.isEmpty())
        return QString();

    return QStringLiteral("%1/qtvirtualkeyboard/hunspell/%2-%3.txt")
                    .arg(location)
                    .arg(dictionaryType)
                    .arg(locale);
}

void HunspellInputMethodPrivate::loadCustomDictionary(const QSharedPointer<HunspellWordList> &wordList,
                                                      const QString &dictionaryType) const
{
    QSharedPointer<HunspellLoadWordListTask> loadWordsTask(new HunspellLoadWordListTask());
    loadWordsTask->filePath = customDictionaryLocation(dictionaryType);
    loadWordsTask->wordList = wordList;
    hunspellWorker->addTask(loadWordsTask);
}

void HunspellInputMethodPrivate::saveCustomDictionary(const QSharedPointer<HunspellWordList> &wordList,
                                                      const QString &dictionaryType) const
{
    QSharedPointer<HunspellSaveWordListTask> saveWordsTask(new HunspellSaveWordListTask());
    saveWordsTask->filePath = customDictionaryLocation(dictionaryType);
    saveWordsTask->wordList = wordList;
    hunspellWorker->addTask(saveWordsTask);
}

void HunspellInputMethodPrivate::addToHunspell(const QSharedPointer<HunspellWordList> &wordList) const
{
    QSharedPointer<HunspellAddWordTask> addWordTask(new HunspellAddWordTask());
    addWordTask->wordList = wordList;
    hunspellWorker->addTask(addWordTask);
}

void HunspellInputMethodPrivate::removeFromHunspell(const QSharedPointer<HunspellWordList> &wordList) const
{
    QSharedPointer<HunspellRemoveWordTask> removeWordTask(new HunspellRemoveWordTask());
    removeWordTask->wordList = wordList;
    hunspellWorker->addTask(removeWordTask);
}

void HunspellInputMethodPrivate::removeFromDictionary(const QString &word)
{
    if (userDictionaryWords->removeWord(word) > 0) {
        saveCustomDictionary(userDictionaryWords, QLatin1String("userdictionary"));
    } else if (!blacklistedWords->contains(word)) {
        blacklistedWords->appendWord(word);
        saveCustomDictionary(blacklistedWords, QLatin1String("blacklist"));
    }

    QSharedPointer<HunspellWordList> wordList(new HunspellWordList());
    wordList->appendWord(word);
    removeFromHunspell(wordList);

    updateSuggestions();
}

void HunspellInputMethodPrivate::addToDictionary()
{
    Q_Q(HunspellInputMethod);
    // This feature is not allowed when dealing with sensitive information
    const Qt::InputMethodHints inputMethodHints(q->inputContext()->inputMethodHints());
    const bool userDictionaryEnabled =
            !inputMethodHints.testFlag(Qt::ImhHiddenText) &&
            !inputMethodHints.testFlag(Qt::ImhSensitiveData);
    if (!userDictionaryEnabled)
        return;

    if (wordCandidates.isEmpty())
        return;

    QString word;
    HunspellWordList::Flags wordFlags;
    const int activeWordIndex = wordCandidates.index();
    wordCandidates.wordAt(activeWordIndex, word, wordFlags);
    if (activeWordIndex == 0) {
        if (blacklistedWords->removeWord(word) > 0) {
            saveCustomDictionary(blacklistedWords, QLatin1String("blacklist"));
        } else if (word.length() > 1 && !wordFlags.testFlag(HunspellWordList::SpellCheckOk) && !userDictionaryWords->contains(word)) {
            userDictionaryWords->appendWord(word);
            saveCustomDictionary(userDictionaryWords, QLatin1String("userdictionary"));
        } else {
            // Avoid adding words to Hunspell which are too short or passed spell check
            return;
        }

        QSharedPointer<HunspellWordList> wordList(new HunspellWordList());
        wordList->appendWord(word);
        addToHunspell(wordList);
    } else {
        // Check if found in the user dictionary and move as last in the list.
        // This way the list is always ordered by use.
        // If userDictionaryMaxSize is greater than zero the number of words in the
        // list will be limited to that amount. By pushing last used items to end of
        // list we can avoid (to certain extent) removing frequently used words.
        int userDictionaryIndex = userDictionaryWords->indexOfWord(word);
        if (userDictionaryIndex != -1) {
            userDictionaryWords->moveWord(userDictionaryIndex, userDictionaryWords->size() - 1);
            saveCustomDictionary(userDictionaryWords, QLatin1String("userdictionary"));
        }
    }
}

} // namespace QtVirtualKeyboard
QT_END_NAMESPACE