Codebase list mozc / 4700ed5
Update from the upstream. * Code refactoring. Hiroyuki Komatsu 3 years ago
174 changed file(s) with 1125 addition(s) and 998 deletion(s). Raw diff Collapse all Expand all
145145 oss_android = ["//android/jni:mozc_lib"],
146146 oss_linux = [
147147 "//gui/tool:mozc_tool",
148 "//unix/emacs:mozc_emacs_helper",
149 "//unix/ibus:ibus_mozc",
148150 "//renderer:mozc_renderer",
149151 "//server:mozc_server",
150 "//unix/ibus:ibus_mozc",
151152 ],
152153 ),
153154 )
6868 }
6969 #elif defined(OS_NACL)
7070 const time_t localtime_sec = modified_sec + timezone_offset_sec_;
71 if (gmtime_r(&localtime_sec, output) == NULL) {
71 if (gmtime_r(&localtime_sec, output) == nullptr) {
7272 return false;
7373 }
7474 #else // !OS_WIN && !OS_NACL
75 if (gmtime_r(&modified_sec, output) == NULL) {
75 if (gmtime_r(&modified_sec, output) == nullptr) {
7676 return false;
7777 }
7878 #endif
210210 // "Compiler warning C4355: 'this': used in base member initializer list"
211211 // http://msdn.microsoft.com/en-us/library/3c594ae3.aspx
212212 // example:
213 // Foo::Foo() : x(NULL), ALLOW_THIS_IN_INITIALIZER_LIST(y(this)) {}
213 // Foo::Foo() : x(nullptr), ALLOW_THIS_IN_INITIALIZER_LIST(y(this)) {}
214214 #if defined(_MSC_VER)
215215 #define ALLOW_THIS_IN_INITIALIZER_LIST(code) \
216216 __pragma(warning(push)) __pragma(warning(disable : 4355)) \
103103 return ifs;
104104 }
105105 delete ifs;
106 return NULL;
106 return nullptr;
107107 }
108108 }
109109 // user://foo.bar.txt
117117 return ifs;
118118 }
119119 delete ifs;
120 return NULL;
120 return nullptr;
121121 // file:///foo.map
122122 } else if (Util::StartsWith(filename, kFilePrefix)) {
123123 const std::string new_filename = RemovePrefix(kFilePrefix, filename);
127127 return ifs;
128128 }
129129 delete ifs;
130 return NULL;
130 return nullptr;
131131 } else if (Util::StartsWith(filename, kMemoryPrefix)) {
132132 std::istringstream *ifs = new std::istringstream(
133133 Singleton<OnMemoryFileMap>::get()->get(filename), mode);
136136 return ifs;
137137 }
138138 delete ifs;
139 return NULL;
139 return nullptr;
140140 } else {
141141 LOG(WARNING) << filename << " has no prefix. open from localfile";
142142 InputFileStream *ifs = new InputFileStream(filename.c_str(), mode);
145145 return ifs;
146146 }
147147 delete ifs;
148 return NULL;
149 }
150
151 return NULL;
148 return nullptr;
149 }
150
151 return nullptr;
152152 }
153153
154154 bool ConfigFileStream::AtomicUpdate(const std::string &filename,
168168 // OSX's basic_info_t has no filed |creation_time|, we cannot use it.
169169 // The initial value might be different from the real CPU load.
170170 struct timeval tv;
171 gettimeofday(&tv, NULL);
171 gettimeofday(&tv, nullptr);
172172
173173 const uint64 total_times = 1000000ULL * tv.tv_sec + tv.tv_usec;
174174 const uint64 cpu_times = TimeValueTToInt64(task_times_info.user_time) +
7777
7878 // The CRITICAL_SECTION struct used for creating or deleting ExceptionHandler in
7979 // a mutually exclusive manner.
80 CRITICAL_SECTION *g_critical_section = NULL;
81
82 google_breakpad::ExceptionHandler *g_handler = NULL;
80 CRITICAL_SECTION *g_critical_section = nullptr;
81
82 google_breakpad::ExceptionHandler *g_handler = nullptr;
8383
8484 // Returns the name of the build mode.
8585 std::wstring GetBuildMode() {
9393 }
9494
9595 // Reduces the size of the string |str| to a max of 64 chars (Extra 1 char is
96 // trimmed for NULL-terminator so effective characters are 63 characters).
96 // trimmed for nullptr-terminator so effective characters are 63 characters).
9797 // Required because breakpad's CustomInfoEntry raises an invalid_parameter error
9898 // if the string we want to set is longer than 64 characters, including
99 // NULL-terminator.
99 // nullptr-terminator.
100100 std::wstring TrimToBreakpadMax(const std::wstring &str) {
101101 std::wstring shorter(str);
102102 return shorter.substr(0,
119119 {
120120 int num_args = 0;
121121 wchar_t **args = ::CommandLineToArgvW(::GetCommandLineW(), &num_args);
122 if (args != NULL) {
122 if (args != nullptr) {
123123 if (num_args > 1) {
124124 switch1.set_value(TrimToBreakpadMax(args[1]).c_str());
125125 }
152152 public:
153153 explicit ScopedCriticalSection(CRITICAL_SECTION *critical_section)
154154 : critical_section_(critical_section) {
155 if (critical_section_ != NULL) {
155 if (critical_section_ != nullptr) {
156156 EnterCriticalSection(critical_section_);
157157 }
158158 }
159159 ~ScopedCriticalSection() {
160 if (critical_section_ != NULL) {
160 if (critical_section_ != nullptr) {
161161 LeaveCriticalSection(critical_section_);
162162 }
163163 }
168168
169169 // get the handle to the module containing the given executing address
170170 HMODULE GetModuleHandleFromAddress(void *address) {
171 // address may be NULL
171 // address may be nullptr
172172 MEMORY_BASIC_INFORMATION mbi;
173173 SIZE_T result = VirtualQuery(address, &mbi, sizeof(mbi));
174174 if (0 == result) {
175 return NULL;
175 return nullptr;
176176 }
177177 return static_cast<HMODULE>(mbi.AllocationBase);
178178 }
184184
185185 // Check to see if an address is in the current module.
186186 bool IsAddressInCurrentModule(void *address) {
187 // address may be NULL
187 // address may be nullptr
188188 return GetCurrentModuleHandle() == GetModuleHandleFromAddress(address);
189189 }
190190
225225
226226 bool FilterHandler(void *context, EXCEPTION_POINTERS *exinfo,
227227 MDRawAssertionInfo *assertion) {
228 if (exinfo == NULL) {
228 if (exinfo == nullptr) {
229229 // We do not catch CRT error in release build.
230230 #ifdef MOZC_NO_LOGGING
231231 return false;
254254 ScopedCriticalSection critical_section(g_critical_section);
255255 DCHECK_GE(g_reference_count, 0);
256256 ++g_reference_count;
257 if (g_reference_count == 1 && g_handler == NULL) {
257 if (g_reference_count == 1 && g_handler == nullptr) {
258258 const string acrashdump_directory = SystemUtil::GetCrashReportDirectory();
259259 // create a crash dump directory if not exist.
260260 if (!FileUtil::FileExists(acrashdump_directory)) {
265265 Util::UTF8ToWide(acrashdump_directory, &crashdump_directory);
266266
267267 google_breakpad::ExceptionHandler::FilterCallback filter_callback =
268 check_address ? FilterHandler : NULL;
268 check_address ? FilterHandler : nullptr;
269269 const auto kCrashDumpType = static_cast<MINIDUMP_TYPE>(
270270 MiniDumpWithUnloadedModules | MiniDumpWithProcessThreadData);
271271 g_handler = new google_breakpad::ExceptionHandler(
272272 crashdump_directory.c_str(), filter_callback,
273 NULL, // MinidumpCallback
274 NULL, // callback_context
273 nullptr, // MinidumpCallback
274 nullptr, // callback_context
275275 google_breakpad::ExceptionHandler::HANDLER_ALL, kCrashDumpType,
276276 GetCrashHandlerPipeName().c_str(), GetCustomInfo());
277277
292292 ScopedCriticalSection critical_section(g_critical_section);
293293 --g_reference_count;
294294 DCHECK_GE(g_reference_count, 0);
295 if (g_reference_count == 0 && g_handler != NULL) {
295 if (g_reference_count == 0 && g_handler != nullptr) {
296296 delete g_handler;
297 g_handler = NULL;
297 g_handler = nullptr;
298298 return true;
299299 }
300300 return false;
161161 return false;
162162 }
163163
164 if (iv != NULL) {
164 if (iv != nullptr) {
165165 memcpy(data_->iv, iv, iv_size());
166166 } else {
167167 memset(data_->iv, '\0', iv_size());
184184 Encryptor::Key::~Key() {}
185185
186186 bool Encryptor::EncryptString(const Encryptor::Key &key, std::string *data) {
187 if (data == NULL || data->empty()) {
188 LOG(ERROR) << "data is NULL or empty";
187 if (data == nullptr || data->empty()) {
188 LOG(ERROR) << "data is nullptr or empty";
189189 return false;
190190 }
191191 size_t size = data->size();
200200 }
201201
202202 bool Encryptor::DecryptString(const Encryptor::Key &key, std::string *data) {
203 if (data == NULL || data->empty()) {
204 LOG(ERROR) << "data is NULL or empty";
203 if (data == nullptr || data->empty()) {
204 LOG(ERROR) << "data is nullptr or empty";
205205 return false;
206206 }
207207 size_t size = data->size();
222222 return false;
223223 }
224224
225 if (buf == NULL || buf_size == NULL || *buf_size == 0) {
225 if (buf == nullptr || buf_size == nullptr || *buf_size == 0) {
226226 LOG(ERROR) << "invalid buffer given";
227227 return false;
228228 }
251251 return false;
252252 }
253253
254 if (buf == NULL || buf_size == NULL || *buf_size == 0) {
254 if (buf == nullptr || buf_size == nullptr || *buf_size == 0) {
255255 LOG(ERROR) << "invalid buffer given";
256256 return false;
257257 }
303303 input.cbData = static_cast<DWORD>(plain_text.size());
304304
305305 DATA_BLOB output;
306 const BOOL result = ::CryptProtectData(&input, L"", NULL, NULL, NULL,
306 const BOOL result = ::CryptProtectData(&input, L"", nullptr, nullptr, nullptr,
307307 CRYPTPROTECT_UI_FORBIDDEN, &output);
308308 if (!result) {
309309 LOG(ERROR) << "CryptProtectData failed: " << ::GetLastError();
326326 input.cbData = static_cast<DWORD>(cipher_text.length());
327327
328328 DATA_BLOB output;
329 const BOOL result = ::CryptUnprotectData(&input, NULL, NULL, NULL, NULL,
330 CRYPTPROTECT_UI_FORBIDDEN, &output);
329 const BOOL result =
330 ::CryptUnprotectData(&input, nullptr, nullptr, nullptr, nullptr,
331 CRYPTPROTECT_UI_FORBIDDEN, &output);
331332 if (!result) {
332333 LOG(ERROR) << "CryptUnprotectData failed: " << ::GetLastError();
333334 return false;
4444 // Make a session key from password and salt.
4545 // You can also set an initialization vector whose
4646 // size must be iv_size().
47 // if iv is NULL, default iv is used.
47 // if iv is nullptr, default iv is used.
4848 bool DeriveFromPassword(const std::string &password,
4949 const std::string &salt, const uint8 *iv);
5050
5151 // use default iv.
5252 bool DeriveFromPassword(const std::string &password,
5353 const std::string &salt) {
54 return DeriveFromPassword(password, salt, NULL);
54 return DeriveFromPassword(password, salt, nullptr);
5555 }
5656
5757 // use empty salt and default iv
5858 bool DeriveFromPassword(const std::string &password) {
59 return DeriveFromPassword(password, "", NULL);
59 return DeriveFromPassword(password, "", nullptr);
6060 }
6161
6262 // return block size. the result should be 16byte with AES
6868 }
6969
7070 const uint8 *iv = FLAGS_iv.empty()
71 ? NULL
71 ? nullptr
7272 : reinterpret_cast<const uint8 *>(FLAGS_iv.data());
7373
7474 if (!FLAGS_input_file.empty() && !FLAGS_output_file.empty()) {
212212 EXPECT_NE(original, encrypted4);
213213
214214 // invalid values
215 EXPECT_FALSE(Encryptor::EncryptString(key1, NULL));
216 EXPECT_FALSE(Encryptor::DecryptString(key1, NULL));
215 EXPECT_FALSE(Encryptor::EncryptString(key1, nullptr));
216 EXPECT_FALSE(Encryptor::DecryptString(key1, nullptr));
217217
218218 // empty string
219219 std::string empty_string;
4848 InputMultiFile::~InputMultiFile() { ifs_.reset(); }
4949
5050 bool InputMultiFile::ReadLine(std::string *line) {
51 if (ifs_.get() == NULL) {
51 if (ifs_.get() == nullptr) {
5252 return false;
5353 }
5454 do {
182182 } // namespace
183183
184184 ReaderWriterMutex::ReaderWriterMutex() {
185 pthread_rwlock_init(AsPthreadRWLockT(&opaque_buffer_), NULL);
185 pthread_rwlock_init(AsPthreadRWLockT(&opaque_buffer_), nullptr);
186186 }
187187
188188 ReaderWriterMutex::~ReaderWriterMutex() {
212212 // Fallback implementations as ReaderWriterLock is not available.
213213 ReaderWriterMutex::ReaderWriterMutex() {
214214 // Non-recursive lock is OK.
215 pthread_mutex_init(AsPthreadMutexT(&opaque_buffer_), NULL);
215 pthread_mutex_init(AsPthreadMutexT(&opaque_buffer_), nullptr);
216216 }
217217
218218 ReaderWriterMutex::~ReaderWriterMutex() {
179179 }
180180
181181 bool PlainPasswordManager::GetPassword(std::string *password) const {
182 if (password == NULL) {
183 LOG(ERROR) << "password is NULL";
182 if (password == nullptr) {
183 LOG(ERROR) << "password is nullptr";
184184 return false;
185185 }
186186
230230 }
231231
232232 bool WinMacPasswordManager::GetPassword(string *password) const {
233 if (password == NULL) {
234 LOG(ERROR) << "password is NULL";
233 if (password == nullptr) {
234 LOG(ERROR) << "password is nullptr";
235235 return false;
236236 }
237237
278278 public:
279279 PasswordManagerImpl() {
280280 password_manager_ = Singleton<DefaultPasswordManager>::get();
281 DCHECK(password_manager_ != NULL);
281 DCHECK(password_manager_ != nullptr);
282282 }
283283
284284 bool InitPassword() {
7474 #include <crt_externs.h>
7575 static char **environ = *_NSGetEnviron();
7676 #elif !defined(OS_WIN)
77 // Defined somewhere in libc. We can't pass NULL as the 6th argument of
77 // Defined somewhere in libc. We can't pass nullptr as the 6th argument of
7878 // posix_spawn() since Qt applications use (at least) DISPLAY and QT_IM_MODULE
7979 // environment variables.
8080 extern char **environ;
133133 si.dwFlags = STARTF_FORCEOFFFEEDBACK;
134134 PROCESS_INFORMATION pi = {0};
135135
136 // If both |lpApplicationName| and |lpCommandLine| are non-NULL,
136 // If both |lpApplicationName| and |lpCommandLine| are non-nullptr,
137137 // the argument array of the process will be shifted.
138138 // http://support.microsoft.com/kb/175986
139139 const bool create_process_succeeded =
140140 ::CreateProcessW(
141 NULL, wpath2.get(), NULL, NULL, FALSE, CREATE_DEFAULT_ERROR_MODE,
142 NULL,
141 nullptr, wpath2.get(), nullptr, nullptr, FALSE,
142 CREATE_DEFAULT_ERROR_MODE, nullptr,
143143 // NOTE: Working directory will be locked by the system.
144144 // We use system directory to spawn process so that users will not
145145 // to be aware of any undeletable directory. (http://b/2017482)
165165 for (size_t i = 0; i < arg_tmp.size(); ++i) {
166166 argv[i + 1] = arg_tmp[i].c_str();
167167 }
168 argv[arg_tmp.size() + 1] = NULL;
168 argv[arg_tmp.size() + 1] = nullptr;
169169
170170 struct stat statbuf;
171171 if (::stat(path.c_str(), &statbuf) != 0) {
214214 // the return value of posix_spawn is basically determined
215215 // by the return value of fork().
216216 const int result =
217 ::posix_spawn(&tmp_pid, path.c_str(), NULL, NULL,
217 ::posix_spawn(&tmp_pid, path.c_str(), nullptr, nullptr,
218218 const_cast<char *const *>(argv.get()), environ);
219219 if (result == 0) {
220220 VLOG(1) << "posix_spawn: child pid is " << tmp_pid;
222222 LOG(ERROR) << "posix_spawn failed: " << strerror(result);
223223 }
224224
225 if (pid != NULL) {
225 if (pid != nullptr) {
226226 *pid = tmp_pid;
227227 }
228228 return result == 0;
249249 #ifdef OS_WIN
250250 DWORD processe_id = static_cast<DWORD>(pid);
251251 ScopedHandle handle(::OpenProcess(SYNCHRONIZE, FALSE, processe_id));
252 if (handle.get() == NULL) {
252 if (handle.get() == nullptr) {
253253 LOG(ERROR) << "Cannot get handle id";
254254 return true;
255255 }
299299 {
300300 ScopedHandle handle(
301301 ::OpenProcess(SYNCHRONIZE, FALSE, static_cast<DWORD>(pid)));
302 if (NULL == handle.get()) {
302 if (nullptr == handle.get()) {
303303 const DWORD error = ::GetLastError();
304304 if (error == ERROR_ACCESS_DENIED) {
305305 LOG(ERROR) << "OpenProcess failed: " << error;
340340 {
341341 ScopedHandle handle(
342342 ::OpenThread(SYNCHRONIZE, FALSE, static_cast<DWORD>(thread_id)));
343 if (NULL == handle.get()) {
343 if (nullptr == handle.get()) {
344344 const DWORD error = ::GetLastError();
345345 if (error == ERROR_ACCESS_DENIED) {
346346 LOG(ERROR) << "OpenThread failed: " << error;
5757 namespace {
5858
5959 std::string CreateProcessMutexFileName(const char *name) {
60 name = (name == NULL) ? "NULL" : name;
60 name = (name == nullptr) ? "nullptr" : name;
6161
6262 #ifdef OS_WIN
6363 string basename;
102102 }
103103 handle_.reset(::CreateFileW(wfilename.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
104104 &serucity_attributes, CREATE_ALWAYS, kAttribute,
105 NULL));
105 nullptr));
106106 ::LocalFree(serucity_attributes.lpSecurityDescriptor);
107107
108 locked_ = (handle_.get() != NULL);
108 locked_ = (handle_.get() != nullptr);
109109
110110 if (!locked_) {
111111 VLOG(1) << "already locked";
115115 if (!message.empty()) {
116116 DWORD size = 0;
117117 if (!::WriteFile(handle_.get(), message.data(), message.size(), &size,
118 NULL)) {
118 nullptr)) {
119119 const int last_error = ::GetLastError();
120120 LOG(ERROR) << "Cannot write message: " << message
121121 << ", last_error:" << last_error;
128128 }
129129
130130 bool ProcessMutex::UnLock() {
131 handle_.reset(NULL);
131 handle_.reset(nullptr);
132132 FileUtil::Unlink(filename_);
133133 locked_ = false;
134134 return true;
212212 bool Lock(const std::string &filename, int *fd) {
213213 scoped_lock l(&mutex_);
214214
215 if (fd == NULL) {
216 LOG(ERROR) << "fd is NULL";
215 if (fd == nullptr) {
216 LOG(ERROR) << "fd is nullptr";
217217 return false;
218218 }
219219
156156 }
157157
158158 // Get process token
159 HANDLE hProcessToken = NULL;
159 HANDLE hProcessToken = nullptr;
160160 if (!::OpenProcessToken(::GetCurrentProcess(),
161161 TOKEN_QUERY | TOKEN_QUERY_SOURCE, &hProcessToken)) {
162162 return RunLevel::DENY;
171171 }
172172
173173 // Get thread token (if any)
174 HANDLE hThreadToken = NULL;
174 HANDLE hThreadToken = nullptr;
175175 if (!::OpenThreadToken(::GetCurrentThread(), TOKEN_QUERY, TRUE,
176176 &hThreadToken) &&
177177 ERROR_NO_TOKEN != ::GetLastError()) {
181181 ScopedHandle thread_token(hThreadToken);
182182
183183 // Thread token (if any) must not a service account.
184 if (NULL != thread_token.get()) {
184 if (nullptr != thread_token.get()) {
185185 bool is_service_thread = false;
186186 if (!WinUtil::IsServiceUser(thread_token.get(), &is_service_thread)) {
187187 // Returns DENY conservatively.
202202 }
203203
204204 // Thread token must be created by sandbox.
205 if (NULL == thread_token.get()) {
205 if (nullptr == thread_token.get()) {
206206 return RunLevel::DENY;
207207 }
208208
218218 std::wstring dir;
219219 Util::UTF8ToWide(user_dir, &dir);
220220 ScopedHandle dir_handle(::CreateFile(dir.c_str(), READ_CONTROL | WRITE_DAC,
221 0, NULL, OPEN_EXISTING,
221 0, nullptr, OPEN_EXISTING,
222222 FILE_FLAG_BACKUP_SEMANTICS, 0));
223 if (NULL != dir_handle.get()) {
223 if (nullptr != dir_handle.get()) {
224224 BYTE buffer[sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE];
225225 DWORD size = 0;
226226 if (::GetTokenInformation(thread_token.get(), TokenUser, buffer,
302302
303303 JOBOBJECT_EXTENDED_LIMIT_INFORMATION JobExtLimitInfo;
304304 // Get the job information of the current process
305 if (!::QueryInformationJobObject(NULL, JobObjectExtendedLimitInformation,
305 if (!::QueryInformationJobObject(nullptr, JobObjectExtendedLimitInformation,
306306 &JobExtLimitInfo, sizeof(JobExtLimitInfo),
307 NULL)) {
307 nullptr)) {
308308 return false;
309309 }
310310
324324 bool RunLevel::IsElevatedByUAC() {
325325 #ifdef OS_WIN
326326 // Get process token
327 HANDLE hProcessToken = NULL;
327 HANDLE hProcessToken = nullptr;
328328 if (!::OpenProcessToken(::GetCurrentProcess(),
329329 TOKEN_QUERY | TOKEN_QUERY_SOURCE, &hProcessToken)) {
330330 return false;
341341 #ifdef OS_WIN
342342 HKEY key = 0;
343343 LONG result =
344 ::RegCreateKeyExW(HKEY_CURRENT_USER, kElevatedProcessDisabledKey, 0, NULL,
345 0, KEY_WRITE, NULL, &key, NULL);
344 ::RegCreateKeyExW(HKEY_CURRENT_USER, kElevatedProcessDisabledKey, 0,
345 nullptr, 0, KEY_WRITE, nullptr, &key, nullptr);
346346
347347 if (ERROR_SUCCESS != result) {
348348 return false;
364364 #ifdef OS_WIN
365365 HKEY key = 0;
366366 LONG result = ::RegOpenKeyExW(HKEY_CURRENT_USER, kElevatedProcessDisabledKey,
367 NULL, KEY_READ, &key);
367 0, KEY_READ, &key);
368368 if (ERROR_SUCCESS != result) {
369369 return false;
370370 }
373373 DWORD value_size = sizeof(value);
374374 DWORD value_type = 0;
375375 result =
376 ::RegQueryValueEx(key, kElevatedProcessDisabledName, NULL, &value_type,
376 ::RegQueryValueEx(key, kElevatedProcessDisabledName, nullptr, &value_type,
377377 reinterpret_cast<BYTE *>(&value), &value_size);
378378 ::RegCloseKey(key);
379379
123123 : setting_(setting),
124124 skip_count_(0),
125125 backoff_count_(0),
126 timer_(NULL),
126 timer_(nullptr),
127127 running_(false) {}
128128
129 ~Job() { set_timer(NULL); }
129 ~Job() { set_timer(nullptr); }
130130
131131 const Scheduler::JobSetting setting() const { return setting_; }
132132
141141 uint32 backoff_count() const { return backoff_count_; }
142142
143143 void set_timer(QueueTimer *timer) {
144 if (timer_ != NULL) {
144 if (timer_ != nullptr) {
145145 delete timer_;
146146 }
147147 timer_ = timer;
183183 DCHECK_NE(0, job_setting.default_interval());
184184 DCHECK_NE(0, job_setting.max_interval());
185185 // do not use DCHECK_NE as a type checker raises an error.
186 DCHECK(job_setting.callback() != NULL);
186 DCHECK(job_setting.callback() != nullptr);
187187 }
188188
189189 virtual bool AddJob(const Scheduler::JobSetting &job_setting) {
209209 // TODO(hsumita): Make Job class uncopiable.
210210 job->set_timer(new QueueTimer(std::bind(TimerCallback, job), delay,
211211 job_setting.default_interval()));
212 if (job->timer() == NULL) {
212 if (job->timer() == nullptr) {
213213 LOG(ERROR) << "failed to create QueueTimer";
214214 return false;
215215 }
245245 }
246246 job->set_running(true);
247247 Scheduler::JobSetting::CallbackFunc callback = job->setting().callback();
248 DCHECK(callback != NULL);
248 DCHECK(callback != nullptr);
249249 const bool success = callback(job->setting().data());
250250 job->set_running(false);
251251 if (success) {
275275 DISALLOW_COPY_AND_ASSIGN(SchedulerImpl);
276276 };
277277
278 Scheduler::SchedulerInterface *g_scheduler_handler = NULL;
278 Scheduler::SchedulerInterface *g_scheduler_handler = nullptr;
279279
280280 Scheduler::SchedulerInterface *GetSchedulerHandler() {
281 if (g_scheduler_handler != NULL) {
281 if (g_scheduler_handler != nullptr) {
282282 return g_scheduler_handler;
283283 } else {
284284 return Singleton<SchedulerImpl>::get();
3737 // usage:
3838 // // start scheduled job
3939 // Scheduler::AddJob(Scheduler::JobSetting(
40 // "TimerName", 60*1000, 60*60*1000, 30*1000, 60*1000, &Callback, NULL));
41 // (NULL is the args for Callback)
40 // "TimerName", 60*1000, 60*60*1000, 30*1000, 60*1000, &Callback, nullptr));
41 // (nullptr is the args for Callback)
4242 // // stop job
4343 // Scheduler::RemoveJob("TimerName");
4444
3838 // ... (Do something)
3939 // scheduler_stub.PutClockForward(60*1000);
4040 // ... (Do something)
41 // Scheduler::SetSchedulerHandler(NULL);
41 // Scheduler::SetSchedulerHandler(nullptr);
4242 // }
4343
4444 #include <map>
5858 SchedulerStub scheduler_stub;
5959 EXPECT_FALSE(scheduler_stub.HasJob("Test"));
6060 scheduler_stub.AddJob(
61 Scheduler::JobSetting("Test", 1000, 100000, 5000, 0, &TestFunc, NULL));
61 Scheduler::JobSetting("Test", 1000, 100000, 5000, 0, &TestFunc, nullptr));
6262 EXPECT_TRUE(scheduler_stub.HasJob("Test"));
6363 EXPECT_EQ(0, g_counter);
6464 scheduler_stub.PutClockForward(1000);
8989 TEST_F(SchedulerStubTest, BackOff) {
9090 SchedulerStub scheduler_stub;
9191 scheduler_stub.AddJob(
92 Scheduler::JobSetting("Test", 1000, 6000, 3000, 0, &TestFunc, NULL));
92 Scheduler::JobSetting("Test", 1000, 6000, 3000, 0, &TestFunc, nullptr));
9393 g_result = false;
9494 EXPECT_EQ(0, g_counter);
9595 scheduler_stub.PutClockForward(1000);
156156
157157 TEST_F(SchedulerStubTest, AddRemoveJobs) {
158158 SchedulerStub scheduler_stub;
159 scheduler_stub.AddJob(
160 Scheduler::JobSetting("Test1", 1000, 100000, 1000, 0, &TestFunc, NULL));
159 scheduler_stub.AddJob(Scheduler::JobSetting("Test1", 1000, 100000, 1000, 0,
160 &TestFunc, nullptr));
161161 EXPECT_EQ(0, g_counter);
162162 scheduler_stub.PutClockForward(1000); // delay
163163 EXPECT_EQ(1, g_counter);
164164
165 scheduler_stub.AddJob(
166 Scheduler::JobSetting("Test2", 1000, 100000, 1000, 0, &TestFunc, NULL));
165 scheduler_stub.AddJob(Scheduler::JobSetting("Test2", 1000, 100000, 1000, 0,
166 &TestFunc, nullptr));
167167
168168 scheduler_stub.PutClockForward(1000); // delay + interval
169169 EXPECT_EQ(3, g_counter);
3636 class scoped_cftyperef {
3737 public:
3838 typedef T element_type;
39 explicit scoped_cftyperef(T p = NULL, bool do_retain = false) : ptr_(p) {
40 if (do_retain && p != NULL) {
39 explicit scoped_cftyperef(T p = nullptr, bool do_retain = false) : ptr_(p) {
40 if (do_retain && p != nullptr) {
4141 CFRetain(ptr_);
4242 }
4343 }
4444
4545 ~scoped_cftyperef() {
46 if (ptr_ != NULL) {
46 if (ptr_ != nullptr) {
4747 CFRelease(ptr_);
4848 }
4949 }
5050
51 void reset(T p = NULL) {
52 if (ptr_ != NULL) {
51 void reset(T p = nullptr) {
52 if (ptr_ != nullptr) {
5353 CFRelease(ptr_);
5454 }
5555 ptr_ = p;
5858 T get() const { return ptr_; }
5959
6060 bool Verify(CFTypeID type_id) {
61 return ptr_ != NULL &&
61 return ptr_ != nullptr &&
6262 CFGetTypeID(reinterpret_cast<CFTypeRef>(ptr_)) == type_id;
6363 }
6464
3333
3434 namespace mozc {
3535
36 ScopedHandle::ScopedHandle() : handle_(NULL) {}
36 ScopedHandle::ScopedHandle() : handle_(nullptr) {}
3737
38 ScopedHandle::ScopedHandle(Win32Handle handle) : handle_(NULL) {
38 ScopedHandle::ScopedHandle(Win32Handle handle) : handle_(nullptr) {
3939 reset(handle);
4040 }
4141
6868 // transfers ownership away from this object
6969 ScopedHandle::Win32Handle ScopedHandle::take() {
7070 HANDLE handle = handle_;
71 handle_ = NULL;
71 handle_ = nullptr;
7272 return handle;
7373 }
7474
7575 void ScopedHandle::Close() {
76 if (handle_ != NULL) {
76 if (handle_ != nullptr) {
7777 ::CloseHandle(handle_);
78 handle_ = NULL;
78 handle_ = nullptr;
7979 }
8080 }
8181
4343 // assume HANDLE type is a synonym of void *.
4444 typedef void *Win32Handle;
4545
46 // Initializes with NULL.
46 // Initializes with nullptr.
4747 ScopedHandle();
4848
4949 // Initializes with taking ownership of |handle|.
5050 // Covert: If |handle| is INVALID_HANDLE_VALUE, this wrapper treat
51 // it as NULL.
51 // it as nullptr.
5252 explicit ScopedHandle(Win32Handle handle);
5353
5454 // Call ::CloseHandle API against the current object (if any).
5555 void ExitWithError() {
5656 // This logic is copied from logging.h
5757 #ifdef OS_WIN
58 ::RaiseException(::GetLastError(), EXCEPTION_NONCONTINUABLE, NULL, NULL);
58 ::RaiseException(::GetLastError(), EXCEPTION_NONCONTINUABLE, 0, nullptr);
5959 #else
6060 exit(-1);
6161 #endif
7272
7373 static void Delete() {
7474 delete instance_;
75 instance_ = NULL;
75 instance_ = nullptr;
7676 ResetOnce(&once_);
7777 }
7878
8484 once_t Singleton<T>::once_ = MOZC_ONCE_INIT;
8585
8686 template <typename T>
87 T *Singleton<T>::instance_ = NULL;
87 T *Singleton<T>::instance_ = nullptr;
8888 } // namespace mozc
8989
9090 #endif // MOZC_BASE_SINGLETON_H_
5858
5959 ThreadInstance *get() { return instance_; }
6060
61 ThreadTest() : instance_(NULL) {}
61 ThreadTest() : instance_(nullptr) {}
6262
6363 private:
6464 ThreadInstance *instance_;
5454 v.push_back(new InstanceCounter<std::string>());
5555 v.push_back(new InstanceCounter<std::string>());
5656 EXPECT_EQ(3, InstanceCounter<std::string>::instance_count);
57 v.push_back(NULL);
57 v.push_back(nullptr);
5858 EXPECT_EQ(3, InstanceCounter<std::string>::instance_count);
5959 mozc::STLDeleteElements(&v);
6060 EXPECT_EQ(0, InstanceCounter<std::string>::instance_count);
6161 EXPECT_EQ(0, v.size());
6262
63 // Deleting NULL pointers to containers is ok.
64 std::vector<InstanceCounter<std::string> *> *p = NULL;
63 // Deleting nullptr pointers to containers is ok.
64 std::vector<InstanceCounter<std::string> *> *p = nullptr;
6565 mozc::STLDeleteElements(p);
6666 }
6767
4040 #include <pwd.h>
4141 #include <sys/mman.h>
4242 #include <unistd.h>
43 #endif // OS_WIN
44
4345 #ifdef __APPLE__
4446 #include <sys/stat.h>
4547 #include <sys/sysctl.h>
46 #endif // __APPLE__
47 #endif // OS_WIN
48
49 #ifdef __APPLE__
5048 #include <cerrno>
5149 #endif // __APPLE__
50
5251 #include <cstdlib>
5352 #include <cstring>
53
5454 #ifdef OS_WIN
5555 #include <memory>
5656 #endif // OS_WIN
57
5758 #include <sstream>
5859 #include <string>
60
61 #ifdef OS_ANDROID
62 #include "base/android_util.h"
63 #endif // OS_ANDROID
5964
6065 #include "base/const.h"
6166 #include "base/file_util.h"
6267 #include "base/logging.h"
68
6369 #ifdef __APPLE__
6470 #include "base/mac_util.h"
6571 #endif // __APPLE__
72
6673 #include "base/singleton.h"
6774 #include "base/util.h"
75
6876 #ifdef OS_WIN
6977 #include "base/win_util.h"
70 #endif // OS_WIN
71
72 #ifdef OS_ANDROID
73 #include "base/android_util.h"
74 #endif // OS_ANDROID
75
76 #ifdef OS_WIN
77 using std::unique_ptr;
7878 #endif // OS_WIN
7979
8080 namespace mozc {
209209 // NaCL platform is correct.
210210 dir_ = "/mutable";
211211 return;
212 #else // OS_NACL || OS_CHROMEOS
212 #endif // OS_NACL || OS_CHROMEOS
213
214 #if defined(OS_WASM)
215 // Do nothing for WebAssembly.
216 return;
217 #endif // OS_WASM
218
219 #if defined(OS_ANDROID)
220 // For android, we do nothing here because user profile directory,
221 // of which the path depends on active user,
222 // is injected from Java layer.
223 return;
224 #endif // OS_ANDROID
225
213226 std::string dir;
214227
215228 #ifdef OS_IOS
220233 // because the support directory doesn't exist by default. Also, it is backed
221234 // up by iTunes and iCloud.
222235 dir = FileUtil::JoinPath({MacUtil::GetCachesDirectory(), kProductPrefix});
223
224 #elif defined(OS_WIN)
236 #endif // OS_IOS
237
238 #if defined(OS_WIN)
225239 DCHECK(SUCCEEDED(Singleton<LocalAppDataDirectoryCache>::get()->result()));
226240 dir = Singleton<LocalAppDataDirectoryCache>::get()->path();
227 #ifdef GOOGLE_JAPANESE_INPUT_BUILD
241 # ifdef GOOGLE_JAPANESE_INPUT_BUILD
228242 dir = FileUtil::JoinPath(dir, kCompanyNameInEnglish);
229243 FileUtil::CreateDirectory(dir);
230 #endif // GOOGLE_JAPANESE_INPUT_BUILD
244 # endif // GOOGLE_JAPANESE_INPUT_BUILD
231245 dir = FileUtil::JoinPath(dir, kProductNameInEnglish);
232
233 #elif defined(__APPLE__)
246 #endif // OS_WIN
247
248 #if defined(__APPLE__)
234249 dir = MacUtil::GetApplicationSupportDirectory();
235 #ifdef GOOGLE_JAPANESE_INPUT_BUILD
250 # ifdef GOOGLE_JAPANESE_INPUT_BUILD
236251 dir = FileUtil::JoinPath(dir, "Google");
237252 // The permission of ~/Library/Application Support/Google seems to be 0755.
238253 // TODO(komatsu): nice to make a wrapper function.
239254 ::mkdir(dir.c_str(), 0755);
240255 dir = FileUtil::JoinPath(dir, "JapaneseInput");
241 #else // GOOGLE_JAPANESE_INPUT_BUILD
256 # else // GOOGLE_JAPANESE_INPUT_BUILD
242257 dir = FileUtil::JoinPath(dir, "Mozc");
243 #endif // GOOGLE_JAPANESE_INPUT_BUILD
244
245 #elif defined(OS_WASM)
246 // Do nothing for WebAssembly.
247 return;
248 #elif defined(OS_ANDROID)
249 // For android, we do nothing here because user profile directory,
250 // of which the path depends on active user,
251 // is injected from Java layer.
252
253 #else // !OS_IOS && !OS_WIN && !__APPLE__ && !OS_ANDROID
258 # endif // GOOGLE_JAPANESE_INPUT_BUILD
259 #endif // __APPLE__
260
261 #if defined(OS_LINUX)
254262 char buf[1024];
255263 struct passwd pw, *ppw;
256264 const uid_t uid = geteuid();
259267 CHECK_LT(0, strlen(pw.pw_dir))
260268 << "Home directory for uid " << uid << " is not set.";
261269 dir = FileUtil::JoinPath(pw.pw_dir, ".mozc");
262 #endif // !OS_IOS && !OS_WIN && !__APPLE__ && !OS_ANDROID
270 #endif // OS_LINUX
263271
264272 FileUtil::CreateDirectory(dir);
265273 if (!FileUtil::DirectoryExists(dir)) {
268276
269277 // set User profile directory
270278 dir_ = dir;
271 #endif // !OS_NACL && !OS_CHROMEOS
272279 }
273280
274281 } // namespace
366373 std::string SystemUtil::GetServerDirectory() {
367374 #ifdef OS_WIN
368375 DCHECK(SUCCEEDED(Singleton<ProgramFilesX86Cache>::get()->result()));
369 #if defined(GOOGLE_JAPANESE_INPUT_BUILD)
376 # if defined(GOOGLE_JAPANESE_INPUT_BUILD)
370377 return FileUtil::JoinPath(
371378 FileUtil::JoinPath(Singleton<ProgramFilesX86Cache>::get()->path(),
372379 kCompanyNameInEnglish),
373380 kProductNameInEnglish);
374 #else // GOOGLE_JAPANESE_INPUT_BUILD
381 # else // GOOGLE_JAPANESE_INPUT_BUILD
375382 return FileUtil::JoinPath(Singleton<ProgramFilesX86Cache>::get()->path(),
376383 kProductNameInEnglish);
377 #endif // GOOGLE_JAPANESE_INPUT_BUILD
378
379 #elif defined(__APPLE__)
384 # endif // GOOGLE_JAPANESE_INPUT_BUILD
385 #endif // OS_WIN
386
387 #if defined(__APPLE__)
380388 return MacUtil::GetServerDirectory();
381
382 #elif defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_NACL) || \
389 #endif // __APPLE__
390
391 #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_NACL) || \
383392 defined(OS_WASM)
384 #if defined(MOZC_SERVER_DIRECTORY)
393 # if defined(MOZC_SERVER_DIRECTORY)
385394 return MOZC_SERVER_DIRECTORY;
386 #else
395 # else
387396 return "/usr/lib/mozc";
388 #endif // MOZC_SERVER_DIRECTORY
389
390 #endif // OS_WIN, __APPLE__, OS_LINUX, ...
397 # endif // MOZC_SERVER_DIRECTORY
398
399 #else // OS_LINUX || OS_ANDROID || OS_NACL || OS_WASM
400 # error "unknown platform"
401
402 #endif // OS_LINUX || OS_ANDROID || OS_NACL || OS_WASM
391403 }
392404
393405 std::string SystemUtil::GetServerPath() {
437449 #ifdef OS_NACL
438450 LOG(ERROR) << "SystemUtil::GetUserNameAsString() is not implemented in NaCl.";
439451 return "username";
440
441 #elif defined(OS_WIN) // OS_NACL
452 #endif // OS_NACL
453
454 #if defined(OS_WIN)
442455 wchar_t wusername[UNLEN + 1];
443456 DWORD name_size = UNLEN + 1;
444457 // Call the same name Windows API. (include Advapi32.lib).
450463 string username;
451464 Util::WideToUTF8(&wusername[0], &username);
452465 return username;
453
454 #elif defined(OS_ANDROID) // OS_WIN
466 #endif // OS_WIN
467
468 #if defined(OS_ANDROID)
455469 // Android doesn't seem to support getpwuid_r.
456470 struct passwd *ppw = getpwuid(geteuid());
457 CHECK(ppw != NULL);
471 CHECK(ppw != nullptr);
458472 return ppw->pw_name;
459
460 #else // OS_ANDROID
473 #endif // OS_ANDROID
474
461475 // __APPLE__, OS_LINUX or OS_NACL
462476 struct passwd pw, *ppw;
463477 char buf[1024];
464478 CHECK_EQ(0, getpwuid_r(geteuid(), &pw, buf, sizeof(buf), &ppw));
465479 return pw.pw_name;
466 #endif // !OS_NACL && !OS_WIN && !OS_ANDROID
467480 }
468481
469482 #ifdef OS_WIN
488501
489502 DWORD length = 0;
490503 ::GetTokenInformation(htoken, TokenUser, nullptr, 0, &length);
491 unique_ptr<char[]> buf(new char[length]);
504 std::unique_ptr<char[]> buf(new char[length]);
492505 PTOKEN_USER p_user = reinterpret_cast<PTOKEN_USER>(buf.get());
493506
494507 if (length == 0 ||
545558 return "";
546559 }
547560
548 unique_ptr<char[]> buf(new char[size]);
561 std::unique_ptr<char[]> buf(new char[size]);
549562 DWORD return_size = 0;
550563 if (!::GetUserObjectInformationA(handle, UOI_NAME, buf.get(), size,
551564 &return_size)) {
559572 }
560573
561574 char *result = buf.get();
562 result[return_size - 1] = '\0'; // just make sure NULL terminated
575 result[return_size - 1] = '\0'; // just make sure nullptr terminated
563576
564577 return result;
565578 }
621634 #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_NACL) || \
622635 defined(OS_WASM)
623636 const char *display = getenv("DISPLAY");
624 if (display == NULL) {
637 if (display == nullptr) {
625638 return "";
626639 }
627640 return display;
628
629 #elif defined(__APPLE__)
641 #endif // OS_LINUX || OS_ANDROID || OS_NACL || OS_WASM
642
643 #if defined(__APPLE__)
630644 return "";
631
632 #elif defined(OS_WIN)
645 #endif // __APPLE__
646
647 #if defined(OS_WIN)
633648 const string &session_id = GetSessionIdString();
634649 if (session_id.empty()) {
635650 DLOG(ERROR) << "Failed to retrieve session id";
649664 }
650665
651666 return (session_id + "." + window_station_name + "." + desktop_name);
652 #endif // OS_LINUX, __APPLE__, OS_WIN, ...
667 #endif // OS_WIN
653668 }
654669
655670 #ifdef OS_WIN
839854 return 0;
840855 }
841856 return memory_status.ullTotalPhys;
842 #elif defined(__APPLE__)
857 #endif // OS_WIN
858
859 #if defined(__APPLE__)
843860 int mib[] = {CTL_HW, HW_MEMSIZE};
844861 uint64 total_memory = 0;
845862 size_t size = sizeof(total_memory);
846 const int error = sysctl(mib, arraysize(mib), &total_memory, &size, NULL, 0);
863 const int error =
864 sysctl(mib, arraysize(mib), &total_memory, &size, nullptr, 0);
847865 if (error == -1) {
848866 const int error = errno;
849867 LOG(ERROR) << "sysctl with hw.memsize failed. "
851869 return 0;
852870 }
853871 return total_memory;
854 #elif defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_NACL) || \
872 #endif // __APPLE__
873
874 #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_NACL) || \
855875 defined(OS_WASM)
856 #if defined(_SC_PAGESIZE) && defined(_SC_PHYS_PAGES)
857 const long page_size = sysconf(_SC_PAGESIZE);
858 const long number_of_phyisical_pages = sysconf(_SC_PHYS_PAGES);
876 # if defined(_SC_PAGESIZE) && defined(_SC_PHYS_PAGES)
877 const int32 page_size = sysconf(_SC_PAGESIZE);
878 const int32 number_of_phyisical_pages = sysconf(_SC_PHYS_PAGES);
859879 if (number_of_phyisical_pages < 0) {
860880 // likely to be overflowed.
861881 LOG(FATAL) << number_of_phyisical_pages << ", " << page_size;
862882 return 0;
863883 }
864884 return static_cast<uint64>(number_of_phyisical_pages) * page_size;
865 #else // defined(_SC_PAGESIZE) && defined(_SC_PHYS_PAGES)
885 # else // defined(_SC_PAGESIZE) && defined(_SC_PHYS_PAGES)
866886 return 0;
867 #endif // defined(_SC_PAGESIZE) && defined(_SC_PHYS_PAGES)
868 #else // !(defined(OS_WIN) || defined(__APPLE__) || defined(OS_LINUX))
869 #error "unknown platform"
870 #endif // OS_WIN, __APPLE__, OS_LINUX
887 # endif // defined(_SC_PAGESIZE) && defined(_SC_PHYS_PAGES)
888
889 #else // OS_LINUX || OS_ANDROID || OS_NACL || OS_WASM
890 # error "unknown platform"
891
892 #endif // OS_LINUX || OS_ANDROID || OS_NACL || OS_WASM
871893 }
872894
873895 } // namespace mozc
141141 static void SetIsWindowsX64ModeForTest(IsWindowsX64Mode mode);
142142
143143 #ifdef OS_WIN
144 // return system directory. If failed, return NULL.
144 // return system directory. If failed, return nullptr.
145145 // You need not to delete the returned pointer.
146146 // This function is thread safe.
147147 static const wchar_t *GetSystemDir();
4343
4444 #ifdef OS_WIN
4545 UnnamedEvent::UnnamedEvent()
46 : handle_(::CreateEvent(NULL, FALSE, FALSE, NULL)) {
46 : handle_(::CreateEvent(nullptr, FALSE, FALSE, nullptr)) {
4747 // Use Auto reset mode of Win32 Event. (2nd arg of CreateEvent).
4848 // pthread_cond_signal: auto reset mode.
4949 // pthread_cond_broadcast: manual reset mode.
50 if (NULL == handle_.get()) {
50 if (nullptr == handle_.get()) {
5151 LOG(ERROR) << "CreateEvent failed: " << ::GetLastError();
5252 }
5353 }
5454
5555 UnnamedEvent::~UnnamedEvent() {}
5656
57 bool UnnamedEvent::IsAvailable() const { return (NULL != handle_.get()); }
57 bool UnnamedEvent::IsAvailable() const { return (nullptr != handle_.get()); }
5858
5959 bool UnnamedEvent::Notify() {
6060 if (!IsAvailable()) {
9999 } // namespace
100100
101101 UnnamedEvent::UnnamedEvent() : notified_(false) {
102 pthread_mutex_init(&mutex_, NULL);
103 pthread_cond_init(&cond_, NULL);
102 pthread_mutex_init(&mutex_, nullptr);
103 pthread_cond_init(&cond_, nullptr);
104104 }
105105
106106 // It is necessary to ensure that no threads wait for this event before the
155155 } else {
156156 // Wait with time out.
157157 struct timeval tv;
158 if (gettimeofday(&tv, NULL) != 0) {
158 if (gettimeofday(&tv, nullptr) != 0) {
159159 LOG(ERROR) << "Failed to take the current time: " << errno;
160160 return false;
161161 }
4444 L"Software\\Google\\Update\\ClientState\\"
4545 L"{DDCCD2A9-025E-4142-BCEB-F467B88CF830}";
4646 HKEY key;
47 LONG result = RegCreateKeyExW(HKEY_CURRENT_USER, kOmahaUsageKey, 0, NULL, 0,
48 KEY_WRITE, NULL, &key, NULL);
47 LONG result = RegCreateKeyExW(HKEY_CURRENT_USER, kOmahaUsageKey, 0, nullptr,
48 0, KEY_WRITE, nullptr, &key, nullptr);
4949 if (ERROR_SUCCESS != result) {
5050 return false;
5151 }
3535 // clang-format on
3636 #include <stdio.h> // MSVC requires this for _vsnprintf
3737 #include <time.h>
38 #else // OS_WIN
38 #endif // OS_WIN
3939
4040 #ifdef __APPLE__
4141 #include <mach/mach.h>
4242 #include <mach/mach_time.h>
43
44 #elif defined(OS_NACL) // __APPLE__
43 #endif // __APPLE__
44
45 #if defined(OS_NACL)
4546 #include <irt.h>
46 #endif // __APPLE__ or OS_NACL
47 #endif // OS_NACL
48
49 #ifndef OS_WIN
4750 #include <sys/mman.h>
4851 #include <sys/time.h>
4952 #include <unistd.h>
50 #endif // OS_WIN
53 #endif // !OS_WIN
5154
5255 #include <algorithm>
5356 #include <cctype>
240243 str[input.size()] = '\0';
241244
242245 char *eos = str + input.size();
243 char *start = NULL;
244 char *end = NULL;
246 char *start = nullptr;
247 char *end = nullptr;
245248 output->clear();
246249
247250 while (str < eos) {
495498 bool Util::SplitFirstChar32(absl::string_view s, char32 *first_char32,
496499 absl::string_view *rest) {
497500 char32 dummy_char32 = 0;
498 if (first_char32 == NULL) {
501 if (first_char32 == nullptr) {
499502 first_char32 = &dummy_char32;
500503 }
501504 absl::string_view dummy_rest;
502 if (rest == NULL) {
505 if (rest == nullptr) {
503506 rest = &dummy_rest;
504507 }
505508
587590 bool Util::SplitLastChar32(absl::string_view s, absl::string_view *rest,
588591 char32 *last_char32) {
589592 absl::string_view dummy_rest;
590 if (rest == NULL) {
593 if (rest == nullptr) {
591594 rest = &dummy_rest;
592595 }
593596 char32 dummy_char32 = 0;
594 if (last_char32 == NULL) {
597 if (last_char32 == nullptr) {
595598 last_char32 = &dummy_char32;
596599 }
597600
700703 #ifdef OS_WIN
701704 size_t Util::WideCharsLen(absl::string_view src) {
702705 const int num_chars =
703 ::MultiByteToWideChar(CP_UTF8, 0, src.begin(), src.size(), NULL, 0);
706 ::MultiByteToWideChar(CP_UTF8, 0, src.begin(), src.size(), nullptr, 0);
704707 if (num_chars <= 0) {
705708 return 0;
706709 }
725728
726729 int Util::WideToUTF8(const wchar_t *input, string *output) {
727730 const int output_length =
728 WideCharToMultiByte(CP_UTF8, 0, input, -1, NULL, 0, NULL, NULL);
731 WideCharToMultiByte(CP_UTF8, 0, input, -1, nullptr, 0, nullptr, nullptr);
729732 if (output_length == 0) {
730733 return 0;
731734 }
733736 std::unique_ptr<char[]> input_encoded(new char[output_length + 1]);
734737 const int result =
735738 WideCharToMultiByte(CP_UTF8, 0, input, -1, input_encoded.get(),
736 output_length + 1, NULL, NULL);
739 output_length + 1, nullptr, nullptr);
737740 if (result > 0) {
738741 output->assign(input_encoded.get());
739742 }
825828 memset(buf, '\0', buf_size);
826829 #ifdef OS_WIN
827830 HCRYPTPROV hprov;
828 if (!::CryptAcquireContext(&hprov, NULL, NULL, PROV_RSA_FULL,
831 if (!::CryptAcquireContext(&hprov, nullptr, nullptr, PROV_RSA_FULL,
829832 CRYPT_VERIFYCONTEXT)) {
830833 return false;
831834 }
836839 }
837840 ::CryptReleaseContext(hprov, 0);
838841 return true;
839 #elif defined(OS_NACL)
842 #endif // OS_WIN
843
844 #if defined(OS_NACL)
840845 struct nacl_irt_random interface;
841846
842847 if (nacl_interface_query(NACL_IRT_RANDOM_v0_1, &interface,
856861 return false;
857862 }
858863 return true;
859 #else // !OS_WIN && !OS_NACL
864 #endif
865
866 #if defined(OS_CHROMEOS)
867 // TODO(googleo): b/171939770 Accessing "/dev/urandom" is not allowed in
868 // "ime" sandbox. Returns false to use the self-implemented random number
869 // instead. When the API is unblocked, remove the hack.
870 return false;
871 #endif // OS_CHROMEOS
872
860873 // Use non blocking interface on Linux.
861874 // Mac also have /dev/urandom (although it's identical with /dev/random)
862875 std::ifstream ifs("/dev/urandom", std::ios::binary);
865878 }
866879 ifs.read(buf, buf_size);
867880 return true;
868 #endif // OS_WIN or OS_NACL
869881 }
870882 } // namespace
871883
12691281 void Util::AppendCGIParams(
12701282 const std::vector<std::pair<std::string, std::string> > &params,
12711283 std::string *base) {
1272 if (params.size() == 0 || base == NULL) {
1284 if (params.size() == 0 || base == nullptr) {
12731285 return;
12741286 }
12751287
15501562 if (s.size() != 8) {
15511563 return false;
15521564 }
1565 // The following operations assume `char` is unsigned (i.e. -funsigned-char).
15531566 *x = static_cast<uint64>(s[0]) << 56 | static_cast<uint64>(s[1]) << 48 |
15541567 static_cast<uint64>(s[2]) << 40 | static_cast<uint64>(s[3]) << 32 |
15551568 static_cast<uint64>(s[4]) << 24 | static_cast<uint64>(s[5]) << 16 |
15601573 bool Util::IsLittleEndian() {
15611574 #ifdef OS_WIN
15621575 return true;
1563 #else // OS_WIN
1576 #endif // OS_WIN
1577
15641578 union {
15651579 unsigned char c[4];
15661580 unsigned int i;
15701584 static_assert(sizeof(u) == sizeof(u.i), "Checking alignment.");
15711585 u.i = 0x12345678U;
15721586 return u.c[0] == 0x78U;
1573 #endif // OS_WIN
15741587 }
15751588
15761589 } // namespace mozc
213213 static size_t UCS4ToUTF8(char32 c, char *output);
214214
215215 // Returns true if |s| is split into |first_char32| + |rest|.
216 // You can pass NULL to |first_char32| and/or |rest| to ignore the matched
216 // You can pass nullptr to |first_char32| and/or |rest| to ignore the matched
217217 // value.
218218 // Returns false if an invalid UTF-8 sequence is prefixed. That is, |rest| may
219219 // contain any invalid sequence even when this method returns true.
221221 absl::string_view *rest);
222222
223223 // Returns true if |s| is split into |rest| + |last_char32|.
224 // You can pass NULL to |rest| and/or |last_char32| to ignore the matched
224 // You can pass nullptr to |rest| and/or |last_char32| to ignore the matched
225225 // value.
226226 // Returns false if an invalid UTF-8 sequence is suffixed. That is, |rest| may
227227 // contain any invalid sequence even when this method returns true.
5858 }
5959
6060 TEST(WinSandboxTest, GetSidsToDisable) {
61 HANDLE process_token_ret = NULL;
61 HANDLE process_token_ret = nullptr;
6262 ::OpenProcessToken(::GetCurrentProcess(), TOKEN_ALL_ACCESS,
6363 &process_token_ret);
6464 ScopedHandle process_token(process_token_ret);
9191 }
9292
9393 TEST(WinSandboxTest, GetPrivilegesToDisable) {
94 HANDLE process_token_ret = NULL;
94 HANDLE process_token_ret = nullptr;
9595 ::OpenProcessToken(::GetCurrentProcess(), TOKEN_ALL_ACCESS,
9696 &process_token_ret);
9797 ScopedHandle process_token(process_token_ret);
117117 }
118118
119119 TEST(WinSandboxTest, GetSidsToRestrict) {
120 HANDLE process_token_ret = NULL;
120 HANDLE process_token_ret = nullptr;
121121 ::OpenProcessToken(::GetCurrentProcess(), TOKEN_ALL_ACCESS,
122122 &process_token_ret);
123123 ScopedHandle process_token(process_token_ret);
4545 // system directory.
4646 // If the function succeeds, the return value is a handle to the module.
4747 // You should call FreeLibrary with the handle.
48 // If the function fails, the return value is NULL.
48 // If the function fails, the return value is nullptr.
4949 static HMODULE LoadSystemLibrary(const std::wstring &base_filename);
5050
5151 // Load a DLL which has the specified base-name and is located in the
5252 // Mozc server directory.
5353 // If the function succeeds, the return value is a handle to the module.
5454 // You should call FreeLibrary with the handle.
55 // If the function fails, the return value is NULL.
55 // If the function fails, the return value is nullptr.
5656 static HMODULE LoadMozcLibrary(const std::wstring &base_filename);
5757
5858 // If a DLL which has the specified base-name and located in the system
6060 // If the function succeeds, the return value is a handle to the module
6161 // without incrementing its reference count so that you should not call
6262 // FreeLibrary with the handle.
63 // If the function fails, the return value is NULL.
63 // If the function fails, the return value is nullptr.
6464 static HMODULE GetSystemModuleHandle(const std::wstring &base_filename);
6565
6666 // A variant ot GetSystemModuleHandle except that this method increments
171171 ScopedCOMInitializer();
172172 ScopedCOMInitializer::~ScopedCOMInitializer();
173173
174 // Returns the error code from CoInitialize(NULL)
174 // Returns the error code from CoInitialize(nullptr)
175175 // (called in constructor)
176176 inline HRESULT error_code() const { return hr_; }
177177
202202 EXPECT_TRUE(LooksLikeNtPath(nt_system_dir));
203203
204204 EXPECT_FALSE(WinUtil::GetNtPath(system_dir, nullptr))
205 << "Must fail against a NULL argument.";
205 << "Must fail against a nullptr argument.";
206206
207207 std::wstring nt_notepad;
208208 EXPECT_TRUE(WinUtil::GetNtPath(notepad, &nt_notepad))
6060 // program name into standard argc/argv parameters.
6161 class WinCommandLine {
6262 public:
63 WinCommandLine() : argc_(0), argv_(NULL) {
63 WinCommandLine() : argc_(0), argv_(nullptr) {
6464 LPWSTR *argvw = ::CommandLineToArgvW(::GetCommandLineW(), &argc_);
65 if (argvw == NULL) {
65 if (argvw == nullptr) {
6666 return;
6767 }
6868
8383 delete[] argv_[i];
8484 }
8585 delete[] argv_;
86 argv_ = NULL;
86 argv_ = nullptr;
8787 }
8888
8989 int argc() const { return argc_; }
117117 DWORD vt = 0;
118118 HKEY hKey = 0;
119119 if (ERROR_SUCCESS == ::RegOpenKeyExW(HKEY_CURRENT_USER, mozc::kMozcRegKey,
120 NULL, KEY_READ, &hKey)) {
120 nullptr, KEY_READ, &hKey)) {
121121 if (ERROR_SUCCESS == ::RegQueryValueExW(
122 hKey, L"debug_sleep_time", NULL, &vt,
122 hKey, L"debug_sleep_time", nullptr, &vt,
123123 reinterpret_cast<BYTE *>(&sleep_time), &size) &&
124124 vt == REG_DWORD && sleep_time > 0) {
125125 ::Sleep(sleep_time * 1000);
292292 static_cast<MozcSessionHandlerThread *>(data);
293293 usage_stats::UsageStats::SetInteger("BigDictionaryState",
294294 self->GetBigDictionaryState());
295 return usage_stats::UsageStatsUploader::Send(NULL);
295 return usage_stats::UsageStatsUploader::Send(nullptr);
296296 }
297297 #endif // GOOGLE_JAPANESE_INPUT_BUILD
298298
390390 // We use dummy argc and argv to call mozc::InitMozc().
391391 int argc = 1;
392392 char argv0[] = "NaclModule";
393 char *argv_body[] = {argv0, NULL};
393 char *argv_body[] = {argv0, nullptr};
394394 char **argv = argv_body;
395395 mozc::InitMozc(argv[0], &argc, &argv);
396396
3232 "cc_binary_mozc",
3333 "cc_library_mozc",
3434 "cc_test_mozc",
35 "py_binary_mozc",
3536 "select_mozc",
3637 )
3738
198199 ],
199200 )
200201
202 py_binary_mozc(
203 name = "gen_client_quality_test_data",
204 srcs = ["gen_client_quality_test_data.py"],
205 )
206
207 genrule(
208 name = "client_quality_test_data",
209 srcs = [
210 # TSV files formatted as "label <tab> expected <tab> query"
211 ],
212 outs = ["client_quality_test_data.inc"],
213 cmd = "$(location :gen_client_quality_test_data) $(SRCS) > $@",
214 exec_tools = [":gen_client_quality_test_data"],
215 )
216
217 cc_binary_mozc(
218 name = "client_quality_test_main",
219 srcs = [
220 "client_quality_test_main.cc",
221 ":client_quality_test_data",
222 ],
223 deps = [
224 ":client",
225 "//base",
226 "//base:file_stream",
227 "//base:flags",
228 "//base:init_mozc",
229 "//base:logging",
230 "//base:multifile",
231 "//base:port",
232 "//base:util",
233 "//evaluation:scorer",
234 "//protocol:commands_proto",
235 "@com_google_absl//absl/strings",
236 ],
237 )
392392 }
393393
394394 void Client::EnableCascadingWindow(const bool enable) {
395 if (preferences_.get() == NULL) {
395 if (preferences_ == nullptr) {
396396 preferences_.reset(new config::Config);
397397 }
398398 preferences_->set_use_cascading_window(enable);
535535
536536 // PingServer ignores all server status
537537 bool Client::PingServer() const {
538 if (client_factory_ == NULL) {
538 if (client_factory_ == nullptr) {
539539 return false;
540540 }
541541
549549 std::unique_ptr<IPCClientInterface> client(client_factory_->NewClient(
550550 kServerAddress, server_launcher_->server_program()));
551551
552 if (client.get() == NULL) {
552 if (client == nullptr) {
553553 LOG(ERROR) << "Cannot make client object";
554554 return false;
555555 }
605605 return false;
606606 }
607607
608 if (client_factory_ == NULL) {
608 if (client_factory_ == nullptr) {
609609 return false;
610610 }
611611
628628 server_product_version_ = Version::GetMozcVersion();
629629 server_process_id_ = 0;
630630
631 if (client.get() == NULL) {
631 if (client == nullptr) {
632632 LOG(ERROR) << "Cannot make client object";
633633 server_status_ = SERVER_FATAL;
634634 return false;
689689 }
690690
691691 bool Client::StartServer() {
692 if (server_launcher_.get() != NULL) {
692 if (server_launcher_ != nullptr) {
693693 return server_launcher_->StartServer(this);
694694 }
695695 return true;
696696 }
697697
698698 void Client::OnFatal(ServerLauncherInterface::ServerErrorType type) {
699 if (server_launcher_.get() != NULL) {
699 if (server_launcher_ != nullptr) {
700700 server_launcher_->OnFatal(type);
701701 }
702702 }
703703
704704 void Client::InitInput(commands::Input *input) const {
705705 input->set_id(id_);
706 if (preferences_.get() != NULL) {
706 if (preferences_ != nullptr) {
707707 input->mutable_config()->CopyFrom(*preferences_);
708708 }
709709 }
791791
792792 bool Client::TranslateProtoBufToMozcToolArg(const commands::Output &output,
793793 std::string *mode) {
794 if (!output.has_launch_tool_mode() || mode == NULL) {
794 if (!output.has_launch_tool_mode() || mode == nullptr) {
795795 return false;
796796 }
797797
906906 virtual ClientInterface *NewClient() { return new Client; }
907907 };
908908
909 ClientFactoryInterface *g_client_factory = NULL;
909 ClientFactoryInterface *g_client_factory = nullptr;
910910 } // namespace
911911
912912 ClientInterface *ClientFactory::NewClient() {
913 if (g_client_factory == NULL) {
913 if (g_client_factory == nullptr) {
914914 return Singleton<DefaultClientFactory>::get()->NewClient();
915915 } else {
916916 return g_client_factory->NewClient();
211211
212212 std::map<std::string, std::vector<double> > scores; // Results to be averaged
213213
214 for (mozc::TestCase* test_case = mozc::test_cases; test_case->source != NULL;
215 ++test_case) {
214 for (mozc::TestCase* test_case = mozc::test_cases;
215 test_case->source != nullptr; ++test_case) {
216216 const std::string& source = test_case->source;
217217 const std::string& hiragana_sentence = test_case->hiragana_sentence;
218218 const std::string& expected_result = test_case->expected_result;
149149 client.SendKey(keys[i], &output);
150150 VLOG(2) << "Output of SendKey: " << output.DebugString();
151151
152 if (renderer_client.get() != NULL) {
152 if (renderer_client != nullptr) {
153153 renderer_command.set_type(commands::RendererCommand::UPDATE);
154154 renderer_command.set_visible(output.has_candidates());
155155 renderer_command.mutable_output()->CopyFrom(output);
178178 }
179179
180180 std::unique_ptr<mozc::InputFileStream> input_file;
181 std::istream *input = NULL;
181 std::istream *input = nullptr;
182182
183183 if (!FLAGS_input.empty()) {
184184 // Batch mode loading the input file.
130130 client.SendKey(keys[i], &output);
131131 VLOG(2) << "Output of SendKey: " << output.DebugString();
132132
133 if (renderer_client.get() != NULL) {
133 if (renderer_client != nullptr) {
134134 renderer_command.set_type(mozc::commands::RendererCommand::UPDATE);
135135 renderer_command.set_visible(output.has_candidates());
136136 renderer_command.mutable_output()->CopyFrom(output);
2727 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2828 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2929
30 """Generate a C++ include file for testing data from TSV files."""
31
32 from __future__ import print_function
33
3034 import codecs
3135 import logging
3236 import sys
3337
3438
3539 def escape(string):
36 return ''.join('\\x%02x' % ord(char) for char in string.encode('utf-8'))
40 return ''.join('\\x%02x' % char for char in string.encode('utf-8'))
3741
3842
3943 def convert_tsv(filename):
44 """Loads a TSV file and returns an entry of TestCase."""
4045 tsv = codecs.open(filename, 'rb', 'utf-8')
4146 for line in tsv:
4247 line = line.rstrip()
5661 expected = fields[4]
5762 query = fields[5]
5863
59 print ' // {"%s", "%s", "%s"},' % (label, expected, query)
60 print (' {"%s", "%s", "%s"},' %
61 (escape(label), escape(expected), escape(query)))
64 print(' // {"%s", "%s", "%s"},' % (label, expected, query))
65 print(' {"%s", "%s", "%s"},' %
66 (escape(label), escape(expected), escape(query)))
6267 tsv.close()
6368
6469
6570 def main():
66 sys.stdin = codecs.getreader('utf-8')(sys.stdin)
67 sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
68 sys.stderr = codecs.getwriter('utf-8')(sys.stderr)
69 logging.basicConfig(level = logging.INFO)
71 sys.stdin = codecs.getreader('utf-8')(sys.stdin.buffer)
72 sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer)
73 sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer)
74 logging.basicConfig(level=logging.INFO)
7075
71 print '// Automatically generated by mozc'
72 print '#ifndef MOZC_SESSION_QUALITY_MAIN_DATA_H_'
73 print '#define MOZC_SESSION_QUALITY_MAIN_DATA_H_'
74 print ''
75 print 'namespace mozc {'
76 print 'struct TestCase {'
77 print ' const char* source;'
78 print ' const char* expected_result;'
79 print ' const char* hiragana_sentence;'
80 print '};'
81 print ''
82 print 'static TestCase test_cases[] = {'
76 print('// Automatically generated by mozc')
77 print('#ifndef MOZC_SESSION_QUALITY_MAIN_DATA_H_')
78 print('#define MOZC_SESSION_QUALITY_MAIN_DATA_H_')
79 print('')
80 print('namespace mozc {')
81 print('struct TestCase {')
82 print(' const char* source;')
83 print(' const char* expected_result;')
84 print(' const char* hiragana_sentence;')
85 print('};')
86 print('')
87 print('static TestCase test_cases[] = {')
8388
8489 for filename in sys.argv[1:]:
8590 convert_tsv(filename)
8691
87 print ' {NULL, NULL, NULL}'
88 print '};'
89 print '} // namespace mozc'
90 print '#endif // MOZC_SESSION_QUALITY_MAIN_DATA_H_'
92 print(' {nullptr, nullptr, nullptr}')
93 print('};')
94 print('} // namespace mozc')
95 print('#endif // MOZC_SESSION_QUALITY_MAIN_DATA_H_')
9196
9297
9398 if __name__ == '__main__':
10431043
10441044 // static
10451045 bool Composer::TransformCharactersForNumbers(std::string *query) {
1046 if (query == NULL) {
1047 LOG(ERROR) << "query is NULL";
1046 if (query == nullptr) {
1047 LOG(ERROR) << "query is nullptr";
10481048 return false;
10491049 }
10501050
11081108 composer_->GetStringForSubmission(&src_composition);
11091109 EXPECT_EQ("", src_composition);
11101110
1111 Composer dest(NULL, request_.get(), config_.get());
1111 Composer dest(nullptr, request_.get(), config_.get());
11121112 dest.CopyFrom(*composer_);
11131113
11141114 ExpectSameComposer(*composer_, dest);
11231123 composer_->GetStringForSubmission(&src_composition);
11241124 EXPECT_EQ("あn", src_composition);
11251125
1126 Composer dest(NULL, request_.get(), config_.get());
1126 Composer dest(nullptr, request_.get(), config_.get());
11271127 dest.CopyFrom(*composer_);
11281128
11291129 ExpectSameComposer(*composer_, dest);
11361136 composer_->GetQueryForConversion(&src_composition);
11371137 EXPECT_EQ("あん", src_composition);
11381138
1139 Composer dest(NULL, request_.get(), config_.get());
1139 Composer dest(nullptr, request_.get(), config_.get());
11401140 dest.CopyFrom(*composer_);
11411141
11421142 ExpectSameComposer(*composer_, dest);
11551155 composer_->GetStringForSubmission(&src_composition);
11561156 EXPECT_EQ("AaAAあ", src_composition);
11571157
1158 Composer dest(NULL, request_.get(), config_.get());
1158 Composer dest(nullptr, request_.get(), config_.get());
11591159 dest.CopyFrom(*composer_);
11601160
11611161 ExpectSameComposer(*composer_, dest);
11731173 composer_->GetStringForSubmission(&src_composition);
11741174 EXPECT_EQ("M", src_composition);
11751175
1176 Composer dest(NULL, request_.get(), config_.get());
1176 Composer dest(nullptr, request_.get(), config_.get());
11771177 dest.CopyFrom(*composer_);
11781178
11791179 ExpectSameComposer(*composer_, dest);
155155 size_t key_length = 0;
156156 bool fixed = false;
157157 const Entry *entry = table_->LookUpPrefix(pending_, &key_length, &fixed);
158 if (entry != NULL && entry->input() == entry->result()) {
158 if (entry != nullptr && entry->input() == entry->result()) {
159159 converted.append(entry->result());
160160 }
161161 }
303303 const Entry *entry = table_->LookUpPrefix(key, &key_length, &fixed);
304304 local_length_cache_ = std::string::npos;
305305
306 if (entry == NULL) {
306 if (entry == nullptr) {
307307 if (key_length == 0) {
308308 // No prefix character is not contained in the table, fallback
309309 // operation is performed.
338338 return kNoLoop;
339339 }
340340
341 // The prefix of key reached a conversion result, thus entry is not NULL.
341 // The prefix of key reached a conversion result, thus entry is not nullptr.
342342
343343 if (key.size() == key_length) {
344344 const bool is_following_entry =
420420 // If this entry is the first entry, the table attributes are
421421 // applied to this chunk.
422422 const Entry *entry = table_->LookUp(pending_);
423 if (entry != NULL) {
423 if (entry != nullptr) {
424424 attributes_ = entry->attributes();
425425 }
426426 return;
430430 size_t key_length = 0;
431431 bool fixed = false;
432432 const Entry *entry = table_->LookUpPrefix(input, &key_length, &fixed);
433 if (entry == NULL) {
433 if (entry == nullptr) {
434434 // Do not modify this char_chunk, all key and converted_char
435435 // values will be used by the next char_chunk.
436436 return;
190190 }
191191
192192 TEST(CharChunkTest, GetLength) {
193 CharChunk chunk1(Transliterators::CONVERSION_STRING, NULL);
193 CharChunk chunk1(Transliterators::CONVERSION_STRING, nullptr);
194194 chunk1.set_conversion("ね");
195195 chunk1.set_pending("");
196196 chunk1.set_raw("ne");
197197 EXPECT_EQ(1, chunk1.GetLength(Transliterators::CONVERSION_STRING));
198198 EXPECT_EQ(2, chunk1.GetLength(Transliterators::RAW_STRING));
199199
200 CharChunk chunk2(Transliterators::CONVERSION_STRING, NULL);
200 CharChunk chunk2(Transliterators::CONVERSION_STRING, nullptr);
201201 chunk2.set_conversion("っと");
202202 chunk2.set_pending("");
203203 chunk2.set_raw("tto");
204204 EXPECT_EQ(2, chunk2.GetLength(Transliterators::CONVERSION_STRING));
205205 EXPECT_EQ(3, chunk2.GetLength(Transliterators::RAW_STRING));
206206
207 CharChunk chunk3(Transliterators::CONVERSION_STRING, NULL);
207 CharChunk chunk3(Transliterators::CONVERSION_STRING, nullptr);
208208 chunk3.set_conversion("が");
209209 chunk3.set_pending("");
210210 chunk3.set_raw("ga");
362362 EXPECT_EQ("mo", output);
363363
364364 // Split "mo" to "m" and "o".
365 CharChunk *left_chunk_ptr = NULL;
365 CharChunk *left_chunk_ptr = nullptr;
366366 chunk.SplitChunk(Transliterators::LOCAL, 1, &left_chunk_ptr);
367367 std::unique_ptr<CharChunk> left_chunk(left_chunk_ptr);
368368
994994 chunk.AddInput(&input);
995995 }
996996
997 CharChunk *left_new_chunk_ptr = NULL;
997 CharChunk *left_new_chunk_ptr = nullptr;
998998 chunk.SplitChunk(Transliterators::HIRAGANA, size_t(1), &left_new_chunk_ptr);
999999 std::unique_ptr<CharChunk> left_new_chunk(left_new_chunk_ptr);
10001000 {
10061006
10071007 TEST(CharChunkTest, Combine) {
10081008 {
1009 CharChunk lhs(Transliterators::CONVERSION_STRING, NULL);
1010 CharChunk rhs(Transliterators::CONVERSION_STRING, NULL);
1009 CharChunk lhs(Transliterators::CONVERSION_STRING, nullptr);
1010 CharChunk rhs(Transliterators::CONVERSION_STRING, nullptr);
10111011 lhs.set_ambiguous("LA");
10121012 lhs.set_conversion("LC");
10131013 lhs.set_pending("LP");
10261026 }
10271027
10281028 { // lhs' ambigous is empty.
1029 CharChunk lhs(Transliterators::CONVERSION_STRING, NULL);
1030 CharChunk rhs(Transliterators::CONVERSION_STRING, NULL);
1029 CharChunk lhs(Transliterators::CONVERSION_STRING, nullptr);
1030 CharChunk rhs(Transliterators::CONVERSION_STRING, nullptr);
10311031
10321032 lhs.set_ambiguous("");
10331033 lhs.set_conversion("LC");
10471047 }
10481048
10491049 { // rhs' ambigous is empty.
1050 CharChunk lhs(Transliterators::CONVERSION_STRING, NULL);
1051 CharChunk rhs(Transliterators::CONVERSION_STRING, NULL);
1050 CharChunk lhs(Transliterators::CONVERSION_STRING, nullptr);
1051 CharChunk rhs(Transliterators::CONVERSION_STRING, nullptr);
10521052
10531053 lhs.set_ambiguous("LA");
10541054 lhs.set_conversion("LC");
12031203
12041204 TEST(CharChunkTest, SplitChunkWithSpecialKeys) {
12051205 {
1206 CharChunk chunk(Transliterators::CONVERSION_STRING, NULL);
1206 CharChunk chunk(Transliterators::CONVERSION_STRING, nullptr);
12071207 chunk.set_raw("a");
12081208 chunk.set_conversion(Table::ParseSpecialKey("ab{1}cd"));
12091209
1210 CharChunk *left_chunk_ptr = NULL;
1210 CharChunk *left_chunk_ptr = nullptr;
12111211 EXPECT_FALSE(chunk.SplitChunk(Transliterators::CONVERSION_STRING, 0,
12121212 &left_chunk_ptr));
12131213 std::unique_ptr<CharChunk> left_chunk(left_chunk_ptr);
12181218 }
12191219
12201220 {
1221 CharChunk chunk(Transliterators::CONVERSION_STRING, NULL);
1221 CharChunk chunk(Transliterators::CONVERSION_STRING, nullptr);
12221222 chunk.set_raw("a");
12231223 chunk.set_conversion(Table::ParseSpecialKey("ab{1}cd"));
12241224
1225 CharChunk *left_chunk_ptr = NULL;
1225 CharChunk *left_chunk_ptr = nullptr;
12261226 EXPECT_TRUE(chunk.SplitChunk(Transliterators::CONVERSION_STRING, 1,
12271227 &left_chunk_ptr));
12281228 std::unique_ptr<CharChunk> left_chunk(left_chunk_ptr);
12311231 }
12321232
12331233 {
1234 CharChunk chunk(Transliterators::CONVERSION_STRING, NULL);
1234 CharChunk chunk(Transliterators::CONVERSION_STRING, nullptr);
12351235 chunk.set_raw("a");
12361236 chunk.set_conversion(Table::ParseSpecialKey("ab{1}cd"));
12371237
1238 CharChunk *left_chunk_ptr = NULL;
1238 CharChunk *left_chunk_ptr = nullptr;
12391239 EXPECT_TRUE(chunk.SplitChunk(Transliterators::CONVERSION_STRING, 2,
12401240 &left_chunk_ptr));
12411241 std::unique_ptr<CharChunk> left_chunk(left_chunk_ptr);
12441244 }
12451245
12461246 {
1247 CharChunk chunk(Transliterators::CONVERSION_STRING, NULL);
1247 CharChunk chunk(Transliterators::CONVERSION_STRING, nullptr);
12481248 chunk.set_raw("a");
12491249 chunk.set_conversion(Table::ParseSpecialKey("ab{1}cd"));
12501250
1251 CharChunk *left_chunk_ptr = NULL;
1251 CharChunk *left_chunk_ptr = nullptr;
12521252 EXPECT_TRUE(chunk.SplitChunk(Transliterators::CONVERSION_STRING, 3,
12531253 &left_chunk_ptr));
12541254 std::unique_ptr<CharChunk> left_chunk(left_chunk_ptr);
17221722 src.attributes_ = NEW_CHUNK;
17231723
17241724 std::unique_ptr<CharChunk> dest(
1725 new CharChunk(Transliterators::CONVERSION_STRING, NULL));
1725 new CharChunk(Transliterators::CONVERSION_STRING, nullptr));
17261726 EXPECT_FALSE(src.transliterator_ == dest->transliterator_);
17271727 EXPECT_FALSE(src.table_ == dest->table_);
17281728 EXPECT_NE(src.raw_, dest->raw_);
120120 continue;
121121 }
122122
123 CharChunk *left_deleted_chunk_ptr = NULL;
123 CharChunk *left_deleted_chunk_ptr = nullptr;
124124 (*chunk_it)->SplitChunk(Transliterators::LOCAL, 1, &left_deleted_chunk_ptr);
125125 std::unique_ptr<CharChunk> left_deleted_chunk(left_deleted_chunk_ptr);
126126 }
369369 // The position is the beginning of composition.
370370 if (pos <= 0) {
371371 *it = chunks_.begin();
372 return NULL;
372 return nullptr;
373373 }
374374
375375 size_t inner_position;
381381 return chunk;
382382 }
383383
384 CharChunk *left_chunk = NULL;
384 CharChunk *left_chunk = nullptr;
385385 chunk->SplitChunk(Transliterators::LOCAL, inner_position, &left_chunk);
386386 chunks_.insert(*it, left_chunk);
387387 return left_chunk;
3434 namespace composer {
3535
3636 CompositionInput::CompositionInput()
37 : has_conversion_(false), is_new_input_(false), transliterator_(NULL) {}
37 : has_conversion_(false), is_new_input_(false), transliterator_(nullptr) {}
3838
3939 CompositionInput::~CompositionInput() {}
4040
4343 conversion_.clear();
4444 has_conversion_ = false;
4545 is_new_input_ = false;
46 transliterator_ = NULL;
46 transliterator_ = nullptr;
4747 }
4848
4949 bool CompositionInput::Empty() const {
4545 EXPECT_FALSE(input.has_conversion());
4646 EXPECT_TRUE(input.conversion().empty());
4747 EXPECT_FALSE(input.is_new_input());
48 EXPECT_TRUE(NULL == input.transliterator());
48 EXPECT_TRUE(nullptr == input.transliterator());
4949 }
5050
5151 { // Value setting
7171 EXPECT_FALSE(input.has_conversion());
7272 EXPECT_TRUE(input.conversion().empty());
7373 EXPECT_FALSE(input.is_new_input());
74 EXPECT_TRUE(NULL == input.transliterator());
74 EXPECT_TRUE(nullptr == input.transliterator());
7575
7676 EXPECT_FALSE(input2.Empty());
7777 EXPECT_EQ("raw", input2.raw());
282282 };
283283 for (int i = 0; i < arraysize(test_cases); ++i) {
284284 const TestCase& test = test_cases[i];
285 CharChunk right_orig_chunk(Transliterators::CONVERSION_STRING, NULL);
285 CharChunk right_orig_chunk(Transliterators::CONVERSION_STRING, nullptr);
286286 right_orig_chunk.set_conversion(test.conversion);
287287 right_orig_chunk.set_pending(test.pending);
288288 right_orig_chunk.set_raw(test.raw);
289 CharChunk* left_new_chunk_ptr = NULL;
289 CharChunk* left_new_chunk_ptr = nullptr;
290290 right_orig_chunk.SplitChunk(Transliterators::RAW_STRING, test.position,
291291 &left_new_chunk_ptr);
292292 std::unique_ptr<CharChunk> left_new_chunk(left_new_chunk_ptr);
293293
294 if (left_new_chunk.get() != NULL) {
294 if (left_new_chunk != nullptr) {
295295 EXPECT_EQ(test.expected_left_conversion, left_new_chunk->conversion());
296296 EXPECT_EQ(test.expected_left_pending, left_new_chunk->pending());
297297 EXPECT_EQ(test.expected_left_raw, left_new_chunk->raw());
327327 };
328328 for (int i = 0; i < arraysize(test_cases); ++i) {
329329 const TestCase& test = test_cases[i];
330 CharChunk right_orig_chunk(Transliterators::CONVERSION_STRING, NULL);
330 CharChunk right_orig_chunk(Transliterators::CONVERSION_STRING, nullptr);
331331 right_orig_chunk.set_conversion(test.conversion);
332332 right_orig_chunk.set_pending(test.pending);
333333 right_orig_chunk.set_raw(test.raw);
334 CharChunk* left_new_chunk_ptr = NULL;
334 CharChunk* left_new_chunk_ptr = nullptr;
335335 right_orig_chunk.SplitChunk(Transliterators::CONVERSION_STRING,
336336 test.position, &left_new_chunk_ptr);
337337 std::unique_ptr<CharChunk> left_new_chunk(left_new_chunk_ptr);
338338
339 if (left_new_chunk.get() != NULL) {
339 if (left_new_chunk != nullptr) {
340340 EXPECT_EQ(test.expected_left_conversion, left_new_chunk->conversion());
341341 EXPECT_EQ(test.expected_left_pending, left_new_chunk->pending());
342342 EXPECT_EQ(test.expected_left_raw, left_new_chunk->raw());
4949 size_t key_length;
5050 bool fixed;
5151 const Entry* entry = table_.LookUpPrefix(key, &key_length, &fixed);
52 if (entry == NULL) {
52 if (entry == nullptr) {
5353 output->append(key, 0, 1);
5454 key.erase(0, 1);
5555 } else {
168168 void TypingCorrector::GetQueriesForPrediction(
169169 std::vector<TypeCorrectedQuery> *queries) const {
170170 queries->clear();
171 if (!IsAvailable() || table_ == NULL || raw_key_.empty()) {
171 if (!IsAvailable() || table_ == nullptr || raw_key_.empty()) {
172172 return;
173173 }
174174 // These objects are for cache. Used and reset repeatedly.
4141 0, 1, 2, 3, 4, 5, 6,
4242 };
4343 TypingModel model(characters, strlen(characters), costs, arraysize(costs),
44 NULL);
44 nullptr);
4545 model.character_to_radix_table_['a'] = 1;
4646 model.character_to_radix_table_['b'] = 2;
4747 model.character_to_radix_table_['c'] = 3;
5555 0, 1, 2, 3, 4, 5, 6,
5656 };
5757 TypingModel model(characters, strlen(characters), costs, arraysize(costs),
58 NULL);
58 nullptr);
5959 ASSERT_EQ(0, model.GetIndex(""));
6060 ASSERT_EQ(1, model.GetIndex("a"));
6161 ASSERT_EQ(4, model.GetIndex("d"));
206206 for (size_t i = 0; i < keys.size(); ++i) {
207207 if (Util::CharsLen(keys[i]) == 1) {
208208 char32 key_code = 0;
209 if (Util::SplitFirstChar32(keys[i], &key_code, NULL)) {
209 if (Util::SplitFirstChar32(keys[i], &key_code, nullptr)) {
210210 key_event->set_key_code(key_code);
211211 }
212212 } else {
197197 table_file_name = kNotouchHalfwidthasciiTableFile;
198198 break;
199199 default:
200 table_file_name = NULL;
200 table_file_name = nullptr;
201201 }
202202 if (table_file_name && LoadFromFile(table_file_name)) {
203203 return true;
228228 // Initialize punctuations.
229229 const config::Config::PunctuationMethod punctuation_method =
230230 config.punctuation_method();
231 const mozc::composer::Entry *entry = NULL;
231 const mozc::composer::Entry *entry = nullptr;
232232
233233 // Comma / Kuten
234234 entry = LookUp(",");
235 if (entry == NULL ||
235 if (entry == nullptr ||
236236 (entry->result() == kKuten && entry->pending().empty())) {
237237 if (punctuation_method == config::Config::COMMA_PERIOD ||
238238 punctuation_method == config::Config::COMMA_TOUTEN) {
244244
245245 // Period / Touten
246246 entry = LookUp(".");
247 if (entry == NULL ||
247 if (entry == nullptr ||
248248 (entry->result() == kTouten && entry->pending().empty())) {
249249 if (punctuation_method == config::Config::COMMA_PERIOD ||
250250 punctuation_method == config::Config::KUTEN_PERIOD) {
259259
260260 // Slash / Middle dot
261261 entry = LookUp("/");
262 if (entry == NULL ||
262 if (entry == nullptr ||
263263 (entry->result() == kMiddleDot && entry->pending().empty())) {
264264 if (symbol_method == config::Config::SQUARE_BRACKET_SLASH ||
265265 symbol_method == config::Config::CORNER_BRACKET_SLASH) {
271271
272272 // Square open bracket / Corner open bracket
273273 entry = LookUp("[");
274 if (entry == NULL ||
274 if (entry == nullptr ||
275275 (entry->result() == kCornerOpen && entry->pending().empty())) {
276276 if (symbol_method == config::Config::CORNER_BRACKET_MIDDLE_DOT ||
277277 symbol_method == config::Config::CORNER_BRACKET_SLASH) {
283283
284284 // Square close bracket / Corner close bracket
285285 entry = LookUp("]");
286 if (entry == NULL ||
286 if (entry == nullptr ||
287287 (entry->result() == kCornerClose && entry->pending().empty())) {
288288 if (symbol_method == config::Config::CORNER_BRACKET_MIDDLE_DOT ||
289289 symbol_method == config::Config::CORNER_BRACKET_SLASH) {
318318 size_t key_length = 0;
319319 bool fixed = false;
320320 const Entry *entry = LookUpPrefix(key, &key_length, &fixed);
321 if (entry == NULL) {
321 if (entry == nullptr) {
322322 return false;
323323 }
324324 DCHECK_LE(key_length, key.size());
349349 if (escaped_input.size() >= kMaxSize || output.size() >= kMaxSize ||
350350 escaped_pending.size() >= kMaxSize) {
351351 LOG(ERROR) << "Invalid input/output/pending";
352 return NULL;
352 return nullptr;
353353 }
354354
355355 const std::string input = ParseSpecialKey(escaped_input);
357357 if (IsLoopingEntry(input, pending)) {
358358 LOG(WARNING) << "Entry " << input << " " << output << " " << pending
359359 << " is removed, since the rule is looping";
360 return NULL;
361 }
362
363 const Entry *old_entry = NULL;
360 return nullptr;
361 }
362
363 const Entry *old_entry = nullptr;
364364 if (entries_->LookUp(input, &old_entry)) {
365365 DeleteEntry(old_entry);
366366 }
407407
408408 bool Table::LoadFromFile(const char *filepath) {
409409 std::unique_ptr<std::istream> ifs(ConfigFileStream::LegacyOpen(filepath));
410 if (ifs.get() == NULL) {
410 if (ifs == nullptr) {
411411 return false;
412412 }
413413 return LoadFromStream(ifs.get());
471471 }
472472
473473 const Entry *Table::LookUp(const std::string &input) const {
474 const Entry *entry = NULL;
474 const Entry *entry = nullptr;
475475 if (case_sensitive_) {
476476 entries_->LookUp(input, &entry);
477477 } else {
484484
485485 const Entry *Table::LookUpPrefix(const std::string &input, size_t *key_length,
486486 bool *fixed) const {
487 const Entry *entry = NULL;
487 const Entry *entry = nullptr;
488488 if (case_sensitive_) {
489489 entries_->LookUpPrefix(input, &entry, key_length, fixed);
490490 } else {
6363
6464 std::string GetResult(const Table &table, const std::string &key) {
6565 const Entry *entry = table.LookUp(key);
66 if (entry == NULL) {
67 return "<NULL>";
66 if (entry == nullptr) {
67 return "<nullptr>";
6868 }
6969 return entry->result();
7070 }
7171
7272 std::string GetInput(const Table &table, const std::string &key) {
7373 const Entry *entry = table.LookUp(key);
74 if (entry == NULL) {
75 return "<NULL>";
74 if (entry == nullptr) {
75 return "<nullptr>";
7676 }
7777 return entry->input();
7878 }
115115 const Entry *entry;
116116 entry = table.LookUp(test.input);
117117
118 EXPECT_EQ(test.expected_result, (entry != NULL));
119 if (entry == NULL) {
118 EXPECT_EQ(test.expected_result, (entry != nullptr));
119 if (entry == nullptr) {
120120 continue;
121121 }
122122 EXPECT_EQ(test.expected_output, entry->result());
159159 ASSERT_TRUE(table.InitializeWithRequestAndConfig(request, config,
160160 mock_data_manager_));
161161 const Entry *entry = table.LookUp(test_cases[i].input);
162 EXPECT_TRUE(entry != NULL) << "Failed index = " << i;
162 EXPECT_TRUE(entry != nullptr) << "Failed index = " << i;
163163 if (entry) {
164164 EXPECT_EQ(test_cases[i].expected, entry->result());
165165 }
195195 ASSERT_TRUE(table.InitializeWithRequestAndConfig(request, config,
196196 mock_data_manager_));
197197 const Entry *entry = table.LookUp(test_cases[i].input);
198 EXPECT_TRUE(entry != NULL) << "Failed index = " << i;
198 EXPECT_TRUE(entry != nullptr) << "Failed index = " << i;
199199 if (entry) {
200200 EXPECT_EQ(test_cases[i].expected, entry->result());
201201 }
212212 mock_data_manager_));
213213
214214 const Entry *entry = table.LookUp("a");
215 ASSERT_TRUE(entry != NULL);
215 ASSERT_TRUE(entry != nullptr);
216216 EXPECT_EQ("あ", entry->result());
217217 EXPECT_TRUE(entry->pending().empty());
218218 }
223223 ASSERT_TRUE(table.InitializeWithRequestAndConfig(request, config_,
224224 mock_data_manager_));
225225 const Entry *entry = table.LookUp("か゛");
226 ASSERT_TRUE(entry != NULL);
226 ASSERT_TRUE(entry != nullptr);
227227 EXPECT_EQ("が", entry->result());
228228 EXPECT_TRUE(entry->pending().empty());
229229 }
237237 EXPECT_TRUE(table.IsLoopingEntry("b", "a"));
238238 table.AddRule("b", "aa", "a"); // looping
239239
240 EXPECT_TRUE(table.LookUp("a") != NULL);
241 EXPECT_TRUE(table.LookUp("b") == NULL);
240 EXPECT_TRUE(table.LookUp("a") != nullptr);
241 EXPECT_TRUE(table.LookUp("b") == nullptr);
242242 }
243243
244244 {
249249 EXPECT_TRUE(table.IsLoopingEntry("b", "a"));
250250 table.AddRule("b", "aa", "a"); // looping
251251
252 EXPECT_TRUE(table.LookUp("a") != NULL);
253 EXPECT_TRUE(table.LookUp("b") == NULL);
252 EXPECT_TRUE(table.LookUp("a") != nullptr);
253 EXPECT_TRUE(table.LookUp("b") == nullptr);
254254 }
255255
256256 {
267267 EXPECT_TRUE(table.IsLoopingEntry("d", "a"));
268268 table.AddRule("d", "aa", "a"); // looping
269269
270 EXPECT_TRUE(table.LookUp("a") != NULL);
271 EXPECT_TRUE(table.LookUp("b") != NULL);
272 EXPECT_TRUE(table.LookUp("c") != NULL);
273 EXPECT_TRUE(table.LookUp("d") == NULL);
270 EXPECT_TRUE(table.LookUp("a") != nullptr);
271 EXPECT_TRUE(table.LookUp("b") != nullptr);
272 EXPECT_TRUE(table.LookUp("c") != nullptr);
273 EXPECT_TRUE(table.LookUp("d") == nullptr);
274274 }
275275
276276 {
281281 EXPECT_FALSE(table.IsLoopingEntry("www", "ww"));
282282 table.AddRule("www", "W", "ww"); // not looping
283283
284 EXPECT_TRUE(table.LookUp("wa") != NULL);
285 EXPECT_TRUE(table.LookUp("ww") != NULL);
286 EXPECT_TRUE(table.LookUp("www") != NULL);
284 EXPECT_TRUE(table.LookUp("wa") != nullptr);
285 EXPECT_TRUE(table.LookUp("ww") != nullptr);
286 EXPECT_TRUE(table.LookUp("www") != nullptr);
287287 }
288288
289289 {
294294 EXPECT_FALSE(table.IsLoopingEntry("ww", "w"));
295295 table.AddRule("ww", "X", "w");
296296
297 EXPECT_TRUE(table.LookUp("wa") != NULL);
298 EXPECT_TRUE(table.LookUp("ww") != NULL);
299 EXPECT_TRUE(table.LookUp("www") != NULL);
297 EXPECT_TRUE(table.LookUp("wa") != nullptr);
298 EXPECT_TRUE(table.LookUp("ww") != nullptr);
299 EXPECT_TRUE(table.LookUp("www") != nullptr);
300300 }
301301
302302 {
304304 EXPECT_TRUE(table.IsLoopingEntry("a", "a"));
305305 table.AddRule("a", "aa", "a"); // looping
306306
307 EXPECT_TRUE(table.LookUp("a") == NULL);
307 EXPECT_TRUE(table.LookUp("a") == nullptr);
308308 }
309309
310310 // Too long input
316316 too_long += 'a';
317317 }
318318 table.AddRule(too_long, "test", "test");
319 EXPECT_TRUE(table.LookUp(too_long) == NULL);
319 EXPECT_TRUE(table.LookUp(too_long) == nullptr);
320320
321321 table.AddRule("a", too_long, "test");
322 EXPECT_TRUE(table.LookUp("a") == NULL);
322 EXPECT_TRUE(table.LookUp("a") == nullptr);
323323
324324 table.AddRule("a", "test", too_long);
325 EXPECT_TRUE(table.LookUp("a") == NULL);
325 EXPECT_TRUE(table.LookUp("a") == nullptr);
326326 }
327327
328328 // reasonably long
334334 reasonably_long += 'a';
335335 }
336336 table.AddRule(reasonably_long, "test", "test");
337 EXPECT_TRUE(table.LookUp(reasonably_long) != NULL);
337 EXPECT_TRUE(table.LookUp(reasonably_long) != nullptr);
338338
339339 table.AddRule("a", reasonably_long, "test");
340 EXPECT_TRUE(table.LookUp("a") != NULL);
340 EXPECT_TRUE(table.LookUp("a") != nullptr);
341341
342342 table.AddRule("a", "test", reasonably_long);
343 EXPECT_TRUE(table.LookUp("a") != NULL);
343 EXPECT_TRUE(table.LookUp("a") != nullptr);
344344 }
345345 }
346346
360360 commands::Request request;
361361 table.InitializeWithRequestAndConfig(request, config_, mock_data_manager_);
362362
363 const Entry *entry = NULL;
363 const Entry *entry = nullptr;
364364 entry = table.LookUp("mozc");
365 ASSERT_TRUE(entry != NULL);
365 ASSERT_TRUE(entry != nullptr);
366366 EXPECT_EQ("MOZC", entry->result());
367367
368368 entry = table.LookUp(",");
369 ASSERT_TRUE(entry != NULL);
369 ASSERT_TRUE(entry != nullptr);
370370 EXPECT_EQ("COMMA", entry->result());
371371
372372 entry = table.LookUp(".");
373 ASSERT_TRUE(entry != NULL);
373 ASSERT_TRUE(entry != nullptr);
374374 EXPECT_EQ("PERIOD", entry->result());
375375
376376 entry = table.LookUp("/");
377 ASSERT_TRUE(entry != NULL);
377 ASSERT_TRUE(entry != nullptr);
378378 EXPECT_EQ("SLASH", entry->result());
379379
380380 entry = table.LookUp("[");
381 ASSERT_TRUE(entry != NULL);
381 ASSERT_TRUE(entry != nullptr);
382382 EXPECT_EQ("OPEN", entry->result());
383383
384384 entry = table.LookUp("]");
385 ASSERT_TRUE(entry != NULL);
385 ASSERT_TRUE(entry != nullptr);
386386 EXPECT_EQ("CLOSE", entry->result());
387387 }
388388
417417 EXPECT_TRUE(table.HasSubRules("Z"));
418418
419419 { // Test for LookUpPrefix
420 const Entry *entry = NULL;
420 const Entry *entry = nullptr;
421421 size_t key_length = 0;
422422 bool fixed = false;
423423 entry = table.LookUpPrefix("bA", &key_length, &fixed);
424 EXPECT_TRUE(entry != NULL);
424 EXPECT_TRUE(entry != nullptr);
425425 EXPECT_EQ("[ba]", entry->result());
426426 EXPECT_EQ(2, key_length);
427427 EXPECT_TRUE(fixed);
435435 EXPECT_EQ("[ba]", GetResult(table, "ba"));
436436 EXPECT_EQ("[BA]", GetResult(table, "BA"));
437437 EXPECT_EQ("[Ba]", GetResult(table, "Ba"));
438 EXPECT_EQ("<NULL>", GetResult(table, "bA"));
438 EXPECT_EQ("<nullptr>", GetResult(table, "bA"));
439439
440440 EXPECT_EQ("a", GetInput(table, "a"));
441441 EXPECT_EQ("A", GetInput(table, "A"));
442442 EXPECT_EQ("ba", GetInput(table, "ba"));
443443 EXPECT_EQ("BA", GetInput(table, "BA"));
444444 EXPECT_EQ("Ba", GetInput(table, "Ba"));
445 EXPECT_EQ("<NULL>", GetInput(table, "bA"));
445 EXPECT_EQ("<nullptr>", GetInput(table, "bA"));
446446
447447 // Test for HasSubRules
448448 EXPECT_FALSE(table.HasSubRules("Z"));
449449
450450 { // Test for LookUpPrefix
451 const Entry *entry = NULL;
451 const Entry *entry = nullptr;
452452 size_t key_length = 0;
453453 bool fixed = false;
454454 entry = table.LookUpPrefix("bA", &key_length, &fixed);
455 EXPECT_TRUE(entry == NULL);
455 EXPECT_TRUE(entry == nullptr);
456456 EXPECT_EQ(1, key_length);
457457 EXPECT_TRUE(fixed);
458458 }
521521 EXPECT_EQ("[ba]", GetResult(table, "ba"));
522522 EXPECT_EQ("[BA]", GetResult(table, "BA"));
523523 EXPECT_EQ("[Ba]", GetResult(table, "Ba"));
524 EXPECT_EQ("<NULL>", GetResult(table, "bA"));
524 EXPECT_EQ("<nullptr>", GetResult(table, "bA"));
525525
526526 EXPECT_EQ("a", GetInput(table, "a"));
527527 EXPECT_EQ("A", GetInput(table, "A"));
528528 EXPECT_EQ("ba", GetInput(table, "ba"));
529529 EXPECT_EQ("BA", GetInput(table, "BA"));
530530 EXPECT_EQ("Ba", GetInput(table, "Ba"));
531 EXPECT_EQ("<NULL>", GetInput(table, "bA"));
531 EXPECT_EQ("<nullptr>", GetInput(table, "bA"));
532532
533533 // Test for HasSubRules
534534 EXPECT_FALSE(table.HasSubRules("Z"));
535535
536536 { // Test for LookUpPrefix
537 const Entry *entry = NULL;
537 const Entry *entry = nullptr;
538538 size_t key_length = 0;
539539 bool fixed = false;
540540 entry = table.LookUpPrefix("bA", &key_length, &fixed);
541 EXPECT_TRUE(entry == NULL);
541 EXPECT_TRUE(entry == nullptr);
542542 EXPECT_EQ(1, key_length);
543543 EXPECT_TRUE(fixed);
544544 }
561561 EXPECT_EQ("[ba]", GetResult(table, "ba"));
562562 EXPECT_EQ("[BA]", GetResult(table, "BA"));
563563 EXPECT_EQ("[Ba]", GetResult(table, "Ba"));
564 EXPECT_EQ("<NULL>", GetResult(table, "bA"));
564 EXPECT_EQ("<nullptr>", GetResult(table, "bA"));
565565
566566 EXPECT_EQ("a", GetInput(table, "a"));
567567 EXPECT_EQ("A", GetInput(table, "A"));
568568 EXPECT_EQ("ba", GetInput(table, "ba"));
569569 EXPECT_EQ("BA", GetInput(table, "BA"));
570570 EXPECT_EQ("Ba", GetInput(table, "Ba"));
571 EXPECT_EQ("<NULL>", GetInput(table, "bA"));
571 EXPECT_EQ("<nullptr>", GetInput(table, "bA"));
572572
573573 // Test for HasSubRules
574574 EXPECT_FALSE(table.HasSubRules("Z"));
575575
576576 { // Test for LookUpPrefix
577 const Entry *entry = NULL;
577 const Entry *entry = nullptr;
578578 size_t key_length = 0;
579579 bool fixed = false;
580580 entry = table.LookUpPrefix("bA", &key_length, &fixed);
581 EXPECT_TRUE(entry == NULL);
581 EXPECT_TRUE(entry == nullptr);
582582 EXPECT_EQ(1, key_length);
583583 EXPECT_TRUE(fixed);
584584 }
601601 EXPECT_EQ("[ba]", GetResult(table, "ba"));
602602 EXPECT_EQ("[BA]", GetResult(table, "BA"));
603603 EXPECT_EQ("[Ba]", GetResult(table, "Ba"));
604 EXPECT_EQ("<NULL>", GetResult(table, "bA"));
604 EXPECT_EQ("<nullptr>", GetResult(table, "bA"));
605605
606606 EXPECT_EQ("a", GetInput(table, "a"));
607607 EXPECT_EQ("A", GetInput(table, "A"));
608608 EXPECT_EQ("ba", GetInput(table, "ba"));
609609 EXPECT_EQ("BA", GetInput(table, "BA"));
610610 EXPECT_EQ("Ba", GetInput(table, "Ba"));
611 EXPECT_EQ("<NULL>", GetInput(table, "bA"));
611 EXPECT_EQ("<nullptr>", GetInput(table, "bA"));
612612
613613 // Test for HasSubRules
614614 EXPECT_FALSE(table.HasSubRules("Z"));
615615
616616 { // Test for LookUpPrefix
617 const Entry *entry = NULL;
617 const Entry *entry = nullptr;
618618 size_t key_length = 0;
619619 bool fixed = false;
620620 entry = table.LookUpPrefix("bA", &key_length, &fixed);
621 EXPECT_TRUE(entry == NULL);
621 EXPECT_TRUE(entry == nullptr);
622622 EXPECT_EQ(1, key_length);
623623 EXPECT_TRUE(fixed);
624624 }
688688 mozc::composer::Table table;
689689 table.InitializeWithRequestAndConfig(request, config_, mock_data_manager_);
690690 {
691 const mozc::composer::Entry *entry = NULL;
691 const mozc::composer::Entry *entry = nullptr;
692692 size_t key_length = 0;
693693 bool fixed = false;
694694 entry = table.LookUpPrefix("2", &key_length, &fixed);
699699 EXPECT_TRUE(fixed);
700700 }
701701 {
702 const mozc::composer::Entry *entry = NULL;
702 const mozc::composer::Entry *entry = nullptr;
703703 size_t key_length = 0;
704704 bool fixed = false;
705705 entry = table.LookUpPrefix("し*", &key_length, &fixed);
718718 mozc::commands::Request::TWELVE_KEYS_TO_HALFWIDTHASCII);
719719 Table table;
720720 table.InitializeWithRequestAndConfig(request, config_, mock_data_manager_);
721 const mozc::composer::Entry *entry = NULL;
721 const mozc::composer::Entry *entry = nullptr;
722722 size_t key_length = 0;
723723 bool fixed = false;
724724 entry = table.LookUpPrefix("2", &key_length, &fixed);
736736 Table table;
737737 table.InitializeWithRequestAndConfig(request, config_, mock_data_manager_);
738738 {
739 const mozc::composer::Entry *entry = NULL;
739 const mozc::composer::Entry *entry = nullptr;
740740 size_t key_length = 0;
741741 bool fixed = false;
742742 entry = table.LookUpPrefix("しゃ*", &key_length, &fixed);
784784
785785 const Entry *entry;
786786 entry = table.LookUp("ww");
787 EXPECT_TRUE(NULL != entry);
787 EXPECT_TRUE(nullptr != entry);
788788
789789 size_t key_length;
790790 bool fixed;
791791 entry = table.LookUpPrefix("ww", &key_length, &fixed);
792 EXPECT_TRUE(NULL != entry);
792 EXPECT_TRUE(nullptr != entry);
793793 EXPECT_EQ(2, key_length);
794794 EXPECT_FALSE(fixed);
795795 }
800800 table.AddRule("www", "w", "ww");
801801 EXPECT_TRUE(table.HasSubRules("ww"));
802802
803 const Entry *entry = NULL;
803 const Entry *entry = nullptr;
804804 entry = table.LookUp("ww");
805 EXPECT_TRUE(NULL != entry);
805 EXPECT_TRUE(nullptr != entry);
806806
807807 size_t key_length = 0;
808808 bool fixed = false;
809809 entry = table.LookUpPrefix("ww", &key_length, &fixed);
810 EXPECT_TRUE(NULL != entry);
810 EXPECT_TRUE(nullptr != entry);
811811 EXPECT_EQ(2, key_length);
812812 EXPECT_FALSE(fixed);
813813 }
825825 const Entry *entry = table.LookUpPrefix(kInput, &key_length, &fixed);
826826 EXPECT_EQ(1, key_length);
827827 EXPECT_TRUE(fixed);
828 ASSERT_TRUE(NULL != entry);
828 ASSERT_TRUE(nullptr != entry);
829829 EXPECT_EQ(kInput, entry->input());
830830 EXPECT_EQ("", entry->result());
831831 EXPECT_EQ("a", entry->pending());
841841 entry = table.LookUpPrefix(kInput2, &key_length, &fixed);
842842 EXPECT_EQ(2, key_length);
843843 EXPECT_TRUE(fixed);
844 ASSERT_TRUE(NULL != entry);
844 ASSERT_TRUE(nullptr != entry);
845845 EXPECT_EQ(kInput2, entry->input());
846846 EXPECT_EQ("", entry->result());
847847 EXPECT_EQ("b", entry->pending());
862862 Table table;
863863 table.LoadFromString(kRule);
864864
865 const Entry *entry = NULL;
865 const Entry *entry = nullptr;
866866 // Test for "a\t[A]\n" -- 2 entry rule
867867 EXPECT_FALSE(table.HasNewChunkEntry("a"));
868868 entry = table.LookUp("a");
869 ASSERT_TRUE(NULL != entry);
869 ASSERT_TRUE(nullptr != entry);
870870 EXPECT_EQ("[A]", entry->result());
871871 EXPECT_EQ("", entry->pending());
872872
873873 // Test for "kk\t[X]\tk\n" -- 3 entry rule
874874 EXPECT_FALSE(table.HasNewChunkEntry("kk"));
875875 entry = table.LookUp("kk");
876 ASSERT_TRUE(NULL != entry);
876 ASSERT_TRUE(nullptr != entry);
877877 EXPECT_EQ("[X]", entry->result());
878878 EXPECT_EQ("k", entry->pending());
879879
880880 // Test for "ww\t[W]\tw\tNewChunk\n" -- 3 entry rule + attribute rule
881881 EXPECT_TRUE(table.HasNewChunkEntry("ww"));
882882 entry = table.LookUp("ww");
883 ASSERT_TRUE(NULL != entry);
883 ASSERT_TRUE(nullptr != entry);
884884 EXPECT_EQ("[W]", entry->result());
885885 EXPECT_EQ("w", entry->pending());
886886 EXPECT_EQ(NEW_CHUNK, entry->attributes());
889889 // attribute rules
890890 EXPECT_TRUE(table.HasNewChunkEntry("xx"));
891891 entry = table.LookUp("xx");
892 ASSERT_TRUE(NULL != entry);
892 ASSERT_TRUE(nullptr != entry);
893893 EXPECT_EQ("[X]", entry->result());
894894 EXPECT_EQ("x", entry->pending());
895895 EXPECT_EQ((NEW_CHUNK | NO_TRANSLITERATION), entry->attributes());
898898 // -- all attributes
899899 EXPECT_TRUE(table.HasNewChunkEntry("yy"));
900900 entry = table.LookUp("yy");
901 ASSERT_TRUE(NULL != entry);
901 ASSERT_TRUE(nullptr != entry);
902902 EXPECT_EQ("[Y]", entry->result());
903903 EXPECT_EQ("y", entry->pending());
904904 EXPECT_EQ((NEW_CHUNK | NO_TRANSLITERATION | DIRECT_INPUT | END_CHUNK),
906906
907907 // Test for "#\t[#]\n" -- This line starts with '#' but should be a rule.
908908 entry = table.LookUp("#");
909 ASSERT_TRUE(NULL != entry);
909 ASSERT_TRUE(nullptr != entry);
910910 EXPECT_EQ("[#]", entry->result());
911911 EXPECT_EQ("", entry->pending());
912912 }
919919 table.AddRule("x{{}", "X{", "");
920920 table.AddRule("xy", "XY", "");
921921
922 const Entry *entry = NULL;
922 const Entry *entry = nullptr;
923923 entry = table.LookUp("x{#1}y");
924 EXPECT_TRUE(NULL == entry);
924 EXPECT_TRUE(nullptr == entry);
925925
926926 std::string key;
927927 key = Table::ParseSpecialKey("x{#1}y");
928928 entry = table.LookUp(key);
929 ASSERT_TRUE(NULL != entry);
929 ASSERT_TRUE(nullptr != entry);
930930 EXPECT_EQ(key, entry->input());
931931 EXPECT_EQ("X1Y", entry->result());
932932
933933 key = Table::ParseSpecialKey("x{#2}y");
934934 entry = table.LookUp(key);
935 ASSERT_TRUE(NULL != entry);
935 ASSERT_TRUE(nullptr != entry);
936936 EXPECT_EQ(key, entry->input());
937937 EXPECT_EQ("X2Y", entry->result());
938938
939939 key = "x{";
940940 entry = table.LookUp(key);
941 ASSERT_TRUE(NULL != entry);
941 ASSERT_TRUE(nullptr != entry);
942942 EXPECT_EQ(key, entry->input());
943943 EXPECT_EQ("X{", entry->result());
944944 }
10361036 config.set_symbol_method(symbol_method[symbol]);
10371037 const Table *table =
10381038 table_manager.GetTable(request, config, mock_data_manager_);
1039 EXPECT_TRUE(table != NULL);
1039 EXPECT_TRUE(table != nullptr);
10401040 EXPECT_TRUE(table_manager.GetTable(request, config,
10411041 mock_data_manager_) == table);
10421042 EXPECT_TRUE(table_set.find(table) == table_set.end());
10591059 config.set_custom_roman_table(kRule);
10601060 const Table *table =
10611061 table_manager.GetTable(request, config, mock_data_manager_);
1062 EXPECT_TRUE(table != NULL);
1062 EXPECT_TRUE(table != nullptr);
10631063 EXPECT_TRUE(table_manager.GetTable(request, config, mock_data_manager_) ==
10641064 table);
1065 EXPECT_TRUE(NULL != table->LookUp("a"));
1066 EXPECT_TRUE(NULL == table->LookUp("kk"));
1065 EXPECT_TRUE(nullptr != table->LookUp("a"));
1066 EXPECT_TRUE(nullptr == table->LookUp("kk"));
10671067
10681068 const std::string kRule2 =
10691069 "a\t[A]\n" // 2 entry rule
10711071 config.set_custom_roman_table(kRule2);
10721072 const Table *table2 =
10731073 table_manager.GetTable(request, config, mock_data_manager_);
1074 EXPECT_TRUE(table2 != NULL);
1074 EXPECT_TRUE(table2 != nullptr);
10751075 EXPECT_TRUE(table_manager.GetTable(request, config, mock_data_manager_) ==
10761076 table2);
1077 EXPECT_TRUE(NULL != table2->LookUp("a"));
1078 EXPECT_TRUE(NULL != table2->LookUp("kk"));
1077 EXPECT_TRUE(nullptr != table2->LookUp("a"));
1078 EXPECT_TRUE(nullptr != table2->LookUp("kk"));
10791079 }
10801080 }
10811081
211211 std::string tmp;
212212 Util::HalfWidthToFullWidth(str, &tmp);
213213 char32 ucs4 = 0;
214 if (Util::SplitFirstChar32(tmp, &ucs4, NULL) && ucs4 <= 0xffff) {
214 if (Util::SplitFirstChar32(tmp, &ucs4, nullptr) && ucs4 <= 0xffff) {
215215 ucs2 = static_cast<uint16>(ucs4);
216216 } else {
217217 ucs2 = 0x0000; // no conversion as fall back
240240 }
241241
242242 CharacterFormManagerImpl::CharacterFormManagerImpl()
243 : storage_(NULL), require_consistent_conversion_(false) {}
243 : storage_(nullptr), require_consistent_conversion_(false) {}
244244
245245 CharacterFormManagerImpl::~CharacterFormManagerImpl() {}
246246
265265 }
266266
267267 void CharacterFormManagerImpl::ClearHistory() {
268 if (storage_ != NULL) {
268 if (storage_ != nullptr) {
269269 storage_->Clear();
270270 }
271271 }
306306
307307 Config::CharacterForm CharacterFormManagerImpl::GetCharacterFormFromStorage(
308308 uint16 ucs2) const {
309 if (storage_ == NULL) {
309 if (storage_ == nullptr) {
310310 return Config::FULL_WIDTH; // Return default setting
311311 }
312312 const std::string key(reinterpret_cast<const char *>(&ucs2), sizeof(ucs2));
313313 const char *value = storage_->Lookup(key);
314 if (value == NULL) {
314 if (value == nullptr) {
315315 return Config::FULL_WIDTH; // Return default setting
316316 }
317317 const uint32 ivalue = *reinterpret_cast<const uint32 *>(value);
324324 return;
325325 }
326326
327 if (storage_ == NULL) {
327 if (storage_ == nullptr) {
328328 return;
329329 }
330330
331331 const std::string key(reinterpret_cast<const char *>(&ucs2), sizeof(ucs2));
332332 const char *value = storage_->Lookup(key);
333 if (value != NULL && static_cast<Config::CharacterForm>(*value) == form) {
333 if (value != nullptr && static_cast<Config::CharacterForm>(*value) == form) {
334334 return;
335335 }
336336
356356
357357 void CharacterFormManagerImpl::ConvertString(const std::string &str,
358358 std::string *output) const {
359 ConvertStringWithAlternative(str, output, NULL);
359 ConvertStringWithAlternative(str, output, nullptr);
360360 }
361361
362362 bool CharacterFormManagerImpl::TryConvertStringWithPreference(
474474 *output = str;
475475 }
476476
477 if (alternative_output != NULL) {
477 if (alternative_output != nullptr) {
478478 alternative_output->clear();
479479 ConvertStringAlternative(*output, alternative_output);
480480 }
481481
482482 // return true if alternative_output and output are different
483 return (alternative_output != NULL && *alternative_output != *output);
483 return (alternative_output != nullptr && *alternative_output != *output);
484484 }
485485
486486 void CharacterFormManagerImpl::Clear() {
563563 const uint32 key_type = 0;
564564 storage_.reset(LRUStorage::Create(filename.c_str(), sizeof(key_type),
565565 kLRUSize, kSeedValue));
566 LOG_IF(ERROR, storage_.get() == NULL) << "cannot open " << filename;
566 LOG_IF(ERROR, storage_.get() == nullptr) << "cannot open " << filename;
567567 preedit_.reset(new PreeditCharacterFormManagerImpl);
568568 conversion_.reset(new ConversionCharacterFormManagerImpl);
569569 preedit_->set_storage(storage_.get());
6868 // Converts string according to the config rules.
6969 // if alternate output, which should be shown next to
7070 // the output, is defined, it is stored into alternative_output.
71 // If alternative_output is not required, you can pass NULL.
71 // If alternative_output is not required, you can pass nullptr.
7272 // e.g., output = "@" alternative_output = "@"
7373 // return true if both output and alternative_output are defined.
7474 bool ConvertPreeditStringWithAlternative(
213213 Config input_proto;
214214 bool ret_code = true;
215215
216 if (is.get() == NULL) {
216 if (is == nullptr) {
217217 LOG(ERROR) << filename_ << " is not found";
218218 ret_code = false;
219219 } else if (!input_proto.ParseFromIstream(is.get())) {
273273 DISALLOW_COPY_AND_ASSIGN(NullStatsConfigUtilImpl);
274274 };
275275
276 StatsConfigUtilInterface *g_stats_config_util_handler = NULL;
276 StatsConfigUtilInterface *g_stats_config_util_handler = nullptr;
277277
278278 // GetStatsConfigUtil and SetHandler are not thread safe.
279279
294294 #endif
295295
296296 StatsConfigUtilInterface &GetStatsConfigUtil() {
297 if (g_stats_config_util_handler == NULL) {
297 if (g_stats_config_util_handler == nullptr) {
298298 return *(Singleton<DefaultConfigUtilImpl>::get());
299299 } else {
300300 return *g_stats_config_util_handler;
7070 const int kRunLevelHigh = 2;
7171
7272 bool TryGetKnownKey(HKEY key, LPCWSTR sub_key, HKEY *result_key) {
73 HKEY dummy = NULL;
74 HKEY &result = (result_key != NULL ? *result_key : dummy);
73 HKEY dummy = nullptr;
74 HKEY &result = (result_key != nullptr ? *result_key : dummy);
7575 if (HKEY_CURRENT_USER == key) {
7676 if (std::wstring(kOmahaUsageKey) == sub_key) {
7777 result = kHKCU_ClientState;
162162 if (!HasUsagestatsValue(key)) {
163163 return false;
164164 }
165 if (value != NULL) {
165 if (value != nullptr) {
166166 *value =
167167 mozc::Singleton<Property>::get()->get_entry_from_usagestats_map(key);
168168 }
202202 HKEY key, LPCWSTR sub_key, DWORD reserved, LPWSTR class_name,
203203 DWORD options, REGSAM sam, LPSECURITY_ATTRIBUTES security_attributes,
204204 PHKEY result, LPDWORD disposition) {
205 HKEY dummy = NULL;
206 HKEY &result_key = result != NULL ? *result : dummy;
205 HKEY dummy = nullptr;
206 HKEY &result_key = result != nullptr ? *result : dummy;
207207 if (!TryGetKnownKey(key, sub_key, &result_key)) {
208208 return ERROR_ACCESS_DENIED;
209209 }
244244 return ERROR_FILE_NOT_FOUND;
245245 }
246246 GetUsagestatsValue(key, reinterpret_cast<DWORD *>(data));
247 if (type != NULL) {
247 if (type != nullptr) {
248248 *type = REG_DWORD;
249249 }
250250 return ERROR_SUCCESS;
6969 node_freelist_.reset(new FreeList<Node>(1024));
7070 pos_matcher_.Set(mock_data_manager_.GetPOSMatcherData());
7171 {
72 const char *data = NULL;
72 const char *data = nullptr;
7373 size_t size = 0;
7474 mock_data_manager_.GetSuggestionFilterData(&data, &size);
7575 suggestion_filter_.reset(new SuggestionFilter(data, size));
409409 bool ConverterImpl::StartPredictionForRequest(const ConversionRequest &request,
410410 Segments *segments) const {
411411 if (!request.has_composer()) {
412 LOG(ERROR) << "Composer is NULL";
412 LOG(ERROR) << "Composer is nullptr";
413413 return false;
414414 }
415415
174174
175175 inline int GetCost(const Node *lnode, const Node *rnode) const {
176176 const int kInvalidPenaltyCost = 100000;
177 if (rnode->constrained_prev != NULL && lnode != rnode->constrained_prev) {
177 if (rnode->constrained_prev != nullptr &&
178 lnode != rnode->constrained_prev) {
178179 return kInvalidPenaltyCost;
179180 }
180181 return connector_->GetTransitionCost(lnode->rid, rnode->lid) + rnode->wcost;
477477 size_t *length) const {
478478 if (!IsAvailable()) {
479479 *length = 0;
480 return NULL;
480 return nullptr;
481481 }
482482
483483 if (mode_ == KANA) {
484484 *length = 0;
485 return NULL;
485 return nullptr;
486486 }
487487
488488 const size_t corrected_key_pos = GetCorrectedPosition(original_key_pos);
489489 if (!IsValidPosition(corrected_key_pos)) {
490490 *length = 0;
491 return NULL;
491 return nullptr;
492492 }
493493
494494 const char *corrected_substr = corrected_key_.data() + corrected_key_pos;
503503 }
504504
505505 *length = 0;
506 return NULL;
506 return nullptr;
507507 }
508508
509509 size_t KeyCorrector::GetOriginalOffset(const size_t original_key_pos,
8383
8484 // return new prefix of string correspoindng to
8585 // the prefix of the original key at "original_key_pos"
86 // if new prefix and original prefix are the same, return NULL.
87 // Note that return value won't be NULL terminated.
86 // if new prefix and original prefix are the same, return nullptr.
87 // Note that return value won't be nullptr terminated.
8888 // "length" stores the length of return value.
8989 // We don't allow empty matching (see GetPrefix(15) below)
9090 //
101101 // GetPrefix(3) = "かいじゅうのはっぱ"
102102 // GetPrefix(9) = "じゅうのはっぱ"
103103 // GetPrefix(12) = "ゅうのはっぱ"
104 // GetPrefix(15) = NULL (not "うのはっぱ")
104 // GetPrefix(15) = nullptr (not "うのはっぱ")
105105 // "う" itself doesn't correspond to the original key,
106106 // so, we don't make a new prefix
107 // GetPrefix(18) = NULL (same as original)
107 // GetPrefix(18) = nullptr (same as original)
108108 //
109109 // Example2:
110110 // original: "みんあのほん"
111111 // GetPrefix(0) = "みんなのほん"
112112 // GetPrefix(3) = "んなのほん"
113113 // GetPrefix(9) = "なのほん"
114 // GetPrefix(12) = NULL
114 // GetPrefix(12) = nullptr
115115 const char *GetCorrectedPrefix(const size_t original_key_pos,
116116 size_t *length) const;
117117
362362 size_t length = 0;
363363
364364 // same as the original key
365 EXPECT_TRUE(NULL == corrector.GetCorrectedPrefix(0, &length));
366 EXPECT_TRUE(NULL == corrector.GetCorrectedPrefix(1, &length));
367 EXPECT_TRUE(NULL == corrector.GetCorrectedPrefix(2, &length));
368 EXPECT_TRUE(NULL == corrector.GetCorrectedPrefix(3, &length));
365 EXPECT_TRUE(nullptr == corrector.GetCorrectedPrefix(0, &length));
366 EXPECT_TRUE(nullptr == corrector.GetCorrectedPrefix(1, &length));
367 EXPECT_TRUE(nullptr == corrector.GetCorrectedPrefix(2, &length));
368 EXPECT_TRUE(nullptr == corrector.GetCorrectedPrefix(3, &length));
369369 }
370370
371371 {
374374 EXPECT_TRUE(corrector.IsAvailable());
375375 EXPECT_EQ("みんなであそぼう", corrector.corrected_key());
376376
377 const char *output = NULL;
377 const char *output = nullptr;
378378 size_t length = 0;
379379
380380 output = corrector.GetCorrectedPrefix(0, &length);
388388
389389 output = corrector.GetCorrectedPrefix(9, &length);
390390 // same
391 EXPECT_TRUE(NULL == output);
391 EXPECT_TRUE(nullptr == output);
392392 }
393393
394394 {
397397 EXPECT_TRUE(corrector.IsAvailable());
398398 EXPECT_EQ("こんにちは", corrector.corrected_key());
399399
400 const char *output = NULL;
400 const char *output = nullptr;
401401 size_t length = 0;
402402
403403 output = corrector.GetCorrectedPrefix(0, &length);
404404 EXPECT_EQ("こんにちは", std::string(output, length));
405405
406406 output = corrector.GetCorrectedPrefix(3, &length);
407 EXPECT_TRUE(NULL == output);
407 EXPECT_TRUE(nullptr == output);
408408
409409 output = corrector.GetCorrectedPrefix(6, &length);
410 EXPECT_TRUE(NULL == output);
410 EXPECT_TRUE(nullptr == output);
411411
412412 output = corrector.GetCorrectedPrefix(9, &length);
413 EXPECT_TRUE(NULL == output);
413 EXPECT_TRUE(nullptr == output);
414414 }
415415
416416 {
419419 EXPECT_TRUE(corrector.IsAvailable());
420420 EXPECT_EQ("こんにちはせんよう", corrector.corrected_key());
421421
422 const char *output = NULL;
422 const char *output = nullptr;
423423 size_t length = 0;
424424
425425 output = corrector.GetCorrectedPrefix(0, &length);
426426 EXPECT_EQ("こんにちはせんよう", std::string(output, length));
427427
428428 output = corrector.GetCorrectedPrefix(3, &length);
429 EXPECT_TRUE(NULL == output);
429 EXPECT_TRUE(nullptr == output);
430430
431431 output = corrector.GetCorrectedPrefix(6, &length);
432 EXPECT_TRUE(NULL == output);
432 EXPECT_TRUE(nullptr == output);
433433
434434 output = corrector.GetCorrectedPrefix(9, &length);
435435 EXPECT_EQ("にちはせんよう", std::string(output, length));
526526 size_t length = 0;
527527
528528 // same as the original key
529 EXPECT_TRUE(NULL == corrector.GetCorrectedPrefix(0, &length));
530 EXPECT_TRUE(NULL == corrector.GetCorrectedPrefix(1, &length));
531 EXPECT_TRUE(NULL == corrector.GetCorrectedPrefix(2, &length));
532 EXPECT_TRUE(NULL == corrector.GetCorrectedPrefix(3, &length));
529 EXPECT_TRUE(nullptr == corrector.GetCorrectedPrefix(0, &length));
530 EXPECT_TRUE(nullptr == corrector.GetCorrectedPrefix(1, &length));
531 EXPECT_TRUE(nullptr == corrector.GetCorrectedPrefix(2, &length));
532 EXPECT_TRUE(nullptr == corrector.GetCorrectedPrefix(3, &length));
533533 }
534534 }
535535
5656 bos_node->cost = 0;
5757 bos_node->begin_pos = length;
5858 bos_node->end_pos = length;
59 bos_node->enext = NULL;
59 bos_node->enext = nullptr;
6060 return bos_node;
6161 }
6262
7272 eos_node->cost = 0;
7373 eos_node->begin_pos = length;
7474 eos_node->end_pos = length;
75 eos_node->bnext = NULL;
75 eos_node->bnext = nullptr;
7676 return eos_node;
7777 }
7878
7979 bool PathContainsString(const Node *node, size_t begin_pos, size_t end_pos,
8080 const std::string &str) {
8181 CHECK(node);
82 for (; node->prev != NULL; node = node->prev) {
82 for (; node->prev != nullptr; node = node->prev) {
8383 if (node->begin_pos == begin_pos && node->end_pos == end_pos &&
8484 node->value == str) {
8585 return true;
109109 for (const Node *node = end_node; node; node = node->prev) {
110110 node_vector.push_back(node);
111111 }
112 const Node *prev_node = NULL;
112 const Node *prev_node = nullptr;
113113
114114 for (int i = static_cast<int>(node_vector.size()) - 1; i >= 0; --i) {
115115 const Node *node = node_vector[i];
163163 cache_info_.resize(size + 4);
164164
165165 std::fill(begin_nodes_.begin(), begin_nodes_.end(),
166 static_cast<Node *>(NULL));
167 std::fill(end_nodes_.begin(), end_nodes_.end(), static_cast<Node *>(NULL));
166 static_cast<Node *>(nullptr));
167 std::fill(end_nodes_.begin(), end_nodes_.end(), static_cast<Node *>(nullptr));
168168 std::fill(cache_info_.begin(), cache_info_.end(), 0);
169169
170170 end_nodes_[0] = InitBOSNode(this, static_cast<uint16>(0));
177177 Node *Lattice::eos_nodes() const { return begin_nodes_[key_.size()]; }
178178
179179 void Lattice::Insert(size_t pos, Node *node) {
180 for (Node *rnode = node; rnode != NULL; rnode = rnode->bnext) {
180 for (Node *rnode = node; rnode != nullptr; rnode = rnode->bnext) {
181181 const size_t end_pos = std::min(rnode->key.size() + pos, key_.size());
182182 rnode->begin_pos = static_cast<uint16>(pos);
183183 rnode->end_pos = static_cast<uint16>(end_pos);
184 rnode->prev = NULL;
185 rnode->next = NULL;
184 rnode->prev = nullptr;
185 rnode->next = nullptr;
186186 rnode->cost = 0;
187187 rnode->enext = end_nodes_[end_pos];
188188 end_nodes_[end_pos] = rnode;
189189 }
190190
191 if (begin_nodes_[pos] == NULL) {
191 if (begin_nodes_[pos] == nullptr) {
192192 begin_nodes_[pos] = node;
193193 } else {
194 for (Node *rnode = node; rnode != NULL; rnode = rnode->bnext) {
195 if (rnode->bnext == NULL) {
194 for (Node *rnode = node; rnode != nullptr; rnode = rnode->bnext) {
195 if (rnode->bnext == nullptr) {
196196 rnode->bnext = begin_nodes_[pos];
197197 begin_nodes_[pos] = node;
198198 break;
266266 end_nodes_.resize(new_size + 4);
267267
268268 std::fill(begin_nodes_.begin() + old_size, begin_nodes_.end(),
269 static_cast<Node *>(NULL));
269 static_cast<Node *>(nullptr));
270270 std::fill(end_nodes_.begin() + old_size + 1, end_nodes_.end(),
271 static_cast<Node *>(NULL));
271 static_cast<Node *>(nullptr));
272272
273273 end_nodes_[0] = InitBOSNode(this, static_cast<uint16>(0));
274274 begin_nodes_[new_size] = InitEOSNode(this, static_cast<uint16>(new_size));
290290 // erase nodes whose end position exceeds new_len
291291 for (size_t i = 0; i < new_len; ++i) {
292292 Node *begin = begin_nodes_[i];
293 if (begin == NULL) {
293 if (begin == nullptr) {
294294 continue;
295295 }
296296
297 for (Node *prev = begin, *curr = begin->bnext; curr != NULL;) {
297 for (Node *prev = begin, *curr = begin->bnext; curr != nullptr;) {
298298 CHECK(prev);
299299 if (curr->end_pos > new_len) {
300300 prev->bnext = curr->bnext;
311311
312312 // update begin_nodes and end_nodes
313313 for (size_t i = new_len; i <= old_len; ++i) {
314 begin_nodes_[i] = NULL;
314 begin_nodes_[i] = nullptr;
315315 }
316316 for (size_t i = new_len + 1; i <= old_len; ++i) {
317 end_nodes_[i] = NULL;
317 end_nodes_[i] = nullptr;
318318 }
319319 begin_nodes_[new_len] = InitEOSNode(this, static_cast<uint16>(new_len));
320320
340340
341341 void Lattice::ResetNodeCost() {
342342 for (size_t i = 0; i <= key_.size(); ++i) {
343 if (begin_nodes_[i] != NULL) {
344 Node *prev = NULL;
345 for (Node *node = begin_nodes_[i]; node != NULL; node = node->bnext) {
343 if (begin_nodes_[i] != nullptr) {
344 Node *prev = nullptr;
345 for (Node *node = begin_nodes_[i]; node != nullptr; node = node->bnext) {
346346 // do not process BOS / EOS nodes
347347 if (node->node_type == Node::BOS_NODE ||
348348 node->node_type == Node::EOS_NODE) {
354354 node->wcost = node->raw_wcost;
355355 } else {
356356 if (node == begin_nodes_[i]) {
357 if (node->bnext == NULL) {
358 begin_nodes_[i] = NULL;
357 if (node->bnext == nullptr) {
358 begin_nodes_[i] = nullptr;
359359 } else {
360360 begin_nodes_[i] = node->bnext;
361361 }
370370 }
371371 }
372372
373 if (end_nodes_[i] != NULL) {
374 Node *prev = NULL;
375 for (Node *node = end_nodes_[i]; node != NULL; node = node->enext) {
373 if (end_nodes_[i] != nullptr) {
374 Node *prev = nullptr;
375 for (Node *node = end_nodes_[i]; node != nullptr; node = node->enext) {
376376 if (node->node_type == Node::BOS_NODE ||
377377 node->node_type == Node::EOS_NODE) {
378378 continue;
381381 node->wcost = node->raw_wcost;
382382 } else {
383383 if (node == end_nodes_[i]) {
384 if (node->enext == NULL) {
385 end_nodes_[i] = NULL;
384 if (node->enext == nullptr) {
385 end_nodes_[i] = nullptr;
386386 } else {
387387 end_nodes_[i] = node->enext;
388388 }
418418 return os.str();
419419 }
420420
421 for (; node != NULL; node = node->prev) {
421 for (; node != nullptr; node = node->prev) {
422422 best_path_nodes.push_back(node);
423423 }
424424
6161 TEST(LatticeTest, NewNodeTest) {
6262 Lattice lattice;
6363 Node *node = lattice.NewNode();
64 EXPECT_TRUE(node != NULL);
64 EXPECT_TRUE(node != nullptr);
6565 EXPECT_EQ(0, node->lid);
6666 EXPECT_EQ(0, node->rid);
6767 }
9595
9696 int size = 0;
9797 Node *node3 = lattice.end_nodes(3);
98 for (; node3 != NULL; node3 = node3->enext) {
98 for (; node3 != nullptr; node3 = node3->enext) {
9999 ++size;
100100 }
101101 EXPECT_EQ(2, size);
152152 // check for begin_nodes
153153 if (i < key_size) {
154154 std::set<int> lengths;
155 for (Node *node = lattice.begin_nodes(i); node != NULL;
155 for (Node *node = lattice.begin_nodes(i); node != nullptr;
156156 node = node->bnext) {
157157 lengths.insert(node->key.size());
158158 }
161161 // check for end_nodes
162162 if (i > 0) {
163163 std::set<int> lengths;
164 for (Node *node = lattice.end_nodes(i); node != NULL;
164 for (Node *node = lattice.end_nodes(i); node != nullptr;
165165 node = node->enext) {
166166 lengths.insert(node->key.size());
167167 }
202202 // check for begin_nodes
203203 if (i < key_size) {
204204 std::set<int> lengths;
205 for (Node *node = lattice.begin_nodes(i); node != NULL;
205 for (Node *node = lattice.begin_nodes(i); node != nullptr;
206206 node = node->bnext) {
207207 lengths.insert(node->key.size());
208208 }
211211 // check for end_nodes
212212 if (i > 0) {
213213 std::set<int> lengths;
214 for (Node *node = lattice.end_nodes(i); node != NULL;
214 for (Node *node = lattice.end_nodes(i); node != nullptr;
215215 node = node->enext) {
216216 lengths.insert(node->key.size());
217217 }
113113 connector_(connector),
114114 pos_matcher_(pos_matcher),
115115 lattice_(lattice),
116 begin_node_(NULL),
117 end_node_(NULL),
116 begin_node_(nullptr),
117 end_node_(nullptr),
118118 freelist_(kFreeListSize),
119119 filter_(new CandidateFilter(suppression_dic, pos_matcher,
120120 suggestion_filter,
121121 apply_suggestion_filter_for_exact_match)),
122122 viterbi_result_checked_(false),
123123 check_mode_(STRICT),
124 boundary_checker_(NULL) {
124 boundary_checker_(nullptr) {
125125 DCHECK(suppression_dictionary_);
126126 DCHECK(segmenter);
127127 DCHECK(connector);
128 if (lattice_ == NULL || !lattice_->has_lattice()) {
128 if (lattice_ == nullptr || !lattice_->has_lattice()) {
129129 LOG(ERROR) << "lattice is not available";
130130 return;
131131 }
146146 begin_node_ = begin_node;
147147 end_node_ = end_node;
148148
149 for (Node *node = lattice_->begin_nodes(end_node_->begin_pos); node != NULL;
150 node = node->bnext) {
149 for (Node *node = lattice_->begin_nodes(end_node_->begin_pos);
150 node != nullptr; node = node->bnext) {
151151 if (node == end_node_ || (node->lid != end_node_->lid &&
152152 node->cost - end_node_->cost <= kCostDiff &&
153153 node->prev != end_node_->prev)) {
154154 // Push "EOS" nodes.
155 agenda_.Push(CreateNewElement(node, NULL, node->cost, 0, 0, 0));
155 agenda_.Push(CreateNewElement(node, nullptr, node->cost, 0, 0, 0));
156156 }
157157 }
158158
187187 bool is_functional = false;
188188 for (size_t i = 0; i < nodes.size(); ++i) {
189189 const Node *node = nodes[i];
190 DCHECK(node != NULL);
190 DCHECK(node != nullptr);
191191 if (!is_functional && !pos_matcher_->IsFunctional(node->lid)) {
192192 candidate->content_value += node->value;
193193 candidate->content_key += node->key;
197197 candidate->key += node->key;
198198 candidate->value += node->value;
199199
200 if (node->constrained_prev != NULL ||
201 (node->next != NULL && node->next->constrained_prev == node)) {
200 if (node->constrained_prev != nullptr ||
201 (node->next != nullptr && node->next->constrained_prev == node)) {
202202 // If result has constrained_node, set CONTEXT_SENSITIVE.
203203 // If a node has constrained node, the node is generated by
204204 // a) compound node and resegmented via personal name resegmentation
279279 DCHECK(end_node_);
280280
281281 DCHECK(candidate);
282 if (lattice_ == NULL || !lattice_->has_lattice()) {
282 if (lattice_ == nullptr || !lattice_->has_lattice()) {
283283 LOG(ERROR) << "Must create lattice in advance";
284284 return false;
285285 }
345345 // reached to the goal.
346346 if (rnode->end_pos == begin_node_->end_pos) {
347347 nodes_.clear();
348 for (const QueueElement *elm = top->next; elm->next != NULL;
348 for (const QueueElement *elm = top->next; elm->next != nullptr;
349349 elm = elm->next) {
350350 nodes_.push_back(elm->node);
351351 }
367367 // do nothing
368368 }
369369 } else {
370 const QueueElement *best_left_elm = NULL;
370 const QueueElement *best_left_elm = nullptr;
371371 const bool is_right_edge = rnode->begin_pos == end_node_->begin_pos;
372372 const bool is_left_edge = rnode->begin_pos == begin_node_->end_pos;
373373 DCHECK(!(is_right_edge && is_left_edge));
376376 // begin/end node regardless of its value.
377377 const bool is_edge = (is_right_edge || is_left_edge);
378378
379 for (Node *lnode = lattice_->end_nodes(rnode->begin_pos); lnode != NULL;
380 lnode = lnode->enext) {
379 for (Node *lnode = lattice_->end_nodes(rnode->begin_pos);
380 lnode != nullptr; lnode = lnode->enext) {
381381 // is_invalid_position is true if the lnode's location is invalid
382382 // 1. |<-- begin_node_-->|
383383 // |<--lnode-->| <== overlapped.
414414 continue;
415415 }
416416
417 DCHECK(this->boundary_checker_ != NULL);
417 DCHECK(this->boundary_checker_ != nullptr);
418418 BoundaryCheckResult boundary_result =
419419 (this->*boundary_checker_)(lnode, rnode, is_edge);
420420 if (boundary_result == INVALID) {
467467 // Even if expand all left nodes, all the |value| part should
468468 // be identical. Here, we simply use the best left edge node.
469469 // This hack reduces the number of redundant calls of pop().
470 if (best_left_elm == NULL || best_left_elm->fx > fx) {
470 if (best_left_elm == nullptr || best_left_elm->fx > fx) {
471471 best_left_elm =
472472 CreateNewElement(lnode, top, fx, gx, structure_gx, w_gx);
473473 }
477477 }
478478 }
479479
480 if (best_left_elm != NULL) {
480 if (best_left_elm != nullptr) {
481481 agenda_.Push(best_left_elm);
482482 }
483483 }
591591 int NBestGenerator::GetTransitionCost(const Node *lnode,
592592 const Node *rnode) const {
593593 const int kInvalidPenaltyCost = 100000;
594 if (rnode->constrained_prev != NULL && lnode != rnode->constrained_prev) {
594 if (rnode->constrained_prev != nullptr && lnode != rnode->constrained_prev) {
595595 return kInvalidPenaltyCost;
596596 }
597597 return connector_->GetTransitionCost(lnode->rid, rnode->lid);
167167 const Segments &segments, const Node &begin_node,
168168 const std::vector<uint16> &group,
169169 bool is_single_segment) {
170 const Node *end_node = NULL;
171 for (Node *node = begin_node.next; node->next != NULL; node = node->next) {
170 const Node *end_node = nullptr;
171 for (Node *node = begin_node.next; node->next != nullptr;
172 node = node->next) {
172173 end_node = node->next;
173174 if (converter.IsSegmentEndNode(segments, node, group,
174175 is_single_segment)) {
4848 class BaseNodeListBuilder : public dictionary::DictionaryInterface::Callback {
4949 public:
5050 BaseNodeListBuilder(mozc::NodeAllocator *allocator, int limit)
51 : allocator_(allocator), limit_(limit), penalty_(0), result_(NULL) {
52 DCHECK(allocator_) << "Allocator must not be NULL";
51 : allocator_(allocator), limit_(limit), penalty_(0), result_(nullptr) {
52 DCHECK(allocator_) << "Allocator must not be nullptr";
5353 }
5454
5555 BaseNodeListBuilder(const BaseNodeListBuilder &) = delete;
4343 namespace internal {
4444
4545 PosIdPrinter::PosIdPrinter(std::istream *id_def) {
46 if (id_def == NULL) {
46 if (id_def == nullptr) {
4747 return;
4848 }
4949
6767 }
6868
6969 TEST_F(PosIdPrinterTest, NullInput) {
70 PosIdPrinter pos_id_printer(NULL);
70 PosIdPrinter pos_id_printer(nullptr);
7171 EXPECT_EQ("", pos_id_printer.IdToString(-1));
7272 EXPECT_EQ("", pos_id_printer.IdToString(1934));
7373 }
249249 }
250250
251251 int Segment::indexOf(const Segment::Candidate *candidate) {
252 if (candidate == NULL) {
252 if (candidate == nullptr) {
253253 return static_cast<int>(candidates_size());
254254 }
255255
187187 EXPECT_TRUE(segment.is_valid_index(-kMetaCandidatesSize));
188188 EXPECT_FALSE(segment.is_valid_index(-kMetaCandidatesSize - 1));
189189
190 EXPECT_EQ(segment.candidates_size(), segment.indexOf(NULL));
190 EXPECT_EQ(segment.candidates_size(), segment.indexOf(nullptr));
191191
192192 segment.pop_back_candidate();
193193 EXPECT_EQ(cand[3], segment.mutable_candidate(3));
597597 EXPECT_EQ(meta_idx, segment.indexOf(segment.mutable_candidate(meta_idx)));
598598 }
599599
600 EXPECT_EQ(segment.candidates_size(), segment.indexOf(NULL));
600 EXPECT_EQ(segment.candidates_size(), segment.indexOf(nullptr));
601601
602602 // mutable_meta_candidates
603603 {
2727 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2828 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2929
30 load("//tools/build_defs:stubs.bzl", "cc_embed_data")
31
3032 package(default_visibility = [
3133 "//:__subpackages__",
3234 ])
4446 "user_segment_history_pos_group.def",
4547 ])
4648
49 cc_embed_data(
50 name = "dictionary_config_data",
51 srcs = [
52 "boundary.def",
53 "cforms.def",
54 "segmenter.def",
55 "sorting_map.tsv",
56 "special_pos.def",
57 "third_party_pos_map.def",
58 "user_pos.def",
59 "user_segment_history_pos_group.def",
60 ],
61 outs = [
62 "dictionary_config_data.cc",
63 "dictionary_config_data.h",
64 "dictionary_config_data_data.o",
65 ],
66 flatten = 1,
67 strip = "dictionary_config_data",
68 )
195195 // Load embedded suggestion filter (bloom filter)
196196 std::unique_ptr<SuggestionFilter> suggestion_filter;
197197 {
198 const char *data = NULL;
198 const char *data = nullptr;
199199 size_t size;
200200 data_manager_->GetSuggestionFilterData(&data, &size);
201201 suggestion_filter.reset(new SuggestionFilter(data, size));
203203 "//testing:mozctest",
204204 "//usage_stats",
205205 "//usage_stats:usage_stats_testing_util",
206 "@com_google_absl//absl/memory",
206207 "@com_google_absl//absl/strings",
207208 ],
208209 )
524525 "//base:serialized_string_array",
525526 "//base:util",
526527 "//data_manager:data_manager_interface",
528 "@com_google_absl//absl/memory",
527529 "@com_google_absl//absl/strings",
528530 ],
529531 )
185185 DictionaryFileCodecFactory::SetCodec(internal_codec.get());
186186 const DictionaryFileCodecInterface *codec =
187187 DictionaryFileCodecFactory::GetCodec();
188 EXPECT_TRUE(codec != NULL);
188 EXPECT_TRUE(codec != nullptr);
189189 {
190190 std::vector<DictionaryFileSection> write_sections;
191191 const std::string value0 = "Value 0 test";
8080 content.assign(ptr, len);
8181 EXPECT_EQ("9876543210", content);
8282 ptr = df.GetSection("sec3", &len);
83 EXPECT_TRUE(ptr == NULL);
83 EXPECT_TRUE(ptr == nullptr);
8484 }
8585
8686 FileUtil::Unlink(dfn);
807807 } // namespace
808808
809809 namespace {
810 SystemDictionaryCodecInterface *g_system_dictionary_codec = NULL;
810 SystemDictionaryCodecInterface *g_system_dictionary_codec = nullptr;
811811 typedef SystemDictionaryCodec DefaultSystemDictionaryCodec;
812812 } // namespace
813813
814814 SystemDictionaryCodecInterface *SystemDictionaryCodecFactory::GetCodec() {
815 if (g_system_dictionary_codec == NULL) {
815 if (g_system_dictionary_codec == nullptr) {
816816 return Singleton<DefaultSystemDictionaryCodec>::get();
817817 } else {
818818 return g_system_dictionary_codec;
117117 class SystemDictionaryCodecTest : public ::testing::Test {
118118 protected:
119119 void SetUp() override {
120 SystemDictionaryCodecFactory::SetCodec(NULL);
120 SystemDictionaryCodecFactory::SetCodec(nullptr);
121121 ResetAllTokens();
122122 }
123123
124124 void TearDown() override {
125 SystemDictionaryCodecFactory::SetCodec(NULL);
125 SystemDictionaryCodecFactory::SetCodec(nullptr);
126126 ResetAllTokens();
127127 }
128128
274274 void CheckDecoded() const {
275275 EXPECT_EQ(source_tokens_.size(), decoded_tokens_.size());
276276 for (size_t i = 0; i < source_tokens_.size(); ++i) {
277 EXPECT_TRUE(source_tokens_[i].token != NULL);
278 EXPECT_TRUE(decoded_tokens_[i].token != NULL);
277 EXPECT_TRUE(source_tokens_[i].token != nullptr);
278 EXPECT_TRUE(decoded_tokens_[i].token != nullptr);
279279
280280 EXPECT_EQ(source_tokens_[i].token->attributes,
281281 decoded_tokens_[i].token->attributes);
6666 // Usage:
6767 // SystemDictionary::Builder builder(filename);
6868 // builder.SetOptions(SystemDictionary::NONE);
69 // builder.SetCodec(NULL);
69 // builder.SetCodec(nullptr);
7070 // SystemDictionary *dictionary = builder.Build();
7171 // ...
7272 // delete dictionary;
8383 // Sets options (default: NONE)
8484 Builder &SetOptions(Options options);
8585
86 // Sets codec (default: NULL)
87 // Uses default codec if this is NULL
86 // Sets codec (default: nullptr)
87 // Uses default codec if this is nullptr
8888 // Doesn't take the ownership of |codec|.
8989 Builder &SetCodec(const SystemDictionaryCodecInterface *codec);
9090
545545 BuildSystemDictionary(tokens, 100);
546546 std::unique_ptr<SystemDictionary> system_dic =
547547 SystemDictionary::Builder(dic_fn_).Build().value();
548 ASSERT_TRUE(system_dic.get() != NULL)
548 ASSERT_TRUE(system_dic.get() != nullptr)
549549 << "Failed to open dictionary source: " << dic_fn_;
550550
551551 const std::string kKey = "かつこう";
7272 token = t;
7373 }
7474 void Clear() {
75 token = NULL;
75 token = nullptr;
7676 id_in_value_trie = -1;
7777 id_in_frequent_pos_map = -1;
7878 pos_type = DEFAULT_POS;
275275 DISALLOW_COPY_AND_ASSIGN(UserDictionaryReloader);
276276 };
277277
278 UserDictionary::UserDictionary(const UserPOSInterface *user_pos,
278 UserDictionary::UserDictionary(std::unique_ptr<const UserPOSInterface> user_pos,
279279 POSMatcher pos_matcher,
280280 SuppressionDictionary *suppression_dictionary)
281281 : ALLOW_THIS_IN_INITIALIZER_LIST(
282282 reloader_(new UserDictionaryReloader(this))),
283 user_pos_(user_pos),
283 user_pos_(std::move(user_pos)),
284284 pos_matcher_(pos_matcher),
285285 suppression_dictionary_(suppression_dictionary),
286286 tokens_(new TokensIndex(user_pos_.get(), suppression_dictionary)),
4949
5050 class UserDictionary : public DictionaryInterface {
5151 public:
52 UserDictionary(const UserPOSInterface *user_pos, POSMatcher pos_matcher,
52 UserDictionary(std::unique_ptr<const UserPOSInterface> user_pos,
53 POSMatcher pos_matcher,
5354 SuppressionDictionary *suppression_dictionary);
5455 ~UserDictionary() override;
5556
103103 bool ConvertEntryInternal(const POSMap *pos_map, size_t map_size,
104104 const UserDictionaryImporter::RawEntry &from,
105105 UserDictionary::Entry *to) {
106 if (to == NULL) {
106 if (to == nullptr) {
107107 LOG(ERROR) << "Null pointer is passed.";
108108 return false;
109109 }
185185
186186 UserDictionaryImporter::ErrorType UserDictionaryImporter::ImportFromIterator(
187187 InputIteratorInterface *iter, UserDictionary *user_dic) {
188 if (iter == NULL || user_dic == NULL) {
189 LOG(ERROR) << "iter or user_dic is NULL";
188 if (iter == nullptr || user_dic == nullptr) {
189 LOG(ERROR) << "iter or user_dic is nullptr";
190190 return IMPORT_FATAL;
191191 }
192192
317317 return false;
318318 }
319319
320 if (entry == NULL) {
321 LOG(ERROR) << "Entry is NULL";
320 if (entry == nullptr) {
321 LOG(ERROR) << "Entry is nullptr";
322322 return false;
323323 }
324324
4545 class TestInputIterator
4646 : public UserDictionaryImporter::InputIteratorInterface {
4747 public:
48 TestInputIterator() : index_(0), is_available_(false), entries_(NULL) {}
48 TestInputIterator() : index_(0), is_available_(false), entries_(nullptr) {}
4949
5050 bool IsAvailable() const { return is_available_; }
5151
8484 : index_(index), dictionary_(dictionary) {}
8585
8686 virtual bool RunUndo(mozc::UserDictionaryStorage *storage) {
87 if (dictionary_.get() == NULL) {
87 if (dictionary_ == nullptr) {
8888 return false;
8989 }
9090
138138 UserDictionary *dictionary =
139139 UserDictionaryUtil::GetMutableUserDictionaryById(
140140 &storage->GetProto(), dictionary_id_);
141 if (dictionary == NULL) {
141 if (dictionary == nullptr) {
142142 return false;
143143 }
144144
162162 UserDictionary *dictionary =
163163 UserDictionaryUtil::GetMutableUserDictionaryById(
164164 &storage->GetProto(), dictionary_id_);
165 if (dictionary == NULL || dictionary->entries_size() == 0) {
165 if (dictionary == nullptr || dictionary->entries_size() == 0) {
166166 return false;
167167 }
168168
188188 UserDictionary *dictionary =
189189 UserDictionaryUtil::GetMutableUserDictionaryById(
190190 &storage->GetProto(), dictionary_id_);
191 if (dictionary == NULL || index_ < 0 ||
191 if (dictionary == nullptr || index_ < 0 ||
192192 dictionary->entries_size() <= index_) {
193193 return false;
194194 }
233233 UserDictionary *dictionary =
234234 UserDictionaryUtil::GetMutableUserDictionaryById(
235235 &storage->GetProto(), dictionary_id_);
236 if (dictionary == NULL) {
236 if (dictionary == nullptr) {
237237 return false;
238238 }
239239
298298 UserDictionary *dictionary =
299299 UserDictionaryUtil::GetMutableUserDictionaryById(
300300 &storage->GetProto(), dictionary_id_);
301 if (dictionary == NULL) {
301 if (dictionary == nullptr) {
302302 return false;
303303 }
304304
501501 const UserDictionary *dictionary =
502502 UserDictionaryUtil::GetUserDictionaryById(
503503 storage_->GetProto(), dictionary_id);
504 if (dictionary != NULL) {
504 if (dictionary != nullptr) {
505505 // Note that if dictionary is null, it means the dictionary_id is invalid
506506 // so following RenameDictionary will fail, and error handling is done
507507 // in the following codes.
536536 uint64 dictionary_id, const UserDictionary::Entry &entry) {
537537 UserDictionary *dictionary = UserDictionaryUtil::GetMutableUserDictionaryById(
538538 &storage_->GetProto(), dictionary_id);
539 if (dictionary == NULL) {
539 if (dictionary == nullptr) {
540540 return UserDictionaryCommandStatus::UNKNOWN_DICTIONARY_ID;
541541 }
542542
563563 uint64 dictionary_id, int index, const UserDictionary::Entry &entry) {
564564 UserDictionary *dictionary = UserDictionaryUtil::GetMutableUserDictionaryById(
565565 &storage_->GetProto(), dictionary_id);
566 if (dictionary == NULL) {
566 if (dictionary == nullptr) {
567567 return UserDictionaryCommandStatus::UNKNOWN_DICTIONARY_ID;
568568 }
569569
590590 uint64 dictionary_id, const std::vector<int> &index_list) {
591591 UserDictionary *dictionary = UserDictionaryUtil::GetMutableUserDictionaryById(
592592 &storage_->GetProto(), dictionary_id);
593 if (dictionary == NULL) {
593 if (dictionary == nullptr) {
594594 return UserDictionaryCommandStatus::UNKNOWN_DICTIONARY_ID;
595595 }
596596
611611 const int index = index_list[i];
612612
613613 deleted_entries.push_back(std::make_pair(index, data[index]));
614 data[index] = NULL;
615 }
616
617 UserDictionary::Entry **tail = std::remove(
618 data, data + entries->size(), static_cast<UserDictionary::Entry *>(NULL));
614 data[index] = nullptr;
615 }
616
617 UserDictionary::Entry **tail =
618 std::remove(data, data + entries->size(),
619 static_cast<UserDictionary::Entry *>(nullptr));
619620 const int remaining_size = tail - data;
620621 while (entries->size() > remaining_size) {
621622 entries->ReleaseLast();
629630 uint64 dictionary_id, const std::string &data) {
630631 UserDictionary *dictionary = UserDictionaryUtil::GetMutableUserDictionaryById(
631632 &storage_->GetProto(), dictionary_id);
632 if (dictionary == NULL) {
633 if (dictionary == nullptr) {
633634 return UserDictionaryCommandStatus::UNKNOWN_DICTIONARY_ID;
634635 }
635636
692693
693694 UserDictionary *dictionary = UserDictionaryUtil::GetMutableUserDictionaryById(
694695 &storage_->GetProto(), *new_dictionary_id);
695 if (dictionary == NULL) {
696 if (dictionary == nullptr) {
696697 // The dictionary should be always found.
697698 return UserDictionaryCommandStatus::UNKNOWN_ERROR;
698699 }
130130 void UserDictionarySessionHandler::NoOperation(
131131 const UserDictionaryCommand &command, UserDictionaryCommandStatus *status) {
132132 UserDictionarySession *session = GetSession(command, status);
133 if (session == NULL) {
133 if (session == nullptr) {
134134 return;
135135 }
136136
168168 void UserDictionarySessionHandler::DeleteSession(
169169 const UserDictionaryCommand &command, UserDictionaryCommandStatus *status) {
170170 UserDictionarySession *session = GetSession(command, status);
171 if (session == NULL) {
171 if (session == nullptr) {
172172 return;
173173 }
174174
181181 void UserDictionarySessionHandler::SetDefaultDictionaryName(
182182 const UserDictionaryCommand &command, UserDictionaryCommandStatus *status) {
183183 UserDictionarySession *session = GetSession(command, status);
184 if (session == NULL) {
184 if (session == nullptr) {
185185 return;
186186 }
187187
197197 void UserDictionarySessionHandler::CheckUndoability(
198198 const UserDictionaryCommand &command, UserDictionaryCommandStatus *status) {
199199 UserDictionarySession *session = GetSession(command, status);
200 if (session == NULL) {
200 if (session == nullptr) {
201201 return;
202202 }
203203
210210 void UserDictionarySessionHandler::Undo(const UserDictionaryCommand &command,
211211 UserDictionaryCommandStatus *status) {
212212 UserDictionarySession *session = GetSession(command, status);
213 if (session == NULL) {
213 if (session == nullptr) {
214214 return;
215215 }
216216
220220 void UserDictionarySessionHandler::Load(const UserDictionaryCommand &command,
221221 UserDictionaryCommandStatus *status) {
222222 UserDictionarySession *session = GetSession(command, status);
223 if (session == NULL) {
223 if (session == nullptr) {
224224 return;
225225 }
226226
234234 void UserDictionarySessionHandler::Save(const UserDictionaryCommand &command,
235235 UserDictionaryCommandStatus *status) {
236236 UserDictionarySession *session = GetSession(command, status);
237 if (session == NULL) {
237 if (session == nullptr) {
238238 return;
239239 }
240240
244244 void UserDictionarySessionHandler::GetUserDictionaryNameList(
245245 const UserDictionaryCommand &command, UserDictionaryCommandStatus *status) {
246246 UserDictionarySession *session = GetSession(command, status);
247 if (session == NULL) {
247 if (session == nullptr) {
248248 return;
249249 }
250250
268268 void UserDictionarySessionHandler::GetEntrySize(
269269 const UserDictionaryCommand &command, UserDictionaryCommandStatus *status) {
270270 UserDictionarySession *session = GetSession(command, status);
271 if (session == NULL) {
271 if (session == nullptr) {
272272 return;
273273 }
274274
279279
280280 const UserDictionary *dictionary = UserDictionaryUtil::GetUserDictionaryById(
281281 session_->storage(), command.dictionary_id());
282 if (dictionary == NULL) {
282 if (dictionary == nullptr) {
283283 status->set_status(UserDictionaryCommandStatus::UNKNOWN_DICTIONARY_ID);
284284 return;
285285 }
292292 void UserDictionarySessionHandler::GetEntries(
293293 const UserDictionaryCommand &command, UserDictionaryCommandStatus *status) {
294294 UserDictionarySession *session = GetSession(command, status);
295 if (session == NULL) {
295 if (session == nullptr) {
296296 return;
297297 }
298298
303303
304304 const UserDictionary *dictionary = UserDictionaryUtil::GetUserDictionaryById(
305305 session_->storage(), command.dictionary_id());
306 if (dictionary == NULL) {
306 if (dictionary == nullptr) {
307307 status->set_status(UserDictionaryCommandStatus::UNKNOWN_DICTIONARY_ID);
308308 return;
309309 }
332332 void UserDictionarySessionHandler::CheckNewDictionaryAvailability(
333333 const UserDictionaryCommand &command, UserDictionaryCommandStatus *status) {
334334 UserDictionarySession *session = GetSession(command, status);
335 if (session == NULL) {
335 if (session == nullptr) {
336336 return;
337337 }
338338
349349 void UserDictionarySessionHandler::CreateDictionary(
350350 const UserDictionaryCommand &command, UserDictionaryCommandStatus *status) {
351351 UserDictionarySession *session = GetSession(command, status);
352 if (session == NULL) {
352 if (session == nullptr) {
353353 return;
354354 }
355355
370370 void UserDictionarySessionHandler::DeleteDictionary(
371371 const UserDictionaryCommand &command, UserDictionaryCommandStatus *status) {
372372 UserDictionarySession *session = GetSession(command, status);
373 if (session == NULL) {
373 if (session == nullptr) {
374374 return;
375375 }
376376
390390 void UserDictionarySessionHandler::RenameDictionary(
391391 const UserDictionaryCommand &command, UserDictionaryCommandStatus *status) {
392392 UserDictionarySession *session = GetSession(command, status);
393 if (session == NULL) {
393 if (session == nullptr) {
394394 return;
395395 }
396396
406406 void UserDictionarySessionHandler::CheckNewEntryAvailability(
407407 const UserDictionaryCommand &command, UserDictionaryCommandStatus *status) {
408408 UserDictionarySession *session = GetSession(command, status);
409 if (session == NULL) {
409 if (session == nullptr) {
410410 return;
411411 }
412412
417417
418418 const UserDictionary *dictionary = UserDictionaryUtil::GetUserDictionaryById(
419419 session->storage(), command.dictionary_id());
420 if (dictionary == NULL) {
420 if (dictionary == nullptr) {
421421 status->set_status(UserDictionaryCommandStatus::UNKNOWN_DICTIONARY_ID);
422422 return;
423423 }
434434 void UserDictionarySessionHandler::AddEntry(
435435 const UserDictionaryCommand &command, UserDictionaryCommandStatus *status) {
436436 UserDictionarySession *session = GetSession(command, status);
437 if (session == NULL) {
437 if (session == nullptr) {
438438 return;
439439 }
440440
450450 void UserDictionarySessionHandler::EditEntry(
451451 const UserDictionaryCommand &command, UserDictionaryCommandStatus *status) {
452452 UserDictionarySession *session = GetSession(command, status);
453 if (session == NULL) {
453 if (session == nullptr) {
454454 return;
455455 }
456456
467467 void UserDictionarySessionHandler::DeleteEntry(
468468 const UserDictionaryCommand &command, UserDictionaryCommandStatus *status) {
469469 UserDictionarySession *session = GetSession(command, status);
470 if (session == NULL) {
470 if (session == nullptr) {
471471 return;
472472 }
473473
484484 void UserDictionarySessionHandler::ImportData(
485485 const UserDictionaryCommand &command, UserDictionaryCommandStatus *status) {
486486 UserDictionarySession *session = GetSession(command, status);
487 if (session == NULL) {
487 if (session == nullptr) {
488488 return;
489489 }
490490
522522 void UserDictionarySessionHandler::GetStorage(
523523 const UserDictionaryCommand &command, UserDictionaryCommandStatus *status) {
524524 UserDictionarySession *session = GetSession(command, status);
525 if (session == NULL) {
525 if (session == nullptr) {
526526 return;
527527 }
528528 status->mutable_storage()->CopyFrom(session->storage());
534534 const UserDictionaryCommand &command, UserDictionaryCommandStatus *status) {
535535 if (!command.has_session_id()) {
536536 status->set_status(UserDictionaryCommandStatus::INVALID_ARGUMENT);
537 return NULL;
538 }
539
540 if (session_.get() == NULL || session_id_ != command.session_id()) {
537 return nullptr;
538 }
539
540 if (session_ == nullptr || session_id_ != command.session_id()) {
541541 status->set_status(UserDictionaryCommandStatus::UNKNOWN_SESSION_ID);
542 return NULL;
542 return nullptr;
543543 }
544544
545545 return session_.get();
551551 Util::GetRandomSequence(reinterpret_cast<char *>(&id), sizeof(id));
552552
553553 if (id != kInvalidSessionId &&
554 (session_.get() == NULL || session_id_ != id)) {
554 (session_ == nullptr || session_id_ != id)) {
555555 // New id is generated.
556556 break;
557557 }
261261 }
262262
263263 bool UserDictionaryStorage::DeleteDictionary(uint64 dic_id) {
264 if (!UserDictionaryUtil::DeleteDictionary(&proto_, dic_id, NULL, NULL)) {
264 if (!UserDictionaryUtil::DeleteDictionary(&proto_, dic_id, nullptr,
265 nullptr)) {
265266 // Failed to delete dictionary.
266267 last_error_type_ = INVALID_DICTIONARY_ID;
267268 return false;
281282 }
282283
283284 UserDictionary *dic = GetUserDictionary(dic_id);
284 if (dic == NULL) {
285 if (dic == nullptr) {
285286 last_error_type_ = INVALID_DICTIONARY_ID;
286287 LOG(ERROR) << "Invalid dictionary id: " << dic_id;
287288 return false;
131131 for (size_t i = 0; i < kDictionariesSize; ++i) {
132132 EXPECT_EQ(storage.GetProto().mutable_dictionaries(i + dict_size),
133133 storage.GetUserDictionary(id[i]));
134 EXPECT_EQ(NULL, storage.GetUserDictionary(id[i] + 1));
134 EXPECT_EQ(nullptr, storage.GetUserDictionary(id[i] + 1));
135135 }
136136
137137 // empty
5757 #include "testing/base/public/mozctest.h"
5858 #include "usage_stats/usage_stats.h"
5959 #include "usage_stats/usage_stats_testing_util.h"
60 #include "absl/memory/memory.h"
6061 #include "absl/strings/string_view.h"
6162
6263 namespace mozc {
206207 // Creates a user dictionary with mock pos data.
207208 UserDictionary *CreateDictionaryWithMockPos() {
208209 return new UserDictionary(
209 new UserPOSMock(),
210 absl::make_unique<UserPOSMock>(),
210211 dictionary::POSMatcher(mock_data_manager_.GetPOSMatcherData()),
211212 suppression_dictionary_.get());
212213 }
178178 const user_dictionary::UserDictionaryStorage &storage,
179179 uint64 dictionary_id) {
180180 int index = GetUserDictionaryIndexById(storage, dictionary_id);
181 return index >= 0 ? &storage.dictionaries(index) : NULL;
181 return index >= 0 ? &storage.dictionaries(index) : nullptr;
182182 }
183183
184184 user_dictionary::UserDictionary *
185185 UserDictionaryUtil::GetMutableUserDictionaryById(
186186 user_dictionary::UserDictionaryStorage *storage, uint64 dictionary_id) {
187187 int index = GetUserDictionaryIndexById(*storage, dictionary_id);
188 return index >= 0 ? storage->mutable_dictionaries(index) : NULL;
188 return index >= 0 ? storage->mutable_dictionaries(index) : nullptr;
189189 }
190190
191191 int UserDictionaryUtil::GetUserDictionaryIndexById(
314314 if (user_dictionary::UserDictionary::PosType_IsValid(pos_type)) {
315315 return kPosTypeStringTable[pos_type];
316316 }
317 return NULL;
317 return nullptr;
318318 }
319319
320320 user_dictionary::UserDictionary::PosType UserDictionaryUtil::ToPosType(
372372 return UserDictionaryCommandStatus::DICTIONARY_SIZE_LIMIT_EXCEEDED;
373373 }
374374
375 if (new_dictionary_id == NULL) {
376 LOG(ERROR) << "new_dictionary_id is NULL";
375 if (new_dictionary_id == nullptr) {
376 LOG(ERROR) << "new_dictionary_id is nullptr";
377377 return UserDictionaryCommandStatus::UNKNOWN_ERROR;
378378 }
379379
380380 *new_dictionary_id = CreateNewDictionaryId(*storage);
381381 user_dictionary::UserDictionary *dictionary = storage->add_dictionaries();
382 if (dictionary == NULL) {
382 if (dictionary == nullptr) {
383383 LOG(ERROR) << "add_dictionaries failed.";
384384 return UserDictionaryCommandStatus::UNKNOWN_ERROR;
385385 }
393393 user_dictionary::UserDictionaryStorage *storage, uint64 dictionary_id,
394394 int *original_index, user_dictionary::UserDictionary **deleted_dictionary) {
395395 const int index = GetUserDictionaryIndexById(*storage, dictionary_id);
396 if (original_index != NULL) {
396 if (original_index != nullptr) {
397397 *original_index = index;
398398 }
399399
409409 dictionaries->pointer_begin() + index + 1,
410410 dictionaries->pointer_end());
411411
412 if (deleted_dictionary == NULL) {
412 if (deleted_dictionary == nullptr) {
413413 dictionaries->RemoveLast();
414414 } else {
415415 *deleted_dictionary = dictionaries->ReleaseLast();
109109 static bool IsDictionaryFull(
110110 const user_dictionary::UserDictionary &dictionary);
111111
112 // Returns UserDictionary with the given id, or NULL if not found.
112 // Returns UserDictionary with the given id, or nullptr if not found.
113113 static const user_dictionary::UserDictionary *GetUserDictionaryById(
114114 const user_dictionary::UserDictionaryStorage &storage,
115115 uint64 dictionary_id);
125125 // Returns the file name of UserDictionary.
126126 static std::string GetUserDictionaryFileName();
127127
128 // Returns the string representation of PosType, or NULL if the given
128 // Returns the string representation of PosType, or nullptr if the given
129129 // pos is invalid.
130130 // For historicall reason, the pos was represented in Japanese characters.
131131 static const char *GetStringPosType(
132132 user_dictionary::UserDictionary::PosType pos_type);
133133
134 // Returns the string representation of PosType, or NULL if the given
134 // Returns the string representation of PosType, or nullptr if the given
135135 // pos is invalid.
136136 static user_dictionary::UserDictionary::PosType ToPosType(
137137 const char *string_pos_type);
146146 const std::string &dictionary_name, uint64 *new_dictionary_id);
147147
148148 // Deletes dictionary specified by the given dictionary_id.
149 // If the deleted_dictionary is not NULL, the pointer to the
149 // If the deleted_dictionary is not nullptr, the pointer to the
150150 // delete dictionary is stored into it. In other words,
151151 // caller has responsibility to actual deletion of the instance.
152152 // Returns true if succeeded, otherwise false.
278278 &storage.dictionaries(0));
279279 EXPECT_TRUE(UserDictionaryUtil::GetUserDictionaryById(storage, 2) ==
280280 &storage.dictionaries(1));
281 EXPECT_TRUE(UserDictionaryUtil::GetUserDictionaryById(storage, -1) == NULL);
281 EXPECT_TRUE(UserDictionaryUtil::GetUserDictionaryById(storage, -1) ==
282 nullptr);
282283 }
283284
284285 TEST(UserDictionaryUtilTest, GetMutableUserDictionaryById) {
291292 EXPECT_TRUE(UserDictionaryUtil::GetMutableUserDictionaryById(&storage, 2) ==
292293 storage.mutable_dictionaries(1));
293294 EXPECT_TRUE(UserDictionaryUtil::GetMutableUserDictionaryById(&storage, -1) ==
294 NULL);
295 nullptr);
295296 }
296297
297298 TEST(UserDictionaryUtilTest, GetUserDictionaryIndexById) {
325326 &dictionary_id));
326327
327328 storage.Clear();
328 EXPECT_EQ(
329 UserDictionaryCommandStatus::UNKNOWN_ERROR,
330 UserDictionaryUtil::CreateDictionary(&storage, "new dictionary", NULL));
329 EXPECT_EQ(UserDictionaryCommandStatus::UNKNOWN_ERROR,
330 UserDictionaryUtil::CreateDictionary(&storage, "new dictionary",
331 nullptr));
331332
332333 ASSERT_EQ(UserDictionaryCommandStatus::USER_DICTIONARY_COMMAND_SUCCESS,
333334 UserDictionaryUtil::CreateDictionary(&storage, "new dictionary",
348349
349350 // Simplest deleting case.
350351 int original_index;
351 ASSERT_TRUE(
352 UserDictionaryUtil::DeleteDictionary(&storage, 1, &original_index, NULL));
352 ASSERT_TRUE(UserDictionaryUtil::DeleteDictionary(&storage, 1, &original_index,
353 nullptr));
353354 EXPECT_EQ(0, original_index);
354355 ASSERT_EQ(1, storage.dictionaries_size());
355356 EXPECT_EQ(2, storage.dictionaries(0).id());
358359 storage.Clear();
359360 storage.add_dictionaries()->set_id(1);
360361 storage.add_dictionaries()->set_id(2);
361 EXPECT_FALSE(UserDictionaryUtil::DeleteDictionary(&storage, 100, NULL, NULL));
362 EXPECT_FALSE(
363 UserDictionaryUtil::DeleteDictionary(&storage, 100, nullptr, nullptr));
362364
363365 // Keep deleted dictionary.
364366 storage.Clear();
366368 storage.add_dictionaries()->set_id(2);
367369 UserDictionary *expected_deleted_dictionary = storage.mutable_dictionaries(0);
368370 UserDictionary *deleted_dictionary;
369 EXPECT_TRUE(UserDictionaryUtil::DeleteDictionary(&storage, 1, NULL,
371 EXPECT_TRUE(UserDictionaryUtil::DeleteDictionary(&storage, 1, nullptr,
370372 &deleted_dictionary));
371373 ASSERT_EQ(1, storage.dictionaries_size());
372374 EXPECT_EQ(2, storage.dictionaries(0).id());
3333
3434 #include "base/logging.h"
3535 #include "base/util.h"
36 #include "absl/memory/memory.h"
3637 #include "absl/strings/string_view.h"
3738
3839 namespace mozc {
159160 return true;
160161 }
161162
162 UserPOS *UserPOS::CreateFromDataManager(const DataManagerInterface &manager) {
163 std::unique_ptr<UserPOS> UserPOS::CreateFromDataManager(
164 const DataManagerInterface &manager) {
163165 absl::string_view token_array_data, string_array_data;
164166 manager.GetUserPOSData(&token_array_data, &string_array_data);
165 return new UserPOS(token_array_data, string_array_data);
167 return absl::make_unique<UserPOS>(token_array_data, string_array_data);
166168 }
167169
168170 } // namespace dictionary
169169
170170 using const_iterator = iterator;
171171
172 static UserPOS *CreateFromDataManager(const DataManagerInterface &manager);
172 static std::unique_ptr<UserPOS> CreateFromDataManager(
173 const DataManagerInterface &manager);
173174
174175 // Initializes the user pos from the given binary data. The provided byte
175176 // data must outlive this instance.
8888 "//base:version",
8989 "//gui/base:gui_base",
9090 "//gui/base:singleton_window_helper",
91 "@com_google_absl//absl/memory",
9192 ],
9293 )
9394
2929 #include "gui/about_dialog/about_dialog.h"
3030
3131 #include <QtGui/QtGui>
32
3332 #include <string>
3433
3534 #include "base/file_util.h"
3938 #include "base/util.h"
4039 #include "base/version.h"
4140 #include "gui/base/util.h"
41 #include "absl/memory/memory.h"
4242
4343 namespace mozc {
4444 namespace gui {
111111 SetLabelText(label_terms);
112112 SetLabelText(label_credits);
113113
114 product_image_.reset(new QImage(":/product_logo.png"));
114 product_image_ = absl::make_unique<QImage>(":/product_logo.png");
115115 }
116116
117117 void AboutDialog::paintEvent(QPaintEvent *event) {
3232 #define MOZC_GUI_ABOUT_DIALOG_ABOUT_DIALOG_H_
3333
3434 #include <QtWidgets/QDialog>
35
3635 #include <memory>
3736
3837 #include "base/port.h"
5655 explicit AboutDialog(QWidget *parent = nullptr);
5756 void SetLinkCallback(LinkCallbackInterface *callback);
5857
59 void paintEvent(QPaintEvent *event);
58 void paintEvent(QPaintEvent *event) override;
6059
6160 public slots:
6261 void linkActivated(const QString &link);
2828
2929 #include <QtGui/QGuiApplication>
3030 #include <QtGui/QtGui>
31
3132 #include "base/system_util.h"
3233 #include "gui/about_dialog/about_dialog.h"
3334 #include "gui/base/singleton_window_helper.h"
4141
4242 public:
4343 AdministrationDialog();
44 virtual ~AdministrationDialog();
44 ~AdministrationDialog() override;
4545
4646 protected slots:
4747 virtual void clicked(QAbstractButton *button);
4848
4949 protected:
50 bool eventFilter(QObject *obj, QEvent *event);
50 bool eventFilter(QObject *obj, QEvent *event) override;
5151
5252 private:
5353 bool CanStartService();
165165 "//base:version",
166166 "//ipc",
167167 "//ipc:window_info_proto",
168 "@com_google_absl//absl/memory",
168169 ],
169170 )
4646 #include "base/util.h"
4747 #include "gui/base/win_util.h"
4848 #include "ipc/window_info.pb.h"
49 #include "absl/memory/memory.h"
4950
5051 namespace mozc {
5152 namespace gui {
112113 } // namespace
113114
114115 SingletonWindowHelper::SingletonWindowHelper(const std::string &name) {
115 mutex_.reset(new mozc::ProcessMutex(name.c_str()));
116 mutex_ = absl::make_unique<mozc::ProcessMutex>(name.c_str());
116117 }
117118
118119 SingletonWindowHelper::~SingletonWindowHelper() {}
3535 #endif // CHANNEL_DEV && GOOGLE_JAPANESE_INPUT_BUILD
3636
3737
38 #include <memory>
39
4038 #include <QtCore/QObject>
4139 #include <QtGui/QFont>
4240 #include <QtGui/QGuiApplication>
4442 #include <QtWidgets/QAbstractButton>
4543 #include <QtWidgets/QApplication>
4644 #include <QtWidgets/QStyleFactory>
45 #include <memory>
4746
47 #include "base/logging.h"
4848 #include "absl/memory/memory.h"
49 #include "base/logging.h"
5049
5150 #ifdef MOZC_SHOW_BUILD_NUMBER_ON_TITLE
5251 #include "gui/base/window_title_modifier.h"
2626 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2727 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2828
29 #include "gui/base/window_title_modifier.h"
30
2931 #include <QtCore/QObject>
3032 #include <QtCore/QString>
3133 #include <QtGui/QGuiApplication>
3335 #include <QtWidgets/QWidget>
3436
3537 #include "base/version.h"
36 #include "gui/base/window_title_modifier.h"
3738
3839 namespace mozc {
3940 namespace gui {
2626 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2727 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2828
29 #ifndef MOZC_GUI_BASE_WINDOW_TITLE_MODIFIER_
30 #define MOZC_GUI_BASE_WINDOW_TITLE_MODIFIER_
29 #ifndef MOZC_GUI_BASE_WINDOW_TITLE_MODIFIER_H_
30 #define MOZC_GUI_BASE_WINDOW_TITLE_MODIFIER_H_
3131
3232 #include <QtCore/QEvent>
3333 #include <QtCore/QObject>
4343 ~WindowTitleModifier() override = default;
4444
4545 protected:
46 bool eventFilter(QObject *obj, QEvent *event);
46 bool eventFilter(QObject *obj, QEvent *event) override;
4747 };
4848 } // namespace gui
4949 } // namespace mozc
5050
51 #endif // MOZC_GUI_BASE_WINDOW_TITLE_MODIFIER_
51 #endif // MOZC_GUI_BASE_WINDOW_TITLE_MODIFIER_H_
208208 "//protocol:commands_proto",
209209 "//protocol:config_proto",
210210 "//session/internal:keymap",
211 "@com_google_absl//absl/memory",
211212 ],
212213 )
213214
3030
3131 #include <QtGui/QtGui>
3232 #include <QtWidgets/QHeaderView>
33
3433 #include <memory>
3534
3635 #include "config/config_handler.h"
3736 #include "gui/config_dialog/combobox_delegate.h"
37 #include "absl/memory/memory.h"
3838
3939 namespace mozc {
4040 namespace gui {
126126
127127 // make sure that table isn't empty.
128128 if (config.character_form_rules_size() == 0) {
129 default_config.reset(new config::Config);
129 default_config = absl::make_unique<config::Config>();
130130 config::ConfigHandler::GetDefaultConfig(default_config.get());
131131 target_config = default_config.get();
132132 }
3030 #define MOZC_GUI_CONFIG_DIALOG_CHARACTER_FORM_EDITOR_H_
3131
3232 #include <QtWidgets/QTableWidget>
33
3433 #include <memory>
3534
3635 #include "base/port.h"
4948 Q_OBJECT
5049 public:
5150 explicit CharacterFormEditor(QWidget *parent = nullptr);
52 virtual ~CharacterFormEditor();
51 ~CharacterFormEditor() override;
5352
5453 void Load(const config::Config &config);
5554 void Save(config::Config *config);
4444 Q_OBJECT
4545 public:
4646 explicit ComboBoxDelegate(QObject *parent = nullptr);
47 virtual ~ComboBoxDelegate();
47 ~ComboBoxDelegate() override;
4848
4949 void SetItemList(const QStringList &item_list);
5050
5151 QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
52 const QModelIndex &index) const;
52 const QModelIndex &index) const override;
5353
54 void setEditorData(QWidget *editor, const QModelIndex &index) const;
54 void setEditorData(QWidget *editor, const QModelIndex &index) const override;
5555 void setModelData(QWidget *editor, QAbstractItemModel *model,
56 const QModelIndex &index) const;
56 const QModelIndex &index) const override;
5757
5858 void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
59 const QModelIndex &index) const;
59 const QModelIndex &index) const override;
6060
6161 private slots:
6262 void CommitAndCloseEditor(const QString &str);
3333
3434 #include <QtCore/QObject>
3535 #include <QtCore/QTimer>
36
3736 #include <map>
3837 #include <memory>
3938 #include <string>
5857
5958 public:
6059 ConfigDialog();
61 virtual ~ConfigDialog();
60 ~ConfigDialog() override;
6261
6362 // Methods defined in the 'slots' section (Qt's extention) will be processed
6463 // by Qt's moc tool (moc.exe on Windows). Unfortunately, preprocessor macros
8685 virtual void EnableApplyButton();
8786
8887 protected:
89 bool eventFilter(QObject *obj, QEvent *event);
88 bool eventFilter(QObject *obj, QEvent *event) override;
9089
9190 private:
9291 bool GetConfig(config::Config *config);
142142 rows.push_back(selected[i]->row());
143143 }
144144
145 std::vector<int>::iterator last = unique(rows.begin(), rows.end());
145 std::vector<int>::iterator last = std::unique(rows.begin(), rows.end());
146146 rows.erase(last, rows.end());
147147
148148 if (rows.empty()) {
4545
4646 public:
4747 explicit GenericTableEditorDialog(QWidget *parent, size_t column_size);
48 virtual ~GenericTableEditorDialog();
48 ~GenericTableEditorDialog() override;
4949
5050 bool LoadFromString(const std::string &table);
5151 const std::string &table() const;
4949 #include "base/logging.h"
5050 #include "base/util.h"
5151 #include "gui/base/util.h"
52 #include "absl/memory/memory.h"
5253
5354 namespace mozc {
5455 namespace gui {
157158 class KeyBindingFilter : public QObject {
158159 public:
159160 KeyBindingFilter(QLineEdit *line_edit, QPushButton *ok_button);
160 virtual ~KeyBindingFilter();
161 ~KeyBindingFilter() override;
161162
162163 enum KeyState { DENY_KEY, ACCEPT_KEY, SUBMIT_KEY };
163164
164165 protected:
165 bool eventFilter(QObject *obj, QEvent *event);
166 bool eventFilter(QObject *obj, QEvent *event) override;
166167
167168 private:
168169 void Reset();
490491 KeyBindingEditorbuttonBox->button(QDialogButtonBox::Ok);
491492 CHECK(ok_button != nullptr);
492493
493 filter_.reset(new KeyBindingFilter(KeyBindingLineEdit, ok_button));
494 filter_ = absl::make_unique<KeyBindingFilter>(KeyBindingLineEdit, ok_button);
494495 KeyBindingLineEdit->installEventFilter(filter_.get());
495496
496497 // no right click
3131
3232 #include <QtGui/QGuiApplication>
3333 #include <QtGui/QtGui>
34
3534 #include <memory>
3635 #include <string>
3736
4948 // |trigger_parent| is the object who was the trigger of launching the editor.
5049 // QPushButton can be a trigger_parent.
5150 KeyBindingEditor(QWidget *parent, QWidget *trigger_parent);
52 virtual ~KeyBindingEditor();
51 ~KeyBindingEditor() override;
5352
5453 QWidget *mutable_trigger_parent() const { return trigger_parent_; }
5554
6059 // For some reason, KeyBindingEditor lanuched by
6160 // QItemDelegate looses focus. We overwrite
6261 // setVisible() function to call raise() and activateWindow().
63 virtual void setVisible(bool visible) {
62 void setVisible(bool visible) override {
6463 QWidget::setVisible(visible);
6564 if (visible) {
6665 raise();
3030
3131 #include <QtGui/QtGui>
3232 #include <QtWidgets/QPushButton>
33
3433 #include <memory>
3534
3635 #include "base/logging.h"
2626 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2727 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2828
29 #ifndef MOZC_GUI_KEYCOMMAND_DIALOG_KEYBINDING_EDITOR_DELEGATE_H_
30 #define MOZC_GUI_KEYCOMMAND_DIALOG_KEYBINDING_EDITOR_DELEGATE_H_
29 #ifndef MOZC_GUI_CONFIG_DIALOG_KEYBINDING_EDITOR_DELEGATE_H_
30 #define MOZC_GUI_CONFIG_DIALOG_KEYBINDING_EDITOR_DELEGATE_H_
3131
3232 #include <QtCore/QModelIndex>
3333 #include <QtCore/QObject>
4242 Q_OBJECT
4343 public:
4444 explicit KeyBindingEditorDelegate(QObject *parent = nullptr);
45 virtual ~KeyBindingEditorDelegate();
45 ~KeyBindingEditorDelegate() override;
4646
4747 QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
48 const QModelIndex &index) const;
48 const QModelIndex &index) const override;
4949
50 void setEditorData(QWidget *editor, const QModelIndex &index) const;
50 void setEditorData(QWidget *editor, const QModelIndex &index) const override;
5151 void setModelData(QWidget *editor, QAbstractItemModel *model,
52 const QModelIndex &index) const;
52 const QModelIndex &index) const override;
5353
5454 void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
55 const QModelIndex &index) const;
55 const QModelIndex &index) const override;
5656
5757 private slots:
5858 void CommitAndCloseEditor();
6060 };
6161 } // namespace gui
6262 } // namespace mozc
63 #endif // MOZC_GUI_KEYCOMMAND_DIALOG_KEYBINDING_EDITOR_DELEGATE_H_
63 #endif // MOZC_GUI_CONFIG_DIALOG_KEYBINDING_EDITOR_DELEGATE_H_
3737 #include <QtWidgets/QFileDialog>
3838 #include <QtWidgets/QMenu>
3939 #include <QtWidgets/QMessageBox>
40
4140 #include <algorithm> // for unique
4241 #include <cctype>
4342 #include <memory>
325324 }
326325
327326 std::string line;
328 if (!getline(*is, line)) { // must have 1st line
327 if (!std::getline(*is, line)) { // must have 1st line
329328 return false;
330329 }
331330
336335
337336 invisible_keymap_table_.clear();
338337 direct_mode_commands_.clear();
339 while (getline(*is, line)) {
338 while (std::getline(*is, line)) {
340339 if (line.empty() || line[0] == '#') {
341340 continue;
342341 }
3030 #define MOZC_GUI_CONFIG_DIALOG_KEYMAP_EDITOR_H_
3131
3232 #include <QtWidgets/QWidget>
33
3433 #include <map>
3534 #include <memory>
3635 #include <set>
5251
5352 public:
5453 explicit KeyMapEditorDialog(QWidget *parent);
55 virtual ~KeyMapEditorDialog();
54 ~KeyMapEditorDialog() override;
5655
5756 // show a modal dialog
5857 static bool Show(QWidget *parent, const std::string &current_keymap,
5958 std::string *new_keymap);
6059
6160 protected slots:
62 virtual void UpdateMenuStatus();
63 virtual void OnEditMenuAction(QAction *action);
61 void UpdateMenuStatus() override;
62 void OnEditMenuAction(QAction *action) override;
6463
6564 protected:
66 virtual std::string GetDefaultFilename() const { return "keymap.txt"; }
67 virtual bool LoadFromStream(std::istream *is);
68 virtual bool Update();
65 std::string GetDefaultFilename() const override { return "keymap.txt"; }
66 bool LoadFromStream(std::istream *is) override;
67 bool Update() override;
6968
7069 private:
7170 std::string invisible_keymap_table_;
9696 CHECK(ifs.get() != nullptr); // should never happen
9797 std::string line, result;
9898 std::vector<std::string> fields;
99 while (getline(*ifs.get(), line)) {
99 while (std::getline(*ifs.get(), line)) {
100100 if (line.empty()) {
101101 continue;
102102 }
127127 mutable_table_widget()->verticalHeader()->hide();
128128
129129 int row = 0;
130 while (getline(*is, line)) {
130 while (std::getline(*is, line)) {
131131 if (line.empty()) {
132132 continue;
133133 }
3030 #define MOZC_GUI_CONFIG_DIALOG_ROMAN_TABLE_EDITOR_H_
3131
3232 #include <QtWidgets/QWidget>
33
3433 #include <memory>
3534 #include <string>
3635
4746
4847 public:
4948 explicit RomanTableEditorDialog(QWidget *parent);
50 virtual ~RomanTableEditorDialog();
49 ~RomanTableEditorDialog() override;
5150
5251 // show a modal dialog
5352 static bool Show(QWidget *parent, const std::string &current_keymap,
5453 std::string *new_keymap);
5554
5655 protected slots:
57 virtual void UpdateMenuStatus();
58 virtual void OnEditMenuAction(QAction *action);
56 void UpdateMenuStatus() override;
57 void OnEditMenuAction(QAction *action) override;
5958
6059 protected:
61 virtual std::string GetDefaultFilename() const { return "romantable.txt"; }
62 virtual bool LoadFromStream(std::istream *is);
63 virtual bool Update();
60 std::string GetDefaultFilename() const override { return "romantable.txt"; }
61 bool LoadFromStream(std::istream *is) override;
62 bool Update() override;
6463
6564 private:
6665 bool LoadDefaultRomanTable();
2626 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2727 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2828
29 #ifndef MOZC_GUI_CONFIRMATION_DIALOG_H_
30 #define MOZC_GUI_CONFIRMATION_DIALOG_H_
29 #ifndef MOZC_GUI_CONFIRMATION_DIALOG_CONFIRMATION_DIALOG_H_
30 #define MOZC_GUI_CONFIRMATION_DIALOG_CONFIRMATION_DIALOG_H_
3131
3232 #include <QtCore/QObject>
3333 #include <QtWidgets/QMessageBox>
4242
4343 } // namespace gui
4444 } // namespace mozc
45 #endif // MOZC_GUI_CONFIRMATION_DIALOG_H_
45 #endif // MOZC_GUI_CONFIRMATION_DIALOG_CONFIRMATION_DIALOG_H_
169169 "//protocol:commands_proto",
170170 "//protocol:config_proto",
171171 "//protocol:user_dictionary_storage_proto",
172 "@com_google_absl//absl/memory",
172173 ],
173174 )
174175
4040 public:
4141 // overwrite paintEvent to draw a striped pattern to all
4242 // view port area This makes the view port Mac style.
43 void paintEvent(QPaintEvent *event);
44 void focusInEvent(QFocusEvent *event);
43 void paintEvent(QPaintEvent *event) override;
44 void focusInEvent(QFocusEvent *event) override;
4545
4646 // overwrite mouseDoubleClickEvent to catch click event
4747 // when user double-clicked empty area in viewport
48 void mouseDoubleClickEvent(QMouseEvent *event);
48 void mouseDoubleClickEvent(QMouseEvent *event) override;
4949
5050 explicit DictionaryContentTableWidget(QWidget *parent);
5151
6868 #include "gui/dictionary_tool/find_dialog.h"
6969 #include "gui/dictionary_tool/import_dialog.h"
7070 #include "protocol/user_dictionary_storage.pb.h"
71 #include "absl/memory/memory.h"
7172
7273 #ifdef OS_WIN
7374 #include "gui/base/win_util.h"
131132 progress_.reset(CreateProgressDialog(message, parent, file_.size()));
132133 }
133134
134 bool IsAvailable() const { return file_.error() == QFile::NoError; }
135
136 bool Next(std::string *line) {
135 bool IsAvailable() const override { return file_.error() == QFile::NoError; }
136
137 bool Next(std::string *line) override {
137138 if (stream_->atEnd()) {
138139 return false;
139140 }
160161 return true;
161162 }
162163
163 void Reset() {
164 void Reset() override {
164165 file_.seek(0);
165 stream_.reset(new QTextStream);
166 stream_ = absl::make_unique<QTextStream>();
166167 stream_->setDevice(&file_);
167168 stream_->setCodec("UTF-16");
168169 }
189190 progress_.reset(CreateProgressDialog(message, parent, size));
190191 }
191192
192 bool IsAvailable() const {
193 bool IsAvailable() const override {
193194 // This means that neither failbit nor badbit is set.
194195 // TODO(yukawa): Consider to remove |ifs_->eof()|. Furthermore, we should
195196 // replace IsAvailable() with something easier to understand, e.g.,
197198 return ifs_->good() || ifs_->eof();
198199 }
199200
200 bool Next(std::string *line) {
201 bool Next(std::string *line) override {
201202 if (!ifs_->good()) {
202203 return false;
203204 }
239240 return true;
240241 }
241242
242 void Reset() {
243 void Reset() override {
243244 // Clear state bit (eofbit, failbit, badbit).
244245 ifs_->clear();
245246 ifs_->seekg(0, std::ios_base::beg);
10301031 }
10311032
10321033 std::sort(rows->begin(), rows->end(), std::greater<int>());
1033 std::vector<int>::const_iterator end = unique(rows->begin(), rows->end());
1034 std::vector<int>::const_iterator end =
1035 std::unique(rows->begin(), rows->end());
10341036
10351037 rows->resize(end - rows->begin());
10361038 }
3333 #include <QtWidgets/QPushButton>
3434 #include <QtWidgets/QSplitter>
3535 #include <QtWidgets/QSplitterHandle>
36
3736 #include <memory>
3837 #include <string>
3938 #include <vector>
6463
6564 public:
6665 explicit DictionaryTool(QWidget *parent = 0);
67 virtual ~DictionaryTool();
66 ~DictionaryTool() override;
6867
6968 // return true DictionaryTool is available.
7069 bool IsAvailable() const { return is_available_; }
7271 protected:
7372 // Override the default implementation to check unsaved
7473 // modifications on data before closing the window.
75 void closeEvent(QCloseEvent *event);
76
77 bool eventFilter(QObject *obj, QEvent *event);
74 void closeEvent(QCloseEvent *event) override;
75
76 bool eventFilter(QObject *obj, QEvent *event) override;
7877
7978 private slots:
8079 void CreateDictionary();
2929 #include <QtCore/QTextCodec>
3030 #include <QtCore/QTranslator>
3131 #include <QtGui/QGuiApplication>
32 #include <string>
3233
33 #include <string>
3434 #include "base/logging.h"
3535 #include "base/system_util.h"
3636 #include "gui/base/singleton_window_helper.h"
4444
4545 public:
4646 FindDialog(QWidget *parent, QTableWidget *table);
47 virtual ~FindDialog();
47 ~FindDialog() override;
4848
4949 protected:
50 void closeEvent(QCloseEvent *event);
51 void showEvent(QShowEvent *event);
50 void closeEvent(QCloseEvent *event) override;
51 void showEvent(QShowEvent *event) override;
5252
5353 private slots:
5454 void FindForward();
5050
5151 public:
5252 ImportDialog(QWidget *parent = 0);
53 virtual ~ImportDialog();
53 ~ImportDialog() override;
5454
5555 // Accessor methods to get form values.
5656 const QString file_name() const;
3939
4040 public:
4141 ZeroWidthSplitterHandle(Qt::Orientation orientation, QSplitter *parent);
42 virtual ~ZeroWidthSplitterHandle();
42 ~ZeroWidthSplitterHandle() override;
4343
44 void paintEvent(QPaintEvent *event);
45 QSize sizeHint() const;
44 void paintEvent(QPaintEvent *event) override;
45 QSize sizeHint() const override;
4646 };
4747
4848 class ZeroWidthSplitter : public QSplitter {
4949 public:
5050 ZeroWidthSplitter(QWidget *parent);
51 QSplitterHandle *createHandle();
51 QSplitterHandle *createHandle() override;
5252 };
5353
5454 #endif // MOZC_GUI_DICTIONARY_TOOL_ZERO_WIDTH_SPLITTER_H_
2626 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2727 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2828
29 #ifndef MOZC_GUI_ERROR_MESSAGE_DIALOG_H_
30 #define MOZC_GUI_ERROR_MESSAGE_DIALOG_H_
29 #ifndef MOZC_GUI_ERROR_MESSAGE_DIALOG_ERROR_MESSAGE_DIALOG_H_
30 #define MOZC_GUI_ERROR_MESSAGE_DIALOG_ERROR_MESSAGE_DIALOG_H_
3131
3232 #include <QtCore/QObject>
3333 #include <QtWidgets/QMessageBox>
5151
5252 public:
5353 DeleyedMessageDialogHandler(QMessageBox *message_box);
54 virtual ~DeleyedMessageDialogHandler();
54 ~DeleyedMessageDialogHandler() override;
5555
5656 void Exec();
5757
6363 };
6464 } // namespace gui
6565 } // namespace mozc
66 #endif // MOZC_GUI_ERROR_MESSAGE_DIALOG_H_
66 #endif // MOZC_GUI_ERROR_MESSAGE_DIALOG_ERROR_MESSAGE_DIALOG_H_
3333 #endif
3434
3535 #include <QtGui/QtGui>
36
3637 #include "base/logging.h"
3738 #include "base/process.h"
3839 #include "base/run_level.h"
2626 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2727 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2828
29 #ifndef MOZC_GUI_POST_INSTALL_DIALOG_H_
30 #define MOZC_GUI_POST_INSTALL_DIALOG_H_
29 #ifndef MOZC_GUI_POST_INSTALL_DIALOG_POST_INSTALL_DIALOG_H_
30 #define MOZC_GUI_POST_INSTALL_DIALOG_POST_INSTALL_DIALOG_H_
3131
3232 #include <memory>
3333
4747
4848 public:
4949 PostInstallDialog();
50 virtual ~PostInstallDialog();
50 ~PostInstallDialog() override;
5151
5252 protected slots:
5353 virtual void OnOk();
5454 virtual void OnsetAsDefaultCheckBoxToggled(int state);
55 virtual void reject();
55 void reject() override;
5656
5757 private:
5858 // - Sets this IME as the default IME if the check box on the
6767 } // namespace gui
6868 } // namespace mozc
6969
70 #endif // MOZC_GUI_POST_INSTALL_DIALOG_H_
70 #endif // MOZC_GUI_POST_INSTALL_DIALOG_POST_INSTALL_DIALOG_H_
3333 #endif
3434
3535 #include <QtGui/QtGui>
36
3736 #include <memory>
3837
3938 #include "base/logging.h"
4040
4141 public:
4242 SetDefaultDialog();
43 virtual ~SetDefaultDialog();
43 ~SetDefaultDialog() override;
4444
4545 protected slots:
46 virtual void accept();
47 virtual void reject();
46 void accept() override;
47 void reject() override;
4848
4949 private:
5050 bool SetCheckDefault(bool check_default);
3232 "//tools/build_defs:qt.bzl",
3333 "cc_qt_binary_mozc",
3434 "cc_qt_library_mozc",
35 )
36
37 package(
38 default_visibility = ["//gui:__subpackages__"],
3935 )
4036
4137 cc_library_mozc(
2626 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2727 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2828
29 #ifndef MOZC_GUI_WORD_REGISTER_DIALOG_H_
30 #define MOZC_GUI_WORD_REGISTER_DIALOG_H_
29 #ifndef MOZC_GUI_WORD_REGISTER_DIALOG_WORD_REGISTER_DIALOG_H_
30 #define MOZC_GUI_WORD_REGISTER_DIALOG_WORD_REGISTER_DIALOG_H_
3131
3232 #include <QtCore/QString>
3333 #include <QtGui/QtGui>
3434 #include <QtWidgets/QDialog>
35
3635 #include <memory>
3736
3837 #include "base/port.h"
5655
5756 public:
5857 WordRegisterDialog();
59 virtual ~WordRegisterDialog();
58 ~WordRegisterDialog() override;
6059
6160 bool IsAvailable() const;
6261
120119 } // namespace gui
121120 } // namespace mozc
122121
123 #endif // MOZC_GUI_WORD_REGISTER_DIALOG_H_
122 #endif // MOZC_GUI_WORD_REGISTER_DIALOG_WORD_REGISTER_DIALOG_H_
5353 explicit IPCServerThread(IPCServer *server) : server_(server) {}
5454 virtual ~IPCServerThread() {}
5555 virtual void Run() {
56 if (server_ != NULL) {
56 if (server_ != nullptr) {
5757 server_->Loop();
5858 }
5959 }
6767 } // namespace
6868
6969 void IPCServer::LoopAndReturn() {
70 if (server_thread_.get() == NULL) {
70 if (server_thread_ == nullptr) {
7171 server_thread_.reset(new IPCServerThread(this));
7272 server_thread_->SetJoinable(true);
7373 server_thread_->Start("IPCServer");
7777 }
7878
7979 void IPCServer::Wait() {
80 if (server_thread_.get() != NULL) {
80 if (server_thread_ != nullptr) {
8181 server_thread_->Join();
8282 server_thread_.reset();
8383 }
136136 #ifdef OS_WIN
137137 HANDLE handle =
138138 ::OpenProcess(PROCESS_TERMINATE, false, static_cast<DWORD>(pid));
139 if (NULL == handle) {
139 if (nullptr == handle) {
140140 LOG(ERROR) << "OpenProcess failed: " << ::GetLastError();
141141 return false;
142142 }
189189
190190 IPCPathManager *IPCPathManager::GetIPCPathManager(const std::string &name) {
191191 IPCPathManagerMap *manager_map = Singleton<IPCPathManagerMap>::get();
192 DCHECK(manager_map != NULL);
192 DCHECK(manager_map != nullptr);
193193 return manager_map->GetIPCPathManager(name);
194194 }
195195
203203
204204 bool IPCPathManager::SavePathName() {
205205 scoped_lock l(mutex_.get());
206 if (path_mutex_.get() != NULL) {
206 if (path_mutex_ != nullptr) {
207207 return true;
208208 }
209209
274274 }
275275
276276 bool IPCPathManager::GetPathName(std::string *ipc_name) const {
277 if (ipc_name == NULL) {
278 LOG(ERROR) << "ipc_name is NULL";
277 if (ipc_name == nullptr) {
278 LOG(ERROR) << "ipc_name is nullptr";
279279 return false;
280280 }
281281
388388 #ifdef __APPLE__
389389 int name[] = {CTL_KERN, KERN_PROCARGS, static_cast<int>(pid)};
390390 size_t data_len = 0;
391 if (sysctl(name, arraysize(name), NULL, &data_len, NULL, 0) < 0) {
391 if (sysctl(name, arraysize(name), nullptr, &data_len, nullptr, 0) < 0) {
392392 LOG(ERROR) << "sysctl KERN_PROCARGS failed";
393393 return false;
394394 }
395395
396396 server_path_.resize(data_len);
397 if (sysctl(name, arraysize(name), &server_path_[0], &data_len, NULL, 0) < 0) {
397 if (sysctl(name, arraysize(name), &server_path_[0], &data_len, nullptr, 0) <
398 0) {
398399 LOG(ERROR) << "sysctl KERN_PROCARGS failed";
399400 return false;
400401 }
485486 ScopedHandle handle(
486487 ::CreateFileW(wfilename.c_str(), GENERIC_READ,
487488 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
488 NULL, OPEN_EXISTING, 0, NULL));
489 nullptr, OPEN_EXISTING, 0, nullptr));
489490
490491 // ScopedHandle does not receive INVALID_HANDLE_VALUE and
491 // NULL check is appropriate here.
492 if (NULL == handle.get()) {
492 // nullptr check is appropriate here.
493 if (nullptr == handle.get()) {
493494 LOG(ERROR) << "cannot open: " << filename << " " << ::GetLastError();
494495 return false;
495496 }
496497
497 const DWORD size = ::GetFileSize(handle.get(), NULL);
498 const DWORD size = ::GetFileSize(handle.get(), nullptr);
498499 if (-1 == static_cast<int>(size)) {
499500 LOG(ERROR) << "GetFileSize failed: " << ::GetLastError();
500501 return false;
509510 std::unique_ptr<char[]> buf(new char[size]);
510511
511512 DWORD read_size = 0;
512 if (!::ReadFile(handle.get(), buf.get(), size, &read_size, NULL)) {
513 if (!::ReadFile(handle.get(), buf.get(), size, &read_size, nullptr)) {
513514 LOG(ERROR) << "ReadFile failed: " << ::GetLastError();
514515 return false;
515516 }
122122 for (size_t i = 0; i < threads.size(); ++i) {
123123 threads[i]->Join();
124124 delete threads[i];
125 threads[i] = NULL;
125 threads[i] = nullptr;
126126 }
127127 }
128128
6565 class MultiConnections : public mozc::Thread {
6666 public:
6767 #ifdef __APPLE__
68 MultiConnections() : mach_port_manager_(NULL) {}
68 MultiConnections() : mach_port_manager_(nullptr) {}
6969
7070 void SetMachPortManager(mozc::MachPortManagerInterface *manager) {
7171 mach_port_manager_ = manager;
141141 for (size_t i = 0; i < cons.size(); ++i) {
142142 cons[i]->Join();
143143 delete cons[i];
144 cons[i] = NULL;
144 cons[i] = nullptr;
145145 }
146146
147147 mozc::IPCClient kill(kServerAddress, "");
2929 // The IPC implementation using core Mach APIs.
3030 #ifdef __APPLE__
3131
32 #include "ipc/ipc.h"
33
34 #include <map>
35
3632 #include <launch.h>
3733 #include <mach/mach.h>
3834 #include <servers/bootstrap.h>
35
36 #include <map>
3937
4038 #include "base/logging.h"
4139 #include "base/mac_util.h"
4240 #include "base/singleton.h"
4341 #include "base/thread.h"
42 #include "ipc/ipc.h"
4443 #include "ipc/ipc_path_manager.h"
4544
4645 namespace mozc {
10099 LAUNCH_KEY_GETJOB);
101100 launch_data_t job = launch_msg(request);
102101 launch_data_free(request);
103 if (job == NULL) {
102 if (job == nullptr) {
104103 LOG(ERROR) << "Server job not found";
105104 return false;
106105 }
112111 }
113112
114113 launch_data_t pid_data = launch_data_dict_lookup(job, LAUNCH_JOBKEY_PID);
115 if (pid_data == NULL ||
114 if (pid_data == nullptr ||
116115 launch_data_get_type(pid_data) != LAUNCH_DATA_INTEGER) {
117116 // PID information is unavailable, which means server is not running.
118117 VLOG(2) << "Returned job is formatted wrongly: cannot find PID data.";
189188
190189 // Client implementation
191190 IPCClient::IPCClient(const string &name)
192 : name_(name), mach_port_manager_(NULL), ipc_path_manager_(NULL) {
191 : name_(name), mach_port_manager_(nullptr), ipc_path_manager_(nullptr) {
193192 Init(name, "");
194193 }
195194
196195 IPCClient::IPCClient(const string &name, const string &server_path)
197 : name_(name), mach_port_manager_(NULL), ipc_path_manager_(NULL) {
196 : name_(name), mach_port_manager_(nullptr), ipc_path_manager_(nullptr) {
198197 Init(name, server_path);
199198 }
200199
213212 size_t *response_size, int32 timeout) {
214213 last_ipc_error_ = IPC_NO_ERROR;
215214 MachPortManagerInterface *manager = mach_port_manager_;
216 if (manager == NULL) {
215 if (manager == nullptr) {
217216 manager = Singleton<DefaultClientMachPortManager>::get();
218217 }
219218
220219 // Obtain the server port
221220 mach_port_t server_port;
222 if (manager == NULL || !manager->GetMachPort(name_, &server_port)) {
221 if (manager == nullptr || !manager->GetMachPort(name_, &server_port)) {
223222 last_ipc_error_ = IPC_NO_CONNECTION;
224223 LOG(ERROR) << "Cannot connect to the server";
225224 return false;
335334 }
336335
337336 MachPortManagerInterface *manager = mach_port_manager_;
338 if (manager == NULL) {
337 if (manager == nullptr) {
339338 manager = Singleton<DefaultClientMachPortManager>::get();
340339 }
341340
344343
345344 // Server implementation
346345 IPCServer::IPCServer(const string &name, int32 num_connections, int32 timeout)
347 : name_(name), mach_port_manager_(NULL), timeout_(timeout) {
346 : name_(name), mach_port_manager_(nullptr), timeout_(timeout) {
348347 // This is a fake IPC path manager: it just stores the server
349348 // version and IPC name but we don't use the stored IPC name itself.
350349 // It's just for compatibility.
369368
370369 bool IPCServer::Connected() const {
371370 MachPortManagerInterface *manager = mach_port_manager_;
372 if (manager == NULL) {
371 if (manager == nullptr) {
373372 manager = Singleton<DefaultServerMachPortManager>::get();
374373 }
375374
378377
379378 void IPCServer::Loop() {
380379 MachPortManagerInterface *manager = mach_port_manager_;
381 if (manager == NULL) {
380 if (manager == nullptr) {
382381 manager = Singleton<DefaultServerMachPortManager>::get();
383382 }
384383
385384 // Obtain the server port
386385 mach_port_t server_port;
387 if (manager == NULL || !manager->GetMachPort(name_, &server_port)) {
386 if (manager == nullptr || !manager->GetMachPort(name_, &server_port)) {
388387 LOG(ERROR) << "Failed to reserve the port.";
389388 return;
390389 }
7676 } // namespace
7777
7878 const std::string NamedEventUtil::GetEventPath(const char *name) {
79 name = (name == NULL) ? "NULL" : name;
79 name = (name == nullptr) ? "nullptr" : name;
8080 std::string event_name = kEventPathPrefix;
8181 event_name += SystemUtil::GetUserSidAsString();
8282 event_name += ".";
102102
103103 #ifdef OS_WIN
104104 NamedEventListener::NamedEventListener(const char *name)
105 : is_owner_(false), handle_(NULL) {
105 : is_owner_(false), handle_(nullptr) {
106106 std::wstring event_path;
107107 Util::UTF8ToWide(NamedEventUtil::GetEventPath(name), &event_path);
108108
109109 handle_ = ::OpenEventW(EVENT_ALL_ACCESS, false, event_path.c_str());
110110
111 if (handle_ == NULL) {
111 if (handle_ == nullptr) {
112112 SECURITY_ATTRIBUTES security_attributes;
113113 if (!WinSandbox::MakeSecurityAttributes(WinSandbox::kSharableEvent,
114114 &security_attributes)) {
119119 handle_ =
120120 ::CreateEventW(&security_attributes, true, false, event_path.c_str());
121121 ::LocalFree(security_attributes.lpSecurityDescriptor);
122 if (handle_ == NULL) {
122 if (handle_ == nullptr) {
123123 LOG(ERROR) << "CreateEvent() failed: " << ::GetLastError();
124124 return;
125125 }
131131 }
132132
133133 NamedEventListener::~NamedEventListener() {
134 if (NULL != handle_) {
134 if (nullptr != handle_) {
135135 ::CloseHandle(handle_);
136136 }
137 handle_ = NULL;
138 }
139
140 bool NamedEventListener::IsAvailable() const { return (handle_ != NULL); }
137 handle_ = nullptr;
138 }
139
140 bool NamedEventListener::IsAvailable() const { return (handle_ != nullptr); }
141141
142142 bool NamedEventListener::IsOwner() const {
143143 return (IsAvailable() && is_owner_);
168168 }
169169
170170 HANDLE handle = ::OpenProcess(SYNCHRONIZE, FALSE, static_cast<DWORD>(pid));
171 if (NULL == handle) {
171 if (nullptr == handle) {
172172 LOG(ERROR) << "OpenProcess: failed() " << ::GetLastError() << " " << pid;
173173 if (::GetLastError() == ERROR_INVALID_PARAMETER) {
174174 LOG(ERROR) << "No such process found: " << pid;
182182
183183 HANDLE handles[2] = {handle_, handle};
184184
185 const DWORD handles_size = (handle == NULL) ? 1 : 2;
185 const DWORD handles_size = (handle == nullptr) ? 1 : 2;
186186
187187 const DWORD ret =
188188 ::WaitForMultipleObjects(handles_size, handles, FALSE, msec);
205205 break;
206206 }
207207
208 if (NULL != handle) {
208 if (nullptr != handle) {
209209 ::CloseHandle(handle);
210210 }
211211
212212 return result;
213213 }
214214
215 NamedEventNotifier::NamedEventNotifier(const char *name) : handle_(NULL) {
215 NamedEventNotifier::NamedEventNotifier(const char *name) : handle_(nullptr) {
216216 std::wstring event_path;
217217 Util::UTF8ToWide(NamedEventUtil::GetEventPath(name), &event_path);
218218 handle_ = ::OpenEventW(EVENT_MODIFY_STATE, false, event_path.c_str());
219 if (handle_ == NULL) {
219 if (handle_ == nullptr) {
220220 LOG(ERROR) << "Cannot open Event name: " << name;
221221 return;
222222 }
223223 }
224224
225225 NamedEventNotifier::~NamedEventNotifier() {
226 if (NULL != handle_) {
226 if (nullptr != handle_) {
227227 ::CloseHandle(handle_);
228228 }
229 handle_ = NULL;
230 }
231
232 bool NamedEventNotifier::IsAvailable() const { return handle_ != NULL; }
229 handle_ = nullptr;
230 }
231
232 bool NamedEventNotifier::IsAvailable() const { return handle_ != nullptr; }
233233
234234 bool NamedEventNotifier::Notify() {
235235 if (!IsAvailable()) {
4545
4646 #ifdef OS_WIN
4747 ProcessWatchDog::ProcessWatchDog()
48 : event_(::CreateEventW(NULL, TRUE, FALSE, NULL)),
48 : event_(::CreateEventW(nullptr, TRUE, FALSE, nullptr)),
4949 process_id_(UnknownProcessID),
5050 thread_id_(UnknownThreadID),
5151 timeout_(-1),
5252 is_finished_(false),
5353 mutex_(new Mutex) {
54 if (event_.get() == NULL) {
54 if (event_.get() == nullptr) {
5555 LOG(ERROR) << "::CreateEvent() failed.";
5656 return;
5757 }
6161 ProcessWatchDog::~ProcessWatchDog() {
6262 is_finished_ = true; // set the flag to terminate the thread
6363
64 if (event_.get() != NULL) {
64 if (event_.get() != nullptr) {
6565 ::SetEvent(event_.get()); // wake up WaitForMultipleObjects
6666 }
6767
7070
7171 bool ProcessWatchDog::SetID(ProcessID process_id, ThreadID thread_id,
7272 int timeout) {
73 if (event_.get() == NULL) {
74 LOG(ERROR) << "event is NULL";
73 if (event_.get() == nullptr) {
74 LOG(ERROR) << "event is nullptr";
7575 return false;
7676 }
7777
109109 const HANDLE handle = ::OpenProcess(SYNCHRONIZE, FALSE, process_id_);
110110 const DWORD error = ::GetLastError();
111111 process_handle.reset(handle);
112 if (process_handle.get() == NULL) {
112 if (process_handle.get() == nullptr) {
113113 LOG(ERROR) << "OpenProcess failed: " << process_id_ << " " << error;
114114 switch (error) {
115115 case ERROR_ACCESS_DENIED:
129129 const HANDLE handle = ::OpenThread(SYNCHRONIZE, FALSE, thread_id_);
130130 const DWORD error = ::GetLastError();
131131 thread_handle.reset(handle);
132 if (thread_handle.get() == NULL) {
132 if (thread_handle.get() == nullptr) {
133133 LOG(ERROR) << "OpenThread failed: " << thread_id_ << " " << error;
134134 switch (error) {
135135 case ERROR_ACCESS_DENIED:
163163
164164 // set handles
165165 DWORD size = 1;
166 if (process_handle.get() != NULL) {
166 if (process_handle.get() != nullptr) {
167167 VLOG(2) << "Inserting process handle";
168168 handles[size] = process_handle.get();
169169 types[size] = ProcessWatchDog::PROCESS_SIGNALED;
170170 ++size;
171171 }
172172
173 if (thread_handle.get() != NULL) {
173 if (thread_handle.get() != nullptr) {
174174 VLOG(2) << "Inserting thread handle";
175175 handles[size] = thread_handle.get();
176176 types[size] = ProcessWatchDog::THREAD_SIGNALED;
275275 if (errno == EPERM) {
276276 Signaled(ProcessWatchDog::PROCESS_ACCESS_DENIED_SIGNALED);
277277 } else if (errno == ESRCH) {
278 // Since we are polling the process by NULL signal,
278 // Since we are polling the process by nullptr signal,
279279 // it is essentially impossible to tell the process is not found
280280 // or terminated.
281281 Signaled(ProcessWatchDog::PROCESS_SIGNALED);
2929 // OS_LINUX only. Note that OS_ANDROID/OS_NACL don't reach here.
3030 #if defined(OS_LINUX)
3131
32 #include "ipc/ipc.h"
33
3432 #include <arpa/inet.h>
3533 #include <fcntl.h>
3634 #include <libgen.h>
5048 #include "base/file_util.h"
5149 #include "base/logging.h"
5250 #include "base/thread.h"
51 #include "ipc/ipc.h"
5352 #include "ipc/ipc_path_manager.h"
5453
5554 #ifndef UNIX_PATH_MAX
8180 FD_SET(socket, &fds);
8281 tv.tv_sec = timeout / 1000;
8382 tv.tv_usec = 1000 * (timeout % 1000);
84 if (select(socket + 1, &fds, NULL, NULL, &tv) < 0) {
83 if (select(socket + 1, &fds, nullptr, nullptr, &tv) < 0) {
8584 // Mac OS X and glibc implementations of strerror() return a pointer to a
8685 // string literal whenever errno is in a valid range, and thus thread-safe.
8786 // Probably we don't have to use the cumbersome strerror_r() function.
106105 FD_SET(socket, &fds);
107106 tv.tv_sec = timeout / 1000;
108107 tv.tv_usec = 1000 * (timeout % 1000);
109 if (select(socket + 1, NULL, &fds, NULL, &tv) < 0) {
108 if (select(socket + 1, nullptr, &fds, nullptr, &tv) < 0) {
110109 LOG(WARNING) << "select() failed: " << strerror(errno);
111110 return true;
112111 }
227226 IPCClient::IPCClient(const std::string &name)
228227 : socket_(kInvalidSocket),
229228 connected_(false),
230 ipc_path_manager_(NULL),
229 ipc_path_manager_(nullptr),
231230 last_ipc_error_(IPC_NO_ERROR) {
232231 Init(name, "");
233232 }
235234 IPCClient::IPCClient(const std::string &name, const std::string &server_path)
236235 : socket_(kInvalidSocket),
237236 connected_(false),
238 ipc_path_manager_(NULL),
237 ipc_path_manager_(nullptr),
239238 last_ipc_error_(IPC_NO_ERROR) {
240239 Init(name, server_path);
241240 }
245244
246245 // Try twice, because key may be changed.
247246 IPCPathManager *manager = IPCPathManager::GetIPCPathManager(name);
248 if (manager == NULL) {
247 if (manager == nullptr) {
249248 LOG(ERROR) << "IPCPathManager::GetIPCPathManager failed";
250249 return;
251250 }
407406 }
408407
409408 IPCServer::~IPCServer() {
410 if (server_thread_.get() != NULL) {
409 if (server_thread_.get() != nullptr) {
411410 server_thread_->Terminate();
412411 }
413412 ::shutdown(socket_, SHUT_RDWR);
429428 IPCErrorType last_ipc_error = IPC_NO_ERROR;
430429 pid_t pid = 0;
431430 while (!error) {
432 const int new_sock = ::accept(socket_, NULL, NULL);
431 const int new_sock = ::accept(socket_, nullptr, nullptr);
433432 if (new_sock < 0) {
434433 LOG(FATAL) << "accept() failed: " << strerror(errno);
435434 return;
7070 : output_string_(output_string),
7171 max_data_size_(max_data_size),
7272 output_size_(0) {
73 if (NULL != output_string_) {
73 if (nullptr != output_string_) {
7474 output_string_->clear();
7575 }
7676 VLOG(2) << "max_data_size=" << max_data_size;
8484 LOG(WARNING) << "too long data max_data_size=" << max_data_size_;
8585 }
8686
87 if (output_string_ != NULL) {
87 if (output_string_ != nullptr) {
8888 VLOG(2) << "Recived: " << size << " bytes to std::string";
8989 output_string_->append(buf, size);
9090 }
108108 public:
109109 explicit ScopedHINTERNET(HINTERNET internet) : internet_(internet) {}
110110 virtual ~ScopedHINTERNET() {
111 if (NULL != internet_) {
111 if (nullptr != internet_) {
112112 VLOG(2) << "InternetCloseHandle() called";
113113 ::InternetCloseHandle(internet_);
114114 }
115 internet_ = NULL;
115 internet_ = nullptr;
116116 }
117117
118118 HINTERNET get() { return internet_; }
177177
178178 Stopwatch stopwatch = stopwatch.StartNew();
179179
180 HANDLE event = ::CreateEvent(NULL, FALSE, FALSE, NULL);
181 if (NULL == event) {
180 HANDLE event = ::CreateEvent(nullptr, FALSE, FALSE, nullptr);
181 if (nullptr == event) {
182182 LOG(ERROR) << "CreateEvent() failed: " << ::GetLastError();
183183 return false;
184184 }
185185
186 ScopedHINTERNET internet(::InternetOpenA(kUserAgent,
187 INTERNET_OPEN_TYPE_PRECONFIG, NULL,
188 NULL, INTERNET_FLAG_ASYNC));
189
190 if (NULL == internet.get()) {
186 ScopedHINTERNET internet(
187 ::InternetOpenA(kUserAgent, INTERNET_OPEN_TYPE_PRECONFIG, nullptr,
188 nullptr, INTERNET_FLAG_ASYNC));
189
190 if (nullptr == internet.get()) {
191191 LOG(ERROR) << "InternetOpen() failed: " << ::GetLastError() << " " << url;
192192 ::CloseHandle(event);
193193 return false;
234234 }
235235
236236 ScopedHINTERNET session(::InternetConnect(internet.get(), uc.lpszHostName,
237 uc.nPort, NULL, NULL,
237 uc.nPort, nullptr, nullptr,
238238 INTERNET_SERVICE_HTTP, 0, 0));
239239
240 if (NULL == session.get()) {
240 if (nullptr == session.get()) {
241241 LOG(ERROR) << "InternetConnect() failed: " << ::GetLastError() << " "
242242 << url;
243243 return false;
254254 CHECK(method);
255255
256256 ScopedHINTERNET handle(::HttpOpenRequestW(
257 session.get(), method, uri.c_str(), NULL, NULL, NULL,
257 session.get(), method, uri.c_str(), nullptr, nullptr, nullptr,
258258 INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_NO_UI |
259259 INTERNET_FLAG_PRAGMA_NOCACHE |
260260 (uc.nScheme == INTERNET_SCHEME_HTTPS ? INTERNET_FLAG_SECURE : 0),
261261 reinterpret_cast<DWORD_PTR>(event)));
262262
263 if (NULL == handle.get()) {
263 if (nullptr == handle.get()) {
264264 LOG(ERROR) << "HttpOpenRequest() failed: " << ::GetLastError() << " "
265265 << url;
266266 return false;
279279 }
280280 }
281281
282 if (!::HttpSendRequest(handle.get(), NULL, 0,
283 (type == HTTP_POST) ? (LPVOID)post_data : NULL,
282 if (!::HttpSendRequest(handle.get(), nullptr, 0,
283 (type == HTTP_POST) ? (LPVOID)post_data : nullptr,
284284 (type == HTTP_POST) ? post_size : 0)) {
285285 if (!CheckTimeout(event, stopwatch.GetElapsedMilliseconds(),
286286 option.timeout)) {
426426 Singleton<CurlInitializer>::get()->Init();
427427
428428 CURL *curl = curl_easy_init();
429 if (NULL == curl) {
429 if (nullptr == curl) {
430430 LOG(ERROR) << "curl_easy_init() failed";
431431 return false;
432432 }
461461 }
462462 }
463463
464 struct curl_slist *slist = NULL;
464 struct curl_slist *slist = nullptr;
465465 for (size_t i = 0; i < option.headers.size(); ++i) {
466466 VLOG(2) << "Add header: " << option.headers[i];
467467 slist = curl_slist_append(slist, option.headers[i].c_str());
468468 }
469469
470 if (slist != NULL) {
470 if (slist != nullptr) {
471471 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
472472 }
473473
511511 }
512512
513513 curl_easy_cleanup(curl);
514 if (slist != NULL) {
514 if (slist != nullptr) {
515515 curl_slist_free_all(slist);
516516 }
517517
542542 public:
543543 virtual bool Get(const std::string &url, const HTTPClient::Option &option,
544544 std::string *output_string) const {
545 return RequestInternal(HTTP_GET, url, NULL, 0, option, output_string);
545 return RequestInternal(HTTP_GET, url, nullptr, 0, option, output_string);
546546 }
547547
548548 virtual bool Head(const std::string &url, const HTTPClient::Option &option,
549549 std::string *output_string) const {
550 return RequestInternal(HTTP_HEAD, url, NULL, 0, option, output_string);
550 return RequestInternal(HTTP_HEAD, url, nullptr, 0, option, output_string);
551551 }
552552
553553 virtual bool Post(const std::string &url, const std::string &data,
560560
561561 namespace {
562562
563 const HTTPClientInterface *g_http_connection_handler = NULL;
563 const HTTPClientInterface *g_http_connection_handler = nullptr;
564564
565565 const HTTPClientInterface &GetHTTPClient() {
566 if (g_http_connection_handler == NULL) {
566 if (g_http_connection_handler == nullptr) {
567567 g_http_connection_handler = Singleton<HTTPClientImpl>::get();
568568 }
569569 return *g_http_connection_handler;
284284 return false;
285285 }
286286 return JsonUtil::JsonValueToProtobufMessage(
287 value, reflection->MutableMessage(message, field, NULL));
287 value, reflection->MutableMessage(message, field, nullptr));
288288 break;
289289 }
290290 default: {
438438 result = false;
439439 } else {
440440 if (!JsonUtil::JsonValueToProtobufMessage(
441 value[i], reflection->AddMessage(message, field, NULL))) {
441 value[i], reflection->AddMessage(message, field, nullptr))) {
442442 result = false;
443443 }
444444 }
179179 }
180180 } else if (reflection->HasField(*message, field)) {
181181 if (field->cpp_type() == protobuf::FieldDescriptor::CPPTYPE_MESSAGE) {
182 FillRequiredFields(reflection->MutableMessage(message, field, NULL));
182 FillRequiredFields(reflection->MutableMessage(message, field, nullptr));
183183 }
184184 } else if (field->is_required()) {
185185 switch (field->cpp_type()) {
220220 break;
221221 }
222222 case protobuf::FieldDescriptor::CPPTYPE_MESSAGE: {
223 FillRequiredFields(reflection->MutableMessage(message, field, NULL));
223 FillRequiredFields(
224 reflection->MutableMessage(message, field, nullptr));
224225 break;
225226 }
226227 default: {
5454 // http://developer.apple.com/samplecode/CFProxySupportTool/
5555 static void PACResultCallback(void *client, CFArrayRef proxies,
5656 CFErrorRef error) {
57 DCHECK((proxies == NULL && error != NULL) ||
58 (proxies != NULL && error == NULL));
57 DCHECK((proxies == nullptr && error != nullptr) ||
58 (proxies != nullptr && error == nullptr));
5959 CFTypeRef *result = static_cast<CFTypeRef *>(client);
6060
61 if (result != NULL && *result == NULL) {
62 if (error != NULL) {
61 if (result != nullptr && *result == nullptr) {
62 if (error != nullptr) {
6363 *result = CFRetain(error);
6464 } else {
6565 *result = CFRetain(proxies);
7676 // The implementation is inspired by
7777 // http://developer.apple.com/samplecode/CFProxySupportTool/
7878 CFDictionaryRef RetainOrExpandPacFile(CFURLRef cfurl, CFDictionaryRef proxy) {
79 CFDictionaryRef final_proxy = NULL;
79 CFDictionaryRef final_proxy = nullptr;
8080 CFStringRef proxy_type = reinterpret_cast<CFStringRef>(
8181 CFDictionaryGetValue(proxy, kCFProxyTypeKey));
8282
8585 // the pac URL server. However, it seems that the function seems to
8686 // take care of caching in memory. So there are no additional
8787 // latency problems here.
88 if (proxy_type != NULL && CFGetTypeID(proxy_type) == CFStringGetTypeID() &&
88 if (proxy_type != nullptr && CFGetTypeID(proxy_type) == CFStringGetTypeID() &&
8989 CFEqual(proxy_type, kCFProxyTypeAutoConfigurationURL)) {
9090 CFURLRef script_url = reinterpret_cast<CFURLRef>(
9191 CFDictionaryGetValue(proxy, kCFProxyAutoConfigurationURLKey));
92 if (script_url != NULL && CFGetTypeID(script_url) == CFURLGetTypeID()) {
93 CFTypeRef result = NULL;
94 CFStreamClientContext context = {0, &result, NULL, NULL, NULL};
92 if (script_url != nullptr && CFGetTypeID(script_url) == CFURLGetTypeID()) {
93 CFTypeRef result = nullptr;
94 CFStreamClientContext context = {0, &result, nullptr, nullptr, nullptr};
9595 scoped_cftyperef<CFRunLoopSourceRef> runloop_source(
9696 CFNetworkExecuteProxyAutoConfigurationURL(
9797 script_url, cfurl, PACResultCallback, &context));
9898 const string label = MacUtil::GetLabelForSuffix("ProxyResolverMac");
9999 scoped_cftyperef<CFStringRef> private_runloop_mode(
100 CFStringCreateWithBytes(NULL,
100 CFStringCreateWithBytes(nullptr,
101101 reinterpret_cast<const UInt8 *>(label.data()),
102102 label.size(), kCFStringEncodingUTF8, false));
103103 CFRunLoopAddSource(CFRunLoopGetCurrent(), runloop_source.get(),
107107 private_runloop_mode.get());
108108
109109 // resolving PAC succeeds
110 if (result != NULL && CFGetTypeID(result) == CFArrayGetTypeID() &&
110 if (result != nullptr && CFGetTypeID(result) == CFArrayGetTypeID() &&
111111 CFArrayGetCount(reinterpret_cast<CFArrayRef>(result)) > 0) {
112112 final_proxy = reinterpret_cast<CFDictionaryRef>(
113113 CFArrayGetValueAtIndex(reinterpret_cast<CFArrayRef>(result), 0));
116116 LOG(WARNING) << "Failed to resolve PAC file. "
117117 << "Possibly wrong PAC file is specified.";
118118 }
119 if (result != NULL) {
119 if (result != nullptr) {
120120 CFRelease(result);
121121 }
122122 }
124124
125125 // If configuration isn't PAC or resolving PAC fails, just returns
126126 // the retained proxy.
127 if (final_proxy == NULL) {
127 if (final_proxy == nullptr) {
128128 final_proxy = reinterpret_cast<CFDictionaryRef>(CFRetain(proxy));
129129 }
130130
145145 CFNetworkCopySystemProxySettings());
146146 #else
147147 scoped_cftyperef<CFDictionaryRef> proxy_settings(
148 SCDynamicStoreCopyProxies(NULL));
148 SCDynamicStoreCopyProxies(nullptr));
149149 #endif // OS_IOS
150150 if (!proxy_settings.Verify(CFDictionaryGetTypeID())) {
151151 LOG(ERROR) << "Failed to create proxy setting";
152152 return false;
153153 }
154154
155 scoped_cftyperef<CFURLRef> cfurl(
156 CFURLCreateWithBytes(NULL, reinterpret_cast<const UInt8 *>(url.data()),
157 url.size(), kCFStringEncodingUTF8, NULL));
155 scoped_cftyperef<CFURLRef> cfurl(CFURLCreateWithBytes(
156 nullptr, reinterpret_cast<const UInt8 *>(url.data()), url.size(),
157 kCFStringEncodingUTF8, nullptr));
158158 if (!cfurl.Verify(CFURLGetTypeID())) {
159159 LOG(ERROR) << "Failed to create URL object from the specified URL";
160160 return false;
188188 if (host.Verify(CFStringGetTypeID())) {
189189 scoped_cftyperef<CFStringRef> host_desc;
190190 if (port.Verify(CFNumberGetTypeID())) {
191 host_desc.reset(CFStringCreateWithFormat(NULL, NULL, CFSTR("%@:%@"),
192 host.get(), port.get()));
191 host_desc.reset(CFStringCreateWithFormat(
192 nullptr, nullptr, CFSTR("%@:%@"), host.get(), port.get()));
193193 } else {
194194 host_desc.reset(reinterpret_cast<CFStringRef>(host.get()));
195195 CFRetain(host.get());
197197 if (host_desc.Verify(CFStringGetTypeID())) {
198198 const char *hostdata_ptr =
199199 CFStringGetCStringPtr(host_desc.get(), kCFStringEncodingUTF8);
200 if (hostdata_ptr != NULL) {
200 if (hostdata_ptr != nullptr) {
201201 hostdata->assign(hostdata_ptr);
202202 proxy_available = true;
203203 } else {
209209 }
210210 if (proxy_available && username.Verify(CFStringGetTypeID()) &&
211211 password.Verify(CFStringGetTypeID())) {
212 scoped_cftyperef<CFStringRef> auth_desc(CFStringCreateWithFormat(
213 NULL, NULL, CFSTR("%@:%@"), username.get(), password.get()));
212 scoped_cftyperef<CFStringRef> auth_desc(
213 CFStringCreateWithFormat(nullptr, nullptr, CFSTR("%@:%@"),
214 username.get(), password.get()));
214215 if (auth_desc.Verify(CFStringGetTypeID())) {
215216 const char *authdata_ptr =
216217 CFStringGetCStringPtr(auth_desc.get(), kCFStringEncodingUTF8);
217 if (authdata_ptr != NULL) {
218 if (authdata_ptr != nullptr) {
218219 authdata->assign(authdata_ptr);
219220 }
220221 }
236237 namespace {
237238
238239 // This is only used for dependency injection
239 ProxyManagerInterface *g_proxy_manager = NULL;
240 ProxyManagerInterface *g_proxy_manager = nullptr;
240241
241242 ProxyManagerInterface *GetProxyManager() {
242 if (g_proxy_manager == NULL) {
243 if (g_proxy_manager == nullptr) {
243244 #ifdef __APPLE__
244245 return Singleton<MacProxyManager>::get();
245246 #else
967967 // candidates that have the same key length as |input_key| so that we can set
968968 // a slightly smaller cost to REALTIME_TOP than these.
969969 int realtime_cost_min = kInfinity;
970 Result *realtime_top_result = NULL;
970 Result *realtime_top_result = nullptr;
971971
972972 for (size_t i = 0; i < results->size(); ++i) {
973973 const Result &result = results->at(i);
10431043
10441044 // Ensure that the REALTIME_TOP candidate has relatively smaller cost than
10451045 // those of REALTIME candidates.
1046 if (realtime_top_result != NULL) {
1046 if (realtime_top_result != nullptr) {
10471047 realtime_top_result->cost = std::max(0, realtime_cost_min - 10);
10481048 }
10491049 }
9494 filter->Insert(words[i]);
9595 }
9696
97 char *buf = NULL;
97 char *buf = nullptr;
9898 size_t size = 0;
9999
100100 LOG(INFO) << "writing bloomfilter: " << FLAGS_output;
368368 // If |entry| is the target of prediction,
369369 // create a new result and insert it to |results|.
370370 // Can set |prev_entry| if there is a history segment just before |input_key|.
371 // |prev_entry| is an optional field. If set NULL, this field is just ignored.
372 // This method adds a new result entry with score, pair<score, entry>, to
373 // |results|.
371 // |prev_entry| is an optional field. If set nullptr, this field is just
372 // ignored. This method adds a new result entry with score,
373 // pair<score, entry>, to |results|.
374374 bool LookupEntry(RequestType request_type, const std::string &input_key,
375375 const std::string &key_base,
376376 const Trie<std::string> *key_expanded, const Entry *entry,
5757 "//ipc",
5858 "//ipc:named_event",
5959 "//protocol:renderer_proto",
60 "@com_google_absl//absl/memory",
6061 ] + select_mozc(
6162 ios = ["//base:mac_util"],
6263 ),
4545 #include "ipc/ipc.h"
4646 #include "ipc/named_event.h"
4747 #include "protocol/renderer_command.pb.h"
48 #include "absl/memory/memory.h"
4849
4950 #ifdef __APPLE__
5051 #include "base/mac_util.h"
8384
8485 class RendererLauncher : public RendererLauncherInterface, public Thread {
8586 public:
86 bool CanConnect() const {
87 bool CanConnect() const override {
8788 switch (renderer_status_) {
8889 case RendererLauncher::RENDERER_UNKNOWN:
8990 case RendererLauncher::RENDERER_READY:
110111 return false;
111112 }
112113
113 bool IsAvailable() const {
114 bool IsAvailable() const override {
114115 return (renderer_status_ == RendererLauncher::RENDERER_READY);
115116 }
116117
117 void StartRenderer(const std::string &name, const std::string &path,
118 bool disable_renderer_path_check,
119 IPCClientFactoryInterface *ipc_client_factory_interface) {
118 void StartRenderer(
119 const std::string &name, const std::string &path,
120 bool disable_renderer_path_check,
121 IPCClientFactoryInterface *ipc_client_factory_interface) override {
120122 renderer_status_ = RendererLauncher::RENDERER_LAUNCHING;
121123 name_ = name;
122124 path_ = path;
125127 Thread::Start("Renderer");
126128 }
127129
128 void Run() {
130 void Run() override {
129131 last_launch_time_ = Clock::GetTime();
130132
131133 NamedEventListener listener(name_.c_str());
205207 }
206208 }
207209
208 bool ForceTerminateRenderer(const std::string &name) {
210 bool ForceTerminateRenderer(const std::string &name) override {
209211 return IPCClient::TerminateServer(name);
210212 }
211213
212 void OnFatal(RendererErrorType type) {
214 void OnFatal(RendererErrorType type) override {
213215 LOG(ERROR) << "OnFatal is called: " << static_cast<int>(type);
214216
215217 std::string error_type;
230232 }
231233 }
232234
233 void SetPendingCommand(const commands::RendererCommand &command) {
235 void SetPendingCommand(const commands::RendererCommand &command) override {
234236 // ignore NOOP|SHUTDOWN
235237 if (command.type() == commands::RendererCommand::UPDATE) {
236238 scoped_lock l(&pending_command_mutex_);
237239 if (!pending_command_) {
238 pending_command_.reset(new commands::RendererCommand);
240 pending_command_ = absl::make_unique<commands::RendererCommand>();
239241 }
240 pending_command_->CopyFrom(command);
241 }
242 }
243
244 void set_suppress_error_dialog(bool suppress) {
242 *pending_command_ = command;
243 }
244 }
245
246 void set_suppress_error_dialog(bool suppress) override {
245247 suppress_error_dialog_ = suppress;
246248 }
247249
253255 suppress_error_dialog_(false),
254256 ipc_client_factory_interface_(nullptr) {}
255257
256 virtual ~RendererLauncher() {
258 ~RendererLauncher() override {
257259 if (!IsRunning()) {
258260 return;
259261 }
8080 class RendererClient : public RendererInterface {
8181 public:
8282 RendererClient();
83 virtual ~RendererClient();
83 ~RendererClient() override;
8484
8585 // set IPC factory
8686 void SetIPCClientFactory(
9595 // platform separately.
9696 // TODO(taku): move win32 code into RendererClient
9797 void SetSendCommandInterface(
98 client::SendCommandInterface *send_command_interface) {}
98 client::SendCommandInterface *send_command_interface) override {}
9999
100100 // activate renderer server
101 bool Activate();
101 bool Activate() override;
102102
103103 // return true if the renderer is available
104 bool IsAvailable() const;
104 bool IsAvailable() const override;
105105
106106 // shutdown the renderer if it is running
107107 // return true if the function finishes without error.
109109 // Otherwise command::RendererCommand::SHUDDOWN is used.
110110 bool Shutdown(bool force);
111111
112 bool ExecCommand(const commands::RendererCommand &command);
112 bool ExecCommand(const commands::RendererCommand &command) override;
113113
114114 // Don't check the renderer server path.
115115 // DO NOT call it except for testing
6767 class TestIPCClient : public IPCClientInterface {
6868 public:
6969 TestIPCClient() { g_server_product_version = Version::GetMozcVersion(); }
70 ~TestIPCClient() {}
71
72 bool Connected() const { return g_connected; }
73
74 uint32 GetServerProtocolVersion() const { return g_server_protocol_version; }
75
76 const std::string &GetServerProductVersion() const {
70 ~TestIPCClient() override {}
71
72 bool Connected() const override { return g_connected; }
73
74 uint32 GetServerProtocolVersion() const override {
75 return g_server_protocol_version;
76 }
77
78 const std::string &GetServerProductVersion() const override {
7779 return g_server_product_version;
7880 }
7981
80 uint32 GetServerProcessId() const { return 0; }
82 uint32 GetServerProcessId() const override { return 0; }
8183
8284 // just count up how many times Call is called.
83 virtual bool Call(const char *request, size_t request_size, char *response,
84 size_t *response_size, int32 timeout) {
85 bool Call(const char *request, size_t request_size, char *response,
86 size_t *response_size, int32 timeout) override {
8587 g_counter++;
8688 return true;
8789 }
9698 g_server_protocol_version = version;
9799 }
98100
99 virtual IPCErrorType GetLastIPCError() const { return IPC_NO_ERROR; }
101 IPCErrorType GetLastIPCError() const override { return IPC_NO_ERROR; }
100102 };
101103
102104 class TestIPCClientFactory : public IPCClientFactoryInterface {
103105 public:
104106 TestIPCClientFactory() {}
105 ~TestIPCClientFactory() {}
106
107 virtual IPCClientInterface *NewClient(const std::string &name,
108 const std::string &path_name) {
107 ~TestIPCClientFactory() override {}
108
109 IPCClientInterface *NewClient(const std::string &name,
110 const std::string &path_name) override {
109111 return new TestIPCClient;
110112 }
111113
112 virtual IPCClientInterface *NewClient(const std::string &name) {
114 IPCClientInterface *NewClient(const std::string &name) override {
113115 return new TestIPCClient;
114116 }
115117 };
121123 force_terminate_renderer_called_(false),
122124 available_(false),
123125 can_connect_(false) {}
124 ~TestRendererLauncher() {}
126 ~TestRendererLauncher() override {}
125127
126128 // implement StartServer.
127129 // return true if server can launched successfully.
128 void StartRenderer(const std::string &name, const std::string &renderer_path,
129 bool disable_renderer_path_check,
130 IPCClientFactoryInterface *ipc_client_factory_interface) {
130 void StartRenderer(
131 const std::string &name, const std::string &renderer_path,
132 bool disable_renderer_path_check,
133 IPCClientFactoryInterface *ipc_client_factory_interface) override {
131134 start_renderer_called_ = true;
132135 LOG(INFO) << name << " " << renderer_path;
133136 }
134137
135 bool ForceTerminateRenderer(const std::string &name) {
138 bool ForceTerminateRenderer(const std::string &name) override {
136139 force_terminate_renderer_called_ = true;
137140 return true;
138141 }
139142
140 void OnFatal(RendererErrorType type) { LOG(ERROR) << static_cast<int>(type); }
143 void OnFatal(RendererErrorType type) override {
144 LOG(ERROR) << static_cast<int>(type);
145 }
141146
142147 // return true if the renderer is running
143 virtual bool IsAvailable() const { return available_; }
148 bool IsAvailable() const override { return available_; }
144149
145150 // return true if client can make a IPC connection.
146 virtual bool CanConnect() const { return can_connect_; }
147
148 virtual void SetPendingCommand(const commands::RendererCommand &command) {
151 bool CanConnect() const override { return can_connect_; }
152
153 void SetPendingCommand(const commands::RendererCommand &command) override {
149154 set_pending_command_called_ = true;
150155 }
151156
152 virtual void set_suppress_error_dialog(bool suppress) {}
157 void set_suppress_error_dialog(bool suppress) override {}
153158
154159 void Reset() {
155160 start_renderer_called_ = false;
8787 public:
8888 explicit ParentApplicationWatchDog(RendererServer *renderer_server)
8989 : renderer_server_(renderer_server) {}
90 virtual ~ParentApplicationWatchDog() {}
91
92 void Signaled(ProcessWatchDog::SignalType type) {
90 ~ParentApplicationWatchDog() override {}
91
92 void Signaled(ProcessWatchDog::SignalType type) override {
9393 if (renderer_server_ == nullptr) {
9494 LOG(ERROR) << "renderer_server is nullptr";
9595 return;
118118 class RendererServerSendCommand : public client::SendCommandInterface {
119119 public:
120120 RendererServerSendCommand() : receiver_handle_(0) {}
121 virtual ~RendererServerSendCommand() {}
121 ~RendererServerSendCommand() override {}
122122
123123 bool SendCommand(const mozc::commands::SessionCommand &command,
124 mozc::commands::Output *output) {
124 mozc::commands::Output *output) override {
125125 #ifdef OS_WIN
126126 if ((command.type() != commands::SessionCommand::SELECT_CANDIDATE) &&
127127 (command.type() != commands::SessionCommand::HIGHLIGHT_CANDIDATE) &&
4747 class RendererServer : public IPCServer {
4848 public:
4949 RendererServer();
50 virtual ~RendererServer();
50 ~RendererServer() override;
5151
5252 void SetRendererInterface(RendererInterface *renderer_interface);
5353
5858 int StartServer();
5959
6060 bool Process(const char *request, size_t request_size, char *response,
61 size_t *response_size);
61 size_t *response_size) override;
6262
6363 // DEPRECATED: this functions is never called
6464 virtual void AsyncHide() {}
5050 public:
5151 TestRenderer() : counter_(0), finished_(false) {}
5252
53 bool Activate() { return true; }
53 bool Activate() override { return true; }
5454
55 bool IsAvailable() const { return true; }
55 bool IsAvailable() const override { return true; }
5656
57 bool ExecCommand(const commands::RendererCommand &command) {
57 bool ExecCommand(const commands::RendererCommand &command) override {
5858 if (finished_) {
5959 return false;
6060 }
7777 public:
7878 TestRendererServer() {}
7979
80 virtual ~TestRendererServer() {}
80 ~TestRendererServer() override {}
8181
82 int StartMessageLoop() { return 0; }
82 int StartMessageLoop() override { return 0; }
8383
8484 // Not async for testing
85 bool AsyncExecCommand(std::string *proto_message) {
85 bool AsyncExecCommand(std::string *proto_message) override {
8686 commands::RendererCommand command;
8787 command.ParseFromString(*proto_message);
8888 delete proto_message;
9393 // A renderer launcher which does nothing.
9494 class DummyRendererLauncher : public RendererLauncherInterface {
9595 public:
96 void StartRenderer(const std::string &name, const std::string &renderer_path,
97 bool disable_renderer_path_check,
98 IPCClientFactoryInterface *ipc_client_factory_interface) {
96 void StartRenderer(
97 const std::string &name, const std::string &renderer_path,
98 bool disable_renderer_path_check,
99 IPCClientFactoryInterface *ipc_client_factory_interface) override {
99100 LOG(INFO) << name << " " << renderer_path;
100101 }
101102
102 bool ForceTerminateRenderer(const std::string &name) { return true; }
103 bool ForceTerminateRenderer(const std::string &name) override { return true; }
103104
104 void OnFatal(RendererErrorType type) { LOG(ERROR) << static_cast<int>(type); }
105 void OnFatal(RendererErrorType type) override {
106 LOG(ERROR) << static_cast<int>(type);
107 }
105108
106 virtual bool IsAvailable() const { return true; }
109 bool IsAvailable() const override { return true; }
107110
108 virtual bool CanConnect() const { return true; }
111 bool CanConnect() const override { return true; }
109112
110 virtual void SetPendingCommand(const commands::RendererCommand &command) {}
113 void SetPendingCommand(const commands::RendererCommand &command) override {}
111114
112 virtual void set_suppress_error_dialog(bool suppress) {}
115 void set_suppress_error_dialog(bool suppress) override {}
113116 };
114117 } // namespace
115118
116119 class RendererServerTest : public ::testing::Test {
117120 protected:
118 virtual void SetUp() {
121 void SetUp() override {
119122 SystemUtil::SetUserProfileDirectory(FLAGS_test_tmpdir);
120123 }
121124 };
7272 }
7373
7474 bool RendererStyleHandlerImpl::GetRendererStyle(RendererStyle *style) {
75 style->CopyFrom(this->style_);
75 *style = this->style_;
7676 return true;
7777 }
7878 bool RendererStyleHandlerImpl::SetRendererStyle(const RendererStyle &style) {
79 style_.CopyFrom(style);
79 style_ = style;
8080 return true;
8181 }
8282 void RendererStyleHandlerImpl::GetDefaultRendererStyle(RendererStyle *style) {
2727 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2828
2929 #include "renderer/renderer_style_handler.h"
30
3031 #include "protocol/renderer_style.pb.h"
3132 #include "testing/base/public/gunit.h"
3233
173173 }
174174
175175 const int all_cell_width =
176 accumulate(column_width_list_.begin(), column_width_list_.end(), 0);
176 std::accumulate(column_width_list_.begin(), column_width_list_.end(), 0);
177177
178178 const int table_width =
179179 row_rect_padding_pixels_ * 2 + // padding left and right
214214 DCHECK(0 <= row && row < number_of_rows_);
215215 DCHECK(0 <= column && column < column_width_list_.size());
216216
217 const int width_of_left_cells = accumulate(
217 const int width_of_left_cells = std::accumulate(
218218 column_width_list_.begin(), column_width_list_.begin() + column, 0);
219219
220220 const int left = window_border_pixels_ + // border left
345345 }
346346 DCHECK(0 <= column && column < column_width_list_.size());
347347
348 const int width_of_left_cells = accumulate(
348 const int width_of_left_cells = std::accumulate(
349349 column_width_list_.begin(), column_width_list_.begin() + column, 0);
350350
351351 const int left = window_border_pixels_ + // border left
113113 TableLayout();
114114
115115 // Reset layout freeze and initialize the number of rows and columns.
116 void Initialize(int num_rows, int num_columns);
116 void Initialize(int num_rows, int num_columns) override;
117117
118118 // Set layout element.
119 void SetVScrollBar(int width_in_pixels);
120 void SetWindowBorder(int width_in_pixels);
121 void SetRowRectPadding(int width_pixels);
119 void SetVScrollBar(int width_in_pixels) override;
120 void SetWindowBorder(int width_in_pixels) override;
121 void SetRowRectPadding(int width_pixels) override;
122122
123123 // Ensure the cell size is same to or larger than the specified size.
124124 // - size.width affects cells within the specified column.
125125 // - size.height affects all cells.
126126 // You should not call this function when the layout is frozen.
127 void EnsureCellSize(int column, const Size &size);
127 void EnsureCellSize(int column, const Size &size) override;
128128
129129 // Ensure the total width from "from_column" to "to_width" is at
130130 // least "width" or larger. If total width is smaller than the
133133 // will be used. Note that "to_column" should be bigger than
134134 // "from_column". Otherwise, the call will be ignored. If you
135135 // want to ensure a cell width, you should use EnsureCellSize instead.
136 void EnsureColumnsWidth(int from_column, int to_column, int width);
136 void EnsureColumnsWidth(int from_column, int to_column, int width) override;
137137
138138 // Ensure the size of header/footer is same to or larger than the
139139 // specified size.
140140 // You should not call this function when the layout is frozen.
141 void EnsureFooterSize(const Size &size_in_pixels);
142 void EnsureHeaderSize(const Size &size_in_pixels);
141 void EnsureFooterSize(const Size &size_in_pixels) override;
142 void EnsureHeaderSize(const Size &size_in_pixels) override;
143143
144144 // Fix the layout and calculate the total size.
145 void FreezeLayout();
146 bool IsLayoutFrozen() const;
145 void FreezeLayout() override;
146 bool IsLayoutFrozen() const override;
147147
148148 // Get the rect which is bounding the specified cell.
149149 // This rect does not include RowRectPadding.
150150 // You should call FreezeLayout prior to this function.
151 Rect GetCellRect(int row, int column) const;
151 Rect GetCellRect(int row, int column) const override;
152152
153153 // Get specified component rect.
154154 // You should call FreezeLayout prior to these function.
155 Size GetTotalSize() const;
156 Rect GetHeaderRect() const;
157 Rect GetFooterRect() const;
158 Rect GetVScrollBarRect() const;
155 Size GetTotalSize() const override;
156 Rect GetHeaderRect() const override;
157 Rect GetFooterRect() const override;
158 Rect GetVScrollBarRect() const override;
159159 Rect GetVScrollIndicatorRect(int begin_index, int end_index,
160 int candidates_total) const;
160 int candidates_total) const override;
161161
162162 // Get the rect which is bounding the specified row.
163163 // This rect includes RowRectPadding.
164164 // You should call FreezeLayout prior to these function.
165 Rect GetRowRect(int row) const;
165 Rect GetRowRect(int row) const override;
166166
167167 // Get specified row rect.
168168 // This rect includes RowRectPadding.
169169 // You should call FreezeLayout prior to these function.
170 Rect GetColumnRect(int column) const;
170 Rect GetColumnRect(int column) const override;
171171
172172 // Parameter getters
173 int number_of_rows() const;
174 int number_of_columns() const;
173 int number_of_rows() const override;
174 int number_of_columns() const override;
175175
176176 private:
177177 std::vector<int> column_width_list_;
2727 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2828
2929 #include "renderer/table_layout.h"
30
3031 #include "testing/base/public/gunit.h"
3132
3233 namespace mozc {
3535 namespace mozc {
3636
3737 ConversionRequest::ConversionRequest()
38 : composer_(NULL),
38 : composer_(nullptr),
3939 request_(&commands::Request::default_instance()),
4040 config_(&config::ConfigHandler::DefaultConfig()),
4141 use_actual_converter_for_realtime_conversion_(false),
5656
5757 ConversionRequest::~ConversionRequest() {}
5858
59 bool ConversionRequest::has_composer() const { return composer_ != NULL; }
59 bool ConversionRequest::has_composer() const { return composer_ != nullptr; }
6060
6161 const composer::Composer &ConversionRequest::composer() const {
6262 DCHECK(composer_);
8383 const dictionary::POSMatcher pos_matcher(data_manager.GetPOSMatcherData());
8484 open_bracket_id_ = pos_matcher.GetOpenBracketId();
8585 close_bracket_id_ = pos_matcher.GetCloseBracketId();
86 user_pos_.reset(dictionary::UserPOS::CreateFromDataManager(data_manager));
86 user_pos_ = dictionary::UserPOS::CreateFromDataManager(data_manager);
8787 }
8888
8989 DictionaryGenerator::~DictionaryGenerator() {}
2929
3030 """Stub build rules."""
3131
32 def portable_proto_library(name, proto_deps, deps = [], **kwargs):
33 _ignore = [kwargs]
34 native.cc_proto_library(name = name, deps = deps + proto_deps)
32 def bzl_library(**kwargs):
33 # Do nothing for OSS.
34 _ignore = kwargs
35 pass
36
37 def cc_embed_data(**kwargs):
38 # Do nothing for OSS.
39 _ignore = kwargs
40 pass
3541
3642 def jspb_proto_library(**kwargs):
3743 # Do nothing for OSS.
3844 _ignore = kwargs
3945 pass
4046
41 def bzl_library(**kwargs):
42 # Do nothing for OSS.
43 _ignore = kwargs
44 pass
47 def portable_proto_library(name, proto_deps, deps = [], **kwargs):
48 _ignore = [kwargs]
49 native.cc_proto_library(name = name, deps = deps + proto_deps)
4550
4651 def py2and3_test(**kwargs):
4752 native.py_test(**kwargs)
3737 "cc_test_mozc",
3838 )
3939
40 package(default_visibility = ["//:__subpackages__"])
41
4240 cc_binary_mozc(
4341 name = "mozc_emacs_helper",
4442 srcs = ["mozc_emacs_helper.cc"],
4543 copts = [
4644 "$(STACK_FRAME_UNLIMITED)", # mozc_emacs_helper.cc
4745 ],
46 visibility = ["//:__subpackages__"],
4847 deps = [
4948 ":mozc_emacs_helper_lib",
5049 "//base",