blob: 820f9ab121b429d85c0417d07a8f87e47cd08222 [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
Ken Wakasa2c2f3a92012-11-02 18:29:03 +090062static void addWord(int *word, int length, int frequency, WordsPriorityQueue *queue, int type) {
Jean Chalard926ef062012-08-10 13:14:45 +090063 queue->push(frequency, word, length, type);
satok1147c7b2011-12-14 15:04:58 +090064}
65
Jean Chalardd3043382012-03-21 18:38:25 +090066// Return the replacement code point for a digraph, or 0 if none.
67int UnigramDictionary::getDigraphReplacement(const int *codes, const int i, const int codesSize,
Ken Wakasa0bbb9172012-07-25 17:51:43 +090068 const digraph_t *const digraphs, const unsigned int digraphsSize) const {
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090069
70 // There can't be a digraph if we don't have at least 2 characters to examine
71 if (i + 2 > codesSize) return false;
72
73 // Search for the first char of some digraph
74 int lastDigraphIndex = -1;
satok9df4a452012-03-23 16:05:18 +090075 const int thisChar = codes[i];
Jean Chalard6c300612012-03-06 19:54:03 +090076 for (lastDigraphIndex = digraphsSize - 1; lastDigraphIndex >= 0; --lastDigraphIndex) {
77 if (thisChar == digraphs[lastDigraphIndex].first) break;
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090078 }
79 // No match: return early
Jean Chalardd3043382012-03-21 18:38:25 +090080 if (lastDigraphIndex < 0) return 0;
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090081
82 // It's an interesting digraph if the second char matches too.
satok9df4a452012-03-23 16:05:18 +090083 if (digraphs[lastDigraphIndex].second == codes[i + 1]) {
Jean Chalardd3043382012-03-21 18:38:25 +090084 return digraphs[lastDigraphIndex].replacement;
85 } else {
86 return 0;
87 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090088}
89
90// Mostly the same arguments as the non-recursive version, except:
91// codes is the original value. It points to the start of the work buffer, and gets passed as is.
92// codesSize is the size of the user input (thus, it is the size of codesSrc).
93// codesDest is the current point in the work buffer.
94// codesSrc is the current point in the user-input, original, content-unmodified buffer.
95// codesRemain is the remaining size in codesSrc.
satok1d7eaf82011-07-13 10:32:02 +090096void UnigramDictionary::getWordWithDigraphSuggestionsRec(ProximityInfo *proximityInfo,
satok1147c7b2011-12-14 15:04:58 +090097 const int *xcoordinates, const int *ycoordinates, const int *codesBuffer,
satok219a5142012-03-08 11:53:18 +090098 int *xCoordinatesBuffer, int *yCoordinatesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +090099 const int codesBufferSize, const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900100 const bool useFullEditDistance, const int *codesSrc,
satok1147c7b2011-12-14 15:04:58 +0900101 const int codesRemain, const int currentDepth, int *codesDest, Correction *correction,
Jean Chalard6c300612012-03-06 19:54:03 +0900102 WordsPriorityQueuePool *queuePool,
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900103 const digraph_t *const digraphs, const unsigned int digraphsSize) const {
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900104 assert(sizeof(codesDest[0]) == sizeof(codesSrc[0]));
105 assert(sizeof(xCoordinatesBuffer[0]) == sizeof(xcoordinates[0]));
106 assert(sizeof(yCoordinatesBuffer[0]) == sizeof(ycoordinates[0]));
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900107
Ken Wakasaf2789812012-09-04 12:49:46 +0900108 const int startIndex = static_cast<int>(codesDest - codesBuffer);
Jean Chalard6c300612012-03-06 19:54:03 +0900109 if (currentDepth < MAX_DIGRAPH_SEARCH_DEPTH) {
Jean Chalarda787dba2011-03-04 12:17:48 +0900110 for (int i = 0; i < codesRemain; ++i) {
satok219a5142012-03-08 11:53:18 +0900111 xCoordinatesBuffer[startIndex + i] = xcoordinates[codesBufferSize - codesRemain + i];
112 yCoordinatesBuffer[startIndex + i] = ycoordinates[codesBufferSize - codesRemain + i];
Jean Chalardd3043382012-03-21 18:38:25 +0900113 const int replacementCodePoint =
114 getDigraphReplacement(codesSrc, i, codesRemain, digraphs, digraphsSize);
115 if (0 != replacementCodePoint) {
Jean Chalarda787dba2011-03-04 12:17:48 +0900116 // Found a digraph. We will try both spellings. eg. the word is "pruefen"
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900117
Jean Chalardd3043382012-03-21 18:38:25 +0900118 // Copy the word up to the first char of the digraph, including proximity chars,
119 // and overwrite the primary code with the replacement code point. Then, continue
120 // processing on the remaining part of the word, skipping the second char of the
121 // digraph.
122 // In our example, copy "pru", replace "u" with the version with the diaeresis and
123 // continue running on "fen".
Jean Chalarda787dba2011-03-04 12:17:48 +0900124 // Make i the index of the second char of the digraph for simplicity. Forgetting
125 // to do that results in an infinite recursion so take care!
126 ++i;
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900127 memcpy(codesDest, codesSrc, i * sizeof(codesDest[0]));
128 codesDest[i - 1] = replacementCodePoint;
Jean Chalarda787dba2011-03-04 12:17:48 +0900129 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates,
Jean Chalard338d3ec2012-04-06 19:28:34 +0900130 codesBuffer, xCoordinatesBuffer, yCoordinatesBuffer, codesBufferSize,
Jean Chalard8950ce62012-05-07 16:28:30 +0900131 bigramMap, bigramFilter, useFullEditDistance, codesSrc + i + 1,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900132 codesRemain - i - 1, currentDepth + 1, codesDest + i, correction,
Jean Chalard6c300612012-03-06 19:54:03 +0900133 queuePool, digraphs, digraphsSize);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900134
Jean Chalarda787dba2011-03-04 12:17:48 +0900135 // Copy the second char of the digraph in place, then continue processing on
136 // the remaining part of the word.
137 // In our example, after "pru" in the buffer copy the "e", and continue on "fen"
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900138 memcpy(codesDest + i, codesSrc + i, sizeof(codesDest[0]));
Jean Chalarda787dba2011-03-04 12:17:48 +0900139 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates,
Jean Chalard338d3ec2012-04-06 19:28:34 +0900140 codesBuffer, xCoordinatesBuffer, yCoordinatesBuffer, codesBufferSize,
Jean Chalard8950ce62012-05-07 16:28:30 +0900141 bigramMap, bigramFilter, useFullEditDistance, codesSrc + i, codesRemain - i,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900142 currentDepth + 1, codesDest + i, correction, queuePool, digraphs,
143 digraphsSize);
Jean Chalarda787dba2011-03-04 12:17:48 +0900144 return;
145 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900146 }
147 }
148
149 // If we come here, we hit the end of the word: let's check it against the dictionary.
150 // In our example, we'll come here once for "prufen" and then once for "pruefen".
151 // If the word contains several digraphs, we'll come it for the product of them.
152 // eg. if the word is "ueberpruefen" we'll test, in order, against
153 // "uberprufen", "uberpruefen", "ueberprufen", "ueberpruefen".
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900154 const unsigned int remainingBytes = sizeof(codesDest[0]) * codesRemain;
satok219a5142012-03-08 11:53:18 +0900155 if (0 != remainingBytes) {
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900156 memcpy(codesDest, codesSrc, remainingBytes);
satok219a5142012-03-08 11:53:18 +0900157 memcpy(&xCoordinatesBuffer[startIndex], &xcoordinates[codesBufferSize - codesRemain],
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900158 sizeof(xCoordinatesBuffer[0]) * codesRemain);
satok219a5142012-03-08 11:53:18 +0900159 memcpy(&yCoordinatesBuffer[startIndex], &ycoordinates[codesBufferSize - codesRemain],
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900160 sizeof(yCoordinatesBuffer[0]) * codesRemain);
satok219a5142012-03-08 11:53:18 +0900161 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900162
satok219a5142012-03-08 11:53:18 +0900163 getWordSuggestions(proximityInfo, xCoordinatesBuffer, yCoordinatesBuffer, codesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +0900164 startIndex + codesRemain, bigramMap, bigramFilter, useFullEditDistance, correction,
satoka7e5a5a2011-12-15 16:49:12 +0900165 queuePool);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900166}
167
Jean Chalard8950ce62012-05-07 16:28:30 +0900168// bigramMap contains the association <bigram address> -> <bigram frequency>
169// bigramFilter is a bloom filter for fast rejection: see functions setInFilter and isInFilter
170// in bigram_dictionary.cpp
Ken Wakasaf2789812012-09-04 12:49:46 +0900171int UnigramDictionary::getSuggestions(ProximityInfo *proximityInfo, const int *xcoordinates,
Jean Chalard338d3ec2012-04-06 19:28:34 +0900172 const int *ycoordinates, const int *codes, const int codesSize,
Jean Chalard8950ce62012-05-07 16:28:30 +0900173 const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Ken Wakasa1e614932012-10-29 18:06:22 +0900174 const bool useFullEditDistance, int *outWords, int *frequencies, int *outputTypes) const {
satokb1ed1d42012-06-14 16:35:23 -0700175 WordsPriorityQueuePool queuePool(MAX_WORDS, SUB_QUEUE_MAX_WORDS, MAX_WORD_LENGTH);
176 queuePool.clearAll();
satok1bc038c2012-06-14 11:25:50 -0700177 Correction masterCorrection;
178 masterCorrection.resetCorrection();
Jean Chalardaa8df592012-04-06 18:54:20 +0900179 if (BinaryFormat::REQUIRES_GERMAN_UMLAUT_PROCESSING & FLAGS)
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900180 { // Incrementally tune the word and try all possibilities
satok9df4a452012-03-23 16:05:18 +0900181 int codesBuffer[getCodesBufferSize(codes, codesSize)];
satok219a5142012-03-08 11:53:18 +0900182 int xCoordinatesBuffer[codesSize];
183 int yCoordinatesBuffer[codesSize];
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900184 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates, codesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +0900185 xCoordinatesBuffer, yCoordinatesBuffer, codesSize, bigramMap, bigramFilter,
satok1bc038c2012-06-14 11:25:50 -0700186 useFullEditDistance, codes, codesSize, 0, codesBuffer, &masterCorrection,
Ken Wakasab02ee3d2012-10-08 11:46:14 +0900187 &queuePool, GERMAN_UMLAUT_DIGRAPHS, NELEMS(GERMAN_UMLAUT_DIGRAPHS));
Jean Chalardaa8df592012-04-06 18:54:20 +0900188 } else if (BinaryFormat::REQUIRES_FRENCH_LIGATURES_PROCESSING & FLAGS) {
satokacb6c542012-03-23 20:58:18 +0900189 int codesBuffer[getCodesBufferSize(codes, codesSize)];
Jean Chalardcc78d032012-03-23 16:48:49 +0900190 int xCoordinatesBuffer[codesSize];
191 int yCoordinatesBuffer[codesSize];
192 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates, codesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +0900193 xCoordinatesBuffer, yCoordinatesBuffer, codesSize, bigramMap, bigramFilter,
satok1bc038c2012-06-14 11:25:50 -0700194 useFullEditDistance, codes, codesSize, 0, codesBuffer, &masterCorrection,
Ken Wakasab02ee3d2012-10-08 11:46:14 +0900195 &queuePool, FRENCH_LIGATURES_DIGRAPHS, NELEMS(FRENCH_LIGATURES_DIGRAPHS));
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900196 } else { // Normal processing
Jean Chalard338d3ec2012-04-06 19:28:34 +0900197 getWordSuggestions(proximityInfo, xcoordinates, ycoordinates, codes, codesSize,
satokb1ed1d42012-06-14 16:35:23 -0700198 bigramMap, bigramFilter, useFullEditDistance, &masterCorrection, &queuePool);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900199 }
200
satok817e5172011-03-04 06:06:45 -0800201 PROF_START(20);
satok8330b482012-01-23 16:52:37 +0900202 if (DEBUG_DICT) {
satokb1ed1d42012-06-14 16:35:23 -0700203 float ns = queuePool.getMasterQueue()->getHighestNormalizedScore(
satok1bc038c2012-06-14 11:25:50 -0700204 masterCorrection.getPrimaryInputWord(), codesSize, 0, 0, 0);
satok8330b482012-01-23 16:52:37 +0900205 ns += 0;
206 AKLOGI("Max normalized score = %f", ns);
207 }
satoka7e5a5a2011-12-15 16:49:12 +0900208 const int suggestedWordsCount =
Jean Chalard926ef062012-08-10 13:14:45 +0900209 queuePool.getMasterQueue()->outputSuggestions(masterCorrection.getPrimaryInputWord(),
210 codesSize, frequencies, outWords, outputTypes);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900211
212 if (DEBUG_DICT) {
satokb1ed1d42012-06-14 16:35:23 -0700213 float ns = queuePool.getMasterQueue()->getHighestNormalizedScore(
satok1bc038c2012-06-14 11:25:50 -0700214 masterCorrection.getPrimaryInputWord(), codesSize, 0, 0, 0);
satok8330b482012-01-23 16:52:37 +0900215 ns += 0;
satok9fb6f472012-01-13 18:01:22 +0900216 AKLOGI("Returning %d words", suggestedWordsCount);
Jean Chalard980d6b62011-06-30 17:02:23 +0900217 /// Print the returned words
218 for (int j = 0; j < suggestedWordsCount; ++j) {
Ken Wakasa1e614932012-10-29 18:06:22 +0900219 int *w = outWords + j * MAX_WORD_LENGTH;
Jean Chalard980d6b62011-06-30 17:02:23 +0900220 char s[MAX_WORD_LENGTH];
221 for (int i = 0; i <= MAX_WORD_LENGTH; i++) s[i] = w[i];
Ken Wakasa7914e902012-09-07 08:55:16 +0900222 (void)s; // To suppress compiler warning
satok9fb6f472012-01-13 18:01:22 +0900223 AKLOGI("%s %i", s, frequencies[j]);
Jean Chalard980d6b62011-06-30 17:02:23 +0900224 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900225 }
satok817e5172011-03-04 06:06:45 -0800226 PROF_END(20);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900227 PROF_CLOSE;
228 return suggestedWordsCount;
229}
230
Ken Wakasa1e614932012-10-29 18:06:22 +0900231void UnigramDictionary::getWordSuggestions(ProximityInfo *proximityInfo, const int *xcoordinates,
232 const int *ycoordinates, const int *codes, const int inputSize,
233 const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
234 const bool useFullEditDistance, Correction *correction, WordsPriorityQueuePool *queuePool)
235 const {
satok61e2f852011-01-05 14:13:07 +0900236 PROF_OPEN;
237 PROF_START(0);
satok61e2f852011-01-05 14:13:07 +0900238 PROF_END(0);
satok30088252010-12-01 21:22:15 +0900239
satok61e2f852011-01-05 14:13:07 +0900240 PROF_START(1);
Jean Chalard8950ce62012-05-07 16:28:30 +0900241 getOneWordSuggestions(proximityInfo, xcoordinates, ycoordinates, codes, bigramMap, bigramFilter,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900242 useFullEditDistance, inputSize, correction, queuePool);
satok61e2f852011-01-05 14:13:07 +0900243 PROF_END(1);
244
245 PROF_START(2);
satok10266c02011-08-19 22:05:59 +0900246 // Note: This line is intentionally left blank
satok61e2f852011-01-05 14:13:07 +0900247 PROF_END(2);
satokcdbbea72010-12-08 16:04:16 +0900248
satok61e2f852011-01-05 14:13:07 +0900249 PROF_START(3);
satok10266c02011-08-19 22:05:59 +0900250 // Note: This line is intentionally left blank
satok61e2f852011-01-05 14:13:07 +0900251 PROF_END(3);
satok30088252010-12-01 21:22:15 +0900252
satok61e2f852011-01-05 14:13:07 +0900253 PROF_START(4);
satok8330b482012-01-23 16:52:37 +0900254 bool hasAutoCorrectionCandidate = false;
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900255 WordsPriorityQueue *masterQueue = queuePool->getMasterQueue();
satok8330b482012-01-23 16:52:37 +0900256 if (masterQueue->size() > 0) {
satok0028ed32012-05-16 20:42:12 +0900257 float nsForMaster = masterQueue->getHighestNormalizedScore(
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900258 correction->getPrimaryInputWord(), inputSize, 0, 0, 0);
satok8330b482012-01-23 16:52:37 +0900259 hasAutoCorrectionCandidate = (nsForMaster > START_TWO_WORDS_CORRECTION_THRESHOLD);
260 }
satok61e2f852011-01-05 14:13:07 +0900261 PROF_END(4);
satoka3d78f62010-12-09 22:08:33 +0900262
satok61e2f852011-01-05 14:13:07 +0900263 PROF_START(5);
satok99557162012-01-26 22:49:13 +0900264 // Multiple word suggestions
265 if (SUGGEST_MULTIPLE_WORDS
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900266 && inputSize >= MIN_USER_TYPED_LENGTH_FOR_MULTIPLE_WORD_SUGGESTION) {
satoka85f4922012-01-30 18:18:30 +0900267 getSplitMultipleWordsSuggestions(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900268 useFullEditDistance, inputSize, correction, queuePool,
satok1f6b52e2012-01-30 13:53:58 +0900269 hasAutoCorrectionCandidate);
satok662fe692010-12-08 17:05:39 +0900270 }
satok61e2f852011-01-05 14:13:07 +0900271 PROF_END(5);
satok817e5172011-03-04 06:06:45 -0800272
273 PROF_START(6);
satok99557162012-01-26 22:49:13 +0900274 // Note: This line is intentionally left blank
satok817e5172011-03-04 06:06:45 -0800275 PROF_END(6);
satok99557162012-01-26 22:49:13 +0900276
satok29dc8062012-01-17 15:59:15 +0900277 if (DEBUG_DICT) {
satok6ad15fc2012-01-16 16:21:21 +0900278 queuePool->dumpSubQueue1TopSuggestions();
satok29dc8062012-01-17 15:59:15 +0900279 for (int i = 0; i < SUB_QUEUE_MAX_COUNT; ++i) {
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900280 WordsPriorityQueue *queue = queuePool->getSubQueue(FIRST_WORD_INDEX, i);
satok29dc8062012-01-17 15:59:15 +0900281 if (queue->size() > 0) {
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900282 WordsPriorityQueue::SuggestedWord *sw = queue->top();
satok29dc8062012-01-17 15:59:15 +0900283 const int score = sw->mScore;
Ken Wakasa1e614932012-10-29 18:06:22 +0900284 const int *word = sw->mWord;
satok29dc8062012-01-17 15:59:15 +0900285 const int wordLength = sw->mWordLength;
satok0028ed32012-05-16 20:42:12 +0900286 float ns = Correction::RankingAlgorithm::calcNormalizedScore(
Satoshi Kataoka4a3db702012-06-08 15:29:44 +0900287 correction->getPrimaryInputWord(), i, word, wordLength, score);
satok29dc8062012-01-17 15:59:15 +0900288 ns += 0;
289 AKLOGI("--- TOP SUB WORDS for %d --- %d %f [%d]", i, score, ns,
satok54af64a2012-01-17 15:58:23 +0900290 (ns > TWO_WORDS_CORRECTION_WITH_OTHER_ERROR_THRESHOLD));
Satoshi Kataoka4a3db702012-06-08 15:29:44 +0900291 DUMP_WORD(correction->getPrimaryInputWord(), i);
satok29dc8062012-01-17 15:59:15 +0900292 DUMP_WORD(word, wordLength);
293 }
294 }
satok6ad15fc2012-01-16 16:21:21 +0900295 }
satok30088252010-12-01 21:22:15 +0900296}
297
Yusuke Nojima258bfe62011-09-28 12:59:43 +0900298void UnigramDictionary::initSuggestions(ProximityInfo *proximityInfo, const int *xCoordinates,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900299 const int *yCoordinates, const int *codes, const int inputSize,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900300 Correction *correction) const {
Ken Wakasade3070a2011-03-19 09:16:42 +0900301 if (DEBUG_DICT) {
satok9fb6f472012-01-13 18:01:22 +0900302 AKLOGI("initSuggest");
Ken Wakasa1e614932012-10-29 18:06:22 +0900303 DUMP_WORD(codes, inputSize);
Ken Wakasade3070a2011-03-19 09:16:42 +0900304 }
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900305 correction->initInputParams(proximityInfo, codes, inputSize, xCoordinates, yCoordinates);
306 const int maxDepth = min(inputSize * MAX_DEPTH_MULTIPLIER, MAX_WORD_LENGTH);
307 correction->initCorrection(proximityInfo, inputSize, maxDepth);
satok30088252010-12-01 21:22:15 +0900308}
309
satok744dab62011-12-15 22:29:05 +0900310void UnigramDictionary::getOneWordSuggestions(ProximityInfo *proximityInfo,
311 const int *xcoordinates, const int *ycoordinates, const int *codes,
Jean Chalard8950ce62012-05-07 16:28:30 +0900312 const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900313 const bool useFullEditDistance, const int inputSize,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900314 Correction *correction, WordsPriorityQueuePool *queuePool) const {
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900315 initSuggestions(proximityInfo, xcoordinates, ycoordinates, codes, inputSize, correction);
316 getSuggestionCandidates(useFullEditDistance, inputSize, bigramMap, bigramFilter, correction,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900317 queuePool, true /* doAutoCompletion */, DEFAULT_MAX_ERRORS, FIRST_WORD_INDEX);
satok744dab62011-12-15 22:29:05 +0900318}
319
satok1147c7b2011-12-14 15:04:58 +0900320void UnigramDictionary::getSuggestionCandidates(const bool useFullEditDistance,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900321 const int inputSize, const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900322 Correction *correction, WordsPriorityQueuePool *queuePool,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900323 const bool doAutoCompletion, const int maxErrors, const int currentWordIndex) const {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900324 uint8_t totalTraverseCount = correction->pushAndGetTotalTraverseCount();
325 if (DEBUG_DICT) {
326 AKLOGI("Traverse count %d", totalTraverseCount);
327 }
328 if (totalTraverseCount > MULTIPLE_WORDS_SUGGESTION_MAX_TOTAL_TRAVERSE_COUNT) {
329 if (DEBUG_DICT) {
330 AKLOGI("Abort traversing %d", totalTraverseCount);
331 }
332 return;
333 }
satok10266c02011-08-19 22:05:59 +0900334 // TODO: Remove setCorrectionParams
satok1147c7b2011-12-14 15:04:58 +0900335 correction->setCorrectionParams(0, 0, 0,
satokd03317c2011-12-14 21:38:11 +0900336 -1 /* spaceProximityPos */, -1 /* missingSpacePos */, useFullEditDistance,
satok1a6da632011-12-16 23:15:06 +0900337 doAutoCompletion, maxErrors);
satok662fe692010-12-08 17:05:39 +0900338 int rootPosition = ROOT_POS;
Jean Chalard980d6b62011-06-30 17:02:23 +0900339 // Get the number of children of root, then increment the position
Jean Chalard6d419812012-01-16 15:19:47 +0900340 int childCount = BinaryFormat::getGroupCountAndForwardPointer(DICT_ROOT, &rootPosition);
satok208268d2011-08-10 15:44:08 +0900341 int outputIndex = 0;
satokd2997922010-12-07 13:08:39 +0900342
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900343 correction->initCorrectionState(rootPosition, childCount, (inputSize <= 0));
satokd2997922010-12-07 13:08:39 +0900344
satok662fe692010-12-08 17:05:39 +0900345 // Depth first search
satok208268d2011-08-10 15:44:08 +0900346 while (outputIndex >= 0) {
satok1147c7b2011-12-14 15:04:58 +0900347 if (correction->initProcessState(outputIndex)) {
348 int siblingPos = correction->getTreeSiblingPos(outputIndex);
satokd2997922010-12-07 13:08:39 +0900349 int firstChildPos;
satok0f6c8e82011-08-03 02:19:44 +0900350
satok4e4e74e2011-08-03 23:27:32 +0900351 const bool needsToTraverseChildrenNodes = processCurrentNode(siblingPos,
Jean Chalard8950ce62012-05-07 16:28:30 +0900352 bigramMap, bigramFilter, correction, &childCount, &firstChildPos, &siblingPos,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900353 queuePool, currentWordIndex);
satok662fe692010-12-08 17:05:39 +0900354 // Update next sibling pos
satok1147c7b2011-12-14 15:04:58 +0900355 correction->setTreeSiblingPos(outputIndex, siblingPos);
satok208268d2011-08-10 15:44:08 +0900356
satokd2997922010-12-07 13:08:39 +0900357 if (needsToTraverseChildrenNodes) {
358 // Goes to child node
satok1147c7b2011-12-14 15:04:58 +0900359 outputIndex = correction->goDownTree(outputIndex, childCount, firstChildPos);
satokd2997922010-12-07 13:08:39 +0900360 }
361 } else {
satokcdbbea72010-12-08 16:04:16 +0900362 // Goes to parent sibling node
satok1147c7b2011-12-14 15:04:58 +0900363 outputIndex = correction->getTreeParentIndex(outputIndex);
satokd2997922010-12-07 13:08:39 +0900364 }
365 }
366}
367
Jean Chalard171d1802012-04-23 18:51:00 +0900368inline void UnigramDictionary::onTerminal(const int probability,
Jean Chalardcf9dbbd2011-12-26 15:16:59 +0900369 const TerminalAttributes& terminalAttributes, Correction *correction,
satok8330b482012-01-23 16:52:37 +0900370 WordsPriorityQueuePool *queuePool, const bool addToMasterQueue,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900371 const int currentWordIndex) const {
satok6ad15fc2012-01-16 16:21:21 +0900372 const int inputIndex = correction->getInputIndex();
373 const bool addToSubQueue = inputIndex < SUB_QUEUE_MAX_COUNT;
satok54af64a2012-01-17 15:58:23 +0900374
satok8876b752011-08-04 18:31:57 +0900375 int wordLength;
Ken Wakasa1e614932012-10-29 18:06:22 +0900376 int *wordPointer;
satok54af64a2012-01-17 15:58:23 +0900377
satok1f6b52e2012-01-30 13:53:58 +0900378 if ((currentWordIndex == FIRST_WORD_INDEX) && addToMasterQueue) {
satok54af64a2012-01-17 15:58:23 +0900379 WordsPriorityQueue *masterQueue = queuePool->getMasterQueue();
Jean Chalard171d1802012-04-23 18:51:00 +0900380 const int finalProbability =
381 correction->getFinalProbability(probability, &wordPointer, &wordLength);
satok54af64a2012-01-17 15:58:23 +0900382
Jean Chalard72b1c932012-08-31 15:24:39 +0900383 if (0 != finalProbability && !terminalAttributes.isBlacklistedOrNotAWord()) {
Jean Chalard8af8c152012-08-17 09:37:39 +0900384 // If the probability is 0, we don't want to add this word. However we still
385 // want to add its shortcuts (including a possible whitelist entry) if any.
Jean Chalard72b1c932012-08-31 15:24:39 +0900386 // Furthermore, if this is not a word (shortcut only for example) or a blacklisted
387 // entry then we never want to suggest this.
Jean Chalard8af8c152012-08-17 09:37:39 +0900388 addWord(wordPointer, wordLength, finalProbability, masterQueue,
389 Dictionary::KIND_CORRECTION);
390 }
391
392 const int shortcutProbability = finalProbability > 0 ? finalProbability - 1 : 0;
393 // Please note that the shortcut candidates will be added to the master queue only.
394 TerminalAttributes::ShortcutIterator iterator =
395 terminalAttributes.getShortcutIterator();
396 while (iterator.hasNextShortcutTarget()) {
397 // TODO: addWord only supports weak ordering, meaning we have no means
398 // to control the order of the shortcuts relative to one another or to the word.
399 // We need to either modulate the probability of each shortcut according
400 // to its own shortcut probability or to make the queue
401 // so that the insert order is protected inside the queue for words
402 // with the same score. For the moment we use -1 to make sure the shortcut will
403 // never be in front of the word.
Ken Wakasa1e614932012-10-29 18:06:22 +0900404 int shortcutTarget[MAX_WORD_LENGTH_INTERNAL];
Jean Chalard8af8c152012-08-17 09:37:39 +0900405 int shortcutFrequency;
406 const int shortcutTargetStringLength = iterator.getNextShortcutTarget(
407 MAX_WORD_LENGTH_INTERNAL, shortcutTarget, &shortcutFrequency);
408 int shortcutScore;
409 int kind;
410 if (shortcutFrequency == BinaryFormat::WHITELIST_SHORTCUT_FREQUENCY
411 && correction->sameAsTyped()) {
412 shortcutScore = S_INT_MAX;
413 kind = Dictionary::KIND_WHITELIST;
414 } else {
415 shortcutScore = shortcutProbability;
416 kind = Dictionary::KIND_CORRECTION;
satok6ad15fc2012-01-16 16:21:21 +0900417 }
Jean Chalard8af8c152012-08-17 09:37:39 +0900418 addWord(shortcutTarget, shortcutTargetStringLength, shortcutScore,
419 masterQueue, kind);
Jean Chalardcf9dbbd2011-12-26 15:16:59 +0900420 }
satok54af64a2012-01-17 15:58:23 +0900421 }
satok6ad15fc2012-01-16 16:21:21 +0900422
satok54af64a2012-01-17 15:58:23 +0900423 // We only allow two words + other error correction for words with SUB_QUEUE_MIN_WORD_LENGTH
424 // or more length.
425 if (inputIndex >= SUB_QUEUE_MIN_WORD_LENGTH && addToSubQueue) {
satok8330b482012-01-23 16:52:37 +0900426 WordsPriorityQueue *subQueue;
satok7409d152012-01-26 16:13:25 +0900427 subQueue = queuePool->getSubQueue(currentWordIndex, inputIndex);
428 if (!subQueue) {
satok8330b482012-01-23 16:52:37 +0900429 return;
430 }
Jean Chalard171d1802012-04-23 18:51:00 +0900431 const int finalProbability = correction->getFinalProbabilityForSubQueue(
432 probability, &wordPointer, &wordLength, inputIndex);
Jean Chalard926ef062012-08-10 13:14:45 +0900433 addWord(wordPointer, wordLength, finalProbability, subQueue, Dictionary::KIND_CORRECTION);
Jean Chalardca5ef282011-06-17 15:36:26 +0900434 }
435}
436
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900437int UnigramDictionary::getSubStringSuggestion(
satok7409d152012-01-26 16:13:25 +0900438 ProximityInfo *proximityInfo, const int *xcoordinates, const int *ycoordinates,
satok3c09bb12012-01-26 18:36:19 +0900439 const int *codes, const bool useFullEditDistance, Correction *correction,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900440 WordsPriorityQueuePool *queuePool, const int inputSize,
satok3c09bb12012-01-26 18:36:19 +0900441 const bool hasAutoCorrectionCandidate, const int currentWordIndex,
442 const int inputWordStartPos, const int inputWordLength,
satok99557162012-01-26 22:49:13 +0900443 const int outputWordStartPos, const bool isSpaceProximity, int *freqArray,
Ken Wakasa1e614932012-10-29 18:06:22 +0900444 int *wordLengthArray, int *outputWord, int *outputWordLength) const {
Satoshi Kataoka67e3cc82012-05-31 15:04:58 +0900445 if (inputWordLength > MULTIPLE_WORDS_SUGGESTION_MAX_WORD_LENGTH) {
446 return FLAG_MULTIPLE_SUGGEST_ABORT;
447 }
448
449 /////////////////////////////////////////////
450 // safety net for multiple word suggestion //
451 // TODO: Remove this safety net //
452 /////////////////////////////////////////////
453 int smallWordCount = 0;
454 int singleLetterWordCount = 0;
455 if (inputWordLength == 1) {
456 ++singleLetterWordCount;
457 }
458 if (inputWordLength <= 2) {
459 // small word == single letter or 2-letter word
460 ++smallWordCount;
461 }
462 for (int i = 0; i < currentWordIndex; ++i) {
463 const int length = wordLengthArray[i];
464 if (length == 1) {
465 ++singleLetterWordCount;
466 // Safety net to avoid suggesting sequential single letter words
467 if (i < (currentWordIndex - 1)) {
468 if (wordLengthArray[i + 1] == 1) {
469 return FLAG_MULTIPLE_SUGGEST_ABORT;
470 }
471 } else if (inputWordLength == 1) {
472 return FLAG_MULTIPLE_SUGGEST_ABORT;
473 }
474 }
475 if (length <= 2) {
476 ++smallWordCount;
477 }
478 // Safety net to avoid suggesting multiple words with many (4 or more, for now) small words
479 if (singleLetterWordCount >= 3 || smallWordCount >= 4) {
480 return FLAG_MULTIPLE_SUGGEST_ABORT;
481 }
482 }
483 //////////////////////////////////////////////
484 // TODO: Remove the safety net above //
485 //////////////////////////////////////////////
486
Ken Wakasa1e614932012-10-29 18:06:22 +0900487 int *tempOutputWord = 0;
satok1f6b52e2012-01-30 13:53:58 +0900488 int nextWordLength = 0;
satok99557162012-01-26 22:49:13 +0900489 // TODO: Optimize init suggestion
490 initSuggestions(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900491 inputSize, correction);
satok99557162012-01-26 22:49:13 +0900492
Ken Wakasa1e614932012-10-29 18:06:22 +0900493 int word[MAX_WORD_LENGTH_INTERNAL];
satok3c09bb12012-01-26 18:36:19 +0900494 int freq = getMostFrequentWordLike(
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900495 inputWordStartPos, inputWordLength, correction, word);
satok3c09bb12012-01-26 18:36:19 +0900496 if (freq > 0) {
satok1f6b52e2012-01-30 13:53:58 +0900497 nextWordLength = inputWordLength;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900498 tempOutputWord = word;
satok3c09bb12012-01-26 18:36:19 +0900499 } else if (!hasAutoCorrectionCandidate) {
500 if (inputWordStartPos > 0) {
501 const int offset = inputWordStartPos;
502 initSuggestions(proximityInfo, &xcoordinates[offset], &ycoordinates[offset],
satok9df4a452012-03-23 16:05:18 +0900503 codes + offset, inputWordLength, correction);
satok3c09bb12012-01-26 18:36:19 +0900504 queuePool->clearSubQueue(currentWordIndex);
Jean Chalard4d9b2022012-04-23 19:25:28 +0900505 // TODO: pass the bigram list for substring suggestion
506 getSuggestionCandidates(useFullEditDistance, inputWordLength,
Jean Chalard8950ce62012-05-07 16:28:30 +0900507 0 /* bigramMap */, 0 /* bigramFilter */, correction, queuePool,
508 false /* doAutoCompletion */, MAX_ERRORS_FOR_TWO_WORDS, currentWordIndex);
satok3c09bb12012-01-26 18:36:19 +0900509 if (DEBUG_DICT) {
satok1f6b52e2012-01-30 13:53:58 +0900510 if (currentWordIndex < MULTIPLE_WORDS_SUGGESTION_MAX_WORDS) {
satok3c09bb12012-01-26 18:36:19 +0900511 AKLOGI("Dump word candidates(%d) %d", currentWordIndex, inputWordLength);
512 for (int i = 0; i < SUB_QUEUE_MAX_COUNT; ++i) {
513 queuePool->getSubQueue(currentWordIndex, i)->dumpTopWord();
514 }
515 }
516 }
517 }
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900518 WordsPriorityQueue *queue = queuePool->getSubQueue(currentWordIndex, inputWordLength);
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900519 // TODO: Return the correct value depending on doAutoCompletion
520 if (!queue || queue->size() <= 0) {
521 return FLAG_MULTIPLE_SUGGEST_ABORT;
satok3c09bb12012-01-26 18:36:19 +0900522 }
523 int score = 0;
satok0028ed32012-05-16 20:42:12 +0900524 const float ns = queue->getHighestNormalizedScore(
Satoshi Kataoka4a3db702012-06-08 15:29:44 +0900525 correction->getPrimaryInputWord(), inputWordLength,
satok1f6b52e2012-01-30 13:53:58 +0900526 &tempOutputWord, &score, &nextWordLength);
satok3c09bb12012-01-26 18:36:19 +0900527 if (DEBUG_DICT) {
528 AKLOGI("NS(%d) = %f, Score = %d", currentWordIndex, ns, score);
529 }
530 // Two words correction won't be done if the score of the first word doesn't exceed the
531 // threshold.
532 if (ns < TWO_WORDS_CORRECTION_WITH_OTHER_ERROR_THRESHOLD
satok1f6b52e2012-01-30 13:53:58 +0900533 || nextWordLength < SUB_QUEUE_MIN_WORD_LENGTH) {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900534 return FLAG_MULTIPLE_SUGGEST_SKIP;
satok3c09bb12012-01-26 18:36:19 +0900535 }
satok1f6b52e2012-01-30 13:53:58 +0900536 freq = score >> (nextWordLength + TWO_WORDS_PLUS_OTHER_ERROR_CORRECTION_DEMOTION_DIVIDER);
satok3c09bb12012-01-26 18:36:19 +0900537 }
538 if (DEBUG_DICT) {
Jean Chalard18ebba32012-09-06 20:37:55 +0900539 AKLOGI("Freq(%d): %d, length: %d, input length: %d, input start: %d (%d)",
540 currentWordIndex, freq, nextWordLength, inputWordLength, inputWordStartPos,
541 (currentWordIndex > 0) ? wordLengthArray[0] : 0);
satok3c09bb12012-01-26 18:36:19 +0900542 }
satok1f6b52e2012-01-30 13:53:58 +0900543 if (freq <= 0 || nextWordLength <= 0
544 || MAX_WORD_LENGTH <= (outputWordStartPos + nextWordLength)) {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900545 return FLAG_MULTIPLE_SUGGEST_SKIP;
satok3c09bb12012-01-26 18:36:19 +0900546 }
satok1f6b52e2012-01-30 13:53:58 +0900547 for (int i = 0; i < nextWordLength; ++i) {
satok3c09bb12012-01-26 18:36:19 +0900548 outputWord[outputWordStartPos + i] = tempOutputWord[i];
549 }
satok99557162012-01-26 22:49:13 +0900550
551 // Put output values
satok1f6b52e2012-01-30 13:53:58 +0900552 freqArray[currentWordIndex] = freq;
satok99557162012-01-26 22:49:13 +0900553 // TODO: put output length instead of input length
satok1f6b52e2012-01-30 13:53:58 +0900554 wordLengthArray[currentWordIndex] = inputWordLength;
555 const int tempOutputWordLength = outputWordStartPos + nextWordLength;
556 if (outputWordLength) {
557 *outputWordLength = tempOutputWordLength;
558 }
satok99557162012-01-26 22:49:13 +0900559
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900560 if ((inputWordStartPos + inputWordLength) < inputSize) {
satok1f6b52e2012-01-30 13:53:58 +0900561 if (outputWordStartPos + nextWordLength >= MAX_WORD_LENGTH) {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900562 return FLAG_MULTIPLE_SUGGEST_SKIP;
satok3c09bb12012-01-26 18:36:19 +0900563 }
Ken Wakasab02ee3d2012-10-08 11:46:14 +0900564 outputWord[tempOutputWordLength] = KEYCODE_SPACE;
satok1f6b52e2012-01-30 13:53:58 +0900565 if (outputWordLength) {
566 ++*outputWordLength;
567 }
568 } else if (currentWordIndex >= 1) {
satok99557162012-01-26 22:49:13 +0900569 // TODO: Handle 3 or more words
satoka85f4922012-01-30 18:18:30 +0900570 const int pairFreq = correction->getFreqForSplitMultipleWords(
571 freqArray, wordLengthArray, currentWordIndex + 1, isSpaceProximity, outputWord);
satok99557162012-01-26 22:49:13 +0900572 if (DEBUG_DICT) {
satoka85f4922012-01-30 18:18:30 +0900573 DUMP_WORD(outputWord, tempOutputWordLength);
satoka0ac31f2012-05-23 19:55:27 +0900574 for (int i = 0; i < currentWordIndex + 1; ++i) {
575 AKLOGI("Split %d,%d words: freq = %d, length = %d", i, currentWordIndex + 1,
576 freqArray[i], wordLengthArray[i]);
577 }
578 AKLOGI("Split two words: freq = %d, length = %d, %d, isSpace ? %d", pairFreq,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900579 inputSize, tempOutputWordLength, isSpaceProximity);
satok99557162012-01-26 22:49:13 +0900580 }
Jean Chalard926ef062012-08-10 13:14:45 +0900581 addWord(outputWord, tempOutputWordLength, pairFreq, queuePool->getMasterQueue(),
582 Dictionary::KIND_CORRECTION);
satok3c09bb12012-01-26 18:36:19 +0900583 }
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900584 return FLAG_MULTIPLE_SUGGEST_CONTINUE;
satok7409d152012-01-26 16:13:25 +0900585}
586
satok1f6b52e2012-01-30 13:53:58 +0900587void UnigramDictionary::getMultiWordsSuggestionRec(ProximityInfo *proximityInfo,
588 const int *xcoordinates, const int *ycoordinates, const int *codes,
Ken Wakasaf2789812012-09-04 12:49:46 +0900589 const bool useFullEditDistance, const int inputSize, Correction *correction,
590 WordsPriorityQueuePool *queuePool, const bool hasAutoCorrectionCandidate,
591 const int startInputPos, const int startWordIndex, const int outputWordLength,
Ken Wakasa1e614932012-10-29 18:06:22 +0900592 int *freqArray, int *wordLengthArray, int *outputWord) const {
satok1f6b52e2012-01-30 13:53:58 +0900593 if (startWordIndex >= (MULTIPLE_WORDS_SUGGESTION_MAX_WORDS - 1)) {
594 // Return if the last word index
595 return;
596 }
satoka85f4922012-01-30 18:18:30 +0900597 if (startWordIndex >= 1
598 && (hasAutoCorrectionCandidate
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900599 || inputSize < MIN_INPUT_LENGTH_FOR_THREE_OR_MORE_WORDS_CORRECTION)) {
satoka85f4922012-01-30 18:18:30 +0900600 // Do not suggest 3+ words if already has auto correction candidate
601 return;
602 }
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900603 for (int i = startInputPos + 1; i < inputSize; ++i) {
satok1f6b52e2012-01-30 13:53:58 +0900604 if (DEBUG_CORRECTION_FREQ) {
satoka85f4922012-01-30 18:18:30 +0900605 AKLOGI("Multi words(%d), start in %d sep %d start out %d",
606 startWordIndex, startInputPos, i, outputWordLength);
607 DUMP_WORD(outputWord, outputWordLength);
satok1f6b52e2012-01-30 13:53:58 +0900608 }
satoka85f4922012-01-30 18:18:30 +0900609 int tempOutputWordLength = 0;
610 // Current word
611 int inputWordStartPos = startInputPos;
612 int inputWordLength = i - startInputPos;
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900613 const int suggestionFlag = getSubStringSuggestion(proximityInfo, xcoordinates, ycoordinates,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900614 codes, useFullEditDistance, correction, queuePool, inputSize,
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900615 hasAutoCorrectionCandidate, startWordIndex, inputWordStartPos, inputWordLength,
616 outputWordLength, true /* not used */, freqArray, wordLengthArray, outputWord,
617 &tempOutputWordLength);
618 if (suggestionFlag == FLAG_MULTIPLE_SUGGEST_ABORT) {
619 // TODO: break here
620 continue;
621 } else if (suggestionFlag == FLAG_MULTIPLE_SUGGEST_SKIP) {
satok1f6b52e2012-01-30 13:53:58 +0900622 continue;
623 }
624
satoka85f4922012-01-30 18:18:30 +0900625 if (DEBUG_CORRECTION_FREQ) {
626 AKLOGI("Do missing space correction");
627 }
628 // Next word
satok1f6b52e2012-01-30 13:53:58 +0900629 // Missing space
630 inputWordStartPos = i;
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900631 inputWordLength = inputSize - i;
Ken Wakasaf2789812012-09-04 12:49:46 +0900632 if (getSubStringSuggestion(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900633 useFullEditDistance, correction, queuePool, inputSize, hasAutoCorrectionCandidate,
satoka85f4922012-01-30 18:18:30 +0900634 startWordIndex + 1, inputWordStartPos, inputWordLength, tempOutputWordLength,
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900635 false /* missing space */, freqArray, wordLengthArray, outputWord, 0)
636 != FLAG_MULTIPLE_SUGGEST_CONTINUE) {
satoka85f4922012-01-30 18:18:30 +0900637 getMultiWordsSuggestionRec(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900638 useFullEditDistance, inputSize, correction, queuePool,
satoka85f4922012-01-30 18:18:30 +0900639 hasAutoCorrectionCandidate, inputWordStartPos, startWordIndex + 1,
640 tempOutputWordLength, freqArray, wordLengthArray, outputWord);
641 }
satok1f6b52e2012-01-30 13:53:58 +0900642
643 // Mistyped space
644 ++inputWordStartPos;
645 --inputWordLength;
646
647 if (inputWordLength <= 0) {
648 continue;
649 }
650
651 const int x = xcoordinates[inputWordStartPos - 1];
652 const int y = ycoordinates[inputWordStartPos - 1];
653 if (!proximityInfo->hasSpaceProximity(x, y)) {
654 continue;
655 }
656
satoka85f4922012-01-30 18:18:30 +0900657 if (DEBUG_CORRECTION_FREQ) {
658 AKLOGI("Do mistyped space correction");
659 }
satok1f6b52e2012-01-30 13:53:58 +0900660 getSubStringSuggestion(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900661 useFullEditDistance, correction, queuePool, inputSize, hasAutoCorrectionCandidate,
satoka85f4922012-01-30 18:18:30 +0900662 startWordIndex + 1, inputWordStartPos, inputWordLength, tempOutputWordLength,
663 true /* mistyped space */, freqArray, wordLengthArray, outputWord, 0);
satok1f6b52e2012-01-30 13:53:58 +0900664 }
665}
666
satoka85f4922012-01-30 18:18:30 +0900667void UnigramDictionary::getSplitMultipleWordsSuggestions(ProximityInfo *proximityInfo,
satok744dab62011-12-15 22:29:05 +0900668 const int *xcoordinates, const int *ycoordinates, const int *codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900669 const bool useFullEditDistance, const int inputSize,
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900670 Correction *correction, WordsPriorityQueuePool *queuePool,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900671 const bool hasAutoCorrectionCandidate) const {
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900672 if (inputSize >= MAX_WORD_LENGTH) return;
satok612c6e42011-08-01 19:35:27 +0900673 if (DEBUG_DICT) {
satok1f6b52e2012-01-30 13:53:58 +0900674 AKLOGI("--- Suggest multiple words");
675 }
satok54af64a2012-01-17 15:58:23 +0900676
satokbd6ccdd2012-01-23 12:30:20 +0900677 // Allocating fixed length array on stack
Ken Wakasa1e614932012-10-29 18:06:22 +0900678 int outputWord[MAX_WORD_LENGTH];
satok1f6b52e2012-01-30 13:53:58 +0900679 int freqArray[MULTIPLE_WORDS_SUGGESTION_MAX_WORDS];
680 int wordLengthArray[MULTIPLE_WORDS_SUGGESTION_MAX_WORDS];
681 const int outputWordLength = 0;
682 const int startInputPos = 0;
683 const int startWordIndex = 0;
684 getMultiWordsSuggestionRec(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900685 useFullEditDistance, inputSize, correction, queuePool, hasAutoCorrectionCandidate,
satok1f6b52e2012-01-30 13:53:58 +0900686 startInputPos, startWordIndex, outputWordLength, freqArray, wordLengthArray,
687 outputWord);
Jean Chalarde6715e32011-06-30 19:47:25 +0900688}
689
Jean Chalard1059f272011-06-28 20:45:05 +0900690// Wrapper for getMostFrequentWordLikeInner, which matches it to the previous
691// interface.
Ken Wakasa2c2f3a92012-11-02 18:29:03 +0900692int UnigramDictionary::getMostFrequentWordLike(const int startInputIndex, const int inputSize,
693 Correction *correction, int *word) const {
Ken Wakasa1e614932012-10-29 18:06:22 +0900694 int inWord[inputSize];
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900695 for (int i = 0; i < inputSize; ++i) {
Ken Wakasa1e614932012-10-29 18:06:22 +0900696 inWord[i] = correction->getPrimaryCodePointAt(startInputIndex + i);
Jean Chalard1059f272011-06-28 20:45:05 +0900697 }
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900698 return getMostFrequentWordLikeInner(inWord, inputSize, word);
Jean Chalard1059f272011-06-28 20:45:05 +0900699}
700
701// This function will take the position of a character array within a CharGroup,
702// and check it actually like-matches the word in inWord starting at startInputIndex,
703// that is, it matches it with case and accents squashed.
704// The function returns true if there was a full match, false otherwise.
705// The function will copy on-the-fly the characters in the CharGroup to outNewWord.
706// It will also place the end position of the array in outPos; in outInputIndex,
707// it will place the index of the first char AFTER the match if there was a match,
708// and the initial position if there was not. It makes sense because if there was
709// a match we want to continue searching, but if there was not, we want to go to
710// the next CharGroup.
711// In and out parameters may point to the same location. This function takes care
712// not to use any input parameters after it wrote into its outputs.
713static inline bool testCharGroupForContinuedLikeness(const uint8_t flags,
Ken Wakasa1e614932012-10-29 18:06:22 +0900714 const uint8_t *const root, const int startPos, const int *const inWord,
715 const int startInputIndex, const int inputSize, int *outNewWord, int *outInputIndex,
Ken Wakasaf2789812012-09-04 12:49:46 +0900716 int *outPos) {
Jean Chalard19560502012-07-31 23:45:32 +0900717 const bool hasMultipleChars = (0 != (BinaryFormat::FLAG_HAS_MULTIPLE_CHARS & flags));
Jean Chalard1059f272011-06-28 20:45:05 +0900718 int pos = startPos;
Ken Wakasa1e614932012-10-29 18:06:22 +0900719 int codePoint = BinaryFormat::getCodePointAndForwardPointer(root, &pos);
720 int baseChar = toBaseLowerCase(codePoint);
721 const int wChar = toBaseLowerCase(inWord[startInputIndex]);
Jean Chalard1059f272011-06-28 20:45:05 +0900722
723 if (baseChar != wChar) {
724 *outPos = hasMultipleChars ? BinaryFormat::skipOtherCharacters(root, pos) : pos;
725 *outInputIndex = startInputIndex;
726 return false;
727 }
728 int inputIndex = startInputIndex;
Ken Wakasaf2789812012-09-04 12:49:46 +0900729 outNewWord[inputIndex] = codePoint;
Jean Chalard1059f272011-06-28 20:45:05 +0900730 if (hasMultipleChars) {
Ken Wakasaf2789812012-09-04 12:49:46 +0900731 codePoint = BinaryFormat::getCodePointAndForwardPointer(root, &pos);
732 while (NOT_A_CODE_POINT != codePoint) {
733 baseChar = toBaseLowerCase(codePoint);
734 if (inputIndex + 1 >= inputSize || toBaseLowerCase(inWord[++inputIndex]) != baseChar) {
Jean Chalard1059f272011-06-28 20:45:05 +0900735 *outPos = BinaryFormat::skipOtherCharacters(root, pos);
736 *outInputIndex = startInputIndex;
737 return false;
738 }
Ken Wakasaf2789812012-09-04 12:49:46 +0900739 outNewWord[inputIndex] = codePoint;
740 codePoint = BinaryFormat::getCodePointAndForwardPointer(root, &pos);
Jean Chalard1059f272011-06-28 20:45:05 +0900741 }
742 }
743 *outInputIndex = inputIndex + 1;
744 *outPos = pos;
745 return true;
746}
747
748// This function is invoked when a word like the word searched for is found.
749// It will compare the frequency to the max frequency, and if greater, will
750// copy the word into the output buffer. In output value maxFreq, it will
751// write the new maximum frequency if it changed.
Ken Wakasa1e614932012-10-29 18:06:22 +0900752static inline void onTerminalWordLike(const int freq, int *newWord, const int length, int *outWord,
753 int *maxFreq) {
Jean Chalard1059f272011-06-28 20:45:05 +0900754 if (freq > *maxFreq) {
Ken Wakasaf2789812012-09-04 12:49:46 +0900755 for (int q = 0; q < length; ++q) {
Jean Chalard1059f272011-06-28 20:45:05 +0900756 outWord[q] = newWord[q];
Ken Wakasaf2789812012-09-04 12:49:46 +0900757 }
Jean Chalard1059f272011-06-28 20:45:05 +0900758 outWord[length] = 0;
759 *maxFreq = freq;
760 }
761}
762
763// Will find the highest frequency of the words like the one passed as an argument,
764// that is, everything that only differs by case/accents.
Ken Wakasa1e614932012-10-29 18:06:22 +0900765int UnigramDictionary::getMostFrequentWordLikeInner(const int *const inWord, const int inputSize,
766 int *outWord) const {
767 int newWord[MAX_WORD_LENGTH_INTERNAL];
Jean Chalard1059f272011-06-28 20:45:05 +0900768 int depth = 0;
769 int maxFreq = -1;
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900770 const uint8_t *const root = DICT_ROOT;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900771 int stackChildCount[MAX_WORD_LENGTH_INTERNAL];
772 int stackInputIndex[MAX_WORD_LENGTH_INTERNAL];
773 int stackSiblingPos[MAX_WORD_LENGTH_INTERNAL];
Jean Chalard1059f272011-06-28 20:45:05 +0900774
Jean Chalard4c0eca62012-01-16 15:15:53 +0900775 int startPos = 0;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900776 stackChildCount[0] = BinaryFormat::getGroupCountAndForwardPointer(root, &startPos);
777 stackInputIndex[0] = 0;
778 stackSiblingPos[0] = startPos;
Jean Chalard1059f272011-06-28 20:45:05 +0900779 while (depth >= 0) {
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900780 const int charGroupCount = stackChildCount[depth];
781 int pos = stackSiblingPos[depth];
Jean Chalard1059f272011-06-28 20:45:05 +0900782 for (int charGroupIndex = charGroupCount - 1; charGroupIndex >= 0; --charGroupIndex) {
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900783 int inputIndex = stackInputIndex[depth];
Jean Chalard1059f272011-06-28 20:45:05 +0900784 const uint8_t flags = BinaryFormat::getFlagsAndForwardPointer(root, &pos);
785 // Test whether all chars in this group match with the word we are searching for. If so,
Ken Wakasaf2789812012-09-04 12:49:46 +0900786 // we want to traverse its children (or if the inputSize match, evaluate its frequency).
Jean Chalard1059f272011-06-28 20:45:05 +0900787 // Note that this function will output the position regardless, but will only write
788 // into inputIndex if there is a match.
789 const bool isAlike = testCharGroupForContinuedLikeness(flags, root, pos, inWord,
Ken Wakasaf2789812012-09-04 12:49:46 +0900790 inputIndex, inputSize, newWord, &inputIndex, &pos);
Jean Chalardd03e0652012-10-18 07:28:18 +0900791 if (isAlike && (!(BinaryFormat::FLAG_IS_NOT_A_WORD & flags))
792 && (BinaryFormat::FLAG_IS_TERMINAL & flags) && (inputIndex == inputSize)) {
Jean Chalard1059f272011-06-28 20:45:05 +0900793 const int frequency = BinaryFormat::readFrequencyWithoutMovingPointer(root, pos);
794 onTerminalWordLike(frequency, newWord, inputIndex, outWord, &maxFreq);
795 }
796 pos = BinaryFormat::skipFrequency(flags, pos);
797 const int siblingPos = BinaryFormat::skipChildrenPosAndAttributes(root, flags, pos);
798 const int childrenNodePos = BinaryFormat::readChildrenPosition(root, flags, pos);
799 // If we had a match and the word has children, we want to traverse them. We don't have
800 // to traverse words longer than the one we are searching for, since they will not match
Ken Wakasaf2789812012-09-04 12:49:46 +0900801 // anyway, so don't traverse unless inputIndex < inputSize.
802 if (isAlike && (-1 != childrenNodePos) && (inputIndex < inputSize)) {
Jean Chalard1059f272011-06-28 20:45:05 +0900803 // Save position for this depth, to get back to this once children are done
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900804 stackChildCount[depth] = charGroupIndex;
805 stackSiblingPos[depth] = siblingPos;
Jean Chalard1059f272011-06-28 20:45:05 +0900806 // Prepare stack values for next depth
807 ++depth;
808 int childrenPos = childrenNodePos;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900809 stackChildCount[depth] =
Jean Chalard1059f272011-06-28 20:45:05 +0900810 BinaryFormat::getGroupCountAndForwardPointer(root, &childrenPos);
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900811 stackSiblingPos[depth] = childrenPos;
812 stackInputIndex[depth] = inputIndex;
Jean Chalard1059f272011-06-28 20:45:05 +0900813 pos = childrenPos;
814 // Go to the next depth level.
815 ++depth;
816 break;
817 } else {
818 // No match, or no children, or word too long to ever match: go the next sibling.
819 pos = siblingPos;
820 }
821 }
822 --depth;
823 }
824 return maxFreq;
825}
826
Ken Wakasa1e614932012-10-29 18:06:22 +0900827int UnigramDictionary::getFrequency(const int *const inWord, const int length) const {
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900828 const uint8_t *const root = DICT_ROOT;
Jean Chalarde9a86e22012-06-28 21:01:29 +0900829 int pos = BinaryFormat::getTerminalPosition(root, inWord, length,
830 false /* forceLowerCaseSearch */);
Satoshi Kataoka2f854e12012-05-29 15:58:13 +0900831 if (NOT_VALID_WORD == pos) {
832 return NOT_A_PROBABILITY;
833 }
834 const uint8_t flags = BinaryFormat::getFlagsAndForwardPointer(root, &pos);
Jean Chalard72b1c932012-08-31 15:24:39 +0900835 if (flags & (BinaryFormat::FLAG_IS_BLACKLISTED | BinaryFormat::FLAG_IS_NOT_A_WORD)) {
836 // If this is not a word, or if it's a blacklisted entry, it should behave as
837 // having no frequency outside of the suggestion process (where it should be used
838 // for shortcuts).
839 return NOT_A_PROBABILITY;
840 }
Jean Chalard19560502012-07-31 23:45:32 +0900841 const bool hasMultipleChars = (0 != (BinaryFormat::FLAG_HAS_MULTIPLE_CHARS & flags));
Satoshi Kataoka2f854e12012-05-29 15:58:13 +0900842 if (hasMultipleChars) {
843 pos = BinaryFormat::skipOtherCharacters(root, pos);
844 } else {
Ken Wakasaf2789812012-09-04 12:49:46 +0900845 BinaryFormat::getCodePointAndForwardPointer(DICT_ROOT, &pos);
Satoshi Kataoka2f854e12012-05-29 15:58:13 +0900846 }
847 const int unigramFreq = BinaryFormat::readFrequencyWithoutMovingPointer(root, pos);
848 return unigramFreq;
Jean Chalard1059f272011-06-28 20:45:05 +0900849}
850
851// TODO: remove this function.
Ken Wakasa1e614932012-10-29 18:06:22 +0900852int UnigramDictionary::getBigramPosition(int pos, int *word, int offset, int length) const {
Jean Chalard1059f272011-06-28 20:45:05 +0900853 return -1;
854}
855
856// ProcessCurrentNode returns a boolean telling whether to traverse children nodes or not.
857// If the return value is false, then the caller should read in the output "nextSiblingPosition"
858// to find out the address of the next sibling node and pass it to a new call of processCurrentNode.
859// It is worthy to note that when false is returned, the output values other than
860// nextSiblingPosition are undefined.
861// If the return value is true, then the caller must proceed to traverse the children of this
862// node. processCurrentNode will output the information about the children: their count in
863// newCount, their position in newChildrenPosition, the traverseAllNodes flag in
864// newTraverseAllNodes, the match weight into newMatchRate, the input index into newInputIndex, the
865// diffs into newDiffs, the sibling position in nextSiblingPosition, and the output index into
866// newOutputIndex. Please also note the following caveat: processCurrentNode does not know when
867// there aren't any more nodes at this level, it merely returns the address of the first byte after
868// the current node in nextSiblingPosition. Thus, the caller must keep count of the nodes at any
869// given level, as output into newCount when traversing this level's parent.
Ken Wakasa2c2f3a92012-11-02 18:29:03 +0900870bool UnigramDictionary::processCurrentNode(const int initialPos,
Jean Chalard8950ce62012-05-07 16:28:30 +0900871 const std::map<int, int> *bigramMap, const uint8_t *bigramFilter, Correction *correction,
872 int *newCount, int *newChildrenPosition, int *nextSiblingPosition,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900873 WordsPriorityQueuePool *queuePool, const int currentWordIndex) const {
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900874 if (DEBUG_DICT) {
satokcfca3c62011-08-10 14:30:10 +0900875 correction->checkState();
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900876 }
Jean Chalard0584f022011-06-30 19:23:16 +0900877 int pos = initialPos;
Jean Chalard0584f022011-06-30 19:23:16 +0900878
Jean Chalard1059f272011-06-28 20:45:05 +0900879 // Flags contain the following information:
880 // - Address type (MASK_GROUP_ADDRESS_TYPE) on two bits:
881 // - FLAG_GROUP_ADDRESS_TYPE_{ONE,TWO,THREE}_BYTES means there are children and their address
882 // is on the specified number of bytes.
883 // - FLAG_GROUP_ADDRESS_TYPE_NOADDRESS means there are no children, and therefore no address.
884 // - FLAG_HAS_MULTIPLE_CHARS: whether this node has multiple char or not.
885 // - FLAG_IS_TERMINAL: whether this node is a terminal or not (it may still have children)
886 // - FLAG_HAS_BIGRAMS: whether this node has bigrams or not
887 const uint8_t flags = BinaryFormat::getFlagsAndForwardPointer(DICT_ROOT, &pos);
Jean Chalard19560502012-07-31 23:45:32 +0900888 const bool hasMultipleChars = (0 != (BinaryFormat::FLAG_HAS_MULTIPLE_CHARS & flags));
889 const bool isTerminalNode = (0 != (BinaryFormat::FLAG_IS_TERMINAL & flags));
satok8876b752011-08-04 18:31:57 +0900890
891 bool needsToInvokeOnTerminal = false;
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900892
Jean Chalard1059f272011-06-28 20:45:05 +0900893 // This gets only ONE character from the stream. Next there will be:
894 // if FLAG_HAS_MULTIPLE CHARS: the other characters of the same node
895 // else if FLAG_IS_TERMINAL: the frequency
896 // else if MASK_GROUP_ADDRESS_TYPE is not NONE: the children address
897 // 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 +0900898 int c = BinaryFormat::getCodePointAndForwardPointer(DICT_ROOT, &pos);
Ken Wakasaf2789812012-09-04 12:49:46 +0900899 assert(NOT_A_CODE_POINT != c);
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900900
Jean Chalard1059f272011-06-28 20:45:05 +0900901 // We are going to loop through each character and make it look like it's a different
902 // node each time. To do that, we will process characters in this node in order until
Ken Wakasaf2789812012-09-04 12:49:46 +0900903 // we find the character terminator. This is signalled by getCodePoint* returning
904 // NOT_A_CODE_POINT.
Jean Chalard1059f272011-06-28 20:45:05 +0900905 // 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 +0900906 // next bytes so we will simulate the NOT_A_CODE_POINT return by testing the flags.
Jean Chalard1059f272011-06-28 20:45:05 +0900907 // This way, each loop run will look like a "virtual node".
908 do {
909 // We prefetch the next char. If 'c' is the last char of this node, we will have
Ken Wakasaf2789812012-09-04 12:49:46 +0900910 // NOT_A_CODE_POINT in the next char. From this we can decide whether this virtual node
Jean Chalard1059f272011-06-28 20:45:05 +0900911 // should behave as a terminal or not and whether we have children.
Ken Wakasa1e614932012-10-29 18:06:22 +0900912 const int nextc = hasMultipleChars
Ken Wakasaf2789812012-09-04 12:49:46 +0900913 ? BinaryFormat::getCodePointAndForwardPointer(DICT_ROOT, &pos) : NOT_A_CODE_POINT;
914 const bool isLastChar = (NOT_A_CODE_POINT == nextc);
Jean Chalard1059f272011-06-28 20:45:05 +0900915 // If there are more chars in this nodes, then this virtual node is not a terminal.
916 // If we are on the last char, this virtual node is a terminal if this node is.
satok8876b752011-08-04 18:31:57 +0900917 const bool isTerminal = isLastChar && isTerminalNode;
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900918
satokcfca3c62011-08-10 14:30:10 +0900919 Correction::CorrectionType stateType = correction->processCharAndCalcState(
satok8876b752011-08-04 18:31:57 +0900920 c, isTerminal);
satokcfca3c62011-08-10 14:30:10 +0900921 if (stateType == Correction::TRAVERSE_ALL_ON_TERMINAL
922 || stateType == Correction::ON_TERMINAL) {
satok8876b752011-08-04 18:31:57 +0900923 needsToInvokeOnTerminal = true;
satokd03317c2011-12-14 21:38:11 +0900924 } else if (stateType == Correction::UNRELATED || correction->needsToPrune()) {
satok8876b752011-08-04 18:31:57 +0900925 // We found that this is an unrelated character, so we should give up traversing
926 // this node and its children entirely.
927 // However we may not be on the last virtual node yet so we skip the remaining
928 // characters in this node, the frequency if it's there, read the next sibling
929 // position to output it, then return false.
930 // We don't have to output other values because we return false, as in
931 // "don't traverse children".
Jean Chalard1059f272011-06-28 20:45:05 +0900932 if (!isLastChar) {
933 pos = BinaryFormat::skipOtherCharacters(DICT_ROOT, pos);
934 }
935 pos = BinaryFormat::skipFrequency(flags, pos);
936 *nextSiblingPosition =
937 BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
938 return false;
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900939 }
940
Jean Chalard1059f272011-06-28 20:45:05 +0900941 // Prepare for the next character. Promote the prefetched char to current char - the loop
942 // will take care of prefetching the next. If we finally found our last char, nextc will
Ken Wakasaf2789812012-09-04 12:49:46 +0900943 // contain NOT_A_CODE_POINT.
Jean Chalard1059f272011-06-28 20:45:05 +0900944 c = nextc;
Ken Wakasaf2789812012-09-04 12:49:46 +0900945 } while (NOT_A_CODE_POINT != c);
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900946
satok8876b752011-08-04 18:31:57 +0900947 if (isTerminalNode) {
satok6ad15fc2012-01-16 16:21:21 +0900948 // The frequency should be here, because we come here only if this is actually
949 // a terminal node, and we are on its last char.
Jean Chalard171d1802012-04-23 18:51:00 +0900950 const int unigramFreq = BinaryFormat::readFrequencyWithoutMovingPointer(DICT_ROOT, pos);
satok6ad15fc2012-01-16 16:21:21 +0900951 const int childrenAddressPos = BinaryFormat::skipFrequency(flags, pos);
952 const int attributesPos = BinaryFormat::skipChildrenPosition(flags, childrenAddressPos);
953 TerminalAttributes terminalAttributes(DICT_ROOT, flags, attributesPos);
Jean Chalard8950ce62012-05-07 16:28:30 +0900954 // bigramMap contains the bigram frequencies indexed by addresses for fast lookup.
955 // bigramFilter is a bloom filter of said frequencies for even faster rejection.
Jean Chalard49ba1352012-05-07 20:14:00 +0900956 const int probability = BinaryFormat::getProbability(initialPos, bigramMap, bigramFilter,
957 unigramFreq);
Jean Chalard171d1802012-04-23 18:51:00 +0900958 onTerminal(probability, terminalAttributes, correction, queuePool, needsToInvokeOnTerminal,
satok8330b482012-01-23 16:52:37 +0900959 currentWordIndex);
Jean Chalard1059f272011-06-28 20:45:05 +0900960
satok8876b752011-08-04 18:31:57 +0900961 // If there are more chars in this node, then this virtual node has children.
962 // If we are on the last char, this virtual node has children if this node has.
963 const bool hasChildren = BinaryFormat::hasChildrenInFlags(flags);
964
965 // This character matched the typed character (enough to traverse the node at least)
966 // so we just evaluated it. Now we should evaluate this virtual node's children - that
967 // is, if it has any. If it has no children, we're done here - so we skip the end of
968 // the node, output the siblings position, and return false "don't traverse children".
969 // Note that !hasChildren implies isLastChar, so we know we don't have to skip any
970 // remaining char in this group for there can't be any.
971 if (!hasChildren) {
972 pos = BinaryFormat::skipFrequency(flags, pos);
973 *nextSiblingPosition =
974 BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
975 return false;
976 }
977
978 // Optimization: Prune out words that are too long compared to how much was typed.
satokcfca3c62011-08-10 14:30:10 +0900979 if (correction->needsToPrune()) {
satok8876b752011-08-04 18:31:57 +0900980 pos = BinaryFormat::skipFrequency(flags, pos);
981 *nextSiblingPosition =
982 BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
satok10266c02011-08-19 22:05:59 +0900983 if (DEBUG_DICT_FULL) {
satok9fb6f472012-01-13 18:01:22 +0900984 AKLOGI("Traversing was pruned.");
satok10266c02011-08-19 22:05:59 +0900985 }
satok8876b752011-08-04 18:31:57 +0900986 return false;
987 }
988 }
Jean Chalard1059f272011-06-28 20:45:05 +0900989
990 // Now we finished processing this node, and we want to traverse children. If there are no
991 // children, we can't come here.
992 assert(BinaryFormat::hasChildrenInFlags(flags));
993
994 // If this node was a terminal it still has the frequency under the pointer (it may have been
995 // read, but not skipped - see readFrequencyWithoutMovingPointer).
996 // Next come the children position, then possibly attributes (attributes are bigrams only for
997 // now, maybe something related to shortcuts in the future).
998 // Once this is read, we still need to output the number of nodes in the immediate children of
999 // this node, so we read and output it before returning true, as in "please traverse children".
1000 pos = BinaryFormat::skipFrequency(flags, pos);
1001 int childrenPos = BinaryFormat::readChildrenPosition(DICT_ROOT, flags, pos);
1002 *nextSiblingPosition = BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
1003 *newCount = BinaryFormat::getGroupCountAndForwardPointer(DICT_ROOT, &childrenPos);
1004 *newChildrenPosition = childrenPos;
1005 return true;
Jean Chalard85a1d1e2011-06-21 22:23:21 +09001006}
satok30088252010-12-01 21:22:15 +09001007} // namespace latinime