aboutsummaryrefslogtreecommitdiffstats
path: root/native/jni/src/proximity_info_state.cpp
blob: e13d4e664560676bc6ba54bb223689e0fcbf5452 (about) (plain) (blame)
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cstring> // for memset()
#include <stdint.h>

#define LOG_TAG "LatinIME: proximity_info_state.cpp"

#include "defines.h"
#include "geometry_utils.h"
#include "proximity_info.h"
#include "proximity_info_state.h"

namespace latinime {
void ProximityInfoState::initInputParams(const int pointerId, const float maxPointToKeyLength,
        const ProximityInfo *proximityInfo, const int32_t *const inputCodes, const int inputSize,
        const int *const xCoordinates, const int *const yCoordinates, const int *const times,
        const int *const pointerIds, const bool isGeometric) {
    mProximityInfo = proximityInfo;
    mHasTouchPositionCorrectionData = proximityInfo->hasTouchPositionCorrectionData();
    mMostCommonKeyWidthSquare = proximityInfo->getMostCommonKeyWidthSquare();
    mLocaleStr = proximityInfo->getLocaleStr();
    mKeyCount = proximityInfo->getKeyCount();
    mCellHeight = proximityInfo->getCellHeight();
    mCellWidth = proximityInfo->getCellWidth();
    mGridHeight = proximityInfo->getGridWidth();
    mGridWidth = proximityInfo->getGridHeight();

    memset(mInputCodes, 0, sizeof(mInputCodes));

    if (!isGeometric && pointerId == 0) {
        // Initialize
        // - mInputCodes
        // - mNormalizedSquaredDistances
        // TODO: Merge
        for (int i = 0; i < inputSize; ++i) {
            const int32_t primaryKey = inputCodes[i];
            const int x = xCoordinates[i];
            const int y = yCoordinates[i];
            int *proximities = &mInputCodes[i * MAX_PROXIMITY_CHARS_SIZE_INTERNAL];
            mProximityInfo->calculateNearbyKeyCodes(x, y, primaryKey, proximities);
        }

        if (DEBUG_PROXIMITY_CHARS) {
            for (int i = 0; i < inputSize; ++i) {
                AKLOGI("---");
                for (int j = 0; j < MAX_PROXIMITY_CHARS_SIZE_INTERNAL; ++j) {
                    int icc = mInputCodes[i * MAX_PROXIMITY_CHARS_SIZE_INTERNAL + j];
                    int icfjc = inputCodes[i * MAX_PROXIMITY_CHARS_SIZE_INTERNAL + j];
                    icc += 0;
                    icfjc += 0;
                    AKLOGI("--- (%d)%c,%c", i, icc, icfjc); AKLOGI("--- A<%d>,B<%d>", icc, icfjc);
                }
            }
        }
    }

    ///////////////////////
    // Setup touch points
    mMaxPointToKeyLength = maxPointToKeyLength;
    mInputXs.clear();
    mInputYs.clear();
    mTimes.clear();
    mLengthCache.clear();
    mDistanceCache.clear();
    mInputSize = 0;

    if (xCoordinates && yCoordinates) {
        const bool proximityOnly = !isGeometric && (xCoordinates[0] < 0 || yCoordinates[0] < 0);
        int lastInputIndex = 0;
        for (int i = 0; i < inputSize; ++i) {
            const int pid = pointerIds ? pointerIds[i] : 0;
            if (pointerId == pid) {
                lastInputIndex = i;
            }
        }
        // Working space to save near keys distances for current, prev and prevprev input point.
        NearKeysDistanceMap nearKeysDistances[3];
        // These pointers are swapped for each inputs points.
        NearKeysDistanceMap *currentNearKeysDistances = &nearKeysDistances[0];
        NearKeysDistanceMap *prevNearKeysDistances = &nearKeysDistances[1];
        NearKeysDistanceMap *prevPrevNearKeysDistances = &nearKeysDistances[2];

        for (int i = 0; i < inputSize; ++i) {
            // Assuming pointerId == 0 if pointerIds is null.
            const int pid = pointerIds ? pointerIds[i] : 0;
            if (pointerId == pid) {
                const int c = isGeometric ? NOT_A_COORDINATE : getPrimaryCharAt(i);
                const int x = proximityOnly ? NOT_A_COORDINATE : xCoordinates[i];
                const int y = proximityOnly ? NOT_A_COORDINATE : yCoordinates[i];
                const int time = times ? times[i] : -1;
                if (pushTouchPoint(c, x, y, time, isGeometric, i == lastInputIndex,
                        currentNearKeysDistances, prevNearKeysDistances,
                        prevPrevNearKeysDistances)) {
                    // Previous point information was popped.
                    NearKeysDistanceMap *tmp = prevNearKeysDistances;
                    prevNearKeysDistances = currentNearKeysDistances;
                    currentNearKeysDistances = tmp;
                } else {
                    NearKeysDistanceMap *tmp = prevPrevNearKeysDistances;
                    prevPrevNearKeysDistances = prevNearKeysDistances;
                    prevNearKeysDistances = currentNearKeysDistances;
                    currentNearKeysDistances = tmp;
                }
            }
        }
        mInputSize = mInputXs.size();
    }

    if (mInputSize > 0) {
        const int keyCount = mProximityInfo->getKeyCount();
        mDistanceCache.resize(mInputSize * keyCount);
        for (int i = 0; i < mInputSize; ++i) {
            for (int k = 0; k < keyCount; ++k) {
                const int index = i * keyCount + k;
                const int x = mInputXs[i];
                const int y = mInputYs[i];
                mDistanceCache[index] =
                        mProximityInfo->getNormalizedSquaredDistanceFromCenterFloat(k, x, y);
            }
        }
    }

    // end
    ///////////////////////

    memset(mNormalizedSquaredDistances, NOT_A_DISTANCE, sizeof(mNormalizedSquaredDistances));
    memset(mPrimaryInputWord, 0, sizeof(mPrimaryInputWord));
    mTouchPositionCorrectionEnabled = mInputSize > 0 && mHasTouchPositionCorrectionData
            && xCoordinates && yCoordinates && !isGeometric;
    if (!isGeometric && pointerId == 0) {
        for (int i = 0; i < inputSize; ++i) {
            mPrimaryInputWord[i] = getPrimaryCharAt(i);
        }

        for (int i = 0; i < mInputSize && mTouchPositionCorrectionEnabled; ++i) {
            const int *proximityChars = getProximityCharsAt(i);
            const int primaryKey = proximityChars[0];
            const int x = xCoordinates[i];
            const int y = yCoordinates[i];
            if (DEBUG_PROXIMITY_CHARS) {
                int a = x + y + primaryKey;
                a += 0;
                AKLOGI("--- Primary = %c, x = %d, y = %d", primaryKey, x, y);
            }
            for (int j = 0; j < MAX_PROXIMITY_CHARS_SIZE_INTERNAL && proximityChars[j] > 0; ++j) {
                const int currentChar = proximityChars[j];
                const float squaredDistance =
                        hasInputCoordinates() ? calculateNormalizedSquaredDistance(
                                mProximityInfo->getKeyIndex(currentChar), i) :
                                NOT_A_DISTANCE_FLOAT;
                if (squaredDistance >= 0.0f) {
                    mNormalizedSquaredDistances[i * MAX_PROXIMITY_CHARS_SIZE_INTERNAL + j] =
                            (int) (squaredDistance * NORMALIZED_SQUARED_DISTANCE_SCALING_FACTOR);
                } else {
                    mNormalizedSquaredDistances[i * MAX_PROXIMITY_CHARS_SIZE_INTERNAL + j] =
                            (j == 0) ? EQUIVALENT_CHAR_WITHOUT_DISTANCE_INFO :
                                    PROXIMITY_CHAR_WITHOUT_DISTANCE_INFO;
                }
                if (DEBUG_PROXIMITY_CHARS) {
                    AKLOGI("--- Proximity (%d) = %c", j, currentChar);
                }
            }
        }
    }
}

// Calculating point to key distance for all near keys and returning the distance between
// the given point and the nearest key position.
float ProximityInfoState::updateNearKeysDistances(const int x, const int y,
        NearKeysDistanceMap *const currentNearKeysDistances) {
    static const float NEAR_KEY_THRESHOLD = 10.0f;

    currentNearKeysDistances->clear();
    const int keyCount = mProximityInfo->getKeyCount();
    float nearestKeyDistance = mMaxPointToKeyLength;
    for (int k = 0; k < keyCount; ++k) {
        const float dist = mProximityInfo->getNormalizedSquaredDistanceFromCenterFloat(k, x, y);
        if (dist < NEAR_KEY_THRESHOLD) {
            currentNearKeysDistances->insert(std::pair<int, float>(k, dist));
        }
        if (nearestKeyDistance > dist) {
            nearestKeyDistance = dist;
        }
    }
    return nearestKeyDistance;
}

// Check if previous point is at local minimum position to near keys.
bool ProximityInfoState::isPrevLocalMin(const NearKeysDistanceMap *const currentNearKeysDistances,
        const NearKeysDistanceMap *const prevNearKeysDistances,
        const NearKeysDistanceMap *const prevPrevNearKeysDistances) const {
    static const float MARGIN = 0.5f;

    for (NearKeysDistanceMap::const_iterator it = prevNearKeysDistances->begin();
        it != prevNearKeysDistances->end(); ++it) {
        NearKeysDistanceMap::const_iterator itPP = prevPrevNearKeysDistances->find(it->first);
        NearKeysDistanceMap::const_iterator itC = currentNearKeysDistances->find(it->first);
        if ((itPP == prevPrevNearKeysDistances->end() || itPP->second > it->second + MARGIN)
                && (itC == currentNearKeysDistances->end() || itC->second > it->second + MARGIN)) {
            return true;
        }
    }
    return false;
}

// Calculating a point score that indicates usefulness of the point.
float ProximityInfoState::getPointScore(
        const int x, const int y, const int time, const bool lastPoint, const float nearest,
        const NearKeysDistanceMap *const currentNearKeysDistances,
        const NearKeysDistanceMap *const prevNearKeysDistances,
        const NearKeysDistanceMap *const prevPrevNearKeysDistances) const {
    static const float BASE_SAMPLE_RATE_SCALE = 0.1f;
    static const float SAVE_DISTANCE_SCALE = 12.0f;
    static const float SAVE_DISTANCE_SCORE = 2.0f;
    static const float SKIP_DISTANCE_SCALE = 1.5f;
    static const float SKIP_DISTANCE_SCORE = -1.0f;
    static const float CHECK_LOCALMIN_DISTANCE_THRESHOLD_SCALE = 2.5f;
    static const float CHECK_LOCALMIN_DISTANCE_SCORE = -1.0f;
    static const float STRAIGHT_ANGLE_THRESHOLD = M_PI_F / 32.0f;
    static const float STRAIGHT_SKIP_DISTANCE_THRESHOLD_SCALE = 4.0f;
    static const float STRAIGHT_SKIP_NEAREST_DISTANCE_THRESHOLD = 0.5f;
    static const float STRAIGHT_SKIP_SCORE = -1.0f;

    const std::size_t size = mInputXs.size();
    if (size <= 1) {
        return 0;
    }
    const float baseSampleRate = mProximityInfo->getMostCommonKeyWidth() * BASE_SAMPLE_RATE_SCALE;
    const float distNext = getDistanceFloat(x, y, mInputXs.back(), mInputYs.back());
    const float distPrev = getDistanceFloat(mInputXs.back(), mInputYs.back(),
            mInputXs[size - 2], mInputYs[size - 2]);
    float score = 0.0f;

    // Sum of distances
    if (distPrev + distNext > baseSampleRate * SAVE_DISTANCE_SCALE) {
        score +=  SAVE_DISTANCE_SCORE;
    }
    // Distance
    if (distPrev < baseSampleRate * SKIP_DISTANCE_SCALE) {
        score += SKIP_DISTANCE_SCORE;
    }
    // Location
    if (!isPrevLocalMin(currentNearKeysDistances, currentNearKeysDistances,
            prevPrevNearKeysDistances)) {
        if (distPrev < baseSampleRate * CHECK_LOCALMIN_DISTANCE_THRESHOLD_SCALE) {
            score += CHECK_LOCALMIN_DISTANCE_SCORE;
        }
    }
    // Angle
    const float angle1 = getAngle(x, y, mInputXs.back(), mInputYs.back());
    const float angle2 = getAngle(mInputXs.back(), mInputYs.back(),
            mInputXs[size - 2], mInputYs[size - 2]);
    if (getAngleDiff(angle1, angle2) < STRAIGHT_ANGLE_THRESHOLD) {
        if (nearest > STRAIGHT_SKIP_NEAREST_DISTANCE_THRESHOLD
                && distPrev < baseSampleRate * STRAIGHT_SKIP_DISTANCE_THRESHOLD_SCALE) {
            score += STRAIGHT_SKIP_SCORE;
        }
    }
    return score;
}

// Sampling touch point and pushing information to vectors.
// Returning if previous point is popped or not.
bool ProximityInfoState::pushTouchPoint(const int nodeChar, int x, int y, const int time,
        const bool sample, const bool isLastPoint,
        NearKeysDistanceMap *const currentNearKeysDistances,
        const NearKeysDistanceMap *const prevNearKeysDistances,
        const NearKeysDistanceMap *const prevPrevNearKeysDistances) {
    static const float LAST_POINT_SKIP_DISTANCE_SCALE = 0.25f;

    uint32_t size = mInputXs.size();
    bool popped = false;
    if (nodeChar < 0 && sample) {
        const float nearest = updateNearKeysDistances(x, y, currentNearKeysDistances);
        const float score = getPointScore(x, y, time, isLastPoint, nearest,
                currentNearKeysDistances, prevNearKeysDistances, prevPrevNearKeysDistances);
        if (score < 0) {
            // Pop previous point because it would be useless.
            mInputXs.pop_back();
            mInputYs.pop_back();
            mTimes.pop_back();
            mLengthCache.pop_back();
            size = mInputXs.size();
            popped = true;
        } else {
            popped = false;
        }
        // Check if the last point should be skipped.
        if (isLastPoint) {
            if (size > 0 && getDistanceFloat(x, y, mInputXs.back(), mInputYs.back())
                    < mProximityInfo->getMostCommonKeyWidth() * LAST_POINT_SKIP_DISTANCE_SCALE) {
                return popped;
            } else if (size > 1) {
                int minChar = 0;
                float minDist = mMaxPointToKeyLength;
                for (NearKeysDistanceMap::const_iterator it = currentNearKeysDistances->begin();
                        it != currentNearKeysDistances->end(); ++it) {
                    if(minDist > it->second){
                        minChar = it->first;
                        minDist = it->second;
                    }
                }
                NearKeysDistanceMap::const_iterator itPP =
                        prevNearKeysDistances->find(minChar);
                if (itPP != prevNearKeysDistances->end() && minDist > itPP->second) {
                    return popped;
                }
            }
        }
    }

    if (nodeChar >= 0 && (x < 0 || y < 0)) {
        const int keyId = mProximityInfo->getKeyIndex(nodeChar);
        if (keyId >= 0) {
            x = mProximityInfo->getKeyCenterXOfIdG(keyId);
            y = mProximityInfo->getKeyCenterYOfIdG(keyId);
        }
    }

    // Pushing point information.
    if (size > 0) {
        mLengthCache.push_back(
                mLengthCache.back() + getDistanceInt(x, y, mInputXs.back(), mInputYs.back()));
    } else {
        mLengthCache.push_back(0);
    }
    mInputXs.push_back(x);
    mInputYs.push_back(y);
    mTimes.push_back(time);
    return popped;
}

float ProximityInfoState::calculateNormalizedSquaredDistance(
        const int keyIndex, const int inputIndex) const {
    if (keyIndex == NOT_AN_INDEX) {
        return NOT_A_DISTANCE_FLOAT;
    }
    if (!mProximityInfo->hasSweetSpotData(keyIndex)) {
        return NOT_A_DISTANCE_FLOAT;
    }
    if (NOT_A_COORDINATE == mInputXs[inputIndex]) {
        return NOT_A_DISTANCE_FLOAT;
    }
    const float squaredDistance = calculateSquaredDistanceFromSweetSpotCenter(
            keyIndex, inputIndex);
    const float squaredRadius = square(mProximityInfo->getSweetSpotRadiiAt(keyIndex));
    return squaredDistance / squaredRadius;
}

int ProximityInfoState::getDuration(const int index) const {
    if (mInputSize > 0 && index > 0 && index < static_cast<int>(mInputSize) - 1) {
        return mTimes[index + 1] - mTimes[index - 1];
    }
    return 0;
}

float ProximityInfoState::getPointToKeyLength(int inputIndex, int charCode, float scale) {
    const int keyId = mProximityInfo->getKeyIndex(charCode);
    if (keyId >= 0) {
        const int index = inputIndex * mProximityInfo->getKeyCount() + keyId;
        return min(mDistanceCache[index] * scale, mMaxPointToKeyLength);
    }
    return 0;
}

int ProximityInfoState::getKeyKeyDistance(int key0, int key1) {
    return mProximityInfo->getKeyKeyDistanceG(key0, key1);
}

int ProximityInfoState::getSpaceY() {
    const int keyId = mProximityInfo->getKeyIndex(' ');
    return mProximityInfo->getKeyCenterYOfIdG(keyId);
}

float ProximityInfoState::calculateSquaredDistanceFromSweetSpotCenter(
        const int keyIndex, const int inputIndex) const {
    const float sweetSpotCenterX = mProximityInfo->getSweetSpotCenterXAt(keyIndex);
    const float sweetSpotCenterY = mProximityInfo->getSweetSpotCenterYAt(keyIndex);
    const float inputX = static_cast<float>(mInputXs[inputIndex]);
    const float inputY = static_cast<float>(mInputYs[inputIndex]);
    return square(inputX - sweetSpotCenterX) + square(inputY - sweetSpotCenterY);
}
} // namespace latinime