blob: 0a144253a2b87577236635e77555e229b3bcc04f [file] [log] [blame]
satok30088252010-12-01 21:22:15 +09001/*
Ken Wakasa5460ea32012-07-30 16:27:44 +09002 * Copyright (C) 2010, The Android Open Source Project
Ken Wakasa0bbb9172012-07-25 17:51:43 +09003 *
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 */
satok30088252010-12-01 21:22:15 +090016
Ken Wakasaf1008c52012-07-31 17:56:40 +090017#include <cstring>
satok30088252010-12-01 21:22:15 +090018
satoke808e432010-12-02 14:53:24 +090019#define LOG_TAG "LatinIME: unigram_dictionary.cpp"
satok30088252010-12-01 21:22:15 +090020
Ken Wakasa77e8e812012-08-02 19:48:08 +090021#include "binary_format.h"
satok30088252010-12-01 21:22:15 +090022#include "char_utils.h"
Ken Wakasa3b088a22012-05-16 23:05:32 +090023#include "defines.h"
satoke808e432010-12-02 14:53:24 +090024#include "dictionary.h"
Ken Wakasa77e8e812012-08-02 19:48:08 +090025#include "proximity_info.h"
Jean Chalardcf9dbbd2011-12-26 15:16:59 +090026#include "terminal_attributes.h"
Ken Wakasa77e8e812012-08-02 19:48:08 +090027#include "unigram_dictionary.h"
28#include "words_priority_queue.h"
29#include "words_priority_queue_pool.h"
Jean Chalard1059f272011-06-28 20:45:05 +090030
satok30088252010-12-01 21:22:15 +090031namespace latinime {
32
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090033const UnigramDictionary::digraph_t UnigramDictionary::GERMAN_UMLAUT_DIGRAPHS[] =
Jean Chalardd3043382012-03-21 18:38:25 +090034 { { 'a', 'e', 0x00E4 }, // U+00E4 : LATIN SMALL LETTER A WITH DIAERESIS
35 { 'o', 'e', 0x00F6 }, // U+00F6 : LATIN SMALL LETTER O WITH DIAERESIS
36 { 'u', 'e', 0x00FC } }; // U+00FC : LATIN SMALL LETTER U WITH DIAERESIS
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090037
Jean Chalardcc78d032012-03-23 16:48:49 +090038const UnigramDictionary::digraph_t UnigramDictionary::FRENCH_LIGATURES_DIGRAPHS[] =
39 { { 'a', 'e', 0x00E6 }, // U+00E6 : LATIN SMALL LETTER AE
40 { 'o', 'e', 0x0153 } }; // U+0153 : LATIN SMALL LIGATURE OE
41
Jean Chalard293ece02011-06-16 20:55:16 +090042// TODO: check the header
Ken Wakasafe9ec6b2012-11-16 19:28:56 +090043UnigramDictionary::UnigramDictionary(const uint8_t *const streamStart, int maxWordLength,
44 int maxWords, const unsigned int flags)
Ken Wakasab02ee3d2012-10-08 11:46:14 +090045 : DICT_ROOT(streamStart), MAX_WORD_LENGTH(maxWordLength), MAX_WORDS(maxWords),
Ken Wakasa44d9c1e2012-11-01 17:05:08 +090046 ROOT_POS(0), MAX_DIGRAPH_SEARCH_DEPTH(DEFAULT_MAX_DIGRAPH_SEARCH_DEPTH), FLAGS(flags) {
Ken Wakasade3070a2011-03-19 09:16:42 +090047 if (DEBUG_DICT) {
satok9fb6f472012-01-13 18:01:22 +090048 AKLOGI("UnigramDictionary - constructor");
Ken Wakasade3070a2011-03-19 09:16:42 +090049 }
satok30088252010-12-01 21:22:15 +090050}
51
satok2df30602011-07-15 13:49:00 +090052UnigramDictionary::~UnigramDictionary() {
satok2df30602011-07-15 13:49:00 +090053}
satok30088252010-12-01 21:22:15 +090054
Ken Wakasa1e614932012-10-29 18:06:22 +090055static inline int getCodesBufferSize(const int *codes, const int codesSize) {
56 return sizeof(*codes) * codesSize;
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090057}
58
Ken Wakasa1e614932012-10-29 18:06:22 +090059// TODO: This needs to take a const int* and not tinker with its contents
Ken Wakasa2c2f3a92012-11-02 18:29:03 +090060static void addWord(int *word, int length, int frequency, WordsPriorityQueue *queue, int type) {
Jean Chalard926ef062012-08-10 13:14:45 +090061 queue->push(frequency, word, length, type);
satok1147c7b2011-12-14 15:04:58 +090062}
63
Jean Chalardd3043382012-03-21 18:38:25 +090064// Return the replacement code point for a digraph, or 0 if none.
65int UnigramDictionary::getDigraphReplacement(const int *codes, const int i, const int codesSize,
Ken Wakasa0bbb9172012-07-25 17:51:43 +090066 const digraph_t *const digraphs, const unsigned int digraphsSize) const {
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090067
68 // There can't be a digraph if we don't have at least 2 characters to examine
69 if (i + 2 > codesSize) return false;
70
71 // Search for the first char of some digraph
72 int lastDigraphIndex = -1;
satok9df4a452012-03-23 16:05:18 +090073 const int thisChar = codes[i];
Jean Chalard6c300612012-03-06 19:54:03 +090074 for (lastDigraphIndex = digraphsSize - 1; lastDigraphIndex >= 0; --lastDigraphIndex) {
75 if (thisChar == digraphs[lastDigraphIndex].first) break;
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090076 }
77 // No match: return early
Jean Chalardd3043382012-03-21 18:38:25 +090078 if (lastDigraphIndex < 0) return 0;
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090079
80 // It's an interesting digraph if the second char matches too.
satok9df4a452012-03-23 16:05:18 +090081 if (digraphs[lastDigraphIndex].second == codes[i + 1]) {
Jean Chalardd3043382012-03-21 18:38:25 +090082 return digraphs[lastDigraphIndex].replacement;
83 } else {
84 return 0;
85 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090086}
87
88// Mostly the same arguments as the non-recursive version, except:
89// codes is the original value. It points to the start of the work buffer, and gets passed as is.
90// codesSize is the size of the user input (thus, it is the size of codesSrc).
91// codesDest is the current point in the work buffer.
92// codesSrc is the current point in the user-input, original, content-unmodified buffer.
93// codesRemain is the remaining size in codesSrc.
satok1d7eaf82011-07-13 10:32:02 +090094void UnigramDictionary::getWordWithDigraphSuggestionsRec(ProximityInfo *proximityInfo,
satok1147c7b2011-12-14 15:04:58 +090095 const int *xcoordinates, const int *ycoordinates, const int *codesBuffer,
satok219a5142012-03-08 11:53:18 +090096 int *xCoordinatesBuffer, int *yCoordinatesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +090097 const int codesBufferSize, const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Jean Chalard4d9b2022012-04-23 19:25:28 +090098 const bool useFullEditDistance, const int *codesSrc,
satok1147c7b2011-12-14 15:04:58 +090099 const int codesRemain, const int currentDepth, int *codesDest, Correction *correction,
Jean Chalard6c300612012-03-06 19:54:03 +0900100 WordsPriorityQueuePool *queuePool,
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900101 const digraph_t *const digraphs, const unsigned int digraphsSize) const {
Ken Wakasaccebd5c2013-01-09 15:21:44 +0900102 ASSERT(sizeof(codesDest[0]) == sizeof(codesSrc[0]));
103 ASSERT(sizeof(xCoordinatesBuffer[0]) == sizeof(xcoordinates[0]));
104 ASSERT(sizeof(yCoordinatesBuffer[0]) == sizeof(ycoordinates[0]));
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900105
Ken Wakasaf2789812012-09-04 12:49:46 +0900106 const int startIndex = static_cast<int>(codesDest - codesBuffer);
Jean Chalard6c300612012-03-06 19:54:03 +0900107 if (currentDepth < MAX_DIGRAPH_SEARCH_DEPTH) {
Jean Chalarda787dba2011-03-04 12:17:48 +0900108 for (int i = 0; i < codesRemain; ++i) {
satok219a5142012-03-08 11:53:18 +0900109 xCoordinatesBuffer[startIndex + i] = xcoordinates[codesBufferSize - codesRemain + i];
110 yCoordinatesBuffer[startIndex + i] = ycoordinates[codesBufferSize - codesRemain + i];
Jean Chalardd3043382012-03-21 18:38:25 +0900111 const int replacementCodePoint =
112 getDigraphReplacement(codesSrc, i, codesRemain, digraphs, digraphsSize);
113 if (0 != replacementCodePoint) {
Jean Chalarda787dba2011-03-04 12:17:48 +0900114 // Found a digraph. We will try both spellings. eg. the word is "pruefen"
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900115
Jean Chalardd3043382012-03-21 18:38:25 +0900116 // Copy the word up to the first char of the digraph, including proximity chars,
117 // and overwrite the primary code with the replacement code point. Then, continue
118 // processing on the remaining part of the word, skipping the second char of the
119 // digraph.
120 // In our example, copy "pru", replace "u" with the version with the diaeresis and
121 // continue running on "fen".
Jean Chalarda787dba2011-03-04 12:17:48 +0900122 // Make i the index of the second char of the digraph for simplicity. Forgetting
123 // to do that results in an infinite recursion so take care!
124 ++i;
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900125 memcpy(codesDest, codesSrc, i * sizeof(codesDest[0]));
126 codesDest[i - 1] = replacementCodePoint;
Jean Chalarda787dba2011-03-04 12:17:48 +0900127 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates,
Jean Chalard338d3ec2012-04-06 19:28:34 +0900128 codesBuffer, xCoordinatesBuffer, yCoordinatesBuffer, codesBufferSize,
Jean Chalard8950ce62012-05-07 16:28:30 +0900129 bigramMap, bigramFilter, useFullEditDistance, codesSrc + i + 1,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900130 codesRemain - i - 1, currentDepth + 1, codesDest + i, correction,
Jean Chalard6c300612012-03-06 19:54:03 +0900131 queuePool, digraphs, digraphsSize);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900132
Jean Chalarda787dba2011-03-04 12:17:48 +0900133 // Copy the second char of the digraph in place, then continue processing on
134 // the remaining part of the word.
135 // In our example, after "pru" in the buffer copy the "e", and continue on "fen"
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900136 memcpy(codesDest + i, codesSrc + i, sizeof(codesDest[0]));
Jean Chalarda787dba2011-03-04 12:17:48 +0900137 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates,
Jean Chalard338d3ec2012-04-06 19:28:34 +0900138 codesBuffer, xCoordinatesBuffer, yCoordinatesBuffer, codesBufferSize,
Jean Chalard8950ce62012-05-07 16:28:30 +0900139 bigramMap, bigramFilter, useFullEditDistance, codesSrc + i, codesRemain - i,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900140 currentDepth + 1, codesDest + i, correction, queuePool, digraphs,
141 digraphsSize);
Jean Chalarda787dba2011-03-04 12:17:48 +0900142 return;
143 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900144 }
145 }
146
147 // If we come here, we hit the end of the word: let's check it against the dictionary.
148 // In our example, we'll come here once for "prufen" and then once for "pruefen".
149 // If the word contains several digraphs, we'll come it for the product of them.
150 // eg. if the word is "ueberpruefen" we'll test, in order, against
151 // "uberprufen", "uberpruefen", "ueberprufen", "ueberpruefen".
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900152 const unsigned int remainingBytes = sizeof(codesDest[0]) * codesRemain;
satok219a5142012-03-08 11:53:18 +0900153 if (0 != remainingBytes) {
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900154 memcpy(codesDest, codesSrc, remainingBytes);
satok219a5142012-03-08 11:53:18 +0900155 memcpy(&xCoordinatesBuffer[startIndex], &xcoordinates[codesBufferSize - codesRemain],
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900156 sizeof(xCoordinatesBuffer[0]) * codesRemain);
satok219a5142012-03-08 11:53:18 +0900157 memcpy(&yCoordinatesBuffer[startIndex], &ycoordinates[codesBufferSize - codesRemain],
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900158 sizeof(yCoordinatesBuffer[0]) * codesRemain);
satok219a5142012-03-08 11:53:18 +0900159 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900160
satok219a5142012-03-08 11:53:18 +0900161 getWordSuggestions(proximityInfo, xCoordinatesBuffer, yCoordinatesBuffer, codesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +0900162 startIndex + codesRemain, bigramMap, bigramFilter, useFullEditDistance, correction,
satoka7e5a5a2011-12-15 16:49:12 +0900163 queuePool);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900164}
165
Jean Chalard8950ce62012-05-07 16:28:30 +0900166// bigramMap contains the association <bigram address> -> <bigram frequency>
167// bigramFilter is a bloom filter for fast rejection: see functions setInFilter and isInFilter
168// in bigram_dictionary.cpp
Ken Wakasaf2789812012-09-04 12:49:46 +0900169int UnigramDictionary::getSuggestions(ProximityInfo *proximityInfo, const int *xcoordinates,
Jean Chalard338d3ec2012-04-06 19:28:34 +0900170 const int *ycoordinates, const int *codes, const int codesSize,
Jean Chalard8950ce62012-05-07 16:28:30 +0900171 const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Ken Wakasa1e614932012-10-29 18:06:22 +0900172 const bool useFullEditDistance, int *outWords, int *frequencies, int *outputTypes) const {
satokb1ed1d42012-06-14 16:35:23 -0700173 WordsPriorityQueuePool queuePool(MAX_WORDS, SUB_QUEUE_MAX_WORDS, MAX_WORD_LENGTH);
174 queuePool.clearAll();
satok1bc038c2012-06-14 11:25:50 -0700175 Correction masterCorrection;
176 masterCorrection.resetCorrection();
Jean Chalardaa8df592012-04-06 18:54:20 +0900177 if (BinaryFormat::REQUIRES_GERMAN_UMLAUT_PROCESSING & FLAGS)
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900178 { // Incrementally tune the word and try all possibilities
satok9df4a452012-03-23 16:05:18 +0900179 int codesBuffer[getCodesBufferSize(codes, codesSize)];
satok219a5142012-03-08 11:53:18 +0900180 int xCoordinatesBuffer[codesSize];
181 int yCoordinatesBuffer[codesSize];
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900182 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates, codesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +0900183 xCoordinatesBuffer, yCoordinatesBuffer, codesSize, bigramMap, bigramFilter,
satok1bc038c2012-06-14 11:25:50 -0700184 useFullEditDistance, codes, codesSize, 0, codesBuffer, &masterCorrection,
Ken Wakasab02ee3d2012-10-08 11:46:14 +0900185 &queuePool, GERMAN_UMLAUT_DIGRAPHS, NELEMS(GERMAN_UMLAUT_DIGRAPHS));
Jean Chalardaa8df592012-04-06 18:54:20 +0900186 } else if (BinaryFormat::REQUIRES_FRENCH_LIGATURES_PROCESSING & FLAGS) {
satokacb6c542012-03-23 20:58:18 +0900187 int codesBuffer[getCodesBufferSize(codes, codesSize)];
Jean Chalardcc78d032012-03-23 16:48:49 +0900188 int xCoordinatesBuffer[codesSize];
189 int yCoordinatesBuffer[codesSize];
190 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates, codesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +0900191 xCoordinatesBuffer, yCoordinatesBuffer, codesSize, bigramMap, bigramFilter,
satok1bc038c2012-06-14 11:25:50 -0700192 useFullEditDistance, codes, codesSize, 0, codesBuffer, &masterCorrection,
Ken Wakasab02ee3d2012-10-08 11:46:14 +0900193 &queuePool, FRENCH_LIGATURES_DIGRAPHS, NELEMS(FRENCH_LIGATURES_DIGRAPHS));
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900194 } else { // Normal processing
Jean Chalard338d3ec2012-04-06 19:28:34 +0900195 getWordSuggestions(proximityInfo, xcoordinates, ycoordinates, codes, codesSize,
satokb1ed1d42012-06-14 16:35:23 -0700196 bigramMap, bigramFilter, useFullEditDistance, &masterCorrection, &queuePool);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900197 }
198
satok817e5172011-03-04 06:06:45 -0800199 PROF_START(20);
satok8330b482012-01-23 16:52:37 +0900200 if (DEBUG_DICT) {
satokb1ed1d42012-06-14 16:35:23 -0700201 float ns = queuePool.getMasterQueue()->getHighestNormalizedScore(
satok1bc038c2012-06-14 11:25:50 -0700202 masterCorrection.getPrimaryInputWord(), codesSize, 0, 0, 0);
satok8330b482012-01-23 16:52:37 +0900203 ns += 0;
204 AKLOGI("Max normalized score = %f", ns);
205 }
satoka7e5a5a2011-12-15 16:49:12 +0900206 const int suggestedWordsCount =
Jean Chalard926ef062012-08-10 13:14:45 +0900207 queuePool.getMasterQueue()->outputSuggestions(masterCorrection.getPrimaryInputWord(),
208 codesSize, frequencies, outWords, outputTypes);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900209
210 if (DEBUG_DICT) {
satokb1ed1d42012-06-14 16:35:23 -0700211 float ns = queuePool.getMasterQueue()->getHighestNormalizedScore(
satok1bc038c2012-06-14 11:25:50 -0700212 masterCorrection.getPrimaryInputWord(), codesSize, 0, 0, 0);
satok8330b482012-01-23 16:52:37 +0900213 ns += 0;
satok9fb6f472012-01-13 18:01:22 +0900214 AKLOGI("Returning %d words", suggestedWordsCount);
Jean Chalard980d6b62011-06-30 17:02:23 +0900215 /// Print the returned words
216 for (int j = 0; j < suggestedWordsCount; ++j) {
Ken Wakasa1e614932012-10-29 18:06:22 +0900217 int *w = outWords + j * MAX_WORD_LENGTH;
Jean Chalard980d6b62011-06-30 17:02:23 +0900218 char s[MAX_WORD_LENGTH];
219 for (int i = 0; i <= MAX_WORD_LENGTH; i++) s[i] = w[i];
Ken Wakasa7914e902012-09-07 08:55:16 +0900220 (void)s; // To suppress compiler warning
satok9fb6f472012-01-13 18:01:22 +0900221 AKLOGI("%s %i", s, frequencies[j]);
Jean Chalard980d6b62011-06-30 17:02:23 +0900222 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900223 }
satok817e5172011-03-04 06:06:45 -0800224 PROF_END(20);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900225 PROF_CLOSE;
226 return suggestedWordsCount;
227}
228
Ken Wakasa1e614932012-10-29 18:06:22 +0900229void UnigramDictionary::getWordSuggestions(ProximityInfo *proximityInfo, const int *xcoordinates,
230 const int *ycoordinates, const int *codes, const int inputSize,
231 const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
232 const bool useFullEditDistance, Correction *correction, WordsPriorityQueuePool *queuePool)
233 const {
satok61e2f852011-01-05 14:13:07 +0900234 PROF_OPEN;
235 PROF_START(0);
satok61e2f852011-01-05 14:13:07 +0900236 PROF_END(0);
satok30088252010-12-01 21:22:15 +0900237
satok61e2f852011-01-05 14:13:07 +0900238 PROF_START(1);
Jean Chalard8950ce62012-05-07 16:28:30 +0900239 getOneWordSuggestions(proximityInfo, xcoordinates, ycoordinates, codes, bigramMap, bigramFilter,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900240 useFullEditDistance, inputSize, correction, queuePool);
satok61e2f852011-01-05 14:13:07 +0900241 PROF_END(1);
242
243 PROF_START(2);
satok10266c02011-08-19 22:05:59 +0900244 // Note: This line is intentionally left blank
satok61e2f852011-01-05 14:13:07 +0900245 PROF_END(2);
satokcdbbea72010-12-08 16:04:16 +0900246
satok61e2f852011-01-05 14:13:07 +0900247 PROF_START(3);
satok10266c02011-08-19 22:05:59 +0900248 // Note: This line is intentionally left blank
satok61e2f852011-01-05 14:13:07 +0900249 PROF_END(3);
satok30088252010-12-01 21:22:15 +0900250
satok61e2f852011-01-05 14:13:07 +0900251 PROF_START(4);
satok8330b482012-01-23 16:52:37 +0900252 bool hasAutoCorrectionCandidate = false;
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900253 WordsPriorityQueue *masterQueue = queuePool->getMasterQueue();
satok8330b482012-01-23 16:52:37 +0900254 if (masterQueue->size() > 0) {
satok0028ed32012-05-16 20:42:12 +0900255 float nsForMaster = masterQueue->getHighestNormalizedScore(
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900256 correction->getPrimaryInputWord(), inputSize, 0, 0, 0);
satok8330b482012-01-23 16:52:37 +0900257 hasAutoCorrectionCandidate = (nsForMaster > START_TWO_WORDS_CORRECTION_THRESHOLD);
258 }
satok61e2f852011-01-05 14:13:07 +0900259 PROF_END(4);
satoka3d78f62010-12-09 22:08:33 +0900260
satok61e2f852011-01-05 14:13:07 +0900261 PROF_START(5);
satok99557162012-01-26 22:49:13 +0900262 // Multiple word suggestions
263 if (SUGGEST_MULTIPLE_WORDS
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900264 && inputSize >= MIN_USER_TYPED_LENGTH_FOR_MULTIPLE_WORD_SUGGESTION) {
satoka85f4922012-01-30 18:18:30 +0900265 getSplitMultipleWordsSuggestions(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900266 useFullEditDistance, inputSize, correction, queuePool,
satok1f6b52e2012-01-30 13:53:58 +0900267 hasAutoCorrectionCandidate);
satok662fe692010-12-08 17:05:39 +0900268 }
satok61e2f852011-01-05 14:13:07 +0900269 PROF_END(5);
satok817e5172011-03-04 06:06:45 -0800270
271 PROF_START(6);
satok99557162012-01-26 22:49:13 +0900272 // Note: This line is intentionally left blank
satok817e5172011-03-04 06:06:45 -0800273 PROF_END(6);
satok99557162012-01-26 22:49:13 +0900274
satok29dc8062012-01-17 15:59:15 +0900275 if (DEBUG_DICT) {
satok6ad15fc2012-01-16 16:21:21 +0900276 queuePool->dumpSubQueue1TopSuggestions();
satok29dc8062012-01-17 15:59:15 +0900277 for (int i = 0; i < SUB_QUEUE_MAX_COUNT; ++i) {
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900278 WordsPriorityQueue *queue = queuePool->getSubQueue(FIRST_WORD_INDEX, i);
satok29dc8062012-01-17 15:59:15 +0900279 if (queue->size() > 0) {
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900280 WordsPriorityQueue::SuggestedWord *sw = queue->top();
satok29dc8062012-01-17 15:59:15 +0900281 const int score = sw->mScore;
Ken Wakasa1e614932012-10-29 18:06:22 +0900282 const int *word = sw->mWord;
satok29dc8062012-01-17 15:59:15 +0900283 const int wordLength = sw->mWordLength;
satok0028ed32012-05-16 20:42:12 +0900284 float ns = Correction::RankingAlgorithm::calcNormalizedScore(
Satoshi Kataoka4a3db702012-06-08 15:29:44 +0900285 correction->getPrimaryInputWord(), i, word, wordLength, score);
satok29dc8062012-01-17 15:59:15 +0900286 ns += 0;
287 AKLOGI("--- TOP SUB WORDS for %d --- %d %f [%d]", i, score, ns,
satok54af64a2012-01-17 15:58:23 +0900288 (ns > TWO_WORDS_CORRECTION_WITH_OTHER_ERROR_THRESHOLD));
Satoshi Kataoka4a3db702012-06-08 15:29:44 +0900289 DUMP_WORD(correction->getPrimaryInputWord(), i);
satok29dc8062012-01-17 15:59:15 +0900290 DUMP_WORD(word, wordLength);
291 }
292 }
satok6ad15fc2012-01-16 16:21:21 +0900293 }
satok30088252010-12-01 21:22:15 +0900294}
295
Yusuke Nojima258bfe62011-09-28 12:59:43 +0900296void UnigramDictionary::initSuggestions(ProximityInfo *proximityInfo, const int *xCoordinates,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900297 const int *yCoordinates, const int *codes, const int inputSize,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900298 Correction *correction) const {
Ken Wakasade3070a2011-03-19 09:16:42 +0900299 if (DEBUG_DICT) {
satok9fb6f472012-01-13 18:01:22 +0900300 AKLOGI("initSuggest");
Ken Wakasa1e614932012-10-29 18:06:22 +0900301 DUMP_WORD(codes, inputSize);
Ken Wakasade3070a2011-03-19 09:16:42 +0900302 }
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900303 correction->initInputParams(proximityInfo, codes, inputSize, xCoordinates, yCoordinates);
304 const int maxDepth = min(inputSize * MAX_DEPTH_MULTIPLIER, MAX_WORD_LENGTH);
305 correction->initCorrection(proximityInfo, inputSize, maxDepth);
satok30088252010-12-01 21:22:15 +0900306}
307
satok744dab62011-12-15 22:29:05 +0900308void UnigramDictionary::getOneWordSuggestions(ProximityInfo *proximityInfo,
309 const int *xcoordinates, const int *ycoordinates, const int *codes,
Jean Chalard8950ce62012-05-07 16:28:30 +0900310 const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900311 const bool useFullEditDistance, const int inputSize,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900312 Correction *correction, WordsPriorityQueuePool *queuePool) const {
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900313 initSuggestions(proximityInfo, xcoordinates, ycoordinates, codes, inputSize, correction);
314 getSuggestionCandidates(useFullEditDistance, inputSize, bigramMap, bigramFilter, correction,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900315 queuePool, true /* doAutoCompletion */, DEFAULT_MAX_ERRORS, FIRST_WORD_INDEX);
satok744dab62011-12-15 22:29:05 +0900316}
317
satok1147c7b2011-12-14 15:04:58 +0900318void UnigramDictionary::getSuggestionCandidates(const bool useFullEditDistance,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900319 const int inputSize, const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900320 Correction *correction, WordsPriorityQueuePool *queuePool,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900321 const bool doAutoCompletion, const int maxErrors, const int currentWordIndex) const {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900322 uint8_t totalTraverseCount = correction->pushAndGetTotalTraverseCount();
323 if (DEBUG_DICT) {
324 AKLOGI("Traverse count %d", totalTraverseCount);
325 }
326 if (totalTraverseCount > MULTIPLE_WORDS_SUGGESTION_MAX_TOTAL_TRAVERSE_COUNT) {
327 if (DEBUG_DICT) {
328 AKLOGI("Abort traversing %d", totalTraverseCount);
329 }
330 return;
331 }
satok10266c02011-08-19 22:05:59 +0900332 // TODO: Remove setCorrectionParams
satok1147c7b2011-12-14 15:04:58 +0900333 correction->setCorrectionParams(0, 0, 0,
satokd03317c2011-12-14 21:38:11 +0900334 -1 /* spaceProximityPos */, -1 /* missingSpacePos */, useFullEditDistance,
satok1a6da632011-12-16 23:15:06 +0900335 doAutoCompletion, maxErrors);
satok662fe692010-12-08 17:05:39 +0900336 int rootPosition = ROOT_POS;
Jean Chalard980d6b62011-06-30 17:02:23 +0900337 // Get the number of children of root, then increment the position
Jean Chalard6d419812012-01-16 15:19:47 +0900338 int childCount = BinaryFormat::getGroupCountAndForwardPointer(DICT_ROOT, &rootPosition);
satok208268d2011-08-10 15:44:08 +0900339 int outputIndex = 0;
satokd2997922010-12-07 13:08:39 +0900340
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900341 correction->initCorrectionState(rootPosition, childCount, (inputSize <= 0));
satokd2997922010-12-07 13:08:39 +0900342
satok662fe692010-12-08 17:05:39 +0900343 // Depth first search
satok208268d2011-08-10 15:44:08 +0900344 while (outputIndex >= 0) {
satok1147c7b2011-12-14 15:04:58 +0900345 if (correction->initProcessState(outputIndex)) {
346 int siblingPos = correction->getTreeSiblingPos(outputIndex);
satokd2997922010-12-07 13:08:39 +0900347 int firstChildPos;
satok0f6c8e82011-08-03 02:19:44 +0900348
satok4e4e74e2011-08-03 23:27:32 +0900349 const bool needsToTraverseChildrenNodes = processCurrentNode(siblingPos,
Jean Chalard8950ce62012-05-07 16:28:30 +0900350 bigramMap, bigramFilter, correction, &childCount, &firstChildPos, &siblingPos,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900351 queuePool, currentWordIndex);
satok662fe692010-12-08 17:05:39 +0900352 // Update next sibling pos
satok1147c7b2011-12-14 15:04:58 +0900353 correction->setTreeSiblingPos(outputIndex, siblingPos);
satok208268d2011-08-10 15:44:08 +0900354
satokd2997922010-12-07 13:08:39 +0900355 if (needsToTraverseChildrenNodes) {
356 // Goes to child node
satok1147c7b2011-12-14 15:04:58 +0900357 outputIndex = correction->goDownTree(outputIndex, childCount, firstChildPos);
satokd2997922010-12-07 13:08:39 +0900358 }
359 } else {
satokcdbbea72010-12-08 16:04:16 +0900360 // Goes to parent sibling node
satok1147c7b2011-12-14 15:04:58 +0900361 outputIndex = correction->getTreeParentIndex(outputIndex);
satokd2997922010-12-07 13:08:39 +0900362 }
363 }
364}
365
Ken Wakasa19d844c2012-11-02 23:57:13 +0900366void UnigramDictionary::onTerminal(const int probability,
Ken Wakasaa10b1a82013-01-08 17:23:43 +0900367 const TerminalAttributes &terminalAttributes, Correction *correction,
satok8330b482012-01-23 16:52:37 +0900368 WordsPriorityQueuePool *queuePool, const bool addToMasterQueue,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900369 const int currentWordIndex) const {
satok6ad15fc2012-01-16 16:21:21 +0900370 const int inputIndex = correction->getInputIndex();
371 const bool addToSubQueue = inputIndex < SUB_QUEUE_MAX_COUNT;
satok54af64a2012-01-17 15:58:23 +0900372
satok8876b752011-08-04 18:31:57 +0900373 int wordLength;
Ken Wakasa1e614932012-10-29 18:06:22 +0900374 int *wordPointer;
satok54af64a2012-01-17 15:58:23 +0900375
satok1f6b52e2012-01-30 13:53:58 +0900376 if ((currentWordIndex == FIRST_WORD_INDEX) && addToMasterQueue) {
satok54af64a2012-01-17 15:58:23 +0900377 WordsPriorityQueue *masterQueue = queuePool->getMasterQueue();
Jean Chalard171d1802012-04-23 18:51:00 +0900378 const int finalProbability =
379 correction->getFinalProbability(probability, &wordPointer, &wordLength);
satok54af64a2012-01-17 15:58:23 +0900380
Jean Chalard72b1c932012-08-31 15:24:39 +0900381 if (0 != finalProbability && !terminalAttributes.isBlacklistedOrNotAWord()) {
Jean Chalard8af8c152012-08-17 09:37:39 +0900382 // If the probability is 0, we don't want to add this word. However we still
383 // want to add its shortcuts (including a possible whitelist entry) if any.
Jean Chalard72b1c932012-08-31 15:24:39 +0900384 // Furthermore, if this is not a word (shortcut only for example) or a blacklisted
385 // entry then we never want to suggest this.
Jean Chalard8af8c152012-08-17 09:37:39 +0900386 addWord(wordPointer, wordLength, finalProbability, masterQueue,
387 Dictionary::KIND_CORRECTION);
388 }
389
390 const int shortcutProbability = finalProbability > 0 ? finalProbability - 1 : 0;
391 // Please note that the shortcut candidates will be added to the master queue only.
Ken Wakasaa10b1a82013-01-08 17:23:43 +0900392 TerminalAttributes::ShortcutIterator iterator = terminalAttributes.getShortcutIterator();
Jean Chalard8af8c152012-08-17 09:37:39 +0900393 while (iterator.hasNextShortcutTarget()) {
394 // TODO: addWord only supports weak ordering, meaning we have no means
395 // to control the order of the shortcuts relative to one another or to the word.
396 // We need to either modulate the probability of each shortcut according
397 // to its own shortcut probability or to make the queue
398 // so that the insert order is protected inside the queue for words
399 // with the same score. For the moment we use -1 to make sure the shortcut will
400 // never be in front of the word.
Ken Wakasa1e614932012-10-29 18:06:22 +0900401 int shortcutTarget[MAX_WORD_LENGTH_INTERNAL];
Jean Chalard8af8c152012-08-17 09:37:39 +0900402 int shortcutFrequency;
403 const int shortcutTargetStringLength = iterator.getNextShortcutTarget(
404 MAX_WORD_LENGTH_INTERNAL, shortcutTarget, &shortcutFrequency);
405 int shortcutScore;
406 int kind;
407 if (shortcutFrequency == BinaryFormat::WHITELIST_SHORTCUT_FREQUENCY
408 && correction->sameAsTyped()) {
409 shortcutScore = S_INT_MAX;
410 kind = Dictionary::KIND_WHITELIST;
411 } else {
412 shortcutScore = shortcutProbability;
413 kind = Dictionary::KIND_CORRECTION;
satok6ad15fc2012-01-16 16:21:21 +0900414 }
Jean Chalard8af8c152012-08-17 09:37:39 +0900415 addWord(shortcutTarget, shortcutTargetStringLength, shortcutScore,
416 masterQueue, kind);
Jean Chalardcf9dbbd2011-12-26 15:16:59 +0900417 }
satok54af64a2012-01-17 15:58:23 +0900418 }
satok6ad15fc2012-01-16 16:21:21 +0900419
satok54af64a2012-01-17 15:58:23 +0900420 // We only allow two words + other error correction for words with SUB_QUEUE_MIN_WORD_LENGTH
421 // or more length.
422 if (inputIndex >= SUB_QUEUE_MIN_WORD_LENGTH && addToSubQueue) {
satok8330b482012-01-23 16:52:37 +0900423 WordsPriorityQueue *subQueue;
satok7409d152012-01-26 16:13:25 +0900424 subQueue = queuePool->getSubQueue(currentWordIndex, inputIndex);
425 if (!subQueue) {
satok8330b482012-01-23 16:52:37 +0900426 return;
427 }
Jean Chalard171d1802012-04-23 18:51:00 +0900428 const int finalProbability = correction->getFinalProbabilityForSubQueue(
429 probability, &wordPointer, &wordLength, inputIndex);
Jean Chalard926ef062012-08-10 13:14:45 +0900430 addWord(wordPointer, wordLength, finalProbability, subQueue, Dictionary::KIND_CORRECTION);
Jean Chalardca5ef282011-06-17 15:36:26 +0900431 }
432}
433
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900434int UnigramDictionary::getSubStringSuggestion(
satok7409d152012-01-26 16:13:25 +0900435 ProximityInfo *proximityInfo, const int *xcoordinates, const int *ycoordinates,
satok3c09bb12012-01-26 18:36:19 +0900436 const int *codes, const bool useFullEditDistance, Correction *correction,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900437 WordsPriorityQueuePool *queuePool, const int inputSize,
satok3c09bb12012-01-26 18:36:19 +0900438 const bool hasAutoCorrectionCandidate, const int currentWordIndex,
439 const int inputWordStartPos, const int inputWordLength,
satok99557162012-01-26 22:49:13 +0900440 const int outputWordStartPos, const bool isSpaceProximity, int *freqArray,
Ken Wakasa1e614932012-10-29 18:06:22 +0900441 int *wordLengthArray, int *outputWord, int *outputWordLength) const {
Satoshi Kataoka67e3cc82012-05-31 15:04:58 +0900442 if (inputWordLength > MULTIPLE_WORDS_SUGGESTION_MAX_WORD_LENGTH) {
443 return FLAG_MULTIPLE_SUGGEST_ABORT;
444 }
445
446 /////////////////////////////////////////////
447 // safety net for multiple word suggestion //
448 // TODO: Remove this safety net //
449 /////////////////////////////////////////////
450 int smallWordCount = 0;
451 int singleLetterWordCount = 0;
452 if (inputWordLength == 1) {
453 ++singleLetterWordCount;
454 }
455 if (inputWordLength <= 2) {
456 // small word == single letter or 2-letter word
457 ++smallWordCount;
458 }
459 for (int i = 0; i < currentWordIndex; ++i) {
460 const int length = wordLengthArray[i];
461 if (length == 1) {
462 ++singleLetterWordCount;
463 // Safety net to avoid suggesting sequential single letter words
464 if (i < (currentWordIndex - 1)) {
465 if (wordLengthArray[i + 1] == 1) {
466 return FLAG_MULTIPLE_SUGGEST_ABORT;
467 }
468 } else if (inputWordLength == 1) {
469 return FLAG_MULTIPLE_SUGGEST_ABORT;
470 }
471 }
472 if (length <= 2) {
473 ++smallWordCount;
474 }
475 // Safety net to avoid suggesting multiple words with many (4 or more, for now) small words
476 if (singleLetterWordCount >= 3 || smallWordCount >= 4) {
477 return FLAG_MULTIPLE_SUGGEST_ABORT;
478 }
479 }
480 //////////////////////////////////////////////
481 // TODO: Remove the safety net above //
482 //////////////////////////////////////////////
483
Ken Wakasa1e614932012-10-29 18:06:22 +0900484 int *tempOutputWord = 0;
satok1f6b52e2012-01-30 13:53:58 +0900485 int nextWordLength = 0;
satok99557162012-01-26 22:49:13 +0900486 // TODO: Optimize init suggestion
487 initSuggestions(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900488 inputSize, correction);
satok99557162012-01-26 22:49:13 +0900489
Ken Wakasa1e614932012-10-29 18:06:22 +0900490 int word[MAX_WORD_LENGTH_INTERNAL];
satok3c09bb12012-01-26 18:36:19 +0900491 int freq = getMostFrequentWordLike(
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900492 inputWordStartPos, inputWordLength, correction, word);
satok3c09bb12012-01-26 18:36:19 +0900493 if (freq > 0) {
satok1f6b52e2012-01-30 13:53:58 +0900494 nextWordLength = inputWordLength;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900495 tempOutputWord = word;
satok3c09bb12012-01-26 18:36:19 +0900496 } else if (!hasAutoCorrectionCandidate) {
497 if (inputWordStartPos > 0) {
498 const int offset = inputWordStartPos;
499 initSuggestions(proximityInfo, &xcoordinates[offset], &ycoordinates[offset],
satok9df4a452012-03-23 16:05:18 +0900500 codes + offset, inputWordLength, correction);
satok3c09bb12012-01-26 18:36:19 +0900501 queuePool->clearSubQueue(currentWordIndex);
Jean Chalard4d9b2022012-04-23 19:25:28 +0900502 // TODO: pass the bigram list for substring suggestion
503 getSuggestionCandidates(useFullEditDistance, inputWordLength,
Jean Chalard8950ce62012-05-07 16:28:30 +0900504 0 /* bigramMap */, 0 /* bigramFilter */, correction, queuePool,
505 false /* doAutoCompletion */, MAX_ERRORS_FOR_TWO_WORDS, currentWordIndex);
satok3c09bb12012-01-26 18:36:19 +0900506 if (DEBUG_DICT) {
satok1f6b52e2012-01-30 13:53:58 +0900507 if (currentWordIndex < MULTIPLE_WORDS_SUGGESTION_MAX_WORDS) {
satok3c09bb12012-01-26 18:36:19 +0900508 AKLOGI("Dump word candidates(%d) %d", currentWordIndex, inputWordLength);
509 for (int i = 0; i < SUB_QUEUE_MAX_COUNT; ++i) {
510 queuePool->getSubQueue(currentWordIndex, i)->dumpTopWord();
511 }
512 }
513 }
514 }
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900515 WordsPriorityQueue *queue = queuePool->getSubQueue(currentWordIndex, inputWordLength);
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900516 // TODO: Return the correct value depending on doAutoCompletion
517 if (!queue || queue->size() <= 0) {
518 return FLAG_MULTIPLE_SUGGEST_ABORT;
satok3c09bb12012-01-26 18:36:19 +0900519 }
520 int score = 0;
satok0028ed32012-05-16 20:42:12 +0900521 const float ns = queue->getHighestNormalizedScore(
Satoshi Kataoka4a3db702012-06-08 15:29:44 +0900522 correction->getPrimaryInputWord(), inputWordLength,
satok1f6b52e2012-01-30 13:53:58 +0900523 &tempOutputWord, &score, &nextWordLength);
satok3c09bb12012-01-26 18:36:19 +0900524 if (DEBUG_DICT) {
525 AKLOGI("NS(%d) = %f, Score = %d", currentWordIndex, ns, score);
526 }
527 // Two words correction won't be done if the score of the first word doesn't exceed the
528 // threshold.
529 if (ns < TWO_WORDS_CORRECTION_WITH_OTHER_ERROR_THRESHOLD
satok1f6b52e2012-01-30 13:53:58 +0900530 || nextWordLength < SUB_QUEUE_MIN_WORD_LENGTH) {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900531 return FLAG_MULTIPLE_SUGGEST_SKIP;
satok3c09bb12012-01-26 18:36:19 +0900532 }
satok1f6b52e2012-01-30 13:53:58 +0900533 freq = score >> (nextWordLength + TWO_WORDS_PLUS_OTHER_ERROR_CORRECTION_DEMOTION_DIVIDER);
satok3c09bb12012-01-26 18:36:19 +0900534 }
535 if (DEBUG_DICT) {
Jean Chalard18ebba32012-09-06 20:37:55 +0900536 AKLOGI("Freq(%d): %d, length: %d, input length: %d, input start: %d (%d)",
537 currentWordIndex, freq, nextWordLength, inputWordLength, inputWordStartPos,
538 (currentWordIndex > 0) ? wordLengthArray[0] : 0);
satok3c09bb12012-01-26 18:36:19 +0900539 }
satok1f6b52e2012-01-30 13:53:58 +0900540 if (freq <= 0 || nextWordLength <= 0
541 || MAX_WORD_LENGTH <= (outputWordStartPos + nextWordLength)) {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900542 return FLAG_MULTIPLE_SUGGEST_SKIP;
satok3c09bb12012-01-26 18:36:19 +0900543 }
satok1f6b52e2012-01-30 13:53:58 +0900544 for (int i = 0; i < nextWordLength; ++i) {
satok3c09bb12012-01-26 18:36:19 +0900545 outputWord[outputWordStartPos + i] = tempOutputWord[i];
546 }
satok99557162012-01-26 22:49:13 +0900547
548 // Put output values
satok1f6b52e2012-01-30 13:53:58 +0900549 freqArray[currentWordIndex] = freq;
satok99557162012-01-26 22:49:13 +0900550 // TODO: put output length instead of input length
satok1f6b52e2012-01-30 13:53:58 +0900551 wordLengthArray[currentWordIndex] = inputWordLength;
552 const int tempOutputWordLength = outputWordStartPos + nextWordLength;
553 if (outputWordLength) {
554 *outputWordLength = tempOutputWordLength;
555 }
satok99557162012-01-26 22:49:13 +0900556
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900557 if ((inputWordStartPos + inputWordLength) < inputSize) {
satok1f6b52e2012-01-30 13:53:58 +0900558 if (outputWordStartPos + nextWordLength >= MAX_WORD_LENGTH) {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900559 return FLAG_MULTIPLE_SUGGEST_SKIP;
satok3c09bb12012-01-26 18:36:19 +0900560 }
Ken Wakasab02ee3d2012-10-08 11:46:14 +0900561 outputWord[tempOutputWordLength] = KEYCODE_SPACE;
satok1f6b52e2012-01-30 13:53:58 +0900562 if (outputWordLength) {
563 ++*outputWordLength;
564 }
565 } else if (currentWordIndex >= 1) {
satok99557162012-01-26 22:49:13 +0900566 // TODO: Handle 3 or more words
satoka85f4922012-01-30 18:18:30 +0900567 const int pairFreq = correction->getFreqForSplitMultipleWords(
568 freqArray, wordLengthArray, currentWordIndex + 1, isSpaceProximity, outputWord);
satok99557162012-01-26 22:49:13 +0900569 if (DEBUG_DICT) {
satoka85f4922012-01-30 18:18:30 +0900570 DUMP_WORD(outputWord, tempOutputWordLength);
satoka0ac31f2012-05-23 19:55:27 +0900571 for (int i = 0; i < currentWordIndex + 1; ++i) {
572 AKLOGI("Split %d,%d words: freq = %d, length = %d", i, currentWordIndex + 1,
573 freqArray[i], wordLengthArray[i]);
574 }
575 AKLOGI("Split two words: freq = %d, length = %d, %d, isSpace ? %d", pairFreq,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900576 inputSize, tempOutputWordLength, isSpaceProximity);
satok99557162012-01-26 22:49:13 +0900577 }
Jean Chalard926ef062012-08-10 13:14:45 +0900578 addWord(outputWord, tempOutputWordLength, pairFreq, queuePool->getMasterQueue(),
579 Dictionary::KIND_CORRECTION);
satok3c09bb12012-01-26 18:36:19 +0900580 }
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900581 return FLAG_MULTIPLE_SUGGEST_CONTINUE;
satok7409d152012-01-26 16:13:25 +0900582}
583
satok1f6b52e2012-01-30 13:53:58 +0900584void UnigramDictionary::getMultiWordsSuggestionRec(ProximityInfo *proximityInfo,
585 const int *xcoordinates, const int *ycoordinates, const int *codes,
Ken Wakasaf2789812012-09-04 12:49:46 +0900586 const bool useFullEditDistance, const int inputSize, Correction *correction,
587 WordsPriorityQueuePool *queuePool, const bool hasAutoCorrectionCandidate,
588 const int startInputPos, const int startWordIndex, const int outputWordLength,
Ken Wakasa1e614932012-10-29 18:06:22 +0900589 int *freqArray, int *wordLengthArray, int *outputWord) const {
satok1f6b52e2012-01-30 13:53:58 +0900590 if (startWordIndex >= (MULTIPLE_WORDS_SUGGESTION_MAX_WORDS - 1)) {
591 // Return if the last word index
592 return;
593 }
satoka85f4922012-01-30 18:18:30 +0900594 if (startWordIndex >= 1
595 && (hasAutoCorrectionCandidate
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900596 || inputSize < MIN_INPUT_LENGTH_FOR_THREE_OR_MORE_WORDS_CORRECTION)) {
satoka85f4922012-01-30 18:18:30 +0900597 // Do not suggest 3+ words if already has auto correction candidate
598 return;
599 }
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900600 for (int i = startInputPos + 1; i < inputSize; ++i) {
satok1f6b52e2012-01-30 13:53:58 +0900601 if (DEBUG_CORRECTION_FREQ) {
satoka85f4922012-01-30 18:18:30 +0900602 AKLOGI("Multi words(%d), start in %d sep %d start out %d",
603 startWordIndex, startInputPos, i, outputWordLength);
604 DUMP_WORD(outputWord, outputWordLength);
satok1f6b52e2012-01-30 13:53:58 +0900605 }
satoka85f4922012-01-30 18:18:30 +0900606 int tempOutputWordLength = 0;
607 // Current word
608 int inputWordStartPos = startInputPos;
609 int inputWordLength = i - startInputPos;
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900610 const int suggestionFlag = getSubStringSuggestion(proximityInfo, xcoordinates, ycoordinates,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900611 codes, useFullEditDistance, correction, queuePool, inputSize,
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900612 hasAutoCorrectionCandidate, startWordIndex, inputWordStartPos, inputWordLength,
613 outputWordLength, true /* not used */, freqArray, wordLengthArray, outputWord,
614 &tempOutputWordLength);
615 if (suggestionFlag == FLAG_MULTIPLE_SUGGEST_ABORT) {
616 // TODO: break here
617 continue;
618 } else if (suggestionFlag == FLAG_MULTIPLE_SUGGEST_SKIP) {
satok1f6b52e2012-01-30 13:53:58 +0900619 continue;
620 }
621
satoka85f4922012-01-30 18:18:30 +0900622 if (DEBUG_CORRECTION_FREQ) {
623 AKLOGI("Do missing space correction");
624 }
625 // Next word
satok1f6b52e2012-01-30 13:53:58 +0900626 // Missing space
627 inputWordStartPos = i;
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900628 inputWordLength = inputSize - i;
Ken Wakasaf2789812012-09-04 12:49:46 +0900629 if (getSubStringSuggestion(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900630 useFullEditDistance, correction, queuePool, inputSize, hasAutoCorrectionCandidate,
satoka85f4922012-01-30 18:18:30 +0900631 startWordIndex + 1, inputWordStartPos, inputWordLength, tempOutputWordLength,
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900632 false /* missing space */, freqArray, wordLengthArray, outputWord, 0)
633 != FLAG_MULTIPLE_SUGGEST_CONTINUE) {
satoka85f4922012-01-30 18:18:30 +0900634 getMultiWordsSuggestionRec(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900635 useFullEditDistance, inputSize, correction, queuePool,
satoka85f4922012-01-30 18:18:30 +0900636 hasAutoCorrectionCandidate, inputWordStartPos, startWordIndex + 1,
637 tempOutputWordLength, freqArray, wordLengthArray, outputWord);
638 }
satok1f6b52e2012-01-30 13:53:58 +0900639
640 // Mistyped space
641 ++inputWordStartPos;
642 --inputWordLength;
643
644 if (inputWordLength <= 0) {
645 continue;
646 }
647
648 const int x = xcoordinates[inputWordStartPos - 1];
649 const int y = ycoordinates[inputWordStartPos - 1];
650 if (!proximityInfo->hasSpaceProximity(x, y)) {
651 continue;
652 }
653
satoka85f4922012-01-30 18:18:30 +0900654 if (DEBUG_CORRECTION_FREQ) {
655 AKLOGI("Do mistyped space correction");
656 }
satok1f6b52e2012-01-30 13:53:58 +0900657 getSubStringSuggestion(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900658 useFullEditDistance, correction, queuePool, inputSize, hasAutoCorrectionCandidate,
satoka85f4922012-01-30 18:18:30 +0900659 startWordIndex + 1, inputWordStartPos, inputWordLength, tempOutputWordLength,
660 true /* mistyped space */, freqArray, wordLengthArray, outputWord, 0);
satok1f6b52e2012-01-30 13:53:58 +0900661 }
662}
663
satoka85f4922012-01-30 18:18:30 +0900664void UnigramDictionary::getSplitMultipleWordsSuggestions(ProximityInfo *proximityInfo,
satok744dab62011-12-15 22:29:05 +0900665 const int *xcoordinates, const int *ycoordinates, const int *codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900666 const bool useFullEditDistance, const int inputSize,
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900667 Correction *correction, WordsPriorityQueuePool *queuePool,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900668 const bool hasAutoCorrectionCandidate) const {
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900669 if (inputSize >= MAX_WORD_LENGTH) return;
satok612c6e42011-08-01 19:35:27 +0900670 if (DEBUG_DICT) {
satok1f6b52e2012-01-30 13:53:58 +0900671 AKLOGI("--- Suggest multiple words");
672 }
satok54af64a2012-01-17 15:58:23 +0900673
satokbd6ccdd2012-01-23 12:30:20 +0900674 // Allocating fixed length array on stack
Ken Wakasa1e614932012-10-29 18:06:22 +0900675 int outputWord[MAX_WORD_LENGTH];
satok1f6b52e2012-01-30 13:53:58 +0900676 int freqArray[MULTIPLE_WORDS_SUGGESTION_MAX_WORDS];
677 int wordLengthArray[MULTIPLE_WORDS_SUGGESTION_MAX_WORDS];
678 const int outputWordLength = 0;
679 const int startInputPos = 0;
680 const int startWordIndex = 0;
681 getMultiWordsSuggestionRec(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900682 useFullEditDistance, inputSize, correction, queuePool, hasAutoCorrectionCandidate,
satok1f6b52e2012-01-30 13:53:58 +0900683 startInputPos, startWordIndex, outputWordLength, freqArray, wordLengthArray,
684 outputWord);
Jean Chalarde6715e32011-06-30 19:47:25 +0900685}
686
Jean Chalard1059f272011-06-28 20:45:05 +0900687// Wrapper for getMostFrequentWordLikeInner, which matches it to the previous
688// interface.
Ken Wakasa2c2f3a92012-11-02 18:29:03 +0900689int UnigramDictionary::getMostFrequentWordLike(const int startInputIndex, const int inputSize,
690 Correction *correction, int *word) const {
Ken Wakasa1e614932012-10-29 18:06:22 +0900691 int inWord[inputSize];
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900692 for (int i = 0; i < inputSize; ++i) {
Ken Wakasa1e614932012-10-29 18:06:22 +0900693 inWord[i] = correction->getPrimaryCodePointAt(startInputIndex + i);
Jean Chalard1059f272011-06-28 20:45:05 +0900694 }
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900695 return getMostFrequentWordLikeInner(inWord, inputSize, word);
Jean Chalard1059f272011-06-28 20:45:05 +0900696}
697
698// This function will take the position of a character array within a CharGroup,
699// and check it actually like-matches the word in inWord starting at startInputIndex,
700// that is, it matches it with case and accents squashed.
701// The function returns true if there was a full match, false otherwise.
702// The function will copy on-the-fly the characters in the CharGroup to outNewWord.
703// It will also place the end position of the array in outPos; in outInputIndex,
704// it will place the index of the first char AFTER the match if there was a match,
705// and the initial position if there was not. It makes sense because if there was
706// a match we want to continue searching, but if there was not, we want to go to
707// the next CharGroup.
708// In and out parameters may point to the same location. This function takes care
709// not to use any input parameters after it wrote into its outputs.
710static inline bool testCharGroupForContinuedLikeness(const uint8_t flags,
Ken Wakasa1e614932012-10-29 18:06:22 +0900711 const uint8_t *const root, const int startPos, const int *const inWord,
712 const int startInputIndex, const int inputSize, int *outNewWord, int *outInputIndex,
Ken Wakasaf2789812012-09-04 12:49:46 +0900713 int *outPos) {
Jean Chalard19560502012-07-31 23:45:32 +0900714 const bool hasMultipleChars = (0 != (BinaryFormat::FLAG_HAS_MULTIPLE_CHARS & flags));
Jean Chalard1059f272011-06-28 20:45:05 +0900715 int pos = startPos;
Ken Wakasa1e614932012-10-29 18:06:22 +0900716 int codePoint = BinaryFormat::getCodePointAndForwardPointer(root, &pos);
717 int baseChar = toBaseLowerCase(codePoint);
718 const int wChar = toBaseLowerCase(inWord[startInputIndex]);
Jean Chalard1059f272011-06-28 20:45:05 +0900719
720 if (baseChar != wChar) {
721 *outPos = hasMultipleChars ? BinaryFormat::skipOtherCharacters(root, pos) : pos;
722 *outInputIndex = startInputIndex;
723 return false;
724 }
725 int inputIndex = startInputIndex;
Ken Wakasaf2789812012-09-04 12:49:46 +0900726 outNewWord[inputIndex] = codePoint;
Jean Chalard1059f272011-06-28 20:45:05 +0900727 if (hasMultipleChars) {
Ken Wakasaf2789812012-09-04 12:49:46 +0900728 codePoint = BinaryFormat::getCodePointAndForwardPointer(root, &pos);
729 while (NOT_A_CODE_POINT != codePoint) {
730 baseChar = toBaseLowerCase(codePoint);
731 if (inputIndex + 1 >= inputSize || toBaseLowerCase(inWord[++inputIndex]) != baseChar) {
Jean Chalard1059f272011-06-28 20:45:05 +0900732 *outPos = BinaryFormat::skipOtherCharacters(root, pos);
733 *outInputIndex = startInputIndex;
734 return false;
735 }
Ken Wakasaf2789812012-09-04 12:49:46 +0900736 outNewWord[inputIndex] = codePoint;
737 codePoint = BinaryFormat::getCodePointAndForwardPointer(root, &pos);
Jean Chalard1059f272011-06-28 20:45:05 +0900738 }
739 }
740 *outInputIndex = inputIndex + 1;
741 *outPos = pos;
742 return true;
743}
744
745// This function is invoked when a word like the word searched for is found.
746// It will compare the frequency to the max frequency, and if greater, will
747// copy the word into the output buffer. In output value maxFreq, it will
748// write the new maximum frequency if it changed.
Ken Wakasa1e614932012-10-29 18:06:22 +0900749static inline void onTerminalWordLike(const int freq, int *newWord, const int length, int *outWord,
750 int *maxFreq) {
Jean Chalard1059f272011-06-28 20:45:05 +0900751 if (freq > *maxFreq) {
Ken Wakasaf2789812012-09-04 12:49:46 +0900752 for (int q = 0; q < length; ++q) {
Jean Chalard1059f272011-06-28 20:45:05 +0900753 outWord[q] = newWord[q];
Ken Wakasaf2789812012-09-04 12:49:46 +0900754 }
Jean Chalard1059f272011-06-28 20:45:05 +0900755 outWord[length] = 0;
756 *maxFreq = freq;
757 }
758}
759
760// Will find the highest frequency of the words like the one passed as an argument,
761// that is, everything that only differs by case/accents.
Ken Wakasa1e614932012-10-29 18:06:22 +0900762int UnigramDictionary::getMostFrequentWordLikeInner(const int *const inWord, const int inputSize,
763 int *outWord) const {
764 int newWord[MAX_WORD_LENGTH_INTERNAL];
Jean Chalard1059f272011-06-28 20:45:05 +0900765 int depth = 0;
766 int maxFreq = -1;
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900767 const uint8_t *const root = DICT_ROOT;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900768 int stackChildCount[MAX_WORD_LENGTH_INTERNAL];
769 int stackInputIndex[MAX_WORD_LENGTH_INTERNAL];
770 int stackSiblingPos[MAX_WORD_LENGTH_INTERNAL];
Jean Chalard1059f272011-06-28 20:45:05 +0900771
Jean Chalard4c0eca62012-01-16 15:15:53 +0900772 int startPos = 0;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900773 stackChildCount[0] = BinaryFormat::getGroupCountAndForwardPointer(root, &startPos);
774 stackInputIndex[0] = 0;
775 stackSiblingPos[0] = startPos;
Jean Chalard1059f272011-06-28 20:45:05 +0900776 while (depth >= 0) {
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900777 const int charGroupCount = stackChildCount[depth];
778 int pos = stackSiblingPos[depth];
Jean Chalard1059f272011-06-28 20:45:05 +0900779 for (int charGroupIndex = charGroupCount - 1; charGroupIndex >= 0; --charGroupIndex) {
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900780 int inputIndex = stackInputIndex[depth];
Jean Chalard1059f272011-06-28 20:45:05 +0900781 const uint8_t flags = BinaryFormat::getFlagsAndForwardPointer(root, &pos);
782 // Test whether all chars in this group match with the word we are searching for. If so,
Ken Wakasaf2789812012-09-04 12:49:46 +0900783 // we want to traverse its children (or if the inputSize match, evaluate its frequency).
Jean Chalard1059f272011-06-28 20:45:05 +0900784 // Note that this function will output the position regardless, but will only write
785 // into inputIndex if there is a match.
786 const bool isAlike = testCharGroupForContinuedLikeness(flags, root, pos, inWord,
Ken Wakasaf2789812012-09-04 12:49:46 +0900787 inputIndex, inputSize, newWord, &inputIndex, &pos);
Jean Chalardd03e0652012-10-18 07:28:18 +0900788 if (isAlike && (!(BinaryFormat::FLAG_IS_NOT_A_WORD & flags))
789 && (BinaryFormat::FLAG_IS_TERMINAL & flags) && (inputIndex == inputSize)) {
Jean Chalard1059f272011-06-28 20:45:05 +0900790 const int frequency = BinaryFormat::readFrequencyWithoutMovingPointer(root, pos);
791 onTerminalWordLike(frequency, newWord, inputIndex, outWord, &maxFreq);
792 }
793 pos = BinaryFormat::skipFrequency(flags, pos);
794 const int siblingPos = BinaryFormat::skipChildrenPosAndAttributes(root, flags, pos);
795 const int childrenNodePos = BinaryFormat::readChildrenPosition(root, flags, pos);
796 // If we had a match and the word has children, we want to traverse them. We don't have
797 // to traverse words longer than the one we are searching for, since they will not match
Ken Wakasaf2789812012-09-04 12:49:46 +0900798 // anyway, so don't traverse unless inputIndex < inputSize.
799 if (isAlike && (-1 != childrenNodePos) && (inputIndex < inputSize)) {
Jean Chalard1059f272011-06-28 20:45:05 +0900800 // Save position for this depth, to get back to this once children are done
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900801 stackChildCount[depth] = charGroupIndex;
802 stackSiblingPos[depth] = siblingPos;
Jean Chalard1059f272011-06-28 20:45:05 +0900803 // Prepare stack values for next depth
804 ++depth;
805 int childrenPos = childrenNodePos;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900806 stackChildCount[depth] =
Jean Chalard1059f272011-06-28 20:45:05 +0900807 BinaryFormat::getGroupCountAndForwardPointer(root, &childrenPos);
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900808 stackSiblingPos[depth] = childrenPos;
809 stackInputIndex[depth] = inputIndex;
Jean Chalard1059f272011-06-28 20:45:05 +0900810 pos = childrenPos;
811 // Go to the next depth level.
812 ++depth;
813 break;
814 } else {
815 // No match, or no children, or word too long to ever match: go the next sibling.
816 pos = siblingPos;
817 }
818 }
819 --depth;
820 }
821 return maxFreq;
822}
823
Ken Wakasa1e614932012-10-29 18:06:22 +0900824int UnigramDictionary::getFrequency(const int *const inWord, const int length) const {
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900825 const uint8_t *const root = DICT_ROOT;
Jean Chalarde9a86e22012-06-28 21:01:29 +0900826 int pos = BinaryFormat::getTerminalPosition(root, inWord, length,
827 false /* forceLowerCaseSearch */);
Satoshi Kataoka2f854e12012-05-29 15:58:13 +0900828 if (NOT_VALID_WORD == pos) {
829 return NOT_A_PROBABILITY;
830 }
831 const uint8_t flags = BinaryFormat::getFlagsAndForwardPointer(root, &pos);
Jean Chalard72b1c932012-08-31 15:24:39 +0900832 if (flags & (BinaryFormat::FLAG_IS_BLACKLISTED | BinaryFormat::FLAG_IS_NOT_A_WORD)) {
833 // If this is not a word, or if it's a blacklisted entry, it should behave as
834 // having no frequency outside of the suggestion process (where it should be used
835 // for shortcuts).
836 return NOT_A_PROBABILITY;
837 }
Jean Chalard19560502012-07-31 23:45:32 +0900838 const bool hasMultipleChars = (0 != (BinaryFormat::FLAG_HAS_MULTIPLE_CHARS & flags));
Satoshi Kataoka2f854e12012-05-29 15:58:13 +0900839 if (hasMultipleChars) {
840 pos = BinaryFormat::skipOtherCharacters(root, pos);
841 } else {
Ken Wakasaf2789812012-09-04 12:49:46 +0900842 BinaryFormat::getCodePointAndForwardPointer(DICT_ROOT, &pos);
Satoshi Kataoka2f854e12012-05-29 15:58:13 +0900843 }
844 const int unigramFreq = BinaryFormat::readFrequencyWithoutMovingPointer(root, pos);
845 return unigramFreq;
Jean Chalard1059f272011-06-28 20:45:05 +0900846}
847
848// TODO: remove this function.
Ken Wakasa1e614932012-10-29 18:06:22 +0900849int UnigramDictionary::getBigramPosition(int pos, int *word, int offset, int length) const {
Jean Chalard1059f272011-06-28 20:45:05 +0900850 return -1;
851}
852
853// ProcessCurrentNode returns a boolean telling whether to traverse children nodes or not.
854// If the return value is false, then the caller should read in the output "nextSiblingPosition"
855// to find out the address of the next sibling node and pass it to a new call of processCurrentNode.
856// It is worthy to note that when false is returned, the output values other than
857// nextSiblingPosition are undefined.
858// If the return value is true, then the caller must proceed to traverse the children of this
859// node. processCurrentNode will output the information about the children: their count in
860// newCount, their position in newChildrenPosition, the traverseAllNodes flag in
861// newTraverseAllNodes, the match weight into newMatchRate, the input index into newInputIndex, the
862// diffs into newDiffs, the sibling position in nextSiblingPosition, and the output index into
863// newOutputIndex. Please also note the following caveat: processCurrentNode does not know when
864// there aren't any more nodes at this level, it merely returns the address of the first byte after
865// the current node in nextSiblingPosition. Thus, the caller must keep count of the nodes at any
866// given level, as output into newCount when traversing this level's parent.
Ken Wakasa2c2f3a92012-11-02 18:29:03 +0900867bool UnigramDictionary::processCurrentNode(const int initialPos,
Jean Chalard8950ce62012-05-07 16:28:30 +0900868 const std::map<int, int> *bigramMap, const uint8_t *bigramFilter, Correction *correction,
869 int *newCount, int *newChildrenPosition, int *nextSiblingPosition,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900870 WordsPriorityQueuePool *queuePool, const int currentWordIndex) const {
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900871 if (DEBUG_DICT) {
satokcfca3c62011-08-10 14:30:10 +0900872 correction->checkState();
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900873 }
Jean Chalard0584f022011-06-30 19:23:16 +0900874 int pos = initialPos;
Jean Chalard0584f022011-06-30 19:23:16 +0900875
Jean Chalard1059f272011-06-28 20:45:05 +0900876 // Flags contain the following information:
877 // - Address type (MASK_GROUP_ADDRESS_TYPE) on two bits:
878 // - FLAG_GROUP_ADDRESS_TYPE_{ONE,TWO,THREE}_BYTES means there are children and their address
879 // is on the specified number of bytes.
880 // - FLAG_GROUP_ADDRESS_TYPE_NOADDRESS means there are no children, and therefore no address.
881 // - FLAG_HAS_MULTIPLE_CHARS: whether this node has multiple char or not.
882 // - FLAG_IS_TERMINAL: whether this node is a terminal or not (it may still have children)
883 // - FLAG_HAS_BIGRAMS: whether this node has bigrams or not
884 const uint8_t flags = BinaryFormat::getFlagsAndForwardPointer(DICT_ROOT, &pos);
Jean Chalard19560502012-07-31 23:45:32 +0900885 const bool hasMultipleChars = (0 != (BinaryFormat::FLAG_HAS_MULTIPLE_CHARS & flags));
886 const bool isTerminalNode = (0 != (BinaryFormat::FLAG_IS_TERMINAL & flags));
satok8876b752011-08-04 18:31:57 +0900887
888 bool needsToInvokeOnTerminal = false;
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900889
Jean Chalard1059f272011-06-28 20:45:05 +0900890 // This gets only ONE character from the stream. Next there will be:
891 // if FLAG_HAS_MULTIPLE CHARS: the other characters of the same node
892 // else if FLAG_IS_TERMINAL: the frequency
893 // else if MASK_GROUP_ADDRESS_TYPE is not NONE: the children address
894 // Note that you can't have a node that both is not a terminal and has no children.
Ken Wakasa1e614932012-10-29 18:06:22 +0900895 int c = BinaryFormat::getCodePointAndForwardPointer(DICT_ROOT, &pos);
Ken Wakasaccebd5c2013-01-09 15:21:44 +0900896 ASSERT(NOT_A_CODE_POINT != c);
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900897
Jean Chalard1059f272011-06-28 20:45:05 +0900898 // We are going to loop through each character and make it look like it's a different
899 // node each time. To do that, we will process characters in this node in order until
Ken Wakasaf2789812012-09-04 12:49:46 +0900900 // we find the character terminator. This is signalled by getCodePoint* returning
901 // NOT_A_CODE_POINT.
Jean Chalard1059f272011-06-28 20:45:05 +0900902 // As a special case, if there is only one character in this node, we must not read the
Ken Wakasaf2789812012-09-04 12:49:46 +0900903 // next bytes so we will simulate the NOT_A_CODE_POINT return by testing the flags.
Jean Chalard1059f272011-06-28 20:45:05 +0900904 // This way, each loop run will look like a "virtual node".
905 do {
906 // We prefetch the next char. If 'c' is the last char of this node, we will have
Ken Wakasaf2789812012-09-04 12:49:46 +0900907 // NOT_A_CODE_POINT in the next char. From this we can decide whether this virtual node
Jean Chalard1059f272011-06-28 20:45:05 +0900908 // should behave as a terminal or not and whether we have children.
Ken Wakasa1e614932012-10-29 18:06:22 +0900909 const int nextc = hasMultipleChars
Ken Wakasaf2789812012-09-04 12:49:46 +0900910 ? BinaryFormat::getCodePointAndForwardPointer(DICT_ROOT, &pos) : NOT_A_CODE_POINT;
911 const bool isLastChar = (NOT_A_CODE_POINT == nextc);
Jean Chalard1059f272011-06-28 20:45:05 +0900912 // If there are more chars in this nodes, then this virtual node is not a terminal.
913 // If we are on the last char, this virtual node is a terminal if this node is.
satok8876b752011-08-04 18:31:57 +0900914 const bool isTerminal = isLastChar && isTerminalNode;
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900915
satokcfca3c62011-08-10 14:30:10 +0900916 Correction::CorrectionType stateType = correction->processCharAndCalcState(
satok8876b752011-08-04 18:31:57 +0900917 c, isTerminal);
satokcfca3c62011-08-10 14:30:10 +0900918 if (stateType == Correction::TRAVERSE_ALL_ON_TERMINAL
919 || stateType == Correction::ON_TERMINAL) {
satok8876b752011-08-04 18:31:57 +0900920 needsToInvokeOnTerminal = true;
satokd03317c2011-12-14 21:38:11 +0900921 } else if (stateType == Correction::UNRELATED || correction->needsToPrune()) {
satok8876b752011-08-04 18:31:57 +0900922 // We found that this is an unrelated character, so we should give up traversing
923 // this node and its children entirely.
924 // However we may not be on the last virtual node yet so we skip the remaining
925 // characters in this node, the frequency if it's there, read the next sibling
926 // position to output it, then return false.
927 // We don't have to output other values because we return false, as in
928 // "don't traverse children".
Jean Chalard1059f272011-06-28 20:45:05 +0900929 if (!isLastChar) {
930 pos = BinaryFormat::skipOtherCharacters(DICT_ROOT, pos);
931 }
932 pos = BinaryFormat::skipFrequency(flags, pos);
933 *nextSiblingPosition =
934 BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
935 return false;
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900936 }
937
Jean Chalard1059f272011-06-28 20:45:05 +0900938 // Prepare for the next character. Promote the prefetched char to current char - the loop
939 // will take care of prefetching the next. If we finally found our last char, nextc will
Ken Wakasaf2789812012-09-04 12:49:46 +0900940 // contain NOT_A_CODE_POINT.
Jean Chalard1059f272011-06-28 20:45:05 +0900941 c = nextc;
Ken Wakasaf2789812012-09-04 12:49:46 +0900942 } while (NOT_A_CODE_POINT != c);
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900943
satok8876b752011-08-04 18:31:57 +0900944 if (isTerminalNode) {
satok6ad15fc2012-01-16 16:21:21 +0900945 // The frequency should be here, because we come here only if this is actually
946 // a terminal node, and we are on its last char.
Jean Chalard171d1802012-04-23 18:51:00 +0900947 const int unigramFreq = BinaryFormat::readFrequencyWithoutMovingPointer(DICT_ROOT, pos);
satok6ad15fc2012-01-16 16:21:21 +0900948 const int childrenAddressPos = BinaryFormat::skipFrequency(flags, pos);
949 const int attributesPos = BinaryFormat::skipChildrenPosition(flags, childrenAddressPos);
950 TerminalAttributes terminalAttributes(DICT_ROOT, flags, attributesPos);
Jean Chalard8950ce62012-05-07 16:28:30 +0900951 // bigramMap contains the bigram frequencies indexed by addresses for fast lookup.
952 // bigramFilter is a bloom filter of said frequencies for even faster rejection.
Jean Chalard49ba1352012-05-07 20:14:00 +0900953 const int probability = BinaryFormat::getProbability(initialPos, bigramMap, bigramFilter,
954 unigramFreq);
Jean Chalard171d1802012-04-23 18:51:00 +0900955 onTerminal(probability, terminalAttributes, correction, queuePool, needsToInvokeOnTerminal,
satok8330b482012-01-23 16:52:37 +0900956 currentWordIndex);
Jean Chalard1059f272011-06-28 20:45:05 +0900957
satok8876b752011-08-04 18:31:57 +0900958 // If there are more chars in this node, then this virtual node has children.
959 // If we are on the last char, this virtual node has children if this node has.
960 const bool hasChildren = BinaryFormat::hasChildrenInFlags(flags);
961
962 // This character matched the typed character (enough to traverse the node at least)
963 // so we just evaluated it. Now we should evaluate this virtual node's children - that
964 // is, if it has any. If it has no children, we're done here - so we skip the end of
965 // the node, output the siblings position, and return false "don't traverse children".
966 // Note that !hasChildren implies isLastChar, so we know we don't have to skip any
967 // remaining char in this group for there can't be any.
968 if (!hasChildren) {
969 pos = BinaryFormat::skipFrequency(flags, pos);
970 *nextSiblingPosition =
971 BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
972 return false;
973 }
974
975 // Optimization: Prune out words that are too long compared to how much was typed.
satokcfca3c62011-08-10 14:30:10 +0900976 if (correction->needsToPrune()) {
satok8876b752011-08-04 18:31:57 +0900977 pos = BinaryFormat::skipFrequency(flags, pos);
978 *nextSiblingPosition =
979 BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
satok10266c02011-08-19 22:05:59 +0900980 if (DEBUG_DICT_FULL) {
satok9fb6f472012-01-13 18:01:22 +0900981 AKLOGI("Traversing was pruned.");
satok10266c02011-08-19 22:05:59 +0900982 }
satok8876b752011-08-04 18:31:57 +0900983 return false;
984 }
985 }
Jean Chalard1059f272011-06-28 20:45:05 +0900986
987 // Now we finished processing this node, and we want to traverse children. If there are no
988 // children, we can't come here.
Ken Wakasaccebd5c2013-01-09 15:21:44 +0900989 ASSERT(BinaryFormat::hasChildrenInFlags(flags));
Jean Chalard1059f272011-06-28 20:45:05 +0900990
991 // If this node was a terminal it still has the frequency under the pointer (it may have been
992 // read, but not skipped - see readFrequencyWithoutMovingPointer).
993 // Next come the children position, then possibly attributes (attributes are bigrams only for
994 // now, maybe something related to shortcuts in the future).
995 // Once this is read, we still need to output the number of nodes in the immediate children of
996 // this node, so we read and output it before returning true, as in "please traverse children".
997 pos = BinaryFormat::skipFrequency(flags, pos);
998 int childrenPos = BinaryFormat::readChildrenPosition(DICT_ROOT, flags, pos);
999 *nextSiblingPosition = BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
1000 *newCount = BinaryFormat::getGroupCountAndForwardPointer(DICT_ROOT, &childrenPos);
1001 *newChildrenPosition = childrenPos;
1002 return true;
Jean Chalard85a1d1e2011-06-21 22:23:21 +09001003}
satok30088252010-12-01 21:22:15 +09001004} // namespace latinime