aboutsummaryrefslogtreecommitdiffstats
path: root/src/virtualkeyboard/t9writeworker.cpp
blob: 955eb9f77a97ca898d6aaecbb01cb6defde00d3a (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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/******************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Virtual Keyboard module.
**
** $QT_BEGIN_LICENSE:COMM$
**
** 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 http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** $QT_END_LICENSE$
**
******************************************************************************/

#include "t9writeworker.h"
#include "virtualkeyboarddebug.h"

#include <QFile>
#include <QTime>

namespace QtVirtualKeyboard {

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

T9WriteTask::T9WriteTask(QObject *parent) :
    QObject(parent),
    decumaSession(0),
    runSema()
{
}

void T9WriteTask::wait()
{
    runSema.acquire();
    runSema.release();
}

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

T9WriteDictionaryTask::T9WriteDictionaryTask(const QString &fileUri,
                                             const DECUMA_MEM_FUNCTIONS &memFuncs) :
    fileUri(fileUri),
    memFuncs(memFuncs)
{
}

void T9WriteDictionaryTask::run()
{
    VIRTUALKEYBOARD_DEBUG() << "T9WriteDictionaryTask::run()";

#ifdef QT_VIRTUALKEYBOARD_DEBUG
    QTime perf;
    perf.start();
#endif

    void *dictionary = 0;

    QFile dictionaryFile(fileUri);
    if (dictionaryFile.open(QIODevice::ReadOnly)) {
        uchar *dictionaryData = dictionaryFile.map(0, dictionaryFile.size(), QFile::NoOptions);
        if (dictionaryData) {

            DECUMA_SRC_DICTIONARY_INFO dictionaryInfo;
            memset(&dictionaryInfo, 0, sizeof(dictionaryInfo));
            dictionaryInfo.srcType = decumaXT9LDB;
            DECUMA_UINT32 dictionarySize = 0;
            DECUMA_STATUS status = decumaConvertDictionary(&dictionary, dictionaryData, dictionaryFile.size(), &dictionaryInfo, &dictionarySize, &memFuncs);
            Q_UNUSED(status)
            Q_ASSERT(status == decumaNoError);
            dictionaryFile.unmap(dictionaryData);
        } else {
            qWarning() << "Could not map dictionary file" << fileUri;
        }
    } else {
        qWarning() << "Could not open dictionary file" << fileUri;
    }

#ifdef QT_VIRTUALKEYBOARD_DEBUG
    VIRTUALKEYBOARD_DEBUG() << "T9WriteDictionaryTask::run(): time:" << perf.elapsed() << "ms";
#endif

    emit completed(fileUri, dictionary);
}

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

T9WriteRecognitionResult::T9WriteRecognitionResult(int id, int maxResults, int maxCharsPerWord) :
    numResults(0),
    instantGesture(0),
    id(id),
    maxResults(maxResults),
    maxCharsPerWord(maxCharsPerWord)
{
    Q_ASSERT(maxResults > 0);
    Q_ASSERT(maxCharsPerWord > 0);
    results.resize(maxResults);
    int bufferLength = (maxCharsPerWord + 1);
    _chars.resize(maxResults * bufferLength);
    _symbolChars.resize(maxResults * bufferLength);
    _symbolStrokes.resize(maxResults * bufferLength);
    for (int i = 0; i < maxResults; i++) {
        DECUMA_HWR_RESULT &hwrResult = results[i];
        hwrResult.pChars = &_chars[i * bufferLength];
        hwrResult.pSymbolChars = &_symbolChars[i * bufferLength];
        hwrResult.pSymbolStrokes = &_symbolStrokes[i * bufferLength];
    }
}

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

T9WriteRecognitionTask::T9WriteRecognitionTask(QSharedPointer<T9WriteRecognitionResult> result,
                                               const DECUMA_INSTANT_GESTURE_SETTINGS &instantGestureSettings,
                                               BOOST_LEVEL boostLevel,
                                               const QString &stringStart) :
    T9WriteTask(),
    result(result),
    instantGestureSettings(instantGestureSettings),
    boostLevel(boostLevel),
    stringStart(stringStart),
    stateCancelled(false)
{
#ifdef SENSITIVE_DEBUG
    VIRTUALKEYBOARD_DEBUG() << "T9WriteRecognitionTask():" << "boostLevel:" << boostLevel << "stringStart:" << stringStart;
#endif
}

void T9WriteRecognitionTask::run()
{
    VIRTUALKEYBOARD_DEBUG() << "T9WriteRecognitionTask::run()";

    if (!decumaSession)
        return;

    {
        QMutexLocker stateGuard(&stateLock);
        Q_UNUSED(stateGuard);
        if (stateCancelled)
            return;
    }

    //In a normal text composition case boostDictWords and canBeContinued are the preffered settings
    DECUMA_RECOGNITION_SETTINGS recSettings;
    memset(&recSettings, 0, sizeof(recSettings));
    recSettings.boostLevel = boostLevel;
    recSettings.stringCompleteness = canBeContinued;
    if (!stringStart.isEmpty())
        recSettings.pStringStart = (DECUMA_UNICODE *)stringStart.utf16();

#ifdef QT_VIRTUALKEYBOARD_DEBUG
    QTime perf;
    perf.start();
#endif

    DECUMA_STATUS status = decumaIndicateInstantGesture(decumaSession, &result->instantGesture, &instantGestureSettings);
    Q_ASSERT(status == decumaNoError);

    DECUMA_INTERRUPT_FUNCTIONS interruptFunctions;
    interruptFunctions.pShouldAbortRecognize = shouldAbortRecognize;
    interruptFunctions.pUserData = (void *)this;
    status = decumaRecognize(decumaSession, result->results.data(), result->results.size(), &result->numResults, result->maxCharsPerWord, &recSettings, &interruptFunctions);
    if (status == decumaAbortRecognitionUnsupported)
        status = decumaRecognize(decumaSession, result->results.data(), result->results.size(), &result->numResults, result->maxCharsPerWord, &recSettings, NULL);
    Q_ASSERT(status == decumaNoError);

    QStringList resultList;
    QString gesture;
    for (int i = 0; i < result->numResults; i++)
    {
        QString resultString;
        resultString.reserve(result->results[i].nChars);
        int charPos = 0;
        for (int symbolIndex = 0; symbolIndex < result->results[i].nSymbols; symbolIndex++) {
            int symbolLength = result->results[i].pSymbolChars[symbolIndex];
            QString symbol(QString::fromUtf16(&result->results[i].pChars[charPos], symbolLength));
            // Do not append gesture symbol to result string
            if (result->results[i].bGesture && symbolIndex == (result->results[i].nSymbols - 1)) {
                if (i == 0 && (result->instantGesture || (symbol != QLatin1String(" ") && symbol != QLatin1String("\b"))))
                    gesture = symbol;
            } else {
                resultString.append(symbol);
            }
            charPos += symbolLength;
        }
        resultList.append(resultString);
    }

#ifdef QT_VIRTUALKEYBOARD_DEBUG
    int perfElapsed = perf.elapsed();
#endif

    {
        QMutexLocker stateGuard(&stateLock);
        Q_UNUSED(stateGuard)
        if (stateCancelled)
            result.reset();
#ifdef QT_VIRTUALKEYBOARD_DEBUG
        VIRTUALKEYBOARD_DEBUG() << "T9WriteRecognitionTask::run(): time:" << perfElapsed << "ms" << (stateCancelled ? "(cancelled)" : "");
#endif
    }
}

int T9WriteRecognitionTask::shouldAbortRecognize(void *pUserData)
{
    T9WriteRecognitionTask *pThis = (T9WriteRecognitionTask *)pUserData;
    QMutexLocker stateGuard(&pThis->stateLock);
    Q_UNUSED(stateGuard)
    return pThis->stateCancelled;
}

bool T9WriteRecognitionTask::cancelRecognition()
{
    QMutexLocker stateGuard(&stateLock);
    Q_UNUSED(stateGuard)
    stateCancelled = true;
    return true;
}

int T9WriteRecognitionTask::resultId() const
{
    return result != 0 ? result->id : -1;
}

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

T9WriteRecognitionResultsTask::T9WriteRecognitionResultsTask(QSharedPointer<T9WriteRecognitionResult> result) :
    T9WriteTask(),
    result(result)
{
}

void T9WriteRecognitionResultsTask::run()
{
    if (!result)
        return;

    QVariantList resultList;
    for (int i = 0; i < result->numResults; i++)
    {
        QVariantMap resultMap;
        QString resultString;
        QString gesture;
        const DECUMA_HWR_RESULT &hwrResult = result->results.at(i);
        resultString.reserve(hwrResult.nChars);
        QVariantList symbolStrokes;
        int charPos = 0;
        for (int symbolIndex = 0; symbolIndex < hwrResult.nSymbols; symbolIndex++) {
            int symbolLength = hwrResult.pSymbolChars[symbolIndex];
            QString symbol(QString::fromUtf16(&hwrResult.pChars[charPos], symbolLength));
            // Do not append gesture symbol to result string
            if (hwrResult.bGesture && symbolIndex == (hwrResult.nSymbols - 1)) {
                if (result->instantGesture || (symbol != QLatin1String(" ") && symbol != QLatin1String("\b")))
                    gesture = symbol;
            } else {
                resultString.append(symbol);
            }
            charPos += symbolLength;
            if (hwrResult.pSymbolStrokes)
                symbolStrokes.append(QVariant((int)hwrResult.pSymbolStrokes[symbolIndex]));
        }

        resultMap["resultId"] = result->id;
        resultMap["chars"] = resultString;
        resultMap["symbolStrokes"] = symbolStrokes;
        if (!gesture.isEmpty())
            resultMap["gesture"] = gesture;

        resultList.append(resultMap);
    }

    if (resultList.isEmpty())
        return;

    emit resultsAvailable(resultList);
}

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

T9WriteWorker::T9WriteWorker(DECUMA_SESSION *decumaSession, QObject *parent) :
    QThread(parent),
    taskSema(),
    taskLock(),
    decumaSession(decumaSession),
    abort(false)
{
}

T9WriteWorker::~T9WriteWorker()
{
    abort = true;
    taskSema.release();
    wait();
}

void T9WriteWorker::addTask(QSharedPointer<T9WriteTask> task)
{
    if (task) {
        QMutexLocker guard(&taskLock);
        task->moveToThread(this);
        taskList.append(task);
        taskSema.release();
    }
}

int T9WriteWorker::removeTask(QSharedPointer<T9WriteTask> task)
{
    int count = 0;
    if (task) {
        QMutexLocker guard(&taskLock);
        count = taskList.removeAll(task);
        taskSema.acquire(qMin(count, taskSema.available()));
    }
    return count;
}

int T9WriteWorker::removeAllTasks()
{
    QMutexLocker guard(&taskLock);
    int count = taskList.count();
    taskList.clear();
    if (taskSema.available())
        taskSema.acquire(taskSema.available());
    return count;
}

void T9WriteWorker::run()
{
    while (!abort) {
        taskSema.acquire();
        if (abort)
            break;
        QSharedPointer<T9WriteTask> currentTask;
        {
            QMutexLocker guard(&taskLock);
            if (!taskList.isEmpty()) {
                currentTask = taskList.front();
                taskList.pop_front();
            }
        }
        if (currentTask) {
            currentTask->decumaSession = decumaSession;
            currentTask->run();
            currentTask->runSema.release();
        }
    }
}

} // namespace QtVirtualKeyboard