blob: 6cde06bfa3d71009bceb47ee8d96f18a7ad20191 [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 <cassert>
18#include <cstring>
satok30088252010-12-01 21:22:15 +090019
satoke808e432010-12-02 14:53:24 +090020#define LOG_TAG "LatinIME: unigram_dictionary.cpp"
satok30088252010-12-01 21:22:15 +090021
Ken Wakasa77e8e812012-08-02 19:48:08 +090022#include "binary_format.h"
satok30088252010-12-01 21:22:15 +090023#include "char_utils.h"
Ken Wakasa3b088a22012-05-16 23:05:32 +090024#include "defines.h"
satoke808e432010-12-02 14:53:24 +090025#include "dictionary.h"
Ken Wakasa77e8e812012-08-02 19:48:08 +090026#include "proximity_info.h"
Jean Chalardcf9dbbd2011-12-26 15:16:59 +090027#include "terminal_attributes.h"
Ken Wakasa77e8e812012-08-02 19:48:08 +090028#include "unigram_dictionary.h"
29#include "words_priority_queue.h"
30#include "words_priority_queue_pool.h"
Jean Chalard1059f272011-06-28 20:45:05 +090031
satok30088252010-12-01 21:22:15 +090032namespace latinime {
33
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090034const UnigramDictionary::digraph_t UnigramDictionary::GERMAN_UMLAUT_DIGRAPHS[] =
Jean Chalardd3043382012-03-21 18:38:25 +090035 { { 'a', 'e', 0x00E4 }, // U+00E4 : LATIN SMALL LETTER A WITH DIAERESIS
36 { 'o', 'e', 0x00F6 }, // U+00F6 : LATIN SMALL LETTER O WITH DIAERESIS
37 { 'u', 'e', 0x00FC } }; // U+00FC : LATIN SMALL LETTER U WITH DIAERESIS
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090038
Jean Chalardcc78d032012-03-23 16:48:49 +090039const UnigramDictionary::digraph_t UnigramDictionary::FRENCH_LIGATURES_DIGRAPHS[] =
40 { { 'a', 'e', 0x00E6 }, // U+00E6 : LATIN SMALL LETTER AE
41 { 'o', 'e', 0x0153 } }; // U+0153 : LATIN SMALL LIGATURE OE
42
Jean Chalard293ece02011-06-16 20:55:16 +090043// TODO: check the header
Ken Wakasab02ee3d2012-10-08 11:46:14 +090044UnigramDictionary::UnigramDictionary(const uint8_t *const streamStart, int fullWordMultiplier,
45 int maxWordLength, int maxWords, const unsigned int flags)
46 : DICT_ROOT(streamStart), MAX_WORD_LENGTH(maxWordLength), MAX_WORDS(maxWords),
47 FULL_WORD_MULTIPLIER(fullWordMultiplier), // TODO : remove this variable.
Ken Wakasa44d9c1e2012-11-01 17:05:08 +090048 ROOT_POS(0), MAX_DIGRAPH_SEARCH_DEPTH(DEFAULT_MAX_DIGRAPH_SEARCH_DEPTH), FLAGS(flags) {
Ken Wakasade3070a2011-03-19 09:16:42 +090049 if (DEBUG_DICT) {
satok9fb6f472012-01-13 18:01:22 +090050 AKLOGI("UnigramDictionary - constructor");
Ken Wakasade3070a2011-03-19 09:16:42 +090051 }
satok30088252010-12-01 21:22:15 +090052}
53
satok2df30602011-07-15 13:49:00 +090054UnigramDictionary::~UnigramDictionary() {
satok2df30602011-07-15 13:49:00 +090055}
satok30088252010-12-01 21:22:15 +090056
Ken Wakasa1e614932012-10-29 18:06:22 +090057static inline int getCodesBufferSize(const int *codes, const int codesSize) {
58 return sizeof(*codes) * codesSize;
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090059}
60
Ken Wakasa1e614932012-10-29 18:06:22 +090061// TODO: This needs to take a const int* and not tinker with its contents
62static inline void addWord(int *word, int length, int frequency, WordsPriorityQueue *queue,
63 int type) {
Jean Chalard926ef062012-08-10 13:14:45 +090064 queue->push(frequency, word, length, type);
satok1147c7b2011-12-14 15:04:58 +090065}
66
Jean Chalardd3043382012-03-21 18:38:25 +090067// Return the replacement code point for a digraph, or 0 if none.
68int UnigramDictionary::getDigraphReplacement(const int *codes, const int i, const int codesSize,
Ken Wakasa0bbb9172012-07-25 17:51:43 +090069 const digraph_t *const digraphs, const unsigned int digraphsSize) const {
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090070
71 // There can't be a digraph if we don't have at least 2 characters to examine
72 if (i + 2 > codesSize) return false;
73
74 // Search for the first char of some digraph
75 int lastDigraphIndex = -1;
satok9df4a452012-03-23 16:05:18 +090076 const int thisChar = codes[i];
Jean Chalard6c300612012-03-06 19:54:03 +090077 for (lastDigraphIndex = digraphsSize - 1; lastDigraphIndex >= 0; --lastDigraphIndex) {
78 if (thisChar == digraphs[lastDigraphIndex].first) break;
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090079 }
80 // No match: return early
Jean Chalardd3043382012-03-21 18:38:25 +090081 if (lastDigraphIndex < 0) return 0;
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090082
83 // It's an interesting digraph if the second char matches too.
satok9df4a452012-03-23 16:05:18 +090084 if (digraphs[lastDigraphIndex].second == codes[i + 1]) {
Jean Chalardd3043382012-03-21 18:38:25 +090085 return digraphs[lastDigraphIndex].replacement;
86 } else {
87 return 0;
88 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090089}
90
91// Mostly the same arguments as the non-recursive version, except:
92// codes is the original value. It points to the start of the work buffer, and gets passed as is.
93// codesSize is the size of the user input (thus, it is the size of codesSrc).
94// codesDest is the current point in the work buffer.
95// codesSrc is the current point in the user-input, original, content-unmodified buffer.
96// codesRemain is the remaining size in codesSrc.
satok1d7eaf82011-07-13 10:32:02 +090097void UnigramDictionary::getWordWithDigraphSuggestionsRec(ProximityInfo *proximityInfo,
satok1147c7b2011-12-14 15:04:58 +090098 const int *xcoordinates, const int *ycoordinates, const int *codesBuffer,
satok219a5142012-03-08 11:53:18 +090099 int *xCoordinatesBuffer, int *yCoordinatesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +0900100 const int codesBufferSize, const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900101 const bool useFullEditDistance, const int *codesSrc,
satok1147c7b2011-12-14 15:04:58 +0900102 const int codesRemain, const int currentDepth, int *codesDest, Correction *correction,
Jean Chalard6c300612012-03-06 19:54:03 +0900103 WordsPriorityQueuePool *queuePool,
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900104 const digraph_t *const digraphs, const unsigned int digraphsSize) const {
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900105 assert(sizeof(codesDest[0]) == sizeof(codesSrc[0]));
106 assert(sizeof(xCoordinatesBuffer[0]) == sizeof(xcoordinates[0]));
107 assert(sizeof(yCoordinatesBuffer[0]) == sizeof(ycoordinates[0]));
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900108
Ken Wakasaf2789812012-09-04 12:49:46 +0900109 const int startIndex = static_cast<int>(codesDest - codesBuffer);
Jean Chalard6c300612012-03-06 19:54:03 +0900110 if (currentDepth < MAX_DIGRAPH_SEARCH_DEPTH) {
Jean Chalarda787dba2011-03-04 12:17:48 +0900111 for (int i = 0; i < codesRemain; ++i) {
satok219a5142012-03-08 11:53:18 +0900112 xCoordinatesBuffer[startIndex + i] = xcoordinates[codesBufferSize - codesRemain + i];
113 yCoordinatesBuffer[startIndex + i] = ycoordinates[codesBufferSize - codesRemain + i];
Jean Chalardd3043382012-03-21 18:38:25 +0900114 const int replacementCodePoint =
115 getDigraphReplacement(codesSrc, i, codesRemain, digraphs, digraphsSize);
116 if (0 != replacementCodePoint) {
Jean Chalarda787dba2011-03-04 12:17:48 +0900117 // Found a digraph. We will try both spellings. eg. the word is "pruefen"
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900118
Jean Chalardd3043382012-03-21 18:38:25 +0900119 // Copy the word up to the first char of the digraph, including proximity chars,
120 // and overwrite the primary code with the replacement code point. Then, continue
121 // processing on the remaining part of the word, skipping the second char of the
122 // digraph.
123 // In our example, copy "pru", replace "u" with the version with the diaeresis and
124 // continue running on "fen".
Jean Chalarda787dba2011-03-04 12:17:48 +0900125 // Make i the index of the second char of the digraph for simplicity. Forgetting
126 // to do that results in an infinite recursion so take care!
127 ++i;
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900128 memcpy(codesDest, codesSrc, i * sizeof(codesDest[0]));
129 codesDest[i - 1] = replacementCodePoint;
Jean Chalarda787dba2011-03-04 12:17:48 +0900130 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates,
Jean Chalard338d3ec2012-04-06 19:28:34 +0900131 codesBuffer, xCoordinatesBuffer, yCoordinatesBuffer, codesBufferSize,
Jean Chalard8950ce62012-05-07 16:28:30 +0900132 bigramMap, bigramFilter, useFullEditDistance, codesSrc + i + 1,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900133 codesRemain - i - 1, currentDepth + 1, codesDest + i, correction,
Jean Chalard6c300612012-03-06 19:54:03 +0900134 queuePool, digraphs, digraphsSize);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900135
Jean Chalarda787dba2011-03-04 12:17:48 +0900136 // Copy the second char of the digraph in place, then continue processing on
137 // the remaining part of the word.
138 // In our example, after "pru" in the buffer copy the "e", and continue on "fen"
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900139 memcpy(codesDest + i, codesSrc + i, sizeof(codesDest[0]));
Jean Chalarda787dba2011-03-04 12:17:48 +0900140 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates,
Jean Chalard338d3ec2012-04-06 19:28:34 +0900141 codesBuffer, xCoordinatesBuffer, yCoordinatesBuffer, codesBufferSize,
Jean Chalard8950ce62012-05-07 16:28:30 +0900142 bigramMap, bigramFilter, useFullEditDistance, codesSrc + i, codesRemain - i,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900143 currentDepth + 1, codesDest + i, correction, queuePool, digraphs,
144 digraphsSize);
Jean Chalarda787dba2011-03-04 12:17:48 +0900145 return;
146 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900147 }
148 }
149
150 // If we come here, we hit the end of the word: let's check it against the dictionary.
151 // In our example, we'll come here once for "prufen" and then once for "pruefen".
152 // If the word contains several digraphs, we'll come it for the product of them.
153 // eg. if the word is "ueberpruefen" we'll test, in order, against
154 // "uberprufen", "uberpruefen", "ueberprufen", "ueberpruefen".
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900155 const unsigned int remainingBytes = sizeof(codesDest[0]) * codesRemain;
satok219a5142012-03-08 11:53:18 +0900156 if (0 != remainingBytes) {
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900157 memcpy(codesDest, codesSrc, remainingBytes);
satok219a5142012-03-08 11:53:18 +0900158 memcpy(&xCoordinatesBuffer[startIndex], &xcoordinates[codesBufferSize - codesRemain],
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900159 sizeof(xCoordinatesBuffer[0]) * codesRemain);
satok219a5142012-03-08 11:53:18 +0900160 memcpy(&yCoordinatesBuffer[startIndex], &ycoordinates[codesBufferSize - codesRemain],
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900161 sizeof(yCoordinatesBuffer[0]) * codesRemain);
satok219a5142012-03-08 11:53:18 +0900162 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900163
satok219a5142012-03-08 11:53:18 +0900164 getWordSuggestions(proximityInfo, xCoordinatesBuffer, yCoordinatesBuffer, codesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +0900165 startIndex + codesRemain, bigramMap, bigramFilter, useFullEditDistance, correction,
satoka7e5a5a2011-12-15 16:49:12 +0900166 queuePool);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900167}
168
Jean Chalard8950ce62012-05-07 16:28:30 +0900169// bigramMap contains the association <bigram address> -> <bigram frequency>
170// bigramFilter is a bloom filter for fast rejection: see functions setInFilter and isInFilter
171// in bigram_dictionary.cpp
Ken Wakasaf2789812012-09-04 12:49:46 +0900172int UnigramDictionary::getSuggestions(ProximityInfo *proximityInfo, const int *xcoordinates,
Jean Chalard338d3ec2012-04-06 19:28:34 +0900173 const int *ycoordinates, const int *codes, const int codesSize,
Jean Chalard8950ce62012-05-07 16:28:30 +0900174 const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Ken Wakasa1e614932012-10-29 18:06:22 +0900175 const bool useFullEditDistance, int *outWords, int *frequencies, int *outputTypes) const {
satokb1ed1d42012-06-14 16:35:23 -0700176 WordsPriorityQueuePool queuePool(MAX_WORDS, SUB_QUEUE_MAX_WORDS, MAX_WORD_LENGTH);
177 queuePool.clearAll();
satok1bc038c2012-06-14 11:25:50 -0700178 Correction masterCorrection;
179 masterCorrection.resetCorrection();
Jean Chalardaa8df592012-04-06 18:54:20 +0900180 if (BinaryFormat::REQUIRES_GERMAN_UMLAUT_PROCESSING & FLAGS)
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900181 { // Incrementally tune the word and try all possibilities
satok9df4a452012-03-23 16:05:18 +0900182 int codesBuffer[getCodesBufferSize(codes, codesSize)];
satok219a5142012-03-08 11:53:18 +0900183 int xCoordinatesBuffer[codesSize];
184 int yCoordinatesBuffer[codesSize];
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900185 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates, codesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +0900186 xCoordinatesBuffer, yCoordinatesBuffer, codesSize, bigramMap, bigramFilter,
satok1bc038c2012-06-14 11:25:50 -0700187 useFullEditDistance, codes, codesSize, 0, codesBuffer, &masterCorrection,
Ken Wakasab02ee3d2012-10-08 11:46:14 +0900188 &queuePool, GERMAN_UMLAUT_DIGRAPHS, NELEMS(GERMAN_UMLAUT_DIGRAPHS));
Jean Chalardaa8df592012-04-06 18:54:20 +0900189 } else if (BinaryFormat::REQUIRES_FRENCH_LIGATURES_PROCESSING & FLAGS) {
satokacb6c542012-03-23 20:58:18 +0900190 int codesBuffer[getCodesBufferSize(codes, codesSize)];
Jean Chalardcc78d032012-03-23 16:48:49 +0900191 int xCoordinatesBuffer[codesSize];
192 int yCoordinatesBuffer[codesSize];
193 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates, codesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +0900194 xCoordinatesBuffer, yCoordinatesBuffer, codesSize, bigramMap, bigramFilter,
satok1bc038c2012-06-14 11:25:50 -0700195 useFullEditDistance, codes, codesSize, 0, codesBuffer, &masterCorrection,
Ken Wakasab02ee3d2012-10-08 11:46:14 +0900196 &queuePool, FRENCH_LIGATURES_DIGRAPHS, NELEMS(FRENCH_LIGATURES_DIGRAPHS));
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900197 } else { // Normal processing
Jean Chalard338d3ec2012-04-06 19:28:34 +0900198 getWordSuggestions(proximityInfo, xcoordinates, ycoordinates, codes, codesSize,
satokb1ed1d42012-06-14 16:35:23 -0700199 bigramMap, bigramFilter, useFullEditDistance, &masterCorrection, &queuePool);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900200 }
201
satok817e5172011-03-04 06:06:45 -0800202 PROF_START(20);
satok8330b482012-01-23 16:52:37 +0900203 if (DEBUG_DICT) {
satokb1ed1d42012-06-14 16:35:23 -0700204 float ns = queuePool.getMasterQueue()->getHighestNormalizedScore(
satok1bc038c2012-06-14 11:25:50 -0700205 masterCorrection.getPrimaryInputWord(), codesSize, 0, 0, 0);
satok8330b482012-01-23 16:52:37 +0900206 ns += 0;
207 AKLOGI("Max normalized score = %f", ns);
208 }
satoka7e5a5a2011-12-15 16:49:12 +0900209 const int suggestedWordsCount =
Jean Chalard926ef062012-08-10 13:14:45 +0900210 queuePool.getMasterQueue()->outputSuggestions(masterCorrection.getPrimaryInputWord(),
211 codesSize, frequencies, outWords, outputTypes);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900212
213 if (DEBUG_DICT) {
satokb1ed1d42012-06-14 16:35:23 -0700214 float ns = queuePool.getMasterQueue()->getHighestNormalizedScore(
satok1bc038c2012-06-14 11:25:50 -0700215 masterCorrection.getPrimaryInputWord(), codesSize, 0, 0, 0);
satok8330b482012-01-23 16:52:37 +0900216 ns += 0;
satok9fb6f472012-01-13 18:01:22 +0900217 AKLOGI("Returning %d words", suggestedWordsCount);
Jean Chalard980d6b62011-06-30 17:02:23 +0900218 /// Print the returned words
219 for (int j = 0; j < suggestedWordsCount; ++j) {
Ken Wakasa1e614932012-10-29 18:06:22 +0900220 int *w = outWords + j * MAX_WORD_LENGTH;
Jean Chalard980d6b62011-06-30 17:02:23 +0900221 char s[MAX_WORD_LENGTH];
222 for (int i = 0; i <= MAX_WORD_LENGTH; i++) s[i] = w[i];
Ken Wakasa7914e902012-09-07 08:55:16 +0900223 (void)s; // To suppress compiler warning
satok9fb6f472012-01-13 18:01:22 +0900224 AKLOGI("%s %i", s, frequencies[j]);
Jean Chalard980d6b62011-06-30 17:02:23 +0900225 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900226 }
satok817e5172011-03-04 06:06:45 -0800227 PROF_END(20);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900228 PROF_CLOSE;
229 return suggestedWordsCount;
230}
231
Ken Wakasa1e614932012-10-29 18:06:22 +0900232void UnigramDictionary::getWordSuggestions(ProximityInfo *proximityInfo, const int *xcoordinates,
233 const int *ycoordinates, const int *codes, const int inputSize,
234 const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
235 const bool useFullEditDistance, Correction *correction, WordsPriorityQueuePool *queuePool)
236 const {
satok61e2f852011-01-05 14:13:07 +0900237 PROF_OPEN;
238 PROF_START(0);
satok61e2f852011-01-05 14:13:07 +0900239 PROF_END(0);
satok30088252010-12-01 21:22:15 +0900240
satok61e2f852011-01-05 14:13:07 +0900241 PROF_START(1);
Jean Chalard8950ce62012-05-07 16:28:30 +0900242 getOneWordSuggestions(proximityInfo, xcoordinates, ycoordinates, codes, bigramMap, bigramFilter,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900243 useFullEditDistance, inputSize, correction, queuePool);
satok61e2f852011-01-05 14:13:07 +0900244 PROF_END(1);
245
246 PROF_START(2);
satok10266c02011-08-19 22:05:59 +0900247 // Note: This line is intentionally left blank
satok61e2f852011-01-05 14:13:07 +0900248 PROF_END(2);
satokcdbbea72010-12-08 16:04:16 +0900249
satok61e2f852011-01-05 14:13:07 +0900250 PROF_START(3);
satok10266c02011-08-19 22:05:59 +0900251 // Note: This line is intentionally left blank
satok61e2f852011-01-05 14:13:07 +0900252 PROF_END(3);
satok30088252010-12-01 21:22:15 +0900253
satok61e2f852011-01-05 14:13:07 +0900254 PROF_START(4);
satok8330b482012-01-23 16:52:37 +0900255 bool hasAutoCorrectionCandidate = false;
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900256 WordsPriorityQueue *masterQueue = queuePool->getMasterQueue();
satok8330b482012-01-23 16:52:37 +0900257 if (masterQueue->size() > 0) {
satok0028ed32012-05-16 20:42:12 +0900258 float nsForMaster = masterQueue->getHighestNormalizedScore(
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900259 correction->getPrimaryInputWord(), inputSize, 0, 0, 0);
satok8330b482012-01-23 16:52:37 +0900260 hasAutoCorrectionCandidate = (nsForMaster > START_TWO_WORDS_CORRECTION_THRESHOLD);
261 }
satok61e2f852011-01-05 14:13:07 +0900262 PROF_END(4);
satoka3d78f62010-12-09 22:08:33 +0900263
satok61e2f852011-01-05 14:13:07 +0900264 PROF_START(5);
satok99557162012-01-26 22:49:13 +0900265 // Multiple word suggestions
266 if (SUGGEST_MULTIPLE_WORDS
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900267 && inputSize >= MIN_USER_TYPED_LENGTH_FOR_MULTIPLE_WORD_SUGGESTION) {
satoka85f4922012-01-30 18:18:30 +0900268 getSplitMultipleWordsSuggestions(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900269 useFullEditDistance, inputSize, correction, queuePool,
satok1f6b52e2012-01-30 13:53:58 +0900270 hasAutoCorrectionCandidate);
satok662fe692010-12-08 17:05:39 +0900271 }
satok61e2f852011-01-05 14:13:07 +0900272 PROF_END(5);
satok817e5172011-03-04 06:06:45 -0800273
274 PROF_START(6);
satok99557162012-01-26 22:49:13 +0900275 // Note: This line is intentionally left blank
satok817e5172011-03-04 06:06:45 -0800276 PROF_END(6);
satok99557162012-01-26 22:49:13 +0900277
satok29dc8062012-01-17 15:59:15 +0900278 if (DEBUG_DICT) {
satok6ad15fc2012-01-16 16:21:21 +0900279 queuePool->dumpSubQueue1TopSuggestions();
satok29dc8062012-01-17 15:59:15 +0900280 for (int i = 0; i < SUB_QUEUE_MAX_COUNT; ++i) {
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900281 WordsPriorityQueue *queue = queuePool->getSubQueue(FIRST_WORD_INDEX, i);
satok29dc8062012-01-17 15:59:15 +0900282 if (queue->size() > 0) {
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900283 WordsPriorityQueue::SuggestedWord *sw = queue->top();
satok29dc8062012-01-17 15:59:15 +0900284 const int score = sw->mScore;
Ken Wakasa1e614932012-10-29 18:06:22 +0900285 const int *word = sw->mWord;
satok29dc8062012-01-17 15:59:15 +0900286 const int wordLength = sw->mWordLength;
satok0028ed32012-05-16 20:42:12 +0900287 float ns = Correction::RankingAlgorithm::calcNormalizedScore(
Satoshi Kataoka4a3db702012-06-08 15:29:44 +0900288 correction->getPrimaryInputWord(), i, word, wordLength, score);
satok29dc8062012-01-17 15:59:15 +0900289 ns += 0;
290 AKLOGI("--- TOP SUB WORDS for %d --- %d %f [%d]", i, score, ns,
satok54af64a2012-01-17 15:58:23 +0900291 (ns > TWO_WORDS_CORRECTION_WITH_OTHER_ERROR_THRESHOLD));
Satoshi Kataoka4a3db702012-06-08 15:29:44 +0900292 DUMP_WORD(correction->getPrimaryInputWord(), i);
satok29dc8062012-01-17 15:59:15 +0900293 DUMP_WORD(word, wordLength);
294 }
295 }
satok6ad15fc2012-01-16 16:21:21 +0900296 }
satok30088252010-12-01 21:22:15 +0900297}
298
Yusuke Nojima258bfe62011-09-28 12:59:43 +0900299void UnigramDictionary::initSuggestions(ProximityInfo *proximityInfo, const int *xCoordinates,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900300 const int *yCoordinates, const int *codes, const int inputSize,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900301 Correction *correction) const {
Ken Wakasade3070a2011-03-19 09:16:42 +0900302 if (DEBUG_DICT) {
satok9fb6f472012-01-13 18:01:22 +0900303 AKLOGI("initSuggest");
Ken Wakasa1e614932012-10-29 18:06:22 +0900304 DUMP_WORD(codes, inputSize);
Ken Wakasade3070a2011-03-19 09:16:42 +0900305 }
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900306 correction->initInputParams(proximityInfo, codes, inputSize, xCoordinates, yCoordinates);
307 const int maxDepth = min(inputSize * MAX_DEPTH_MULTIPLIER, MAX_WORD_LENGTH);
308 correction->initCorrection(proximityInfo, inputSize, maxDepth);
satok30088252010-12-01 21:22:15 +0900309}
310
satok744dab62011-12-15 22:29:05 +0900311void UnigramDictionary::getOneWordSuggestions(ProximityInfo *proximityInfo,
312 const int *xcoordinates, const int *ycoordinates, const int *codes,
Jean Chalard8950ce62012-05-07 16:28:30 +0900313 const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900314 const bool useFullEditDistance, const int inputSize,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900315 Correction *correction, WordsPriorityQueuePool *queuePool) const {
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900316 initSuggestions(proximityInfo, xcoordinates, ycoordinates, codes, inputSize, correction);
317 getSuggestionCandidates(useFullEditDistance, inputSize, bigramMap, bigramFilter, correction,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900318 queuePool, true /* doAutoCompletion */, DEFAULT_MAX_ERRORS, FIRST_WORD_INDEX);
satok744dab62011-12-15 22:29:05 +0900319}
320
satok1147c7b2011-12-14 15:04:58 +0900321void UnigramDictionary::getSuggestionCandidates(const bool useFullEditDistance,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900322 const int inputSize, const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900323 Correction *correction, WordsPriorityQueuePool *queuePool,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900324 const bool doAutoCompletion, const int maxErrors, const int currentWordIndex) const {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900325 uint8_t totalTraverseCount = correction->pushAndGetTotalTraverseCount();
326 if (DEBUG_DICT) {
327 AKLOGI("Traverse count %d", totalTraverseCount);
328 }
329 if (totalTraverseCount > MULTIPLE_WORDS_SUGGESTION_MAX_TOTAL_TRAVERSE_COUNT) {
330 if (DEBUG_DICT) {
331 AKLOGI("Abort traversing %d", totalTraverseCount);
332 }
333 return;
334 }
satok10266c02011-08-19 22:05:59 +0900335 // TODO: Remove setCorrectionParams
satok1147c7b2011-12-14 15:04:58 +0900336 correction->setCorrectionParams(0, 0, 0,
satokd03317c2011-12-14 21:38:11 +0900337 -1 /* spaceProximityPos */, -1 /* missingSpacePos */, useFullEditDistance,
satok1a6da632011-12-16 23:15:06 +0900338 doAutoCompletion, maxErrors);
satok662fe692010-12-08 17:05:39 +0900339 int rootPosition = ROOT_POS;
Jean Chalard980d6b62011-06-30 17:02:23 +0900340 // Get the number of children of root, then increment the position
Jean Chalard6d419812012-01-16 15:19:47 +0900341 int childCount = BinaryFormat::getGroupCountAndForwardPointer(DICT_ROOT, &rootPosition);
satok208268d2011-08-10 15:44:08 +0900342 int outputIndex = 0;
satokd2997922010-12-07 13:08:39 +0900343
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900344 correction->initCorrectionState(rootPosition, childCount, (inputSize <= 0));
satokd2997922010-12-07 13:08:39 +0900345
satok662fe692010-12-08 17:05:39 +0900346 // Depth first search
satok208268d2011-08-10 15:44:08 +0900347 while (outputIndex >= 0) {
satok1147c7b2011-12-14 15:04:58 +0900348 if (correction->initProcessState(outputIndex)) {
349 int siblingPos = correction->getTreeSiblingPos(outputIndex);
satokd2997922010-12-07 13:08:39 +0900350 int firstChildPos;
satok0f6c8e82011-08-03 02:19:44 +0900351
satok4e4e74e2011-08-03 23:27:32 +0900352 const bool needsToTraverseChildrenNodes = processCurrentNode(siblingPos,
Jean Chalard8950ce62012-05-07 16:28:30 +0900353 bigramMap, bigramFilter, correction, &childCount, &firstChildPos, &siblingPos,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900354 queuePool, currentWordIndex);
satok662fe692010-12-08 17:05:39 +0900355 // Update next sibling pos
satok1147c7b2011-12-14 15:04:58 +0900356 correction->setTreeSiblingPos(outputIndex, siblingPos);
satok208268d2011-08-10 15:44:08 +0900357
satokd2997922010-12-07 13:08:39 +0900358 if (needsToTraverseChildrenNodes) {
359 // Goes to child node
satok1147c7b2011-12-14 15:04:58 +0900360 outputIndex = correction->goDownTree(outputIndex, childCount, firstChildPos);
satokd2997922010-12-07 13:08:39 +0900361 }
362 } else {
satokcdbbea72010-12-08 16:04:16 +0900363 // Goes to parent sibling node
satok1147c7b2011-12-14 15:04:58 +0900364 outputIndex = correction->getTreeParentIndex(outputIndex);
satokd2997922010-12-07 13:08:39 +0900365 }
366 }
367}
368
Jean Chalard171d1802012-04-23 18:51:00 +0900369inline void UnigramDictionary::onTerminal(const int probability,
Jean Chalardcf9dbbd2011-12-26 15:16:59 +0900370 const TerminalAttributes& terminalAttributes, Correction *correction,
satok8330b482012-01-23 16:52:37 +0900371 WordsPriorityQueuePool *queuePool, const bool addToMasterQueue,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900372 const int currentWordIndex) const {
satok6ad15fc2012-01-16 16:21:21 +0900373 const int inputIndex = correction->getInputIndex();
374 const bool addToSubQueue = inputIndex < SUB_QUEUE_MAX_COUNT;
satok54af64a2012-01-17 15:58:23 +0900375
satok8876b752011-08-04 18:31:57 +0900376 int wordLength;
Ken Wakasa1e614932012-10-29 18:06:22 +0900377 int *wordPointer;
satok54af64a2012-01-17 15:58:23 +0900378
satok1f6b52e2012-01-30 13:53:58 +0900379 if ((currentWordIndex == FIRST_WORD_INDEX) && addToMasterQueue) {
satok54af64a2012-01-17 15:58:23 +0900380 WordsPriorityQueue *masterQueue = queuePool->getMasterQueue();
Jean Chalard171d1802012-04-23 18:51:00 +0900381 const int finalProbability =
382 correction->getFinalProbability(probability, &wordPointer, &wordLength);
satok54af64a2012-01-17 15:58:23 +0900383
Jean Chalard72b1c932012-08-31 15:24:39 +0900384 if (0 != finalProbability && !terminalAttributes.isBlacklistedOrNotAWord()) {
Jean Chalard8af8c152012-08-17 09:37:39 +0900385 // If the probability is 0, we don't want to add this word. However we still
386 // want to add its shortcuts (including a possible whitelist entry) if any.
Jean Chalard72b1c932012-08-31 15:24:39 +0900387 // Furthermore, if this is not a word (shortcut only for example) or a blacklisted
388 // entry then we never want to suggest this.
Jean Chalard8af8c152012-08-17 09:37:39 +0900389 addWord(wordPointer, wordLength, finalProbability, masterQueue,
390 Dictionary::KIND_CORRECTION);
391 }
392
393 const int shortcutProbability = finalProbability > 0 ? finalProbability - 1 : 0;
394 // Please note that the shortcut candidates will be added to the master queue only.
395 TerminalAttributes::ShortcutIterator iterator =
396 terminalAttributes.getShortcutIterator();
397 while (iterator.hasNextShortcutTarget()) {
398 // TODO: addWord only supports weak ordering, meaning we have no means
399 // to control the order of the shortcuts relative to one another or to the word.
400 // We need to either modulate the probability of each shortcut according
401 // to its own shortcut probability or to make the queue
402 // so that the insert order is protected inside the queue for words
403 // with the same score. For the moment we use -1 to make sure the shortcut will
404 // never be in front of the word.
Ken Wakasa1e614932012-10-29 18:06:22 +0900405 int shortcutTarget[MAX_WORD_LENGTH_INTERNAL];
Jean Chalard8af8c152012-08-17 09:37:39 +0900406 int shortcutFrequency;
407 const int shortcutTargetStringLength = iterator.getNextShortcutTarget(
408 MAX_WORD_LENGTH_INTERNAL, shortcutTarget, &shortcutFrequency);
409 int shortcutScore;
410 int kind;
411 if (shortcutFrequency == BinaryFormat::WHITELIST_SHORTCUT_FREQUENCY
412 && correction->sameAsTyped()) {
413 shortcutScore = S_INT_MAX;
414 kind = Dictionary::KIND_WHITELIST;
415 } else {
416 shortcutScore = shortcutProbability;
417 kind = Dictionary::KIND_CORRECTION;
satok6ad15fc2012-01-16 16:21:21 +0900418 }
Jean Chalard8af8c152012-08-17 09:37:39 +0900419 addWord(shortcutTarget, shortcutTargetStringLength, shortcutScore,
420 masterQueue, kind);
Jean Chalardcf9dbbd2011-12-26 15:16:59 +0900421 }
satok54af64a2012-01-17 15:58:23 +0900422 }
satok6ad15fc2012-01-16 16:21:21 +0900423
satok54af64a2012-01-17 15:58:23 +0900424 // We only allow two words + other error correction for words with SUB_QUEUE_MIN_WORD_LENGTH
425 // or more length.
426 if (inputIndex >= SUB_QUEUE_MIN_WORD_LENGTH && addToSubQueue) {
satok8330b482012-01-23 16:52:37 +0900427 WordsPriorityQueue *subQueue;
satok7409d152012-01-26 16:13:25 +0900428 subQueue = queuePool->getSubQueue(currentWordIndex, inputIndex);
429 if (!subQueue) {
satok8330b482012-01-23 16:52:37 +0900430 return;
431 }
Jean Chalard171d1802012-04-23 18:51:00 +0900432 const int finalProbability = correction->getFinalProbabilityForSubQueue(
433 probability, &wordPointer, &wordLength, inputIndex);
Jean Chalard926ef062012-08-10 13:14:45 +0900434 addWord(wordPointer, wordLength, finalProbability, subQueue, Dictionary::KIND_CORRECTION);
Jean Chalardca5ef282011-06-17 15:36:26 +0900435 }
436}
437
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900438int UnigramDictionary::getSubStringSuggestion(
satok7409d152012-01-26 16:13:25 +0900439 ProximityInfo *proximityInfo, const int *xcoordinates, const int *ycoordinates,
satok3c09bb12012-01-26 18:36:19 +0900440 const int *codes, const bool useFullEditDistance, Correction *correction,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900441 WordsPriorityQueuePool *queuePool, const int inputSize,
satok3c09bb12012-01-26 18:36:19 +0900442 const bool hasAutoCorrectionCandidate, const int currentWordIndex,
443 const int inputWordStartPos, const int inputWordLength,
satok99557162012-01-26 22:49:13 +0900444 const int outputWordStartPos, const bool isSpaceProximity, int *freqArray,
Ken Wakasa1e614932012-10-29 18:06:22 +0900445 int *wordLengthArray, int *outputWord, int *outputWordLength) const {
Satoshi Kataoka67e3cc82012-05-31 15:04:58 +0900446 if (inputWordLength > MULTIPLE_WORDS_SUGGESTION_MAX_WORD_LENGTH) {
447 return FLAG_MULTIPLE_SUGGEST_ABORT;
448 }
449
450 /////////////////////////////////////////////
451 // safety net for multiple word suggestion //
452 // TODO: Remove this safety net //
453 /////////////////////////////////////////////
454 int smallWordCount = 0;
455 int singleLetterWordCount = 0;
456 if (inputWordLength == 1) {
457 ++singleLetterWordCount;
458 }
459 if (inputWordLength <= 2) {
460 // small word == single letter or 2-letter word
461 ++smallWordCount;
462 }
463 for (int i = 0; i < currentWordIndex; ++i) {
464 const int length = wordLengthArray[i];
465 if (length == 1) {
466 ++singleLetterWordCount;
467 // Safety net to avoid suggesting sequential single letter words
468 if (i < (currentWordIndex - 1)) {
469 if (wordLengthArray[i + 1] == 1) {
470 return FLAG_MULTIPLE_SUGGEST_ABORT;
471 }
472 } else if (inputWordLength == 1) {
473 return FLAG_MULTIPLE_SUGGEST_ABORT;
474 }
475 }
476 if (length <= 2) {
477 ++smallWordCount;
478 }
479 // Safety net to avoid suggesting multiple words with many (4 or more, for now) small words
480 if (singleLetterWordCount >= 3 || smallWordCount >= 4) {
481 return FLAG_MULTIPLE_SUGGEST_ABORT;
482 }
483 }
484 //////////////////////////////////////////////
485 // TODO: Remove the safety net above //
486 //////////////////////////////////////////////
487
Ken Wakasa1e614932012-10-29 18:06:22 +0900488 int *tempOutputWord = 0;
satok1f6b52e2012-01-30 13:53:58 +0900489 int nextWordLength = 0;
satok99557162012-01-26 22:49:13 +0900490 // TODO: Optimize init suggestion
491 initSuggestions(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900492 inputSize, correction);
satok99557162012-01-26 22:49:13 +0900493
Ken Wakasa1e614932012-10-29 18:06:22 +0900494 int word[MAX_WORD_LENGTH_INTERNAL];
satok3c09bb12012-01-26 18:36:19 +0900495 int freq = getMostFrequentWordLike(
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900496 inputWordStartPos, inputWordLength, correction, word);
satok3c09bb12012-01-26 18:36:19 +0900497 if (freq > 0) {
satok1f6b52e2012-01-30 13:53:58 +0900498 nextWordLength = inputWordLength;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900499 tempOutputWord = word;
satok3c09bb12012-01-26 18:36:19 +0900500 } else if (!hasAutoCorrectionCandidate) {
501 if (inputWordStartPos > 0) {
502 const int offset = inputWordStartPos;
503 initSuggestions(proximityInfo, &xcoordinates[offset], &ycoordinates[offset],
satok9df4a452012-03-23 16:05:18 +0900504 codes + offset, inputWordLength, correction);
satok3c09bb12012-01-26 18:36:19 +0900505 queuePool->clearSubQueue(currentWordIndex);
Jean Chalard4d9b2022012-04-23 19:25:28 +0900506 // TODO: pass the bigram list for substring suggestion
507 getSuggestionCandidates(useFullEditDistance, inputWordLength,
Jean Chalard8950ce62012-05-07 16:28:30 +0900508 0 /* bigramMap */, 0 /* bigramFilter */, correction, queuePool,
509 false /* doAutoCompletion */, MAX_ERRORS_FOR_TWO_WORDS, currentWordIndex);
satok3c09bb12012-01-26 18:36:19 +0900510 if (DEBUG_DICT) {
satok1f6b52e2012-01-30 13:53:58 +0900511 if (currentWordIndex < MULTIPLE_WORDS_SUGGESTION_MAX_WORDS) {
satok3c09bb12012-01-26 18:36:19 +0900512 AKLOGI("Dump word candidates(%d) %d", currentWordIndex, inputWordLength);
513 for (int i = 0; i < SUB_QUEUE_MAX_COUNT; ++i) {
514 queuePool->getSubQueue(currentWordIndex, i)->dumpTopWord();
515 }
516 }
517 }
518 }
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900519 WordsPriorityQueue *queue = queuePool->getSubQueue(currentWordIndex, inputWordLength);
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900520 // TODO: Return the correct value depending on doAutoCompletion
521 if (!queue || queue->size() <= 0) {
522 return FLAG_MULTIPLE_SUGGEST_ABORT;
satok3c09bb12012-01-26 18:36:19 +0900523 }
524 int score = 0;
satok0028ed32012-05-16 20:42:12 +0900525 const float ns = queue->getHighestNormalizedScore(
Satoshi Kataoka4a3db702012-06-08 15:29:44 +0900526 correction->getPrimaryInputWord(), inputWordLength,
satok1f6b52e2012-01-30 13:53:58 +0900527 &tempOutputWord, &score, &nextWordLength);
satok3c09bb12012-01-26 18:36:19 +0900528 if (DEBUG_DICT) {
529 AKLOGI("NS(%d) = %f, Score = %d", currentWordIndex, ns, score);
530 }
531 // Two words correction won't be done if the score of the first word doesn't exceed the
532 // threshold.
533 if (ns < TWO_WORDS_CORRECTION_WITH_OTHER_ERROR_THRESHOLD
satok1f6b52e2012-01-30 13:53:58 +0900534 || nextWordLength < SUB_QUEUE_MIN_WORD_LENGTH) {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900535 return FLAG_MULTIPLE_SUGGEST_SKIP;
satok3c09bb12012-01-26 18:36:19 +0900536 }
satok1f6b52e2012-01-30 13:53:58 +0900537 freq = score >> (nextWordLength + TWO_WORDS_PLUS_OTHER_ERROR_CORRECTION_DEMOTION_DIVIDER);
satok3c09bb12012-01-26 18:36:19 +0900538 }
539 if (DEBUG_DICT) {
Jean Chalard18ebba32012-09-06 20:37:55 +0900540 AKLOGI("Freq(%d): %d, length: %d, input length: %d, input start: %d (%d)",
541 currentWordIndex, freq, nextWordLength, inputWordLength, inputWordStartPos,
542 (currentWordIndex > 0) ? wordLengthArray[0] : 0);
satok3c09bb12012-01-26 18:36:19 +0900543 }
satok1f6b52e2012-01-30 13:53:58 +0900544 if (freq <= 0 || nextWordLength <= 0
545 || MAX_WORD_LENGTH <= (outputWordStartPos + nextWordLength)) {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900546 return FLAG_MULTIPLE_SUGGEST_SKIP;
satok3c09bb12012-01-26 18:36:19 +0900547 }
satok1f6b52e2012-01-30 13:53:58 +0900548 for (int i = 0; i < nextWordLength; ++i) {
satok3c09bb12012-01-26 18:36:19 +0900549 outputWord[outputWordStartPos + i] = tempOutputWord[i];
550 }
satok99557162012-01-26 22:49:13 +0900551
552 // Put output values
satok1f6b52e2012-01-30 13:53:58 +0900553 freqArray[currentWordIndex] = freq;
satok99557162012-01-26 22:49:13 +0900554 // TODO: put output length instead of input length
satok1f6b52e2012-01-30 13:53:58 +0900555 wordLengthArray[currentWordIndex] = inputWordLength;
556 const int tempOutputWordLength = outputWordStartPos + nextWordLength;
557 if (outputWordLength) {
558 *outputWordLength = tempOutputWordLength;
559 }
satok99557162012-01-26 22:49:13 +0900560
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900561 if ((inputWordStartPos + inputWordLength) < inputSize) {
satok1f6b52e2012-01-30 13:53:58 +0900562 if (outputWordStartPos + nextWordLength >= MAX_WORD_LENGTH) {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900563 return FLAG_MULTIPLE_SUGGEST_SKIP;
satok3c09bb12012-01-26 18:36:19 +0900564 }
Ken Wakasab02ee3d2012-10-08 11:46:14 +0900565 outputWord[tempOutputWordLength] = KEYCODE_SPACE;
satok1f6b52e2012-01-30 13:53:58 +0900566 if (outputWordLength) {
567 ++*outputWordLength;
568 }
569 } else if (currentWordIndex >= 1) {
satok99557162012-01-26 22:49:13 +0900570 // TODO: Handle 3 or more words
satoka85f4922012-01-30 18:18:30 +0900571 const int pairFreq = correction->getFreqForSplitMultipleWords(
572 freqArray, wordLengthArray, currentWordIndex + 1, isSpaceProximity, outputWord);
satok99557162012-01-26 22:49:13 +0900573 if (DEBUG_DICT) {
satoka85f4922012-01-30 18:18:30 +0900574 DUMP_WORD(outputWord, tempOutputWordLength);
satoka0ac31f2012-05-23 19:55:27 +0900575 for (int i = 0; i < currentWordIndex + 1; ++i) {
576 AKLOGI("Split %d,%d words: freq = %d, length = %d", i, currentWordIndex + 1,
577 freqArray[i], wordLengthArray[i]);
578 }
579 AKLOGI("Split two words: freq = %d, length = %d, %d, isSpace ? %d", pairFreq,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900580 inputSize, tempOutputWordLength, isSpaceProximity);
satok99557162012-01-26 22:49:13 +0900581 }
Jean Chalard926ef062012-08-10 13:14:45 +0900582 addWord(outputWord, tempOutputWordLength, pairFreq, queuePool->getMasterQueue(),
583 Dictionary::KIND_CORRECTION);
satok3c09bb12012-01-26 18:36:19 +0900584 }
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900585 return FLAG_MULTIPLE_SUGGEST_CONTINUE;
satok7409d152012-01-26 16:13:25 +0900586}
587
satok1f6b52e2012-01-30 13:53:58 +0900588void UnigramDictionary::getMultiWordsSuggestionRec(ProximityInfo *proximityInfo,
589 const int *xcoordinates, const int *ycoordinates, const int *codes,
Ken Wakasaf2789812012-09-04 12:49:46 +0900590 const bool useFullEditDistance, const int inputSize, Correction *correction,
591 WordsPriorityQueuePool *queuePool, const bool hasAutoCorrectionCandidate,
592 const int startInputPos, const int startWordIndex, const int outputWordLength,
Ken Wakasa1e614932012-10-29 18:06:22 +0900593 int *freqArray, int *wordLengthArray, int *outputWord) const {
satok1f6b52e2012-01-30 13:53:58 +0900594 if (startWordIndex >= (MULTIPLE_WORDS_SUGGESTION_MAX_WORDS - 1)) {
595 // Return if the last word index
596 return;
597 }
satoka85f4922012-01-30 18:18:30 +0900598 if (startWordIndex >= 1
599 && (hasAutoCorrectionCandidate
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900600 || inputSize < MIN_INPUT_LENGTH_FOR_THREE_OR_MORE_WORDS_CORRECTION)) {
satoka85f4922012-01-30 18:18:30 +0900601 // Do not suggest 3+ words if already has auto correction candidate
602 return;
603 }
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900604 for (int i = startInputPos + 1; i < inputSize; ++i) {
satok1f6b52e2012-01-30 13:53:58 +0900605 if (DEBUG_CORRECTION_FREQ) {
satoka85f4922012-01-30 18:18:30 +0900606 AKLOGI("Multi words(%d), start in %d sep %d start out %d",
607 startWordIndex, startInputPos, i, outputWordLength);
608 DUMP_WORD(outputWord, outputWordLength);
satok1f6b52e2012-01-30 13:53:58 +0900609 }
satoka85f4922012-01-30 18:18:30 +0900610 int tempOutputWordLength = 0;
611 // Current word
612 int inputWordStartPos = startInputPos;
613 int inputWordLength = i - startInputPos;
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900614 const int suggestionFlag = getSubStringSuggestion(proximityInfo, xcoordinates, ycoordinates,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900615 codes, useFullEditDistance, correction, queuePool, inputSize,
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900616 hasAutoCorrectionCandidate, startWordIndex, inputWordStartPos, inputWordLength,
617 outputWordLength, true /* not used */, freqArray, wordLengthArray, outputWord,
618 &tempOutputWordLength);
619 if (suggestionFlag == FLAG_MULTIPLE_SUGGEST_ABORT) {
620 // TODO: break here
621 continue;
622 } else if (suggestionFlag == FLAG_MULTIPLE_SUGGEST_SKIP) {
satok1f6b52e2012-01-30 13:53:58 +0900623 continue;
624 }
625
satoka85f4922012-01-30 18:18:30 +0900626 if (DEBUG_CORRECTION_FREQ) {
627 AKLOGI("Do missing space correction");
628 }
629 // Next word
satok1f6b52e2012-01-30 13:53:58 +0900630 // Missing space
631 inputWordStartPos = i;
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900632 inputWordLength = inputSize - i;
Ken Wakasaf2789812012-09-04 12:49:46 +0900633 if (getSubStringSuggestion(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900634 useFullEditDistance, correction, queuePool, inputSize, hasAutoCorrectionCandidate,
satoka85f4922012-01-30 18:18:30 +0900635 startWordIndex + 1, inputWordStartPos, inputWordLength, tempOutputWordLength,
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900636 false /* missing space */, freqArray, wordLengthArray, outputWord, 0)
637 != FLAG_MULTIPLE_SUGGEST_CONTINUE) {
satoka85f4922012-01-30 18:18:30 +0900638 getMultiWordsSuggestionRec(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900639 useFullEditDistance, inputSize, correction, queuePool,
satoka85f4922012-01-30 18:18:30 +0900640 hasAutoCorrectionCandidate, inputWordStartPos, startWordIndex + 1,
641 tempOutputWordLength, freqArray, wordLengthArray, outputWord);
642 }
satok1f6b52e2012-01-30 13:53:58 +0900643
644 // Mistyped space
645 ++inputWordStartPos;
646 --inputWordLength;
647
648 if (inputWordLength <= 0) {
649 continue;
650 }
651
652 const int x = xcoordinates[inputWordStartPos - 1];
653 const int y = ycoordinates[inputWordStartPos - 1];
654 if (!proximityInfo->hasSpaceProximity(x, y)) {
655 continue;
656 }
657
satoka85f4922012-01-30 18:18:30 +0900658 if (DEBUG_CORRECTION_FREQ) {
659 AKLOGI("Do mistyped space correction");
660 }
satok1f6b52e2012-01-30 13:53:58 +0900661 getSubStringSuggestion(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900662 useFullEditDistance, correction, queuePool, inputSize, hasAutoCorrectionCandidate,
satoka85f4922012-01-30 18:18:30 +0900663 startWordIndex + 1, inputWordStartPos, inputWordLength, tempOutputWordLength,
664 true /* mistyped space */, freqArray, wordLengthArray, outputWord, 0);
satok1f6b52e2012-01-30 13:53:58 +0900665 }
666}
667
satoka85f4922012-01-30 18:18:30 +0900668void UnigramDictionary::getSplitMultipleWordsSuggestions(ProximityInfo *proximityInfo,
satok744dab62011-12-15 22:29:05 +0900669 const int *xcoordinates, const int *ycoordinates, const int *codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900670 const bool useFullEditDistance, const int inputSize,
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900671 Correction *correction, WordsPriorityQueuePool *queuePool,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900672 const bool hasAutoCorrectionCandidate) const {
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900673 if (inputSize >= MAX_WORD_LENGTH) return;
satok612c6e42011-08-01 19:35:27 +0900674 if (DEBUG_DICT) {
satok1f6b52e2012-01-30 13:53:58 +0900675 AKLOGI("--- Suggest multiple words");
676 }
satok54af64a2012-01-17 15:58:23 +0900677
satokbd6ccdd2012-01-23 12:30:20 +0900678 // Allocating fixed length array on stack
Ken Wakasa1e614932012-10-29 18:06:22 +0900679 int outputWord[MAX_WORD_LENGTH];
satok1f6b52e2012-01-30 13:53:58 +0900680 int freqArray[MULTIPLE_WORDS_SUGGESTION_MAX_WORDS];
681 int wordLengthArray[MULTIPLE_WORDS_SUGGESTION_MAX_WORDS];
682 const int outputWordLength = 0;
683 const int startInputPos = 0;
684 const int startWordIndex = 0;
685 getMultiWordsSuggestionRec(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900686 useFullEditDistance, inputSize, correction, queuePool, hasAutoCorrectionCandidate,
satok1f6b52e2012-01-30 13:53:58 +0900687 startInputPos, startWordIndex, outputWordLength, freqArray, wordLengthArray,
688 outputWord);
Jean Chalarde6715e32011-06-30 19:47:25 +0900689}
690
Jean Chalard1059f272011-06-28 20:45:05 +0900691// Wrapper for getMostFrequentWordLikeInner, which matches it to the previous
692// interface.
693inline int UnigramDictionary::getMostFrequentWordLike(const int startInputIndex,
Ken Wakasa1e614932012-10-29 18:06:22 +0900694 const int inputSize, Correction *correction, int *word) const {
695 int inWord[inputSize];
Jean Chalard1059f272011-06-28 20:45:05 +0900696
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900697 for (int i = 0; i < inputSize; ++i) {
Ken Wakasa1e614932012-10-29 18:06:22 +0900698 inWord[i] = correction->getPrimaryCodePointAt(startInputIndex + i);
Jean Chalard1059f272011-06-28 20:45:05 +0900699 }
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900700 return getMostFrequentWordLikeInner(inWord, inputSize, word);
Jean Chalard1059f272011-06-28 20:45:05 +0900701}
702
703// This function will take the position of a character array within a CharGroup,
704// and check it actually like-matches the word in inWord starting at startInputIndex,
705// that is, it matches it with case and accents squashed.
706// The function returns true if there was a full match, false otherwise.
707// The function will copy on-the-fly the characters in the CharGroup to outNewWord.
708// It will also place the end position of the array in outPos; in outInputIndex,
709// it will place the index of the first char AFTER the match if there was a match,
710// and the initial position if there was not. It makes sense because if there was
711// a match we want to continue searching, but if there was not, we want to go to
712// the next CharGroup.
713// In and out parameters may point to the same location. This function takes care
714// not to use any input parameters after it wrote into its outputs.
715static inline bool testCharGroupForContinuedLikeness(const uint8_t flags,
Ken Wakasa1e614932012-10-29 18:06:22 +0900716 const uint8_t *const root, const int startPos, const int *const inWord,
717 const int startInputIndex, const int inputSize, int *outNewWord, int *outInputIndex,
Ken Wakasaf2789812012-09-04 12:49:46 +0900718 int *outPos) {
Jean Chalard19560502012-07-31 23:45:32 +0900719 const bool hasMultipleChars = (0 != (BinaryFormat::FLAG_HAS_MULTIPLE_CHARS & flags));
Jean Chalard1059f272011-06-28 20:45:05 +0900720 int pos = startPos;
Ken Wakasa1e614932012-10-29 18:06:22 +0900721 int codePoint = BinaryFormat::getCodePointAndForwardPointer(root, &pos);
722 int baseChar = toBaseLowerCase(codePoint);
723 const int wChar = toBaseLowerCase(inWord[startInputIndex]);
Jean Chalard1059f272011-06-28 20:45:05 +0900724
725 if (baseChar != wChar) {
726 *outPos = hasMultipleChars ? BinaryFormat::skipOtherCharacters(root, pos) : pos;
727 *outInputIndex = startInputIndex;
728 return false;
729 }
730 int inputIndex = startInputIndex;
Ken Wakasaf2789812012-09-04 12:49:46 +0900731 outNewWord[inputIndex] = codePoint;
Jean Chalard1059f272011-06-28 20:45:05 +0900732 if (hasMultipleChars) {
Ken Wakasaf2789812012-09-04 12:49:46 +0900733 codePoint = BinaryFormat::getCodePointAndForwardPointer(root, &pos);
734 while (NOT_A_CODE_POINT != codePoint) {
735 baseChar = toBaseLowerCase(codePoint);
736 if (inputIndex + 1 >= inputSize || toBaseLowerCase(inWord[++inputIndex]) != baseChar) {
Jean Chalard1059f272011-06-28 20:45:05 +0900737 *outPos = BinaryFormat::skipOtherCharacters(root, pos);
738 *outInputIndex = startInputIndex;
739 return false;
740 }
Ken Wakasaf2789812012-09-04 12:49:46 +0900741 outNewWord[inputIndex] = codePoint;
742 codePoint = BinaryFormat::getCodePointAndForwardPointer(root, &pos);
Jean Chalard1059f272011-06-28 20:45:05 +0900743 }
744 }
745 *outInputIndex = inputIndex + 1;
746 *outPos = pos;
747 return true;
748}
749
750// This function is invoked when a word like the word searched for is found.
751// It will compare the frequency to the max frequency, and if greater, will
752// copy the word into the output buffer. In output value maxFreq, it will
753// write the new maximum frequency if it changed.
Ken Wakasa1e614932012-10-29 18:06:22 +0900754static inline void onTerminalWordLike(const int freq, int *newWord, const int length, int *outWord,
755 int *maxFreq) {
Jean Chalard1059f272011-06-28 20:45:05 +0900756 if (freq > *maxFreq) {
Ken Wakasaf2789812012-09-04 12:49:46 +0900757 for (int q = 0; q < length; ++q) {
Jean Chalard1059f272011-06-28 20:45:05 +0900758 outWord[q] = newWord[q];
Ken Wakasaf2789812012-09-04 12:49:46 +0900759 }
Jean Chalard1059f272011-06-28 20:45:05 +0900760 outWord[length] = 0;
761 *maxFreq = freq;
762 }
763}
764
765// Will find the highest frequency of the words like the one passed as an argument,
766// that is, everything that only differs by case/accents.
Ken Wakasa1e614932012-10-29 18:06:22 +0900767int UnigramDictionary::getMostFrequentWordLikeInner(const int *const inWord, const int inputSize,
768 int *outWord) const {
769 int newWord[MAX_WORD_LENGTH_INTERNAL];
Jean Chalard1059f272011-06-28 20:45:05 +0900770 int depth = 0;
771 int maxFreq = -1;
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900772 const uint8_t *const root = DICT_ROOT;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900773 int stackChildCount[MAX_WORD_LENGTH_INTERNAL];
774 int stackInputIndex[MAX_WORD_LENGTH_INTERNAL];
775 int stackSiblingPos[MAX_WORD_LENGTH_INTERNAL];
Jean Chalard1059f272011-06-28 20:45:05 +0900776
Jean Chalard4c0eca62012-01-16 15:15:53 +0900777 int startPos = 0;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900778 stackChildCount[0] = BinaryFormat::getGroupCountAndForwardPointer(root, &startPos);
779 stackInputIndex[0] = 0;
780 stackSiblingPos[0] = startPos;
Jean Chalard1059f272011-06-28 20:45:05 +0900781 while (depth >= 0) {
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900782 const int charGroupCount = stackChildCount[depth];
783 int pos = stackSiblingPos[depth];
Jean Chalard1059f272011-06-28 20:45:05 +0900784 for (int charGroupIndex = charGroupCount - 1; charGroupIndex >= 0; --charGroupIndex) {
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900785 int inputIndex = stackInputIndex[depth];
Jean Chalard1059f272011-06-28 20:45:05 +0900786 const uint8_t flags = BinaryFormat::getFlagsAndForwardPointer(root, &pos);
787 // Test whether all chars in this group match with the word we are searching for. If so,
Ken Wakasaf2789812012-09-04 12:49:46 +0900788 // we want to traverse its children (or if the inputSize match, evaluate its frequency).
Jean Chalard1059f272011-06-28 20:45:05 +0900789 // Note that this function will output the position regardless, but will only write
790 // into inputIndex if there is a match.
791 const bool isAlike = testCharGroupForContinuedLikeness(flags, root, pos, inWord,
Ken Wakasaf2789812012-09-04 12:49:46 +0900792 inputIndex, inputSize, newWord, &inputIndex, &pos);
Jean Chalardd03e0652012-10-18 07:28:18 +0900793 if (isAlike && (!(BinaryFormat::FLAG_IS_NOT_A_WORD & flags))
794 && (BinaryFormat::FLAG_IS_TERMINAL & flags) && (inputIndex == inputSize)) {
Jean Chalard1059f272011-06-28 20:45:05 +0900795 const int frequency = BinaryFormat::readFrequencyWithoutMovingPointer(root, pos);
796 onTerminalWordLike(frequency, newWord, inputIndex, outWord, &maxFreq);
797 }
798 pos = BinaryFormat::skipFrequency(flags, pos);
799 const int siblingPos = BinaryFormat::skipChildrenPosAndAttributes(root, flags, pos);
800 const int childrenNodePos = BinaryFormat::readChildrenPosition(root, flags, pos);
801 // If we had a match and the word has children, we want to traverse them. We don't have
802 // to traverse words longer than the one we are searching for, since they will not match
Ken Wakasaf2789812012-09-04 12:49:46 +0900803 // anyway, so don't traverse unless inputIndex < inputSize.
804 if (isAlike && (-1 != childrenNodePos) && (inputIndex < inputSize)) {
Jean Chalard1059f272011-06-28 20:45:05 +0900805 // Save position for this depth, to get back to this once children are done
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900806 stackChildCount[depth] = charGroupIndex;
807 stackSiblingPos[depth] = siblingPos;
Jean Chalard1059f272011-06-28 20:45:05 +0900808 // Prepare stack values for next depth
809 ++depth;
810 int childrenPos = childrenNodePos;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900811 stackChildCount[depth] =
Jean Chalard1059f272011-06-28 20:45:05 +0900812 BinaryFormat::getGroupCountAndForwardPointer(root, &childrenPos);
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900813 stackSiblingPos[depth] = childrenPos;
814 stackInputIndex[depth] = inputIndex;
Jean Chalard1059f272011-06-28 20:45:05 +0900815 pos = childrenPos;
816 // Go to the next depth level.
817 ++depth;
818 break;
819 } else {
820 // No match, or no children, or word too long to ever match: go the next sibling.
821 pos = siblingPos;
822 }
823 }
824 --depth;
825 }
826 return maxFreq;
827}
828
Ken Wakasa1e614932012-10-29 18:06:22 +0900829int UnigramDictionary::getFrequency(const int *const inWord, const int length) const {
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900830 const uint8_t *const root = DICT_ROOT;
Jean Chalarde9a86e22012-06-28 21:01:29 +0900831 int pos = BinaryFormat::getTerminalPosition(root, inWord, length,
832 false /* forceLowerCaseSearch */);
Satoshi Kataoka2f854e12012-05-29 15:58:13 +0900833 if (NOT_VALID_WORD == pos) {
834 return NOT_A_PROBABILITY;
835 }
836 const uint8_t flags = BinaryFormat::getFlagsAndForwardPointer(root, &pos);
Jean Chalard72b1c932012-08-31 15:24:39 +0900837 if (flags & (BinaryFormat::FLAG_IS_BLACKLISTED | BinaryFormat::FLAG_IS_NOT_A_WORD)) {
838 // If this is not a word, or if it's a blacklisted entry, it should behave as
839 // having no frequency outside of the suggestion process (where it should be used
840 // for shortcuts).
841 return NOT_A_PROBABILITY;
842 }
Jean Chalard19560502012-07-31 23:45:32 +0900843 const bool hasMultipleChars = (0 != (BinaryFormat::FLAG_HAS_MULTIPLE_CHARS & flags));
Satoshi Kataoka2f854e12012-05-29 15:58:13 +0900844 if (hasMultipleChars) {
845 pos = BinaryFormat::skipOtherCharacters(root, pos);
846 } else {
Ken Wakasaf2789812012-09-04 12:49:46 +0900847 BinaryFormat::getCodePointAndForwardPointer(DICT_ROOT, &pos);
Satoshi Kataoka2f854e12012-05-29 15:58:13 +0900848 }
849 const int unigramFreq = BinaryFormat::readFrequencyWithoutMovingPointer(root, pos);
850 return unigramFreq;
Jean Chalard1059f272011-06-28 20:45:05 +0900851}
852
853// TODO: remove this function.
Ken Wakasa1e614932012-10-29 18:06:22 +0900854int UnigramDictionary::getBigramPosition(int pos, int *word, int offset, int length) const {
Jean Chalard1059f272011-06-28 20:45:05 +0900855 return -1;
856}
857
858// ProcessCurrentNode returns a boolean telling whether to traverse children nodes or not.
859// If the return value is false, then the caller should read in the output "nextSiblingPosition"
860// to find out the address of the next sibling node and pass it to a new call of processCurrentNode.
861// It is worthy to note that when false is returned, the output values other than
862// nextSiblingPosition are undefined.
863// If the return value is true, then the caller must proceed to traverse the children of this
864// node. processCurrentNode will output the information about the children: their count in
865// newCount, their position in newChildrenPosition, the traverseAllNodes flag in
866// newTraverseAllNodes, the match weight into newMatchRate, the input index into newInputIndex, the
867// diffs into newDiffs, the sibling position in nextSiblingPosition, and the output index into
868// newOutputIndex. Please also note the following caveat: processCurrentNode does not know when
869// there aren't any more nodes at this level, it merely returns the address of the first byte after
870// the current node in nextSiblingPosition. Thus, the caller must keep count of the nodes at any
871// given level, as output into newCount when traversing this level's parent.
satok8876b752011-08-04 18:31:57 +0900872inline bool UnigramDictionary::processCurrentNode(const int initialPos,
Jean Chalard8950ce62012-05-07 16:28:30 +0900873 const std::map<int, int> *bigramMap, const uint8_t *bigramFilter, Correction *correction,
874 int *newCount, int *newChildrenPosition, int *nextSiblingPosition,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900875 WordsPriorityQueuePool *queuePool, const int currentWordIndex) const {
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900876 if (DEBUG_DICT) {
satokcfca3c62011-08-10 14:30:10 +0900877 correction->checkState();
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900878 }
Jean Chalard0584f022011-06-30 19:23:16 +0900879 int pos = initialPos;
Jean Chalard0584f022011-06-30 19:23:16 +0900880
Jean Chalard1059f272011-06-28 20:45:05 +0900881 // Flags contain the following information:
882 // - Address type (MASK_GROUP_ADDRESS_TYPE) on two bits:
883 // - FLAG_GROUP_ADDRESS_TYPE_{ONE,TWO,THREE}_BYTES means there are children and their address
884 // is on the specified number of bytes.
885 // - FLAG_GROUP_ADDRESS_TYPE_NOADDRESS means there are no children, and therefore no address.
886 // - FLAG_HAS_MULTIPLE_CHARS: whether this node has multiple char or not.
887 // - FLAG_IS_TERMINAL: whether this node is a terminal or not (it may still have children)
888 // - FLAG_HAS_BIGRAMS: whether this node has bigrams or not
889 const uint8_t flags = BinaryFormat::getFlagsAndForwardPointer(DICT_ROOT, &pos);
Jean Chalard19560502012-07-31 23:45:32 +0900890 const bool hasMultipleChars = (0 != (BinaryFormat::FLAG_HAS_MULTIPLE_CHARS & flags));
891 const bool isTerminalNode = (0 != (BinaryFormat::FLAG_IS_TERMINAL & flags));
satok8876b752011-08-04 18:31:57 +0900892
893 bool needsToInvokeOnTerminal = false;
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900894
Jean Chalard1059f272011-06-28 20:45:05 +0900895 // This gets only ONE character from the stream. Next there will be:
896 // if FLAG_HAS_MULTIPLE CHARS: the other characters of the same node
897 // else if FLAG_IS_TERMINAL: the frequency
898 // else if MASK_GROUP_ADDRESS_TYPE is not NONE: the children address
899 // 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 +0900900 int c = BinaryFormat::getCodePointAndForwardPointer(DICT_ROOT, &pos);
Ken Wakasaf2789812012-09-04 12:49:46 +0900901 assert(NOT_A_CODE_POINT != c);
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900902
Jean Chalard1059f272011-06-28 20:45:05 +0900903 // We are going to loop through each character and make it look like it's a different
904 // node each time. To do that, we will process characters in this node in order until
Ken Wakasaf2789812012-09-04 12:49:46 +0900905 // we find the character terminator. This is signalled by getCodePoint* returning
906 // NOT_A_CODE_POINT.
Jean Chalard1059f272011-06-28 20:45:05 +0900907 // 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 +0900908 // next bytes so we will simulate the NOT_A_CODE_POINT return by testing the flags.
Jean Chalard1059f272011-06-28 20:45:05 +0900909 // This way, each loop run will look like a "virtual node".
910 do {
911 // We prefetch the next char. If 'c' is the last char of this node, we will have
Ken Wakasaf2789812012-09-04 12:49:46 +0900912 // NOT_A_CODE_POINT in the next char. From this we can decide whether this virtual node
Jean Chalard1059f272011-06-28 20:45:05 +0900913 // should behave as a terminal or not and whether we have children.
Ken Wakasa1e614932012-10-29 18:06:22 +0900914 const int nextc = hasMultipleChars
Ken Wakasaf2789812012-09-04 12:49:46 +0900915 ? BinaryFormat::getCodePointAndForwardPointer(DICT_ROOT, &pos) : NOT_A_CODE_POINT;
916 const bool isLastChar = (NOT_A_CODE_POINT == nextc);
Jean Chalard1059f272011-06-28 20:45:05 +0900917 // If there are more chars in this nodes, then this virtual node is not a terminal.
918 // If we are on the last char, this virtual node is a terminal if this node is.
satok8876b752011-08-04 18:31:57 +0900919 const bool isTerminal = isLastChar && isTerminalNode;
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900920
satokcfca3c62011-08-10 14:30:10 +0900921 Correction::CorrectionType stateType = correction->processCharAndCalcState(
satok8876b752011-08-04 18:31:57 +0900922 c, isTerminal);
satokcfca3c62011-08-10 14:30:10 +0900923 if (stateType == Correction::TRAVERSE_ALL_ON_TERMINAL
924 || stateType == Correction::ON_TERMINAL) {
satok8876b752011-08-04 18:31:57 +0900925 needsToInvokeOnTerminal = true;
satokd03317c2011-12-14 21:38:11 +0900926 } else if (stateType == Correction::UNRELATED || correction->needsToPrune()) {
satok8876b752011-08-04 18:31:57 +0900927 // We found that this is an unrelated character, so we should give up traversing
928 // this node and its children entirely.
929 // However we may not be on the last virtual node yet so we skip the remaining
930 // characters in this node, the frequency if it's there, read the next sibling
931 // position to output it, then return false.
932 // We don't have to output other values because we return false, as in
933 // "don't traverse children".
Jean Chalard1059f272011-06-28 20:45:05 +0900934 if (!isLastChar) {
935 pos = BinaryFormat::skipOtherCharacters(DICT_ROOT, pos);
936 }
937 pos = BinaryFormat::skipFrequency(flags, pos);
938 *nextSiblingPosition =
939 BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
940 return false;
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900941 }
942
Jean Chalard1059f272011-06-28 20:45:05 +0900943 // Prepare for the next character. Promote the prefetched char to current char - the loop
944 // will take care of prefetching the next. If we finally found our last char, nextc will
Ken Wakasaf2789812012-09-04 12:49:46 +0900945 // contain NOT_A_CODE_POINT.
Jean Chalard1059f272011-06-28 20:45:05 +0900946 c = nextc;
Ken Wakasaf2789812012-09-04 12:49:46 +0900947 } while (NOT_A_CODE_POINT != c);
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900948
satok8876b752011-08-04 18:31:57 +0900949 if (isTerminalNode) {
satok6ad15fc2012-01-16 16:21:21 +0900950 // The frequency should be here, because we come here only if this is actually
951 // a terminal node, and we are on its last char.
Jean Chalard171d1802012-04-23 18:51:00 +0900952 const int unigramFreq = BinaryFormat::readFrequencyWithoutMovingPointer(DICT_ROOT, pos);
satok6ad15fc2012-01-16 16:21:21 +0900953 const int childrenAddressPos = BinaryFormat::skipFrequency(flags, pos);
954 const int attributesPos = BinaryFormat::skipChildrenPosition(flags, childrenAddressPos);
955 TerminalAttributes terminalAttributes(DICT_ROOT, flags, attributesPos);
Jean Chalard8950ce62012-05-07 16:28:30 +0900956 // bigramMap contains the bigram frequencies indexed by addresses for fast lookup.
957 // bigramFilter is a bloom filter of said frequencies for even faster rejection.
Jean Chalard49ba1352012-05-07 20:14:00 +0900958 const int probability = BinaryFormat::getProbability(initialPos, bigramMap, bigramFilter,
959 unigramFreq);
Jean Chalard171d1802012-04-23 18:51:00 +0900960 onTerminal(probability, terminalAttributes, correction, queuePool, needsToInvokeOnTerminal,
satok8330b482012-01-23 16:52:37 +0900961 currentWordIndex);
Jean Chalard1059f272011-06-28 20:45:05 +0900962
satok8876b752011-08-04 18:31:57 +0900963 // If there are more chars in this node, then this virtual node has children.
964 // If we are on the last char, this virtual node has children if this node has.
965 const bool hasChildren = BinaryFormat::hasChildrenInFlags(flags);
966
967 // This character matched the typed character (enough to traverse the node at least)
968 // so we just evaluated it. Now we should evaluate this virtual node's children - that
969 // is, if it has any. If it has no children, we're done here - so we skip the end of
970 // the node, output the siblings position, and return false "don't traverse children".
971 // Note that !hasChildren implies isLastChar, so we know we don't have to skip any
972 // remaining char in this group for there can't be any.
973 if (!hasChildren) {
974 pos = BinaryFormat::skipFrequency(flags, pos);
975 *nextSiblingPosition =
976 BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
977 return false;
978 }
979
980 // Optimization: Prune out words that are too long compared to how much was typed.
satokcfca3c62011-08-10 14:30:10 +0900981 if (correction->needsToPrune()) {
satok8876b752011-08-04 18:31:57 +0900982 pos = BinaryFormat::skipFrequency(flags, pos);
983 *nextSiblingPosition =
984 BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
satok10266c02011-08-19 22:05:59 +0900985 if (DEBUG_DICT_FULL) {
satok9fb6f472012-01-13 18:01:22 +0900986 AKLOGI("Traversing was pruned.");
satok10266c02011-08-19 22:05:59 +0900987 }
satok8876b752011-08-04 18:31:57 +0900988 return false;
989 }
990 }
Jean Chalard1059f272011-06-28 20:45:05 +0900991
992 // Now we finished processing this node, and we want to traverse children. If there are no
993 // children, we can't come here.
994 assert(BinaryFormat::hasChildrenInFlags(flags));
995
996 // If this node was a terminal it still has the frequency under the pointer (it may have been
997 // read, but not skipped - see readFrequencyWithoutMovingPointer).
998 // Next come the children position, then possibly attributes (attributes are bigrams only for
999 // now, maybe something related to shortcuts in the future).
1000 // Once this is read, we still need to output the number of nodes in the immediate children of
1001 // this node, so we read and output it before returning true, as in "please traverse children".
1002 pos = BinaryFormat::skipFrequency(flags, pos);
1003 int childrenPos = BinaryFormat::readChildrenPosition(DICT_ROOT, flags, pos);
1004 *nextSiblingPosition = BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
1005 *newCount = BinaryFormat::getGroupCountAndForwardPointer(DICT_ROOT, &childrenPos);
1006 *newChildrenPosition = childrenPos;
1007 return true;
Jean Chalard85a1d1e2011-06-21 22:23:21 +09001008}
satok30088252010-12-01 21:22:15 +09001009} // namespace latinime