blob: 91e3c81340c860deaa0250574b8379f1b78a7ccf [file] [log] [blame]
satok30088252010-12-01 21:22:15 +09001/*
2**
3** Copyright 2010, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
satok48e432c2010-12-06 17:38:58 +090018#include <assert.h>
satok30088252010-12-01 21:22:15 +090019#include <string.h>
20
satoke808e432010-12-02 14:53:24 +090021#define LOG_TAG "LatinIME: unigram_dictionary.cpp"
satok30088252010-12-01 21:22:15 +090022
satok30088252010-12-01 21:22:15 +090023#include "basechars.h"
24#include "char_utils.h"
satoke808e432010-12-02 14:53:24 +090025#include "dictionary.h"
26#include "unigram_dictionary.h"
satok30088252010-12-01 21:22:15 +090027
28namespace latinime {
29
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090030const UnigramDictionary::digraph_t UnigramDictionary::GERMAN_UMLAUT_DIGRAPHS[] =
31 { { 'a', 'e' },
32 { 'o', 'e' },
33 { 'u', 'e' } };
34
Jean Chalard293ece02011-06-16 20:55:16 +090035// TODO: check the header
36UnigramDictionary::UnigramDictionary(const uint8_t* const streamStart, int typedLetterMultiplier,
satok662fe692010-12-08 17:05:39 +090037 int fullWordMultiplier, int maxWordLength, int maxWords, int maxProximityChars,
satok18c28f42010-12-02 18:11:54 +090038 const bool isLatestDictVersion)
Jean Chalard293ece02011-06-16 20:55:16 +090039 : DICT_ROOT(streamStart),
40 MAX_WORD_LENGTH(maxWordLength), MAX_WORDS(maxWords),
satok662fe692010-12-08 17:05:39 +090041 MAX_PROXIMITY_CHARS(maxProximityChars), IS_LATEST_DICT_VERSION(isLatestDictVersion),
42 TYPED_LETTER_MULTIPLIER(typedLetterMultiplier), FULL_WORD_MULTIPLIER(fullWordMultiplier),
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090043 ROOT_POS(isLatestDictVersion ? DICTIONARY_HEADER_SIZE : 0),
Jean Chalarda787dba2011-03-04 12:17:48 +090044 BYTES_IN_ONE_CHAR(MAX_PROXIMITY_CHARS * sizeof(*mInputCodes)),
45 MAX_UMLAUT_SEARCH_DEPTH(DEFAULT_MAX_UMLAUT_SEARCH_DEPTH) {
Ken Wakasade3070a2011-03-19 09:16:42 +090046 if (DEBUG_DICT) {
47 LOGI("UnigramDictionary - constructor");
48 }
satok30088252010-12-01 21:22:15 +090049}
50
satok18c28f42010-12-02 18:11:54 +090051UnigramDictionary::~UnigramDictionary() {}
satok30088252010-12-01 21:22:15 +090052
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090053static inline unsigned int getCodesBufferSize(const int* codes, const int codesSize,
54 const int MAX_PROXIMITY_CHARS) {
55 return sizeof(*codes) * MAX_PROXIMITY_CHARS * codesSize;
56}
57
58bool UnigramDictionary::isDigraph(const int* codes, const int i, const int codesSize) const {
59
60 // There can't be a digraph if we don't have at least 2 characters to examine
61 if (i + 2 > codesSize) return false;
62
63 // Search for the first char of some digraph
64 int lastDigraphIndex = -1;
65 const int thisChar = codes[i * MAX_PROXIMITY_CHARS];
66 for (lastDigraphIndex = sizeof(GERMAN_UMLAUT_DIGRAPHS) / sizeof(GERMAN_UMLAUT_DIGRAPHS[0]) - 1;
67 lastDigraphIndex >= 0; --lastDigraphIndex) {
68 if (thisChar == GERMAN_UMLAUT_DIGRAPHS[lastDigraphIndex].first) break;
69 }
70 // No match: return early
71 if (lastDigraphIndex < 0) return false;
72
73 // It's an interesting digraph if the second char matches too.
74 return GERMAN_UMLAUT_DIGRAPHS[lastDigraphIndex].second == codes[(i + 1) * MAX_PROXIMITY_CHARS];
75}
76
77// Mostly the same arguments as the non-recursive version, except:
78// codes is the original value. It points to the start of the work buffer, and gets passed as is.
79// codesSize is the size of the user input (thus, it is the size of codesSrc).
80// codesDest is the current point in the work buffer.
81// codesSrc is the current point in the user-input, original, content-unmodified buffer.
82// codesRemain is the remaining size in codesSrc.
83void UnigramDictionary::getWordWithDigraphSuggestionsRec(const ProximityInfo *proximityInfo,
84 const int *xcoordinates, const int* ycoordinates, const int *codesBuffer,
85 const int codesBufferSize, const int flags, const int* codesSrc, const int codesRemain,
satok3c4bb772011-03-04 22:50:19 -080086 const int currentDepth, int* codesDest, unsigned short* outWords, int* frequencies) {
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090087
Jean Chalarda787dba2011-03-04 12:17:48 +090088 if (currentDepth < MAX_UMLAUT_SEARCH_DEPTH) {
89 for (int i = 0; i < codesRemain; ++i) {
90 if (isDigraph(codesSrc, i, codesRemain)) {
91 // Found a digraph. We will try both spellings. eg. the word is "pruefen"
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090092
Jean Chalarda787dba2011-03-04 12:17:48 +090093 // Copy the word up to the first char of the digraph, then continue processing
94 // on the remaining part of the word, skipping the second char of the digraph.
95 // In our example, copy "pru" and continue running on "fen"
96 // Make i the index of the second char of the digraph for simplicity. Forgetting
97 // to do that results in an infinite recursion so take care!
98 ++i;
99 memcpy(codesDest, codesSrc, i * BYTES_IN_ONE_CHAR);
100 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates,
101 codesBuffer, codesBufferSize, flags,
102 codesSrc + (i + 1) * MAX_PROXIMITY_CHARS, codesRemain - i - 1,
103 currentDepth + 1, codesDest + i * MAX_PROXIMITY_CHARS, outWords,
104 frequencies);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900105
Jean Chalarda787dba2011-03-04 12:17:48 +0900106 // Copy the second char of the digraph in place, then continue processing on
107 // the remaining part of the word.
108 // In our example, after "pru" in the buffer copy the "e", and continue on "fen"
109 memcpy(codesDest + i * MAX_PROXIMITY_CHARS, codesSrc + i * MAX_PROXIMITY_CHARS,
110 BYTES_IN_ONE_CHAR);
111 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates,
112 codesBuffer, codesBufferSize, flags, codesSrc + i * MAX_PROXIMITY_CHARS,
113 codesRemain - i, currentDepth + 1, codesDest + i * MAX_PROXIMITY_CHARS,
114 outWords, frequencies);
115 return;
116 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900117 }
118 }
119
120 // If we come here, we hit the end of the word: let's check it against the dictionary.
121 // In our example, we'll come here once for "prufen" and then once for "pruefen".
122 // If the word contains several digraphs, we'll come it for the product of them.
123 // eg. if the word is "ueberpruefen" we'll test, in order, against
124 // "uberprufen", "uberpruefen", "ueberprufen", "ueberpruefen".
125 const unsigned int remainingBytes = BYTES_IN_ONE_CHAR * codesRemain;
126 if (0 != remainingBytes)
127 memcpy(codesDest, codesSrc, remainingBytes);
128
129 getWordSuggestions(proximityInfo, xcoordinates, ycoordinates, codesBuffer,
130 (codesDest - codesBuffer) / MAX_PROXIMITY_CHARS + codesRemain, outWords, frequencies);
131}
132
133int UnigramDictionary::getSuggestions(const ProximityInfo *proximityInfo, const int *xcoordinates,
134 const int *ycoordinates, const int *codes, const int codesSize, const int flags,
135 unsigned short *outWords, int *frequencies) {
136
137 if (REQUIRES_GERMAN_UMLAUT_PROCESSING & flags)
138 { // Incrementally tune the word and try all possibilities
139 int codesBuffer[getCodesBufferSize(codes, codesSize, MAX_PROXIMITY_CHARS)];
140 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates, codesBuffer,
Jean Chalarda787dba2011-03-04 12:17:48 +0900141 codesSize, flags, codes, codesSize, 0, codesBuffer, outWords, frequencies);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900142 } else { // Normal processing
143 getWordSuggestions(proximityInfo, xcoordinates, ycoordinates, codes, codesSize,
144 outWords, frequencies);
145 }
146
satok817e5172011-03-04 06:06:45 -0800147 PROF_START(20);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900148 // Get the word count
149 int suggestedWordsCount = 0;
150 while (suggestedWordsCount < MAX_WORDS && mFrequencies[suggestedWordsCount] > 0) {
151 suggestedWordsCount++;
152 }
153
154 if (DEBUG_DICT) {
155 LOGI("Returning %d words", suggestedWordsCount);
156 LOGI("Next letters: ");
157 for (int k = 0; k < NEXT_LETTERS_SIZE; k++) {
158 if (mNextLettersFrequency[k] > 0) {
159 LOGI("%c = %d,", k, mNextLettersFrequency[k]);
160 }
161 }
162 }
satok817e5172011-03-04 06:06:45 -0800163 PROF_END(20);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900164 PROF_CLOSE;
165 return suggestedWordsCount;
166}
167
168void UnigramDictionary::getWordSuggestions(const ProximityInfo *proximityInfo,
169 const int *xcoordinates, const int *ycoordinates, const int *codes, const int codesSize,
170 unsigned short *outWords, int *frequencies) {
171
satok61e2f852011-01-05 14:13:07 +0900172 PROF_OPEN;
173 PROF_START(0);
satok30088252010-12-01 21:22:15 +0900174 initSuggestions(codes, codesSize, outWords, frequencies);
satok54fe9e02010-12-13 14:42:35 +0900175 if (DEBUG_DICT) assert(codesSize == mInputLength);
176
satoka3d78f62010-12-09 22:08:33 +0900177 const int MAX_DEPTH = min(mInputLength * MAX_DEPTH_MULTIPLIER, MAX_WORD_LENGTH);
satok61e2f852011-01-05 14:13:07 +0900178 PROF_END(0);
satok30088252010-12-01 21:22:15 +0900179
satok61e2f852011-01-05 14:13:07 +0900180 PROF_START(1);
Tadashi G. Takaoka887f11e2011-02-10 20:53:58 +0900181 getSuggestionCandidates(-1, -1, -1, mNextLettersFrequency, NEXT_LETTERS_SIZE, MAX_DEPTH);
satok61e2f852011-01-05 14:13:07 +0900182 PROF_END(1);
183
184 PROF_START(2);
satok662fe692010-12-08 17:05:39 +0900185 // Suggestion with missing character
186 if (SUGGEST_WORDS_WITH_MISSING_CHARACTER) {
satok30088252010-12-01 21:22:15 +0900187 for (int i = 0; i < codesSize; ++i) {
Ken Wakasade3070a2011-03-19 09:16:42 +0900188 if (DEBUG_DICT) {
189 LOGI("--- Suggest missing characters %d", i);
190 }
satok54fe9e02010-12-13 14:42:35 +0900191 getSuggestionCandidates(i, -1, -1, NULL, 0, MAX_DEPTH);
satokcdbbea72010-12-08 16:04:16 +0900192 }
193 }
satok61e2f852011-01-05 14:13:07 +0900194 PROF_END(2);
satokcdbbea72010-12-08 16:04:16 +0900195
satok61e2f852011-01-05 14:13:07 +0900196 PROF_START(3);
satok662fe692010-12-08 17:05:39 +0900197 // Suggestion with excessive character
satok54fe9e02010-12-13 14:42:35 +0900198 if (SUGGEST_WORDS_WITH_EXCESSIVE_CHARACTER
199 && mInputLength >= MIN_USER_TYPED_LENGTH_FOR_EXCESSIVE_CHARACTER_SUGGESTION) {
satokcdbbea72010-12-08 16:04:16 +0900200 for (int i = 0; i < codesSize; ++i) {
Ken Wakasade3070a2011-03-19 09:16:42 +0900201 if (DEBUG_DICT) {
202 LOGI("--- Suggest excessive characters %d", i);
203 }
satok54fe9e02010-12-13 14:42:35 +0900204 getSuggestionCandidates(-1, i, -1, NULL, 0, MAX_DEPTH);
satok30088252010-12-01 21:22:15 +0900205 }
206 }
satok61e2f852011-01-05 14:13:07 +0900207 PROF_END(3);
satok30088252010-12-01 21:22:15 +0900208
satok61e2f852011-01-05 14:13:07 +0900209 PROF_START(4);
satoka3d78f62010-12-09 22:08:33 +0900210 // Suggestion with transposed characters
211 // Only suggest words that length is mInputLength
212 if (SUGGEST_WORDS_WITH_TRANSPOSED_CHARACTERS) {
213 for (int i = 0; i < codesSize; ++i) {
Ken Wakasade3070a2011-03-19 09:16:42 +0900214 if (DEBUG_DICT) {
215 LOGI("--- Suggest transposed characters %d", i);
216 }
satok54fe9e02010-12-13 14:42:35 +0900217 getSuggestionCandidates(-1, -1, i, NULL, 0, mInputLength - 1);
satoka3d78f62010-12-09 22:08:33 +0900218 }
219 }
satok61e2f852011-01-05 14:13:07 +0900220 PROF_END(4);
satoka3d78f62010-12-09 22:08:33 +0900221
satok61e2f852011-01-05 14:13:07 +0900222 PROF_START(5);
satok662fe692010-12-08 17:05:39 +0900223 // Suggestions with missing space
satok54fe9e02010-12-13 14:42:35 +0900224 if (SUGGEST_WORDS_WITH_MISSING_SPACE_CHARACTER
225 && mInputLength >= MIN_USER_TYPED_LENGTH_FOR_MISSING_SPACE_SUGGESTION) {
satok662fe692010-12-08 17:05:39 +0900226 for (int i = 1; i < codesSize; ++i) {
Ken Wakasade3070a2011-03-19 09:16:42 +0900227 if (DEBUG_DICT) {
228 LOGI("--- Suggest missing space characters %d", i);
229 }
satok662fe692010-12-08 17:05:39 +0900230 getMissingSpaceWords(mInputLength, i);
231 }
232 }
satok61e2f852011-01-05 14:13:07 +0900233 PROF_END(5);
satok817e5172011-03-04 06:06:45 -0800234
235 PROF_START(6);
Jean Chalarde93b1f222011-06-01 17:12:25 +0900236 if (SUGGEST_WORDS_WITH_SPACE_PROXIMITY && proximityInfo) {
satok817e5172011-03-04 06:06:45 -0800237 // The first and last "mistyped spaces" are taken care of by excessive character handling
238 for (int i = 1; i < codesSize - 1; ++i) {
Ken Wakasade3070a2011-03-19 09:16:42 +0900239 if (DEBUG_DICT) {
240 LOGI("--- Suggest words with proximity space %d", i);
241 }
satok817e5172011-03-04 06:06:45 -0800242 const int x = xcoordinates[i];
243 const int y = ycoordinates[i];
Ken Wakasade3070a2011-03-19 09:16:42 +0900244 if (DEBUG_PROXIMITY_INFO) {
satok817e5172011-03-04 06:06:45 -0800245 LOGI("Input[%d] x = %d, y = %d, has space proximity = %d",
246 i, x, y, proximityInfo->hasSpaceProximity(x, y));
Ken Wakasade3070a2011-03-19 09:16:42 +0900247 }
satok817e5172011-03-04 06:06:45 -0800248 if (proximityInfo->hasSpaceProximity(x, y)) {
249 getMistypedSpaceWords(mInputLength, i);
250 }
satok817e5172011-03-04 06:06:45 -0800251 }
252 }
253 PROF_END(6);
satok30088252010-12-01 21:22:15 +0900254}
255
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900256void UnigramDictionary::initSuggestions(const int *codes, const int codesSize,
257 unsigned short *outWords, int *frequencies) {
Ken Wakasade3070a2011-03-19 09:16:42 +0900258 if (DEBUG_DICT) {
259 LOGI("initSuggest");
260 }
satok30088252010-12-01 21:22:15 +0900261 mFrequencies = frequencies;
262 mOutputChars = outWords;
263 mInputCodes = codes;
264 mInputLength = codesSize;
265 mMaxEditDistance = mInputLength < 5 ? 2 : mInputLength / 2;
266}
267
Jean Chalard8124e642011-06-16 22:33:41 +0900268static inline void registerNextLetter(unsigned short c, int *nextLetters, int nextLettersSize) {
satok30088252010-12-01 21:22:15 +0900269 if (c < nextLettersSize) {
270 nextLetters[c]++;
271 }
272}
273
satok662fe692010-12-08 17:05:39 +0900274// TODO: We need to optimize addWord by using STL or something
satok28bd03b2010-12-03 16:39:16 +0900275bool UnigramDictionary::addWord(unsigned short *word, int length, int frequency) {
satok30088252010-12-01 21:22:15 +0900276 word[length] = 0;
satok662fe692010-12-08 17:05:39 +0900277 if (DEBUG_DICT && DEBUG_SHOW_FOUND_WORD) {
satok30088252010-12-01 21:22:15 +0900278 char s[length + 1];
279 for (int i = 0; i <= length; i++) s[i] = word[i];
satok662fe692010-12-08 17:05:39 +0900280 LOGI("Found word = %s, freq = %d", s, frequency);
satok30088252010-12-01 21:22:15 +0900281 }
satokf5cded12010-12-06 21:28:24 +0900282 if (length > MAX_WORD_LENGTH) {
Ken Wakasade3070a2011-03-19 09:16:42 +0900283 if (DEBUG_DICT) {
284 LOGI("Exceeded max word length.");
285 }
satokf5cded12010-12-06 21:28:24 +0900286 return false;
287 }
satok30088252010-12-01 21:22:15 +0900288
289 // Find the right insertion point
290 int insertAt = 0;
291 while (insertAt < MAX_WORDS) {
satok715514d2010-12-02 20:19:59 +0900292 if (frequency > mFrequencies[insertAt] || (mFrequencies[insertAt] == frequency
293 && length < Dictionary::wideStrLen(mOutputChars + insertAt * MAX_WORD_LENGTH))) {
satok30088252010-12-01 21:22:15 +0900294 break;
295 }
296 insertAt++;
297 }
298 if (insertAt < MAX_WORDS) {
satokcdbbea72010-12-08 16:04:16 +0900299 if (DEBUG_DICT) {
300 char s[length + 1];
301 for (int i = 0; i <= length; i++) s[i] = word[i];
satokb2e5e592011-04-26 14:50:54 +0900302 LOGI("Added word = %s, freq = %d, %d", s, frequency, S_INT_MAX);
satokcdbbea72010-12-08 16:04:16 +0900303 }
satok30088252010-12-01 21:22:15 +0900304 memmove((char*) mFrequencies + (insertAt + 1) * sizeof(mFrequencies[0]),
305 (char*) mFrequencies + insertAt * sizeof(mFrequencies[0]),
306 (MAX_WORDS - insertAt - 1) * sizeof(mFrequencies[0]));
307 mFrequencies[insertAt] = frequency;
308 memmove((char*) mOutputChars + (insertAt + 1) * MAX_WORD_LENGTH * sizeof(short),
satok715514d2010-12-02 20:19:59 +0900309 (char*) mOutputChars + insertAt * MAX_WORD_LENGTH * sizeof(short),
satok30088252010-12-01 21:22:15 +0900310 (MAX_WORDS - insertAt - 1) * sizeof(short) * MAX_WORD_LENGTH);
satok715514d2010-12-02 20:19:59 +0900311 unsigned short *dest = mOutputChars + insertAt * MAX_WORD_LENGTH;
satok30088252010-12-01 21:22:15 +0900312 while (length--) {
313 *dest++ = *word++;
314 }
315 *dest = 0; // NULL terminate
Ken Wakasade3070a2011-03-19 09:16:42 +0900316 if (DEBUG_DICT) {
317 LOGI("Added word at %d", insertAt);
318 }
satok30088252010-12-01 21:22:15 +0900319 return true;
320 }
321 return false;
322}
323
Jean Chalard8124e642011-06-16 22:33:41 +0900324static inline unsigned short toBaseLowerCase(unsigned short c) {
satok30088252010-12-01 21:22:15 +0900325 if (c < sizeof(BASE_CHARS) / sizeof(BASE_CHARS[0])) {
326 c = BASE_CHARS[c];
327 }
328 if (c >='A' && c <= 'Z') {
329 c |= 32;
330 } else if (c > 127) {
331 c = latin_tolower(c);
332 }
333 return c;
334}
335
satok28bd03b2010-12-03 16:39:16 +0900336bool UnigramDictionary::sameAsTyped(unsigned short *word, int length) {
satok30088252010-12-01 21:22:15 +0900337 if (length != mInputLength) {
338 return false;
339 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900340 const int *inputCodes = mInputCodes;
satok30088252010-12-01 21:22:15 +0900341 while (length--) {
342 if ((unsigned int) *inputCodes != (unsigned int) *word) {
343 return false;
344 }
satok662fe692010-12-08 17:05:39 +0900345 inputCodes += MAX_PROXIMITY_CHARS;
satok30088252010-12-01 21:22:15 +0900346 word++;
347 }
348 return true;
349}
350
satok715514d2010-12-02 20:19:59 +0900351static const char QUOTE = '\'';
satok662fe692010-12-08 17:05:39 +0900352static const char SPACE = ' ';
satok30088252010-12-01 21:22:15 +0900353
satok54fe9e02010-12-13 14:42:35 +0900354void UnigramDictionary::getSuggestionCandidates(const int skipPos,
satoka3d78f62010-12-09 22:08:33 +0900355 const int excessivePos, const int transposedPos, int *nextLetters,
356 const int nextLettersSize, const int maxDepth) {
satok54fe9e02010-12-13 14:42:35 +0900357 if (DEBUG_DICT) {
358 LOGI("getSuggestionCandidates %d", maxDepth);
359 assert(transposedPos + 1 < mInputLength);
360 assert(excessivePos < mInputLength);
361 assert(missingPos < mInputLength);
362 }
satok662fe692010-12-08 17:05:39 +0900363 int rootPosition = ROOT_POS;
satokd2997922010-12-07 13:08:39 +0900364 // Get the number of child of root, then increment the position
Jean Chalard293ece02011-06-16 20:55:16 +0900365 int childCount = Dictionary::getCount(DICT_ROOT, &rootPosition);
satokd2997922010-12-07 13:08:39 +0900366 int depth = 0;
367
368 mStackChildCount[0] = childCount;
369 mStackTraverseAll[0] = (mInputLength <= 0);
370 mStackNodeFreq[0] = 1;
371 mStackInputIndex[0] = 0;
372 mStackDiffs[0] = 0;
373 mStackSiblingPos[0] = rootPosition;
374
satok662fe692010-12-08 17:05:39 +0900375 // Depth first search
satokd2997922010-12-07 13:08:39 +0900376 while (depth >= 0) {
377 if (mStackChildCount[depth] > 0) {
378 --mStackChildCount[depth];
379 bool traverseAllNodes = mStackTraverseAll[depth];
Jean Chalardf5f834a2011-02-22 15:12:46 +0900380 int matchWeight = mStackNodeFreq[depth];
satokd2997922010-12-07 13:08:39 +0900381 int inputIndex = mStackInputIndex[depth];
382 int diffs = mStackDiffs[depth];
383 int siblingPos = mStackSiblingPos[depth];
384 int firstChildPos;
satoka3d78f62010-12-09 22:08:33 +0900385 // depth will never be greater than maxDepth because in that case,
satokd2997922010-12-07 13:08:39 +0900386 // needsToTraverseChildrenNodes should be false
387 const bool needsToTraverseChildrenNodes = processCurrentNode(siblingPos, depth,
Jean Chalardf5f834a2011-02-22 15:12:46 +0900388 maxDepth, traverseAllNodes, matchWeight, inputIndex, diffs, skipPos,
389 excessivePos, transposedPos, nextLetters, nextLettersSize, &childCount,
390 &firstChildPos, &traverseAllNodes, &matchWeight, &inputIndex, &diffs,
391 &siblingPos);
satok662fe692010-12-08 17:05:39 +0900392 // Update next sibling pos
satokd2997922010-12-07 13:08:39 +0900393 mStackSiblingPos[depth] = siblingPos;
394 if (needsToTraverseChildrenNodes) {
395 // Goes to child node
396 ++depth;
397 mStackChildCount[depth] = childCount;
398 mStackTraverseAll[depth] = traverseAllNodes;
Jean Chalardf5f834a2011-02-22 15:12:46 +0900399 mStackNodeFreq[depth] = matchWeight;
satokd2997922010-12-07 13:08:39 +0900400 mStackInputIndex[depth] = inputIndex;
401 mStackDiffs[depth] = diffs;
402 mStackSiblingPos[depth] = firstChildPos;
403 }
404 } else {
satokcdbbea72010-12-08 16:04:16 +0900405 // Goes to parent sibling node
satokd2997922010-12-07 13:08:39 +0900406 --depth;
407 }
408 }
409}
410
satokb2e5e592011-04-26 14:50:54 +0900411static const int TWO_31ST_DIV_255 = S_INT_MAX / 255;
412static inline int capped255MultForFullMatchAccentsOrCapitalizationDifference(const int num) {
413 return (num < TWO_31ST_DIV_255 ? 255 * num : S_INT_MAX);
414}
415
416static const int TWO_31ST_DIV_2 = S_INT_MAX / 2;
417inline static void multiplyIntCapped(const int multiplier, int *base) {
418 const int temp = *base;
419 if (temp != S_INT_MAX) {
420 // Branch if multiplier == 2 for the optimization
421 if (multiplier == 2) {
422 *base = TWO_31ST_DIV_2 >= temp ? temp << 1 : S_INT_MAX;
423 } else {
424 const int tempRetval = temp * multiplier;
425 *base = tempRetval >= temp ? tempRetval : S_INT_MAX;
426 }
427 }
428}
429
430inline static int powerIntCapped(const int base, const int n) {
satok0b6b0a52011-04-27 16:29:27 +0900431 if (base == 2) {
satokb2e5e592011-04-26 14:50:54 +0900432 return n < 31 ? 1 << n : S_INT_MAX;
satokf7425bb2011-01-05 16:37:53 +0900433 } else {
satokb2e5e592011-04-26 14:50:54 +0900434 int ret = base;
435 for (int i = 1; i < n; ++i) multiplyIntCapped(base, &ret);
436 return ret;
437 }
438}
439
440inline static void multiplyRate(const int rate, int *freq) {
441 if (*freq != S_INT_MAX) {
442 if (*freq > 1000000) {
443 *freq /= 100;
444 multiplyIntCapped(rate, freq);
445 } else {
446 multiplyIntCapped(rate, freq);
447 *freq /= 100;
448 }
satokf7425bb2011-01-05 16:37:53 +0900449 }
450}
451
satok4c981d32011-04-19 13:58:42 +0900452inline static int calcFreqForSplitTwoWords(
satokd8db9f82011-05-18 15:31:04 +0900453 const int typedLetterMultiplier, const int firstWordLength, const int secondWordLength,
454 const int firstFreq, const int secondFreq, const bool isSpaceProximity) {
satok4c981d32011-04-19 13:58:42 +0900455 if (firstWordLength == 0 || secondWordLength == 0) {
456 return 0;
457 }
458 const int firstDemotionRate = 100 - 100 / (firstWordLength + 1);
459 int tempFirstFreq = firstFreq;
460 multiplyRate(firstDemotionRate, &tempFirstFreq);
461
462 const int secondDemotionRate = 100 - 100 / (secondWordLength + 1);
463 int tempSecondFreq = secondFreq;
464 multiplyRate(secondDemotionRate, &tempSecondFreq);
465
466 const int totalLength = firstWordLength + secondWordLength;
467
468 // Promote pairFreq with multiplying by 2, because the word length is the same as the typed
469 // length.
470 int totalFreq = tempFirstFreq + tempSecondFreq;
471
472 // This is a workaround to try offsetting the not-enough-demotion which will be done in
473 // calcNormalizedScore in Utils.java.
474 // In calcNormalizedScore the score will be demoted by (1 - 1 / length)
475 // but we demoted only (1 - 1 / (length + 1)) so we will additionally adjust freq by
476 // (1 - 1 / length) / (1 - 1 / (length + 1)) = (1 - 1 / (length * length))
477 const int normalizedScoreNotEnoughDemotionAdjustment = 100 - 100 / (totalLength * totalLength);
478 multiplyRate(normalizedScoreNotEnoughDemotionAdjustment, &totalFreq);
479
480 // At this moment, totalFreq is calculated by the following formula:
481 // (firstFreq * (1 - 1 / (firstWordLength + 1)) + secondFreq * (1 - 1 / (secondWordLength + 1)))
482 // * (1 - 1 / totalLength) / (1 - 1 / (totalLength + 1))
483
satokb2e5e592011-04-26 14:50:54 +0900484 multiplyIntCapped(powerIntCapped(typedLetterMultiplier, totalLength), &totalFreq);
satok4c981d32011-04-19 13:58:42 +0900485
486 // This is another workaround to offset the demotion which will be done in
487 // calcNormalizedScore in Utils.java.
488 // In calcNormalizedScore the score will be demoted by (1 - 1 / length) so we have to promote
489 // the same amount because we already have adjusted the synthetic freq of this "missing or
490 // mistyped space" suggestion candidate above in this method.
491 const int normalizedScoreDemotionRateOffset = (100 + 100 / totalLength);
492 multiplyRate(normalizedScoreDemotionRateOffset, &totalFreq);
493
satokd8db9f82011-05-18 15:31:04 +0900494 if (isSpaceProximity) {
495 // A word pair with one space proximity correction
496 if (DEBUG_DICT) {
497 LOGI("Found a word pair with space proximity correction.");
498 }
499 multiplyIntCapped(typedLetterMultiplier, &totalFreq);
500 multiplyRate(WORDS_WITH_PROXIMITY_CHARACTER_DEMOTION_RATE, &totalFreq);
501 }
502
satok4c981d32011-04-19 13:58:42 +0900503 multiplyRate(WORDS_WITH_MISSING_SPACE_CHARACTER_DEMOTION_RATE, &totalFreq);
504 return totalFreq;
505}
506
satok817e5172011-03-04 06:06:45 -0800507bool UnigramDictionary::getSplitTwoWordsSuggestion(const int inputLength,
508 const int firstWordStartPos, const int firstWordLength, const int secondWordStartPos,
satokd8db9f82011-05-18 15:31:04 +0900509 const int secondWordLength, const bool isSpaceProximity) {
satok817e5172011-03-04 06:06:45 -0800510 if (inputLength >= MAX_WORD_LENGTH) return false;
511 if (0 >= firstWordLength || 0 >= secondWordLength || firstWordStartPos >= secondWordStartPos
satok3c4bb772011-03-04 22:50:19 -0800512 || firstWordStartPos < 0 || secondWordStartPos + secondWordLength > inputLength)
satok817e5172011-03-04 06:06:45 -0800513 return false;
514 const int newWordLength = firstWordLength + secondWordLength + 1;
satok662fe692010-12-08 17:05:39 +0900515 // Allocating variable length array on stack
516 unsigned short word[newWordLength];
satok817e5172011-03-04 06:06:45 -0800517 const int firstFreq = getBestWordFreq(firstWordStartPos, firstWordLength, mWord);
Ken Wakasade3070a2011-03-19 09:16:42 +0900518 if (DEBUG_DICT) {
519 LOGI("First freq: %d", firstFreq);
520 }
satokaee09dc2010-12-09 19:21:51 +0900521 if (firstFreq <= 0) return false;
522
satok817e5172011-03-04 06:06:45 -0800523 for (int i = 0; i < firstWordLength; ++i) {
satokaee09dc2010-12-09 19:21:51 +0900524 word[i] = mWord[i];
satok662fe692010-12-08 17:05:39 +0900525 }
satokaee09dc2010-12-09 19:21:51 +0900526
satok817e5172011-03-04 06:06:45 -0800527 const int secondFreq = getBestWordFreq(secondWordStartPos, secondWordLength, mWord);
Ken Wakasade3070a2011-03-19 09:16:42 +0900528 if (DEBUG_DICT) {
529 LOGI("Second freq: %d", secondFreq);
530 }
satokaee09dc2010-12-09 19:21:51 +0900531 if (secondFreq <= 0) return false;
532
satok817e5172011-03-04 06:06:45 -0800533 word[firstWordLength] = SPACE;
534 for (int i = (firstWordLength + 1); i < newWordLength; ++i) {
535 word[i] = mWord[i - firstWordLength - 1];
satok662fe692010-12-08 17:05:39 +0900536 }
satokaee09dc2010-12-09 19:21:51 +0900537
satokd8db9f82011-05-18 15:31:04 +0900538 int pairFreq = calcFreqForSplitTwoWords(TYPED_LETTER_MULTIPLIER, firstWordLength,
539 secondWordLength, firstFreq, secondFreq, isSpaceProximity);
satoka4374d22011-04-18 11:40:22 +0900540 if (DEBUG_DICT) {
satokb2e5e592011-04-26 14:50:54 +0900541 LOGI("Split two words: %d, %d, %d, %d, %d", firstFreq, secondFreq, pairFreq, inputLength,
satoka4374d22011-04-18 11:40:22 +0900542 TYPED_LETTER_MULTIPLIER);
543 }
satok662fe692010-12-08 17:05:39 +0900544 addWord(word, newWordLength, pairFreq);
545 return true;
546}
547
satok817e5172011-03-04 06:06:45 -0800548bool UnigramDictionary::getMissingSpaceWords(const int inputLength, const int missingSpacePos) {
549 return getSplitTwoWordsSuggestion(
satokd8db9f82011-05-18 15:31:04 +0900550 inputLength, 0, missingSpacePos, missingSpacePos, inputLength - missingSpacePos, false);
satok817e5172011-03-04 06:06:45 -0800551}
552
553bool UnigramDictionary::getMistypedSpaceWords(const int inputLength, const int spaceProximityPos) {
554 return getSplitTwoWordsSuggestion(
555 inputLength, 0, spaceProximityPos, spaceProximityPos + 1,
satokd8db9f82011-05-18 15:31:04 +0900556 inputLength - spaceProximityPos - 1, true);
satok817e5172011-03-04 06:06:45 -0800557}
558
satok662fe692010-12-08 17:05:39 +0900559// Keep this for comparing spec to new getWords
560void UnigramDictionary::getWordsOld(const int initialPos, const int inputLength, const int skipPos,
satoka3d78f62010-12-09 22:08:33 +0900561 const int excessivePos, const int transposedPos,int *nextLetters,
562 const int nextLettersSize) {
satok662fe692010-12-08 17:05:39 +0900563 int initialPosition = initialPos;
Jean Chalard293ece02011-06-16 20:55:16 +0900564 const int count = Dictionary::getCount(DICT_ROOT, &initialPosition);
satok662fe692010-12-08 17:05:39 +0900565 getWordsRec(count, initialPosition, 0,
566 min(inputLength * MAX_DEPTH_MULTIPLIER, MAX_WORD_LENGTH),
satoka3d78f62010-12-09 22:08:33 +0900567 mInputLength <= 0, 1, 0, 0, skipPos, excessivePos, transposedPos, nextLetters,
568 nextLettersSize);
satok662fe692010-12-08 17:05:39 +0900569}
570
satok68319262010-12-03 19:38:08 +0900571void UnigramDictionary::getWordsRec(const int childrenCount, const int pos, const int depth,
Jean Chalardf5f834a2011-02-22 15:12:46 +0900572 const int maxDepth, const bool traverseAllNodes, const int matchWeight,
573 const int inputIndex, const int diffs, const int skipPos, const int excessivePos,
574 const int transposedPos, int *nextLetters, const int nextLettersSize) {
satok48e432c2010-12-06 17:38:58 +0900575 int siblingPos = pos;
satok68319262010-12-03 19:38:08 +0900576 for (int i = 0; i < childrenCount; ++i) {
satok48e432c2010-12-06 17:38:58 +0900577 int newCount;
578 int newChildPosition;
satokd2997922010-12-07 13:08:39 +0900579 const int newDepth = depth + 1;
satok48e432c2010-12-06 17:38:58 +0900580 bool newTraverseAllNodes;
Jean Chalardf5f834a2011-02-22 15:12:46 +0900581 int newMatchRate;
satok48e432c2010-12-06 17:38:58 +0900582 int newInputIndex;
583 int newDiffs;
584 int newSiblingPos;
585 const bool needsToTraverseChildrenNodes = processCurrentNode(siblingPos, depth, maxDepth,
Jean Chalardf5f834a2011-02-22 15:12:46 +0900586 traverseAllNodes, matchWeight, inputIndex, diffs,
587 skipPos, excessivePos, transposedPos,
satoka3d78f62010-12-09 22:08:33 +0900588 nextLetters, nextLettersSize,
Jean Chalardf5f834a2011-02-22 15:12:46 +0900589 &newCount, &newChildPosition, &newTraverseAllNodes, &newMatchRate,
satok48e432c2010-12-06 17:38:58 +0900590 &newInputIndex, &newDiffs, &newSiblingPos);
591 siblingPos = newSiblingPos;
satok30088252010-12-01 21:22:15 +0900592
satok48e432c2010-12-06 17:38:58 +0900593 if (needsToTraverseChildrenNodes) {
594 getWordsRec(newCount, newChildPosition, newDepth, maxDepth, newTraverseAllNodes,
Jean Chalardf5f834a2011-02-22 15:12:46 +0900595 newMatchRate, newInputIndex, newDiffs, skipPos, excessivePos, transposedPos,
satoka3d78f62010-12-09 22:08:33 +0900596 nextLetters, nextLettersSize);
satok30088252010-12-01 21:22:15 +0900597 }
598 }
599}
600
satok58c49b92011-01-27 03:23:39 +0900601inline int UnigramDictionary::calculateFinalFreq(const int inputIndex, const int depth,
Jean Chalardf5f834a2011-02-22 15:12:46 +0900602 const int matchWeight, const int skipPos, const int excessivePos, const int transposedPos,
Jean Chalard07a84062011-03-03 10:22:10 +0900603 const int freq, const bool sameLength) const {
satoka3d78f62010-12-09 22:08:33 +0900604 // TODO: Demote by edit distance
Jean Chalardf5f834a2011-02-22 15:12:46 +0900605 int finalFreq = freq * matchWeight;
Jean Chalard07a84062011-03-03 10:22:10 +0900606 if (skipPos >= 0) {
satokdc5301e2011-04-11 16:14:45 +0900607 if (mInputLength >= 2) {
608 const int demotionRate = WORDS_WITH_MISSING_CHARACTER_DEMOTION_RATE
609 * (10 * mInputLength - WORDS_WITH_MISSING_CHARACTER_DEMOTION_START_POS_10X)
610 / (10 * mInputLength
611 - WORDS_WITH_MISSING_CHARACTER_DEMOTION_START_POS_10X + 10);
satok9674f652011-04-20 17:15:27 +0900612 if (DEBUG_DICT_FULL) {
satok72bc17e2011-04-13 17:23:27 +0900613 LOGI("Demotion rate for missing character is %d.", demotionRate);
614 }
satokdc5301e2011-04-11 16:14:45 +0900615 multiplyRate(demotionRate, &finalFreq);
Jean Chalard07a84062011-03-03 10:22:10 +0900616 } else {
617 finalFreq = 0;
618 }
619 }
satokf7425bb2011-01-05 16:37:53 +0900620 if (transposedPos >= 0) multiplyRate(
621 WORDS_WITH_TRANSPOSED_CHARACTERS_DEMOTION_RATE, &finalFreq);
satok54fe9e02010-12-13 14:42:35 +0900622 if (excessivePos >= 0) {
satokf7425bb2011-01-05 16:37:53 +0900623 multiplyRate(WORDS_WITH_EXCESSIVE_CHARACTER_DEMOTION_RATE, &finalFreq);
satok54fe9e02010-12-13 14:42:35 +0900624 if (!existsAdjacentProximityChars(inputIndex, mInputLength)) {
satokf7425bb2011-01-05 16:37:53 +0900625 multiplyRate(WORDS_WITH_EXCESSIVE_CHARACTER_OUT_OF_PROXIMITY_DEMOTION_RATE, &finalFreq);
satok54fe9e02010-12-13 14:42:35 +0900626 }
627 }
satok58c49b92011-01-27 03:23:39 +0900628 int lengthFreq = TYPED_LETTER_MULTIPLIER;
satokb2e5e592011-04-26 14:50:54 +0900629 multiplyIntCapped(powerIntCapped(TYPED_LETTER_MULTIPLIER, depth), &lengthFreq);
Jean Chalardf5f834a2011-02-22 15:12:46 +0900630 if (lengthFreq == matchWeight) {
satok72bc17e2011-04-13 17:23:27 +0900631 // Full exact match
Jean Chalard8dc754a2011-01-27 14:20:22 +0900632 if (depth > 1) {
Ken Wakasade3070a2011-03-19 09:16:42 +0900633 if (DEBUG_DICT) {
634 LOGI("Found full matched word.");
635 }
Jean Chalard8dc754a2011-01-27 14:20:22 +0900636 multiplyRate(FULL_MATCHED_WORDS_PROMOTION_RATE, &finalFreq);
637 }
638 if (sameLength && transposedPos < 0 && skipPos < 0 && excessivePos < 0) {
Jean Chalarda5d58492011-02-18 17:50:58 +0900639 finalFreq = capped255MultForFullMatchAccentsOrCapitalizationDifference(finalFreq);
Jean Chalard8dc754a2011-01-27 14:20:22 +0900640 }
satok9674f652011-04-20 17:15:27 +0900641 } else if (sameLength && transposedPos < 0 && skipPos < 0 && excessivePos < 0 && depth > 0) {
satok9d2a3022011-04-14 19:13:34 +0900642 // A word with proximity corrections
satok72bc17e2011-04-13 17:23:27 +0900643 if (DEBUG_DICT) {
644 LOGI("Found one proximity correction.");
645 }
satokb2e5e592011-04-26 14:50:54 +0900646 multiplyIntCapped(TYPED_LETTER_MULTIPLIER, &finalFreq);
satok9d2a3022011-04-14 19:13:34 +0900647 multiplyRate(WORDS_WITH_PROXIMITY_CHARACTER_DEMOTION_RATE, &finalFreq);
satok58c49b92011-01-27 03:23:39 +0900648 }
satok9674f652011-04-20 17:15:27 +0900649 if (DEBUG_DICT) {
650 LOGI("calc: %d, %d", depth, sameLength);
651 }
satokb2e5e592011-04-26 14:50:54 +0900652 if (sameLength) multiplyIntCapped(FULL_WORD_MULTIPLIER, &finalFreq);
satok54fe9e02010-12-13 14:42:35 +0900653 return finalFreq;
654}
satoka3d78f62010-12-09 22:08:33 +0900655
satok54fe9e02010-12-13 14:42:35 +0900656inline void UnigramDictionary::onTerminalWhenUserTypedLengthIsGreaterThanInputLength(
Jean Chalardf5f834a2011-02-22 15:12:46 +0900657 unsigned short *word, const int inputIndex, const int depth, const int matchWeight,
satok54fe9e02010-12-13 14:42:35 +0900658 int *nextLetters, const int nextLettersSize, const int skipPos, const int excessivePos,
659 const int transposedPos, const int freq) {
Jean Chalardf5f834a2011-02-22 15:12:46 +0900660 const int finalFreq = calculateFinalFreq(inputIndex, depth, matchWeight, skipPos, excessivePos,
satok58c49b92011-01-27 03:23:39 +0900661 transposedPos, freq, false);
satoka3d78f62010-12-09 22:08:33 +0900662 if (depth >= MIN_SUGGEST_DEPTH) addWord(word, depth + 1, finalFreq);
satok54fe9e02010-12-13 14:42:35 +0900663 if (depth >= mInputLength && skipPos < 0) {
satok715514d2010-12-02 20:19:59 +0900664 registerNextLetter(mWord[mInputLength], nextLetters, nextLettersSize);
665 }
666}
667
668inline void UnigramDictionary::onTerminalWhenUserTypedLengthIsSameAsInputLength(
Jean Chalardf5f834a2011-02-22 15:12:46 +0900669 unsigned short *word, const int inputIndex, const int depth, const int matchWeight,
Jean Chalard8dc754a2011-01-27 14:20:22 +0900670 const int skipPos, const int excessivePos, const int transposedPos, const int freq) {
satok54fe9e02010-12-13 14:42:35 +0900671 if (sameAsTyped(word, depth + 1)) return;
Jean Chalardf5f834a2011-02-22 15:12:46 +0900672 const int finalFreq = calculateFinalFreq(inputIndex, depth, matchWeight, skipPos,
satok54fe9e02010-12-13 14:42:35 +0900673 excessivePos, transposedPos, freq, true);
674 // Proximity collection will promote a word of the same length as what user typed.
675 if (depth >= MIN_SUGGEST_DEPTH) addWord(word, depth + 1, finalFreq);
satok715514d2010-12-02 20:19:59 +0900676}
satok28bd03b2010-12-03 16:39:16 +0900677
678inline bool UnigramDictionary::needsToSkipCurrentNode(const unsigned short c,
satok68319262010-12-03 19:38:08 +0900679 const int inputIndex, const int skipPos, const int depth) {
satok8fbd5522011-02-22 17:28:55 +0900680 const unsigned short userTypedChar = getInputCharsAt(inputIndex)[0];
satok28bd03b2010-12-03 16:39:16 +0900681 // Skip the ' or other letter and continue deeper
682 return (c == QUOTE && userTypedChar != QUOTE) || skipPos == depth;
683}
684
satoke07baa62010-12-09 21:55:40 +0900685inline bool UnigramDictionary::existsAdjacentProximityChars(const int inputIndex,
Jean Chalard07a84062011-03-03 10:22:10 +0900686 const int inputLength) const {
satoke07baa62010-12-09 21:55:40 +0900687 if (inputIndex < 0 || inputIndex >= inputLength) return false;
688 const int currentChar = *getInputCharsAt(inputIndex);
689 const int leftIndex = inputIndex - 1;
690 if (leftIndex >= 0) {
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900691 const int *leftChars = getInputCharsAt(leftIndex);
satoke07baa62010-12-09 21:55:40 +0900692 int i = 0;
693 while (leftChars[i] > 0 && i < MAX_PROXIMITY_CHARS) {
694 if (leftChars[i++] == currentChar) return true;
695 }
696 }
697 const int rightIndex = inputIndex + 1;
698 if (rightIndex < inputLength) {
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900699 const int *rightChars = getInputCharsAt(rightIndex);
satoke07baa62010-12-09 21:55:40 +0900700 int i = 0;
701 while (rightChars[i] > 0 && i < MAX_PROXIMITY_CHARS) {
702 if (rightChars[i++] == currentChar) return true;
703 }
704 }
705 return false;
706}
707
Jean Chalarda5d58492011-02-18 17:50:58 +0900708
709// In the following function, c is the current character of the dictionary word
710// currently examined.
711// currentChars is an array containing the keys close to the character the
712// user actually typed at the same position. We want to see if c is in it: if so,
713// then the word contains at that position a character close to what the user
714// typed.
715// What the user typed is actually the first character of the array.
716// Notice : accented characters do not have a proximity list, so they are alone
717// in their list. The non-accented version of the character should be considered
718// "close", but not the other keys close to the non-accented version.
Jean Chalard8dc754a2011-01-27 14:20:22 +0900719inline UnigramDictionary::ProximityType UnigramDictionary::getMatchedProximityId(
720 const int *currentChars, const unsigned short c, const int skipPos,
721 const int excessivePos, const int transposedPos) {
Jean Chalardf5f834a2011-02-22 15:12:46 +0900722 const unsigned short baseLowerC = toBaseLowerCase(c);
Jean Chalarda5d58492011-02-18 17:50:58 +0900723
724 // The first char in the array is what user typed. If it matches right away,
725 // that means the user typed that same char for this pos.
Jean Chalardf5f834a2011-02-22 15:12:46 +0900726 if (currentChars[0] == baseLowerC || currentChars[0] == c)
Jean Chalarda5d58492011-02-18 17:50:58 +0900727 return SAME_OR_ACCENTED_OR_CAPITALIZED_CHAR;
728
729 // If one of those is true, we should not check for close characters at all.
730 if (skipPos >= 0 || excessivePos >= 0 || transposedPos >= 0)
731 return UNRELATED_CHAR;
732
733 // If the non-accented, lowercased version of that first character matches c,
734 // then we have a non-accented version of the accented character the user
735 // typed. Treat it as a close char.
Jean Chalardf5f834a2011-02-22 15:12:46 +0900736 if (toBaseLowerCase(currentChars[0]) == baseLowerC)
Jean Chalarda5d58492011-02-18 17:50:58 +0900737 return NEAR_PROXIMITY_CHAR;
738
739 // Not an exact nor an accent-alike match: search the list of close keys
740 int j = 1;
satoke07baa62010-12-09 21:55:40 +0900741 while (currentChars[j] > 0 && j < MAX_PROXIMITY_CHARS) {
Jean Chalardf5f834a2011-02-22 15:12:46 +0900742 const bool matched = (currentChars[j] == baseLowerC || currentChars[j] == c);
Jean Chalarda5d58492011-02-18 17:50:58 +0900743 if (matched) return NEAR_PROXIMITY_CHAR;
satok28bd03b2010-12-03 16:39:16 +0900744 ++j;
745 }
Jean Chalarda5d58492011-02-18 17:50:58 +0900746
747 // Was not included, signal this as an unrelated character.
Jean Chalard8dc754a2011-01-27 14:20:22 +0900748 return UNRELATED_CHAR;
satok28bd03b2010-12-03 16:39:16 +0900749}
750
satok48e432c2010-12-06 17:38:58 +0900751inline bool UnigramDictionary::processCurrentNode(const int pos, const int depth,
Jean Chalardf5f834a2011-02-22 15:12:46 +0900752 const int maxDepth, const bool traverseAllNodes, int matchWeight, int inputIndex,
satoka3d78f62010-12-09 22:08:33 +0900753 const int diffs, const int skipPos, const int excessivePos, const int transposedPos,
754 int *nextLetters, const int nextLettersSize, int *newCount, int *newChildPosition,
Jean Chalardf5f834a2011-02-22 15:12:46 +0900755 bool *newTraverseAllNodes, int *newMatchRate, int *newInputIndex, int *newDiffs,
satoka3d78f62010-12-09 22:08:33 +0900756 int *nextSiblingPosition) {
757 if (DEBUG_DICT) {
758 int inputCount = 0;
759 if (skipPos >= 0) ++inputCount;
760 if (excessivePos >= 0) ++inputCount;
761 if (transposedPos >= 0) ++inputCount;
762 assert(inputCount <= 1);
763 }
satok48e432c2010-12-06 17:38:58 +0900764 unsigned short c;
765 int childPosition;
766 bool terminal;
767 int freq;
satokfd16f1d2011-01-27 16:25:16 +0900768 bool isSameAsUserTypedLength = false;
satokcdbbea72010-12-08 16:04:16 +0900769
satokfd16f1d2011-01-27 16:25:16 +0900770 if (excessivePos == depth && inputIndex < mInputLength - 1) ++inputIndex;
satokcdbbea72010-12-08 16:04:16 +0900771
Jean Chalard293ece02011-06-16 20:55:16 +0900772 *nextSiblingPosition = Dictionary::setDictionaryValues(DICT_ROOT, IS_LATEST_DICT_VERSION, pos,
773 &c, &childPosition, &terminal, &freq);
satok48e432c2010-12-06 17:38:58 +0900774
775 const bool needsToTraverseChildrenNodes = childPosition != 0;
776
777 // If we are only doing traverseAllNodes, no need to look at the typed characters.
778 if (traverseAllNodes || needsToSkipCurrentNode(c, inputIndex, skipPos, depth)) {
779 mWord[depth] = c;
780 if (traverseAllNodes && terminal) {
satok54fe9e02010-12-13 14:42:35 +0900781 onTerminalWhenUserTypedLengthIsGreaterThanInputLength(mWord, inputIndex, depth,
Jean Chalardf5f834a2011-02-22 15:12:46 +0900782 matchWeight, nextLetters, nextLettersSize, skipPos, excessivePos, transposedPos,
783 freq);
satok48e432c2010-12-06 17:38:58 +0900784 }
785 if (!needsToTraverseChildrenNodes) return false;
786 *newTraverseAllNodes = traverseAllNodes;
Jean Chalardf5f834a2011-02-22 15:12:46 +0900787 *newMatchRate = matchWeight;
satok48e432c2010-12-06 17:38:58 +0900788 *newDiffs = diffs;
789 *newInputIndex = inputIndex;
satok48e432c2010-12-06 17:38:58 +0900790 } else {
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900791 const int *currentChars = getInputCharsAt(inputIndex);
satoka3d78f62010-12-09 22:08:33 +0900792
793 if (transposedPos >= 0) {
794 if (inputIndex == transposedPos) currentChars += MAX_PROXIMITY_CHARS;
795 if (inputIndex == (transposedPos + 1)) currentChars -= MAX_PROXIMITY_CHARS;
796 }
797
798 int matchedProximityCharId = getMatchedProximityId(currentChars, c, skipPos, excessivePos,
799 transposedPos);
Jean Chalard8dc754a2011-01-27 14:20:22 +0900800 if (UNRELATED_CHAR == matchedProximityCharId) return false;
satok48e432c2010-12-06 17:38:58 +0900801 mWord[depth] = c;
802 // If inputIndex is greater than mInputLength, that means there is no
803 // proximity chars. So, we don't need to check proximity.
Jean Chalard8dc754a2011-01-27 14:20:22 +0900804 if (SAME_OR_ACCENTED_OR_CAPITALIZED_CHAR == matchedProximityCharId) {
satokb2e5e592011-04-26 14:50:54 +0900805 multiplyIntCapped(TYPED_LETTER_MULTIPLIER, &matchWeight);
Jean Chalard8dc754a2011-01-27 14:20:22 +0900806 }
satokfd16f1d2011-01-27 16:25:16 +0900807 bool isSameAsUserTypedLength = mInputLength == inputIndex + 1
808 || (excessivePos == mInputLength - 1 && inputIndex == mInputLength - 2);
satok48e432c2010-12-06 17:38:58 +0900809 if (isSameAsUserTypedLength && terminal) {
Jean Chalardf5f834a2011-02-22 15:12:46 +0900810 onTerminalWhenUserTypedLengthIsSameAsInputLength(mWord, inputIndex, depth, matchWeight,
Jean Chalard8dc754a2011-01-27 14:20:22 +0900811 skipPos, excessivePos, transposedPos, freq);
satok48e432c2010-12-06 17:38:58 +0900812 }
813 if (!needsToTraverseChildrenNodes) return false;
814 // Start traversing all nodes after the index exceeds the user typed length
815 *newTraverseAllNodes = isSameAsUserTypedLength;
Jean Chalardf5f834a2011-02-22 15:12:46 +0900816 *newMatchRate = matchWeight;
Jean Chalard8dc754a2011-01-27 14:20:22 +0900817 *newDiffs = diffs + ((NEAR_PROXIMITY_CHAR == matchedProximityCharId) ? 1 : 0);
satok48e432c2010-12-06 17:38:58 +0900818 *newInputIndex = inputIndex + 1;
satok48e432c2010-12-06 17:38:58 +0900819 }
820 // Optimization: Prune out words that are too long compared to how much was typed.
satokd2997922010-12-07 13:08:39 +0900821 if (depth >= maxDepth || *newDiffs > mMaxEditDistance) {
satok48e432c2010-12-06 17:38:58 +0900822 return false;
823 }
824
825 // If inputIndex is greater than mInputLength, that means there are no proximity chars.
satokfd16f1d2011-01-27 16:25:16 +0900826 // TODO: Check if this can be isSameAsUserTypedLength only.
827 if (isSameAsUserTypedLength || mInputLength <= *newInputIndex) {
satok48e432c2010-12-06 17:38:58 +0900828 *newTraverseAllNodes = true;
829 }
830 // get the count of nodes and increment childAddress.
Jean Chalard293ece02011-06-16 20:55:16 +0900831 *newCount = Dictionary::getCount(DICT_ROOT, &childPosition);
satok48e432c2010-12-06 17:38:58 +0900832 *newChildPosition = childPosition;
833 if (DEBUG_DICT) assert(needsToTraverseChildrenNodes);
834 return needsToTraverseChildrenNodes;
835}
836
satokaee09dc2010-12-09 19:21:51 +0900837inline int UnigramDictionary::getBestWordFreq(const int startInputIndex, const int inputLength,
838 unsigned short *word) {
satok662fe692010-12-08 17:05:39 +0900839 int pos = ROOT_POS;
Jean Chalard293ece02011-06-16 20:55:16 +0900840 int count = Dictionary::getCount(DICT_ROOT, &pos);
satokaee09dc2010-12-09 19:21:51 +0900841 int maxFreq = 0;
842 int depth = 0;
843 unsigned short newWord[MAX_WORD_LENGTH_INTERNAL];
satok662fe692010-12-08 17:05:39 +0900844 bool terminal = false;
845
satokaee09dc2010-12-09 19:21:51 +0900846 mStackChildCount[0] = count;
847 mStackSiblingPos[0] = pos;
848
849 while (depth >= 0) {
850 if (mStackChildCount[depth] > 0) {
851 --mStackChildCount[depth];
852 int firstChildPos;
853 int newFreq;
854 int siblingPos = mStackSiblingPos[depth];
855 const bool needsToTraverseChildrenNodes = processCurrentNodeForExactMatch(siblingPos,
856 startInputIndex, depth, newWord, &firstChildPos, &count, &terminal, &newFreq,
857 &siblingPos);
858 mStackSiblingPos[depth] = siblingPos;
859 if (depth == (inputLength - 1)) {
860 // Traverse sibling node
861 if (terminal) {
862 if (newFreq > maxFreq) {
863 for (int i = 0; i < inputLength; ++i) word[i] = newWord[i];
864 if (DEBUG_DICT && DEBUG_NODE) {
865 char s[inputLength + 1];
866 for (int i = 0; i < inputLength; ++i) s[i] = word[i];
867 s[inputLength] = 0;
868 LOGI("New missing space word found: %d > %d (%s), %d, %d",
869 newFreq, maxFreq, s, inputLength, depth);
870 }
871 maxFreq = newFreq;
872 }
873 }
874 } else if (needsToTraverseChildrenNodes) {
875 // Traverse children nodes
876 ++depth;
877 mStackChildCount[depth] = count;
878 mStackSiblingPos[depth] = firstChildPos;
879 }
880 } else {
881 // Traverse parent node
882 --depth;
satok662fe692010-12-08 17:05:39 +0900883 }
884 }
satokaee09dc2010-12-09 19:21:51 +0900885
886 word[inputLength] = 0;
887 return maxFreq;
satok662fe692010-12-08 17:05:39 +0900888}
889
890inline bool UnigramDictionary::processCurrentNodeForExactMatch(const int firstChildPos,
satokaee09dc2010-12-09 19:21:51 +0900891 const int startInputIndex, const int depth, unsigned short *word, int *newChildPosition,
892 int *newCount, bool *newTerminal, int *newFreq, int *siblingPos) {
893 const int inputIndex = startInputIndex + depth;
satok8fbd5522011-02-22 17:28:55 +0900894 const int *currentChars = getInputCharsAt(inputIndex);
satok662fe692010-12-08 17:05:39 +0900895 unsigned short c;
Jean Chalard293ece02011-06-16 20:55:16 +0900896 *siblingPos = Dictionary::setDictionaryValues(DICT_ROOT, IS_LATEST_DICT_VERSION, firstChildPos,
897 &c, newChildPosition, newTerminal, newFreq);
satokaee09dc2010-12-09 19:21:51 +0900898 const unsigned int inputC = currentChars[0];
Ken Wakasade3070a2011-03-19 09:16:42 +0900899 if (DEBUG_DICT) {
900 assert(inputC <= U_SHORT_MAX);
901 }
Jean Chalardf5f834a2011-02-22 15:12:46 +0900902 const unsigned short baseLowerC = toBaseLowerCase(c);
903 const bool matched = (inputC == baseLowerC || inputC == c);
satokaee09dc2010-12-09 19:21:51 +0900904 const bool hasChild = *newChildPosition != 0;
905 if (matched) {
906 word[depth] = c;
907 if (DEBUG_DICT && DEBUG_NODE) {
908 LOGI("Node(%c, %c)<%d>, %d, %d", inputC, c, matched, hasChild, *newFreq);
Ken Wakasade3070a2011-03-19 09:16:42 +0900909 if (*newTerminal) {
910 LOGI("Terminal %d", *newFreq);
911 }
satok662fe692010-12-08 17:05:39 +0900912 }
satokaee09dc2010-12-09 19:21:51 +0900913 if (hasChild) {
Jean Chalard293ece02011-06-16 20:55:16 +0900914 *newCount = Dictionary::getCount(DICT_ROOT, newChildPosition);
satokaee09dc2010-12-09 19:21:51 +0900915 return true;
916 } else {
917 return false;
918 }
919 } else {
920 // If this node is not user typed character, this method treats this word as unmatched.
921 // Thus newTerminal shouldn't be true.
922 *newTerminal = false;
923 return false;
satok662fe692010-12-08 17:05:39 +0900924 }
satok662fe692010-12-08 17:05:39 +0900925}
Jean Chalard8124e642011-06-16 22:33:41 +0900926
927// TODO: use uint32_t instead of unsigned short
928bool UnigramDictionary::isValidWord(unsigned short *word, int length) {
929 if (IS_LATEST_DICT_VERSION) {
930 return (isValidWordRec(DICTIONARY_HEADER_SIZE, word, 0, length) != NOT_VALID_WORD);
931 } else {
932 return (isValidWordRec(0, word, 0, length) != NOT_VALID_WORD);
933 }
934}
935
936int UnigramDictionary::isValidWordRec(int pos, unsigned short *word, int offset, int length) {
937 // returns address of bigram data of that word
938 // return -99 if not found
939
940 int count = Dictionary::getCount(DICT_ROOT, &pos);
941 unsigned short currentChar = (unsigned short) word[offset];
942 for (int j = 0; j < count; j++) {
943 unsigned short c = Dictionary::getChar(DICT_ROOT, &pos);
944 int terminal = Dictionary::getTerminal(DICT_ROOT, &pos);
945 int childPos = Dictionary::getAddress(DICT_ROOT, &pos);
946 if (c == currentChar) {
947 if (offset == length - 1) {
948 if (terminal) {
949 return (pos+1);
950 }
951 } else {
952 if (childPos != 0) {
953 int t = isValidWordRec(childPos, word, offset + 1, length);
954 if (t > 0) {
955 return t;
956 }
957 }
958 }
959 }
960 if (terminal) {
961 Dictionary::getFreq(DICT_ROOT, IS_LATEST_DICT_VERSION, &pos);
962 }
963 // There could be two instances of each alphabet - upper and lower case. So continue
964 // looking ...
965 }
966 return NOT_VALID_WORD;
967}
968
satok30088252010-12-01 21:22:15 +0900969} // namespace latinime