Home | History | Annotate | Download | only in src
      1 /*
      2  * Copyright (C) 2011 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #include <assert.h>
     18 #include <stdio.h>
     19 #include <string.h>
     20 
     21 #define LOG_TAG "LatinIME: proximity_info.cpp"
     22 
     23 #include "dictionary.h"
     24 #include "proximity_info.h"
     25 
     26 namespace latinime {
     27 
     28 inline void copyOrFillZero(void *to, const void *from, size_t size) {
     29     if (from) {
     30         memcpy(to, from, size);
     31     } else {
     32         memset(to, 0, size);
     33     }
     34 }
     35 
     36 ProximityInfo::ProximityInfo(const int maxProximityCharsSize, const int keyboardWidth,
     37         const int keyboardHeight, const int gridWidth, const int gridHeight,
     38         const uint32_t *proximityCharsArray, const int keyCount, const int32_t *keyXCoordinates,
     39         const int32_t *keyYCoordinates, const int32_t *keyWidths, const int32_t *keyHeights,
     40         const int32_t *keyCharCodes, const float *sweetSpotCenterXs, const float *sweetSpotCenterYs,
     41         const float *sweetSpotRadii)
     42         : MAX_PROXIMITY_CHARS_SIZE(maxProximityCharsSize), KEYBOARD_WIDTH(keyboardWidth),
     43           KEYBOARD_HEIGHT(keyboardHeight), GRID_WIDTH(gridWidth), GRID_HEIGHT(gridHeight),
     44           CELL_WIDTH((keyboardWidth + gridWidth - 1) / gridWidth),
     45           CELL_HEIGHT((keyboardHeight + gridHeight - 1) / gridHeight),
     46           KEY_COUNT(min(keyCount, MAX_KEY_COUNT_IN_A_KEYBOARD)),
     47           HAS_TOUCH_POSITION_CORRECTION_DATA(keyCount > 0 && keyXCoordinates && keyYCoordinates
     48                   && keyWidths && keyHeights && keyCharCodes && sweetSpotCenterXs
     49                   && sweetSpotCenterYs && sweetSpotRadii),
     50           mInputXCoordinates(NULL), mInputYCoordinates(NULL),
     51           mTouchPositionCorrectionEnabled(false) {
     52     const int proximityGridLength = GRID_WIDTH * GRID_HEIGHT * MAX_PROXIMITY_CHARS_SIZE;
     53     mProximityCharsArray = new uint32_t[proximityGridLength];
     54     if (DEBUG_PROXIMITY_INFO) {
     55         LOGI("Create proximity info array %d", proximityGridLength);
     56     }
     57     memcpy(mProximityCharsArray, proximityCharsArray,
     58             proximityGridLength * sizeof(mProximityCharsArray[0]));
     59     const int normalizedSquaredDistancesLength =
     60             MAX_PROXIMITY_CHARS_SIZE * MAX_WORD_LENGTH_INTERNAL;
     61     mNormalizedSquaredDistances = new int[normalizedSquaredDistancesLength];
     62     for (int i = 0; i < normalizedSquaredDistancesLength; ++i) {
     63         mNormalizedSquaredDistances[i] = NOT_A_DISTANCE;
     64     }
     65 
     66     copyOrFillZero(mKeyXCoordinates, keyXCoordinates, KEY_COUNT * sizeof(mKeyXCoordinates[0]));
     67     copyOrFillZero(mKeyYCoordinates, keyYCoordinates, KEY_COUNT * sizeof(mKeyYCoordinates[0]));
     68     copyOrFillZero(mKeyWidths, keyWidths, KEY_COUNT * sizeof(mKeyWidths[0]));
     69     copyOrFillZero(mKeyHeights, keyHeights, KEY_COUNT * sizeof(mKeyHeights[0]));
     70     copyOrFillZero(mKeyCharCodes, keyCharCodes, KEY_COUNT * sizeof(mKeyCharCodes[0]));
     71     copyOrFillZero(mSweetSpotCenterXs, sweetSpotCenterXs,
     72             KEY_COUNT * sizeof(mSweetSpotCenterXs[0]));
     73     copyOrFillZero(mSweetSpotCenterYs, sweetSpotCenterYs,
     74             KEY_COUNT * sizeof(mSweetSpotCenterYs[0]));
     75     copyOrFillZero(mSweetSpotRadii, sweetSpotRadii, KEY_COUNT * sizeof(mSweetSpotRadii[0]));
     76 
     77     initializeCodeToKeyIndex();
     78 }
     79 
     80 // Build the reversed look up table from the char code to the index in mKeyXCoordinates,
     81 // mKeyYCoordinates, mKeyWidths, mKeyHeights, mKeyCharCodes.
     82 void ProximityInfo::initializeCodeToKeyIndex() {
     83     memset(mCodeToKeyIndex, -1, (MAX_CHAR_CODE + 1) * sizeof(mCodeToKeyIndex[0]));
     84     for (int i = 0; i < KEY_COUNT; ++i) {
     85         const int code = mKeyCharCodes[i];
     86         if (0 <= code && code <= MAX_CHAR_CODE) {
     87             mCodeToKeyIndex[code] = i;
     88         }
     89     }
     90 }
     91 
     92 ProximityInfo::~ProximityInfo() {
     93     delete[] mNormalizedSquaredDistances;
     94     delete[] mProximityCharsArray;
     95 }
     96 
     97 inline int ProximityInfo::getStartIndexFromCoordinates(const int x, const int y) const {
     98     return ((y / CELL_HEIGHT) * GRID_WIDTH + (x / CELL_WIDTH))
     99             * MAX_PROXIMITY_CHARS_SIZE;
    100 }
    101 
    102 bool ProximityInfo::hasSpaceProximity(const int x, const int y) const {
    103     const int startIndex = getStartIndexFromCoordinates(x, y);
    104     if (DEBUG_PROXIMITY_INFO) {
    105         LOGI("hasSpaceProximity: index %d", startIndex);
    106     }
    107     for (int i = 0; i < MAX_PROXIMITY_CHARS_SIZE; ++i) {
    108         if (DEBUG_PROXIMITY_INFO) {
    109             LOGI("Index: %d", mProximityCharsArray[startIndex + i]);
    110         }
    111         if (mProximityCharsArray[startIndex + i] == KEYCODE_SPACE) {
    112             return true;
    113         }
    114     }
    115     return false;
    116 }
    117 
    118 // TODO: Calculate nearby codes here.
    119 void ProximityInfo::setInputParams(const int* inputCodes, const int inputLength,
    120         const int* xCoordinates, const int* yCoordinates) {
    121     mInputCodes = inputCodes;
    122     mInputXCoordinates = xCoordinates;
    123     mInputYCoordinates = yCoordinates;
    124     mTouchPositionCorrectionEnabled =
    125             HAS_TOUCH_POSITION_CORRECTION_DATA && xCoordinates && yCoordinates;
    126     mInputLength = inputLength;
    127     for (int i = 0; i < inputLength; ++i) {
    128         mPrimaryInputWord[i] = getPrimaryCharAt(i);
    129     }
    130     mPrimaryInputWord[inputLength] = 0;
    131     for (int i = 0; i < mInputLength; ++i) {
    132         const int *proximityChars = getProximityCharsAt(i);
    133         for (int j = 0; j < MAX_PROXIMITY_CHARS_SIZE && proximityChars[j] > 0; ++j) {
    134             const int currentChar = proximityChars[j];
    135             const int keyIndex = getKeyIndex(currentChar);
    136             const float squaredDistance = calculateNormalizedSquaredDistance(keyIndex, i);
    137             if (squaredDistance >= 0.0f) {
    138                 mNormalizedSquaredDistances[i * MAX_PROXIMITY_CHARS_SIZE + j] =
    139                         (int)(squaredDistance * NORMALIZED_SQUARED_DISTANCE_SCALING_FACTOR);
    140             } else {
    141                 mNormalizedSquaredDistances[i * MAX_PROXIMITY_CHARS_SIZE + j] = (j == 0)
    142                         ? EQUIVALENT_CHAR_WITHOUT_DISTANCE_INFO
    143                         : PROXIMITY_CHAR_WITHOUT_DISTANCE_INFO;
    144             }
    145         }
    146     }
    147 }
    148 
    149 inline float square(const float x) { return x * x; }
    150 
    151 float ProximityInfo::calculateNormalizedSquaredDistance(
    152         const int keyIndex, const int inputIndex) const {
    153     static const float NOT_A_DISTANCE_FLOAT = -1.0f;
    154     if (keyIndex == NOT_A_INDEX) {
    155         return NOT_A_DISTANCE_FLOAT;
    156     }
    157     if (!hasSweetSpotData(keyIndex)) {
    158         return NOT_A_DISTANCE_FLOAT;
    159     }
    160     const float squaredDistance = calculateSquaredDistanceFromSweetSpotCenter(keyIndex, inputIndex);
    161     const float squaredRadius = square(mSweetSpotRadii[keyIndex]);
    162     return squaredDistance / squaredRadius;
    163 }
    164 
    165 int ProximityInfo::getKeyIndex(const int c) const {
    166     if (KEY_COUNT == 0 || !mInputXCoordinates || !mInputYCoordinates) {
    167         // We do not have the coordinate data
    168         return NOT_A_INDEX;
    169     }
    170     const unsigned short baseLowerC = Dictionary::toBaseLowerCase(c);
    171     if (baseLowerC > MAX_CHAR_CODE) {
    172         return NOT_A_INDEX;
    173     }
    174     return mCodeToKeyIndex[baseLowerC];
    175 }
    176 
    177 float ProximityInfo::calculateSquaredDistanceFromSweetSpotCenter(
    178         const int keyIndex, const int inputIndex) const {
    179     const float sweetSpotCenterX = mSweetSpotCenterXs[keyIndex];
    180     const float sweetSpotCenterY = mSweetSpotCenterYs[keyIndex];
    181     const float inputX = (float)mInputXCoordinates[inputIndex];
    182     const float inputY = (float)mInputYCoordinates[inputIndex];
    183     return square(inputX - sweetSpotCenterX) + square(inputY - sweetSpotCenterY);
    184 }
    185 
    186 inline const int* ProximityInfo::getProximityCharsAt(const int index) const {
    187     return mInputCodes + (index * MAX_PROXIMITY_CHARS_SIZE);
    188 }
    189 
    190 unsigned short ProximityInfo::getPrimaryCharAt(const int index) const {
    191     return getProximityCharsAt(index)[0];
    192 }
    193 
    194 inline bool ProximityInfo::existsCharInProximityAt(const int index, const int c) const {
    195     const int *chars = getProximityCharsAt(index);
    196     int i = 0;
    197     while (chars[i] > 0 && i < MAX_PROXIMITY_CHARS_SIZE) {
    198         if (chars[i++] == c) {
    199             return true;
    200         }
    201     }
    202     return false;
    203 }
    204 
    205 bool ProximityInfo::existsAdjacentProximityChars(const int index) const {
    206     if (index < 0 || index >= mInputLength) return false;
    207     const int currentChar = getPrimaryCharAt(index);
    208     const int leftIndex = index - 1;
    209     if (leftIndex >= 0 && existsCharInProximityAt(leftIndex, currentChar)) {
    210         return true;
    211     }
    212     const int rightIndex = index + 1;
    213     if (rightIndex < mInputLength && existsCharInProximityAt(rightIndex, currentChar)) {
    214         return true;
    215     }
    216     return false;
    217 }
    218 
    219 // In the following function, c is the current character of the dictionary word
    220 // currently examined.
    221 // currentChars is an array containing the keys close to the character the
    222 // user actually typed at the same position. We want to see if c is in it: if so,
    223 // then the word contains at that position a character close to what the user
    224 // typed.
    225 // What the user typed is actually the first character of the array.
    226 // proximityIndex is a pointer to the variable where getMatchedProximityId returns
    227 // the index of c in the proximity chars of the input index.
    228 // Notice : accented characters do not have a proximity list, so they are alone
    229 // in their list. The non-accented version of the character should be considered
    230 // "close", but not the other keys close to the non-accented version.
    231 ProximityInfo::ProximityType ProximityInfo::getMatchedProximityId(const int index,
    232         const unsigned short c, const bool checkProximityChars, int *proximityIndex) const {
    233     const int *currentChars = getProximityCharsAt(index);
    234     const int firstChar = currentChars[0];
    235     const unsigned short baseLowerC = Dictionary::toBaseLowerCase(c);
    236 
    237     // The first char in the array is what user typed. If it matches right away,
    238     // that means the user typed that same char for this pos.
    239     if (firstChar == baseLowerC || firstChar == c) {
    240         return EQUIVALENT_CHAR;
    241     }
    242 
    243     if (!checkProximityChars) return UNRELATED_CHAR;
    244 
    245     // If the non-accented, lowercased version of that first character matches c,
    246     // then we have a non-accented version of the accented character the user
    247     // typed. Treat it as a close char.
    248     if (Dictionary::toBaseLowerCase(firstChar) == baseLowerC)
    249         return NEAR_PROXIMITY_CHAR;
    250 
    251     // Not an exact nor an accent-alike match: search the list of close keys
    252     int j = 1;
    253     while (j < MAX_PROXIMITY_CHARS_SIZE && currentChars[j] > 0) {
    254         const bool matched = (currentChars[j] == baseLowerC || currentChars[j] == c);
    255         if (matched) {
    256             if (proximityIndex) {
    257                 *proximityIndex = j;
    258             }
    259             return NEAR_PROXIMITY_CHAR;
    260         }
    261         ++j;
    262     }
    263 
    264     // Was not included, signal this as an unrelated character.
    265     return UNRELATED_CHAR;
    266 }
    267 
    268 bool ProximityInfo::sameAsTyped(const unsigned short *word, int length) const {
    269     if (length != mInputLength) {
    270         return false;
    271     }
    272     const int *inputCodes = mInputCodes;
    273     while (length--) {
    274         if ((unsigned int) *inputCodes != (unsigned int) *word) {
    275             return false;
    276         }
    277         inputCodes += MAX_PROXIMITY_CHARS_SIZE;
    278         word++;
    279     }
    280     return true;
    281 }
    282 
    283 const int ProximityInfo::NORMALIZED_SQUARED_DISTANCE_SCALING_FACTOR_LOG_2;
    284 const int ProximityInfo::NORMALIZED_SQUARED_DISTANCE_SCALING_FACTOR;
    285 const int ProximityInfo::MAX_KEY_COUNT_IN_A_KEYBOARD;
    286 const int ProximityInfo::MAX_CHAR_CODE;
    287 
    288 } // namespace latinime
    289