| 1 | /* |
| 2 | * Open Chinese Convert |
| 3 | * |
| 4 | * Copyright 2010-2026 Carbo Kuo and contributors |
| 5 | * |
| 6 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | * you may not use this file except in compliance with the License. |
| 8 | * You may obtain a copy of the License at |
| 9 | * |
| 10 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | * |
| 12 | * Unless required by applicable law or agreed to in writing, software |
| 13 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | * See the License for the specific language governing permissions and |
| 16 | * limitations under the License. |
| 17 | */ |
| 18 | |
| 19 | #include <cstdio> |
| 20 | #include <list> |
| 21 | #include <mutex> |
| 22 | #include <sys/stat.h> |
| 23 | #include <unordered_map> |
| 24 | |
| 25 | #if defined(_WIN32) || defined(_WIN64) |
| 26 | #include "WinUtil.hpp" |
| 27 | #endif |
| 28 | |
| 29 | #include <rapidjson/document.h> |
| 30 | #include <rapidjson/schema.h> |
| 31 | #include <rapidjson/stringbuffer.h> |
| 32 | |
| 33 | #include "Config.hpp" |
| 34 | #include "ConversionChain.hpp" |
| 35 | #include "ConfigBasedConverter.hpp" |
| 36 | #include "Converter.hpp" |
| 37 | #include "SingleStageConverter.hpp" |
| 38 | #include "DictGroup.hpp" |
| 39 | #include "Exception.hpp" |
| 40 | #include "Lexicon.hpp" |
| 41 | #include "MarisaDict.hpp" |
| 42 | #include "MaxMatchSegmentation.hpp" |
| 43 | #include "PluginSegmentation.hpp" |
| 44 | #include "TextDict.hpp" |
| 45 | #include "UTF8Util.hpp" |
| 46 | |
| 47 | #include "DartsDict.hpp" |
| 48 | |
| 49 | typedef rapidjson::GenericValue<rapidjson::UTF8<char>> JSONValue; |
| 50 | |
| 51 | static const char kConfigSchemaJson[] = |
| 52 | #include "opencc_config_schema.inc" |
| 53 | ; |
| 54 | |
| 55 | namespace opencc { |
| 56 | |
| 57 | namespace { |
| 58 | |
| 59 | std::string GetParentDirectory(const std::string& path); |
| 60 | |
| 61 | std::mutex& DictCacheMutex() { |
| 62 | static std::mutex mutex; |
| 63 | return mutex; |
| 64 | } |
| 65 | |
| 66 | std::unordered_map<std::string, std::weak_ptr<Dict>>& DictCache() { |
| 67 | static std::unordered_map<std::string, std::weak_ptr<Dict>> cache; |
| 68 | return cache; |
| 69 | } |
| 70 | |
| 71 | void PruneExpiredDictCache() { |
| 72 | std::unordered_map<std::string, std::weak_ptr<Dict>>& cache = DictCache(); |
| 73 | for (std::unordered_map<std::string, std::weak_ptr<Dict>>::iterator it = |
| 74 | cache.begin(); |
| 75 | it != cache.end();) { |
| 76 | if (it->second.expired()) { |
| 77 | it = cache.erase(it); |
| 78 | } else { |
| 79 | ++it; |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | bool GetFileCacheKey(const std::string& path, std::string* cacheKey) { |
| 85 | #if defined(_WIN32) || defined(_WIN64) |
| 86 | WIN32_FILE_ATTRIBUTE_DATA fileInfo; |
| 87 | const std::wstring widePath = internal::WideFromUtf8(path); |
| 88 | if (widePath.empty() || |
| 89 | !GetFileAttributesExW(widePath.c_str(), GetFileExInfoStandard, |
| 90 | &fileInfo)) { |
| 91 | return false; |
| 92 | } |
| 93 | #else |
| 94 | struct stat statBuf; |
| 95 | if (stat(path.c_str(), &statBuf) != 0) { |
| 96 | return false; |
| 97 | } |
| 98 | #endif |
| 99 | *cacheKey = path; |
| 100 | cacheKey->push_back('\n'); |
| 101 | #if defined(_WIN32) || defined(_WIN64) |
| 102 | cacheKey->append( |
| 103 | std::to_string(static_cast<unsigned long long>( |
| 104 | fileInfo.ftLastWriteTime.dwHighDateTime))); |
| 105 | cacheKey->push_back('.'); |
| 106 | cacheKey->append( |
| 107 | std::to_string(static_cast<unsigned long long>( |
| 108 | fileInfo.ftLastWriteTime.dwLowDateTime))); |
| 109 | cacheKey->push_back('\n'); |
| 110 | cacheKey->append( |
| 111 | std::to_string(static_cast<unsigned long long>(fileInfo.nFileSizeHigh))); |
| 112 | cacheKey->push_back('.'); |
| 113 | cacheKey->append( |
| 114 | std::to_string(static_cast<unsigned long long>(fileInfo.nFileSizeLow))); |
| 115 | #else |
| 116 | cacheKey->append(std::to_string(static_cast<long long>(statBuf.st_mtime))); |
| 117 | cacheKey->push_back('.'); |
| 118 | #if defined(__APPLE__) && defined(__MACH__) |
| 119 | cacheKey->append( |
| 120 | std::to_string(static_cast<long long>(statBuf.st_mtimespec.tv_nsec))); |
| 121 | #elif defined(st_mtime_nsec) |
| 122 | cacheKey->append( |
| 123 | std::to_string(static_cast<long long>(statBuf.st_mtime_nsec))); |
| 124 | #else |
| 125 | cacheKey->append( |
| 126 | std::to_string(static_cast<long long>(statBuf.st_mtim.tv_nsec))); |
| 127 | #endif |
| 128 | cacheKey->push_back('\n'); |
| 129 | cacheKey->append(std::to_string(static_cast<long long>(statBuf.st_size))); |
| 130 | #endif |
| 131 | return true; |
| 132 | } |
| 133 | |
| 134 | FILE* OpenFileUtf8(const std::string& path, const char* mode) { |
| 135 | #if defined(_WIN32) || defined(_WIN64) |
| 136 | return _wfopen(internal::WideFromUtf8(path).c_str(), |
| 137 | internal::WideFromUtf8(mode).c_str()); |
| 138 | #else |
| 139 | return fopen(path.c_str(), mode); |
| 140 | #endif |
| 141 | } |
| 142 | |
| 143 | bool CanOpenFileUtf8(const std::string& path) { |
| 144 | FILE* fp = OpenFileUtf8(path, "rb"); |
| 145 | if (fp == nullptr) { |
| 146 | return false; |
| 147 | } |
| 148 | fclose(fp); |
| 149 | return true; |
| 150 | } |
| 151 | |
| 152 | std::string ReadFileUtf8(const std::string& path) { |
| 153 | FILE* fp = OpenFileUtf8(path, "rb"); |
| 154 | if (fp == nullptr) { |
| 155 | throw FileNotFound(path); |
| 156 | } |
| 157 | |
| 158 | std::string content; |
| 159 | char buffer[4096]; |
| 160 | for (;;) { |
| 161 | const size_t read = fread(buffer, 1, sizeof(buffer), fp); |
| 162 | if (read > 0) { |
| 163 | content.append(buffer, read); |
| 164 | } |
| 165 | if (read < sizeof(buffer)) { |
| 166 | if (ferror(fp)) { |
| 167 | fclose(fp); |
| 168 | throw FileNotFound(path); |
| 169 | } |
| 170 | break; |
| 171 | } |
| 172 | } |
| 173 | fclose(fp); |
| 174 | return content; |
| 175 | } |
| 176 | |
| 177 | #if defined(_WIN32) || defined(_WIN64) |
| 178 | using internal::Utf8FromWide; |
| 179 | using internal::WideFromUtf8; |
| 180 | |
| 181 | std::string NormalizeModulePath(const std::string& path) { |
| 182 | if (path.empty()) { |
| 183 | return ""; |
| 184 | } |
| 185 | |
| 186 | std::wstring widePath = WideFromUtf8(path); |
| 187 | if (widePath.empty()) { |
| 188 | return path; |
| 189 | } |
| 190 | |
| 191 | HANDLE handle = |
| 192 | CreateFileW(widePath.c_str(), 0, |
| 193 | FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, |
| 194 | nullptr, OPEN_EXISTING, |
| 195 | FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, nullptr); |
| 196 | if (handle == INVALID_HANDLE_VALUE) { |
| 197 | return path; |
| 198 | } |
| 199 | |
| 200 | std::wstring finalPath(MAX_PATH, L'\0'); |
| 201 | for (;;) { |
| 202 | DWORD copied = |
| 203 | GetFinalPathNameByHandleW(handle, finalPath.data(), |
| 204 | static_cast<DWORD>(finalPath.size()), |
| 205 | FILE_NAME_NORMALIZED); |
| 206 | if (copied == 0) { |
| 207 | CloseHandle(handle); |
| 208 | return path; |
| 209 | } |
| 210 | if (copied < finalPath.size()) { |
| 211 | finalPath.resize(copied); |
| 212 | break; |
| 213 | } |
| 214 | finalPath.resize(copied + 1); |
| 215 | } |
| 216 | CloseHandle(handle); |
| 217 | |
| 218 | const std::wstring uncPrefix = L"\\\\?\\UNC\\"; |
| 219 | const std::wstring localPrefix = L"\\\\?\\"; |
| 220 | if (finalPath.rfind(uncPrefix, 0) == 0) { |
| 221 | finalPath = L"\\" + finalPath.substr(7); |
| 222 | } else if (finalPath.rfind(localPrefix, 0) == 0) { |
| 223 | finalPath = finalPath.substr(4); |
| 224 | } |
| 225 | return Utf8FromWide(finalPath); |
| 226 | } |
| 227 | |
| 228 | std::string GetModulePath(HMODULE module) { |
| 229 | std::wstring buffer(MAX_PATH, L'\0'); |
| 230 | for (;;) { |
| 231 | DWORD copied = |
| 232 | GetModuleFileNameW(module, buffer.data(), static_cast<DWORD>(buffer.size())); |
| 233 | if (copied == 0) { |
| 234 | return ""; |
| 235 | } |
| 236 | if (copied < buffer.size() - 1) { |
| 237 | buffer.resize(copied); |
| 238 | return NormalizeModulePath(Utf8FromWide(buffer)); |
| 239 | } |
| 240 | buffer.resize(buffer.size() * 2); |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | std::string GetCurrentProcessModulePath() { |
| 245 | return GetModulePath(nullptr); |
| 246 | } |
| 247 | |
| 248 | std::string GetCurrentLibraryModulePath() { |
| 249 | HMODULE module = nullptr; |
| 250 | if (!GetModuleHandleExW( |
| 251 | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | |
| 252 | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, |
| 253 | reinterpret_cast<LPCWSTR>(&GetCurrentLibraryModulePath), &module)) { |
| 254 | return ""; |
| 255 | } |
| 256 | return GetModulePath(module); |
| 257 | } |
| 258 | |
| 259 | void AppendWindowsPortableSearchPaths(std::vector<std::string>& paths, |
| 260 | const std::string& modulePath) { |
| 261 | const std::string parent = GetParentDirectory(modulePath); |
| 262 | if (parent.empty()) { |
| 263 | return; |
| 264 | } |
| 265 | paths.push_back(parent); |
| 266 | paths.push_back(parent + "../share/opencc"); |
| 267 | } |
| 268 | #endif |
| 269 | |
| 270 | class ConfigInternal { |
| 271 | public: |
| 272 | std::vector<std::string> paths; |
| 273 | std::string configDirectory; |
| 274 | std::shared_ptr<ResourceProvider> resourceProvider; |
| 275 | ConfigLoadOptions options; |
| 276 | |
| 277 | const JSONValue& GetProperty(const JSONValue& doc, const char* name) { |
| 278 | if (!doc.HasMember(name)) { |
| 279 | throw InvalidFormat("Required property not found: " + std::string(name)); |
| 280 | } |
| 281 | return doc[name]; |
| 282 | } |
| 283 | |
| 284 | const JSONValue& GetObjectProperty(const JSONValue& doc, const char* name) { |
| 285 | const JSONValue& obj = GetProperty(doc, name); |
| 286 | if (!obj.IsObject()) { |
| 287 | throw InvalidFormat("Property must be an object: " + std::string(name)); |
| 288 | } |
| 289 | return obj; |
| 290 | } |
| 291 | |
| 292 | const JSONValue& GetArrayProperty(const JSONValue& doc, const char* name) { |
| 293 | const JSONValue& obj = GetProperty(doc, name); |
| 294 | if (!obj.IsArray()) { |
| 295 | throw InvalidFormat("Property must be an array: " + std::string(name)); |
| 296 | } |
| 297 | return obj; |
| 298 | } |
| 299 | |
| 300 | const char* GetStringProperty(const JSONValue& doc, const char* name) { |
| 301 | const JSONValue& obj = GetProperty(doc, name); |
| 302 | if (!obj.IsString()) { |
| 303 | throw InvalidFormat("Property must be a std::string: " + |
| 304 | std::string(name)); |
| 305 | } |
| 306 | return obj.GetString(); |
| 307 | } |
| 308 | |
| 309 | bool GetOptionalBoolProperty(const JSONValue& doc, const char* name, |
| 310 | bool defaultValue) { |
| 311 | if (!doc.HasMember(name)) { |
| 312 | return defaultValue; |
| 313 | } |
| 314 | if (!doc[name].IsBool()) { |
| 315 | throw InvalidFormat("Property must be a bool: " + std::string(name)); |
| 316 | } |
| 317 | return doc[name].GetBool(); |
| 318 | } |
| 319 | |
| 320 | DictGroupMatchPolicy GetOptionalDictGroupMatchPolicy(const JSONValue& doc) { |
| 321 | if (!doc.HasMember("match_policy")) { |
| 322 | return DictGroupMatchPolicy::ShortCircuit; |
| 323 | } |
| 324 | if (!doc["match_policy"].IsString()) { |
| 325 | throw InvalidFormat("Property must be a std::string: match_policy"); |
| 326 | } |
| 327 | const std::string matchPolicy = doc["match_policy"].GetString(); |
| 328 | if (matchPolicy == "short_circuit") { |
| 329 | return DictGroupMatchPolicy::ShortCircuit; |
| 330 | } |
| 331 | if (matchPolicy == "union") { |
| 332 | return DictGroupMatchPolicy::Union; |
| 333 | } |
| 334 | throw InvalidFormat("Unknown dictionary group match_policy: " + |
| 335 | matchPolicy); |
| 336 | } |
| 337 | |
| 338 | template <typename DICT> |
| 339 | DictPtr LoadDictWithResourceProvider(const std::string& cachePrefix, |
| 340 | const std::string& fileName) { |
| 341 | if (resourceProvider == nullptr) { |
| 342 | throw FileNotFound(fileName); |
| 343 | } |
| 344 | |
| 345 | const std::string path = resourceProvider->Resolve(fileName); |
| 346 | std::string cacheKey = cachePrefix; |
| 347 | cacheKey.push_back('\n'); |
| 348 | if (!GetFileCacheKey(path, &cacheKey)) { |
| 349 | throw FileNotFound(path); |
| 350 | } |
| 351 | { |
| 352 | std::lock_guard<std::mutex> lock(DictCacheMutex()); |
| 353 | PruneExpiredDictCache(); |
| 354 | const auto cached = DictCache().find(cacheKey); |
| 355 | if (cached != DictCache().end()) { |
| 356 | DictPtr dict = cached->second.lock(); |
| 357 | if (dict != nullptr) { |
| 358 | return dict; |
| 359 | } |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | std::shared_ptr<DICT> dict; |
| 364 | if (SerializableDict::TryLoadFromFile<DICT>(path, &dict)) { |
| 365 | std::lock_guard<std::mutex> lock(DictCacheMutex()); |
| 366 | PruneExpiredDictCache(); |
| 367 | std::weak_ptr<Dict>& cached = DictCache()[cacheKey]; |
| 368 | DictPtr cachedDict = cached.lock(); |
| 369 | if (cachedDict == nullptr) { |
| 370 | cached = dict; |
| 371 | return dict; |
| 372 | } |
| 373 | return cachedDict; |
| 374 | } |
| 375 | throw FileNotFound(path); |
| 376 | } |
| 377 | |
| 378 | DictPtr LoadTextDartsDictWithResourceProvider(const std::string& fileName) { |
| 379 | if (resourceProvider == nullptr) { |
| 380 | throw FileNotFound(fileName); |
| 381 | } |
| 382 | |
| 383 | const std::shared_ptr<const ResourceProvider::Resource> resource = |
| 384 | resourceProvider->GetResource(fileName); |
| 385 | std::string cacheKey = "text-darts\n" + resource->CacheKey(); |
| 386 | { |
| 387 | std::lock_guard<std::mutex> lock(DictCacheMutex()); |
| 388 | PruneExpiredDictCache(); |
| 389 | const auto cached = DictCache().find(cacheKey); |
| 390 | if (cached != DictCache().end()) { |
| 391 | DictPtr dict = cached->second.lock(); |
| 392 | if (dict != nullptr) { |
| 393 | return dict; |
| 394 | } |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | TextDictPtr textDict = TextDict::NewFromBuffer(resource->Data(), |
| 399 | resource->Size()); |
| 400 | DictPtr dict = DartsDict::NewFromDict(*textDict.get()); |
| 401 | { |
| 402 | std::lock_guard<std::mutex> lock(DictCacheMutex()); |
| 403 | PruneExpiredDictCache(); |
| 404 | std::weak_ptr<Dict>& cached = DictCache()[cacheKey]; |
| 405 | DictPtr cachedDict = cached.lock(); |
| 406 | if (cachedDict == nullptr) { |
| 407 | cached = dict; |
| 408 | return dict; |
| 409 | } |
| 410 | return cachedDict; |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | DictPtr LoadOcdDictWithResourceProvider(const std::string& fileName) { |
| 415 | if (resourceProvider == nullptr) { |
| 416 | throw FileNotFound(fileName); |
| 417 | } |
| 418 | const std::shared_ptr<const ResourceProvider::Resource> resource = |
| 419 | resourceProvider->GetResource(fileName); |
| 420 | std::string cacheKey = "ocd\n" + resource->CacheKey(); |
| 421 | { |
| 422 | std::lock_guard<std::mutex> lock(DictCacheMutex()); |
| 423 | PruneExpiredDictCache(); |
| 424 | const auto cached = DictCache().find(cacheKey); |
| 425 | if (cached != DictCache().end()) { |
| 426 | DictPtr dict = cached->second.lock(); |
| 427 | if (dict != nullptr) { |
| 428 | return dict; |
| 429 | } |
| 430 | } |
| 431 | } |
| 432 | DictPtr dict = |
| 433 | DartsDict::NewFromBuffer(resource->Data(), resource->Size()); |
| 434 | { |
| 435 | std::lock_guard<std::mutex> lock(DictCacheMutex()); |
| 436 | PruneExpiredDictCache(); |
| 437 | std::weak_ptr<Dict>& cached = DictCache()[cacheKey]; |
| 438 | DictPtr cachedDict = cached.lock(); |
| 439 | if (cachedDict == nullptr) { |
| 440 | cached = dict; |
| 441 | return dict; |
| 442 | } |
| 443 | return cachedDict; |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | DictPtr LoadOcd2DictWithResourceProvider(const std::string& fileName) { |
| 448 | if (resourceProvider == nullptr) { |
| 449 | throw FileNotFound(fileName); |
| 450 | } |
| 451 | |
| 452 | const std::shared_ptr<const ResourceProvider::Resource> resource = |
| 453 | resourceProvider->GetResource(fileName); |
| 454 | std::string cacheKey = "ocd2-marisa\n" + resource->CacheKey(); |
| 455 | { |
| 456 | std::lock_guard<std::mutex> lock(DictCacheMutex()); |
| 457 | PruneExpiredDictCache(); |
| 458 | const auto cached = DictCache().find(cacheKey); |
| 459 | if (cached != DictCache().end()) { |
| 460 | DictPtr dict = cached->second.lock(); |
| 461 | if (dict != nullptr) { |
| 462 | return dict; |
| 463 | } |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | DictPtr dict = MarisaDict::NewFromBuffer(resource->Data(), resource->Size()); |
| 468 | { |
| 469 | std::lock_guard<std::mutex> lock(DictCacheMutex()); |
| 470 | PruneExpiredDictCache(); |
| 471 | std::weak_ptr<Dict>& cached = DictCache()[cacheKey]; |
| 472 | DictPtr cachedDict = cached.lock(); |
| 473 | if (cachedDict == nullptr) { |
| 474 | cached = dict; |
| 475 | return dict; |
| 476 | } |
| 477 | return cachedDict; |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | DictPtr LoadDictFromFile(const std::string& type, |
| 482 | const std::string& fileName) { |
| 483 | if (type == "text") { |
| 484 | return LoadTextDartsDictWithResourceProvider(fileName); |
| 485 | } |
| 486 | if (type == "ocd") { |
| 487 | if (resourceProvider != nullptr) { |
| 488 | try { |
| 489 | return LoadOcdDictWithResourceProvider(fileName); |
| 490 | } catch (const FileNotFound&) { |
| 491 | // Fallback to loading from resolved file path |
| 492 | } |
| 493 | } |
| 494 | return LoadDictWithResourceProvider<DartsDict>("ocd", fileName); |
| 495 | } |
| 496 | if (type == "ocd2") { |
| 497 | if (resourceProvider != nullptr) { |
| 498 | try { |
| 499 | return LoadOcd2DictWithResourceProvider(fileName); |
| 500 | } catch (const FileNotFound&) { |
| 501 | // Fallback to loading from resolved file path |
| 502 | } |
| 503 | } |
| 504 | return LoadDictWithResourceProvider<MarisaDict>("ocd2", fileName); |
| 505 | } |
| 506 | throw InvalidFormat("Unknown dictionary type: " + type); |
| 507 | return nullptr; |
| 508 | } |
| 509 | |
| 510 | DictPtr LoadInlineDict(const JSONValue& doc) { |
| 511 | if (doc.HasMember("may_output_tofu")) { |
| 512 | throw InvalidFormat("Inline dictionary does not support may_output_tofu"); |
| 513 | } |
| 514 | |
| 515 | const JSONValue& entries = GetObjectProperty(doc, "entries"); |
| 516 | LexiconPtr lexicon(new Lexicon); |
| 517 | for (auto it = entries.MemberBegin(); it != entries.MemberEnd(); ++it) { |
| 518 | if (it->name.GetStringLength() == 0) { |
| 519 | throw InvalidFormat("Inline dictionary key must be a non-empty string"); |
| 520 | } |
| 521 | if (!it->value.IsString() || it->value.GetStringLength() == 0) { |
| 522 | throw InvalidFormat( |
| 523 | "Inline dictionary value must be a non-empty string: " + |
| 524 | std::string(it->name.GetString())); |
| 525 | } |
| 526 | lexicon->Add( |
| 527 | DictEntryFactory::New(it->name.GetString(), it->value.GetString())); |
| 528 | } |
| 529 | |
| 530 | lexicon->Sort(); |
| 531 | std::string duplicateKey; |
| 532 | if (!lexicon->IsUnique(&duplicateKey)) { |
| 533 | throw InvalidFormat("Inline dictionary contains duplicate key: " + |
| 534 | duplicateKey); |
| 535 | } |
| 536 | |
| 537 | return DictPtr(new TextDict(lexicon)); |
| 538 | } |
| 539 | |
| 540 | DictPtr ParseDict(const JSONValue& doc, bool includeTofuRiskDictionaries) { |
| 541 | // Required: type |
| 542 | std::string type = GetStringProperty(doc, "type"); |
| 543 | |
| 544 | if (type == "inline") { |
| 545 | return LoadInlineDict(doc); |
| 546 | } |
| 547 | |
| 548 | const bool mayOutputTofu = |
| 549 | GetOptionalBoolProperty(doc, "may_output_tofu", false); |
| 550 | if (mayOutputTofu && !includeTofuRiskDictionaries) { |
| 551 | return DictPtr(); |
| 552 | } |
| 553 | |
| 554 | if (type == "group") { |
| 555 | const DictGroupMatchPolicy matchPolicy = |
| 556 | GetOptionalDictGroupMatchPolicy(doc); |
| 557 | std::list<DictPtr> dicts; |
| 558 | const JSONValue& docs = GetArrayProperty(doc, "dicts"); |
| 559 | for (rapidjson::SizeType i = 0; i < docs.Size(); i++) { |
| 560 | if (docs[i].IsObject()) { |
| 561 | DictPtr dict = ParseDict(docs[i], includeTofuRiskDictionaries); |
| 562 | if (dict != nullptr) { |
| 563 | dicts.push_back(dict); |
| 564 | } |
| 565 | } else { |
| 566 | throw InvalidFormat("Element of the array must be an object"); |
| 567 | } |
| 568 | } |
| 569 | if (dicts.empty()) { |
| 570 | return DictPtr(); |
| 571 | } |
| 572 | switch (matchPolicy) { |
| 573 | case DictGroupMatchPolicy::ShortCircuit: |
| 574 | return DictGroupPtr(new DictGroup(dicts, matchPolicy)); |
| 575 | case DictGroupMatchPolicy::Union: |
| 576 | return DictGroupPtr(new UnionDictGroup(dicts)); |
| 577 | } |
| 578 | throw InvalidFormat("Unsupported dictionary group match_policy"); |
| 579 | } else { |
| 580 | std::string fileName = GetStringProperty(doc, "file"); |
| 581 | DictPtr dict = LoadDictFromFile(type, fileName); |
| 582 | return dict; |
| 583 | } |
| 584 | } |
| 585 | |
| 586 | SegmentationPtr ParseSegmentation(const JSONValue& doc) { |
| 587 | SegmentationPtr segmentation; |
| 588 | |
| 589 | // Required: type |
| 590 | std::string type = GetStringProperty(doc, "type"); |
| 591 | if (type == "mmseg") { |
| 592 | // Required: dict |
| 593 | DictPtr dict = ParseDict(GetObjectProperty(doc, "dict"), true); |
| 594 | segmentation = SegmentationPtr(new MaxMatchSegmentation(dict)); |
| 595 | } else { |
| 596 | PluginConfigPairs configPairs; |
| 597 | configPairs.push_back(std::make_pair("__config_dir", configDirectory)); |
| 598 | if (doc.HasMember("resources")) { |
| 599 | const JSONValue& resources = GetObjectProperty(doc, "resources"); |
| 600 | for (auto it = resources.MemberBegin(); it != resources.MemberEnd(); |
| 601 | ++it) { |
| 602 | if (!it->value.IsString()) { |
| 603 | throw InvalidFormat("Segmentation resource must be a string: " + |
| 604 | std::string(it->name.GetString())); |
| 605 | } |
| 606 | configPairs.push_back(std::make_pair(it->name.GetString(), |
| 607 | it->value.GetString())); |
| 608 | } |
| 609 | } |
| 610 | for (auto it = doc.MemberBegin(); it != doc.MemberEnd(); ++it) { |
| 611 | const std::string key = it->name.GetString(); |
| 612 | if (key == "type" || key == "resources") { |
| 613 | continue; |
| 614 | } |
| 615 | if (!it->value.IsString()) { |
| 616 | throw InvalidFormat("Segmentation plugin property must be a string: " + |
| 617 | key); |
| 618 | } |
| 619 | configPairs.push_back(std::make_pair(key, it->value.GetString())); |
| 620 | } |
| 621 | segmentation = CreatePluginSegmentation(type, configPairs); |
| 622 | } |
| 623 | return segmentation; |
| 624 | } |
| 625 | |
| 626 | ConversionPtr ParseConversion(const JSONValue& doc) { |
| 627 | // Required: dict |
| 628 | DictPtr dict = ParseDict(GetObjectProperty(doc, "dict"), |
| 629 | options.includeTofuRiskDictionaries); |
| 630 | if (dict == nullptr) { |
| 631 | return ConversionPtr(); |
| 632 | } |
| 633 | ConversionPtr conversion(new Conversion(dict)); |
| 634 | |
| 635 | return conversion; |
| 636 | } |
| 637 | |
| 638 | ConversionChainPtr ParseConversionChain(const JSONValue& docs) { |
| 639 | std::list<ConversionPtr> conversions; |
| 640 | for (rapidjson::SizeType i = 0; i < docs.Size(); i++) { |
| 641 | const JSONValue& doc = docs[i]; |
| 642 | if (doc.IsObject()) { |
| 643 | ConversionPtr conversion = ParseConversion(doc); |
| 644 | if (conversion != nullptr) { |
| 645 | conversions.push_back(conversion); |
| 646 | } |
| 647 | } else { |
| 648 | } |
| 649 | } |
| 650 | ConversionChainPtr chain(new ConversionChain(conversions)); |
| 651 | return chain; |
| 652 | } |
| 653 | |
| 654 | std::string FindConfigFile(std::string fileName) { |
| 655 | // Working directory |
| 656 | if (CanOpenFileUtf8(fileName)) { |
| 657 | return fileName; |
| 658 | } |
| 659 | // Package data directory |
| 660 | if (PACKAGE_DATA_DIRECTORY != "") { |
| 661 | std::string prefixedFileName = PACKAGE_DATA_DIRECTORY + fileName; |
| 662 | if (CanOpenFileUtf8(prefixedFileName)) { |
| 663 | return prefixedFileName; |
| 664 | } |
| 665 | prefixedFileName += ".json"; |
| 666 | if (CanOpenFileUtf8(prefixedFileName)) { |
| 667 | return prefixedFileName; |
| 668 | } |
| 669 | } |
| 670 | |
| 671 | for (const std::string& dirPath : paths) { |
| 672 | std::string path = dirPath + '/' + fileName; |
| 673 | if (CanOpenFileUtf8(path)) { |
| 674 | return path; |
| 675 | } |
| 676 | } |
| 677 | |
| 678 | const char* envPath = std::getenv("OPENCC_DATA_DIR"); |
| 679 | if (envPath != nullptr) { |
| 680 | auto path = std::string(envPath) + '/' + fileName; |
| 681 | if (CanOpenFileUtf8(path)) { |
| 682 | return path; |
| 683 | } |
| 684 | } |
| 685 | |
| 686 | throw FileNotFound(fileName); |
| 687 | } |
| 688 | }; |
| 689 | |
| 690 | std::string GetParentDirectory(const std::string& path) { |
| 691 | size_t pos = path.rfind('/', path.length() - 1); |
| 692 | if (pos == std::string::npos) { |
| 693 | pos = path.rfind('\\', path.length() - 1); |
| 694 | } |
| 695 | if (pos == std::string::npos) { |
| 696 | return ""; |
| 697 | } |
| 698 | return path.substr(0, pos + 1); |
| 699 | } |
| 700 | |
| 701 | bool isRegularFile(const std::string& path) { |
| 702 | #if defined(_WIN32) || defined(_WIN64) |
| 703 | const DWORD attributes = GetFileAttributesW(WideFromUtf8(path).c_str()); |
| 704 | return attributes != INVALID_FILE_ATTRIBUTES && |
| 705 | (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0; |
| 706 | #else |
| 707 | struct stat info; |
| 708 | if (stat(path.c_str(), &info) != 0) { |
| 709 | return false; |
| 710 | } |
| 711 | return (info.st_mode & S_IFMT) == S_IFREG; |
| 712 | #endif |
| 713 | } |
| 714 | |
| 715 | std::shared_ptr<ResourceProvider> |
| 716 | NewFilesystemResourceProvider(const std::string& configDirectory, |
| 717 | const std::vector<std::string>& paths) { |
| 718 | std::vector<std::string> searchPaths; |
| 719 | if (!configDirectory.empty()) { |
| 720 | searchPaths.push_back(configDirectory); |
| 721 | } |
| 722 | searchPaths.push_back("."); |
| 723 | for (const std::string& path : paths) { |
| 724 | if (!path.empty()) { |
| 725 | searchPaths.push_back(path); |
| 726 | } |
| 727 | } |
| 728 | return std::shared_ptr<ResourceProvider>( |
| 729 | new FilesystemResourceProvider(searchPaths)); |
| 730 | } |
| 731 | |
| 732 | } // namespace |
| 733 | |
| 734 | Config::Config() : internal(new ConfigInternal()) {} |
| 735 | |
| 736 | Config::~Config() { delete reinterpret_cast<ConfigInternal*>(internal); } |
| 737 | |
| 738 | ConverterPtr Config::NewFromFile(const std::string& fileName) { |
| 739 | return NewFromFile(fileName, std::vector<std::string>{}, nullptr); |
| 740 | } |
| 741 | |
| 742 | ConverterPtr |
| 743 | Config::NewFromFile(const std::string& fileName, |
| 744 | std::shared_ptr<ResourceProvider> provider) { |
| 745 | return NewFromFile(fileName, provider, ConfigLoadOptions()); |
| 746 | } |
| 747 | |
| 748 | ConverterPtr |
| 749 | Config::NewFromFile(const std::string& fileName, |
| 750 | std::shared_ptr<ResourceProvider> provider, |
| 751 | const ConfigLoadOptions& options) { |
| 752 | ConfigInternal* impl = reinterpret_cast<ConfigInternal*>(internal); |
| 753 | impl->options = options; |
| 754 | impl->paths.clear(); |
| 755 | impl->resourceProvider = provider; |
| 756 | std::string prefixedFileName; |
| 757 | if (provider != nullptr) { |
| 758 | try { |
| 759 | const std::shared_ptr<const ResourceProvider::Resource> resource = |
| 760 | provider->GetResource(fileName); |
| 761 | impl->configDirectory = GetParentDirectory(resource->Name()); |
| 762 | return NewFromString(std::string(resource->Data(), resource->Size()), |
| 763 | provider, options); |
| 764 | } catch (const FileNotFound&) { |
| 765 | // Some callers pass a provider for dictionaries only; keep normal config |
| 766 | // file lookup as a fallback when the provider cannot supply the config. |
| 767 | prefixedFileName = impl->FindConfigFile(fileName); |
| 768 | } |
| 769 | } else { |
| 770 | prefixedFileName = impl->FindConfigFile(fileName); |
| 771 | } |
| 772 | if (!isRegularFile(prefixedFileName)) { |
| 773 | throw FileNotFound(prefixedFileName); |
| 774 | } |
| 775 | std::string content = ReadFileUtf8(prefixedFileName); |
| 776 | |
| 777 | #if defined(_WIN32) || defined(_WIN64) |
| 778 | UTF8Util::ReplaceAll(prefixedFileName, "\\", "/"); |
| 779 | #endif // if defined(_WIN32) || defined(_WIN64) |
| 780 | size_t slashPos = prefixedFileName.rfind("/"); |
| 781 | impl->configDirectory = ""; |
| 782 | if (slashPos != std::string::npos) { |
| 783 | impl->configDirectory = prefixedFileName.substr(0, slashPos) + "/"; |
| 784 | } |
| 785 | std::shared_ptr<ResourceProvider> effectiveProvider = provider; |
| 786 | if (effectiveProvider == nullptr) { |
| 787 | effectiveProvider = |
| 788 | NewFilesystemResourceProvider(impl->configDirectory, impl->paths); |
| 789 | } |
| 790 | return NewFromString(content, effectiveProvider, options); |
| 791 | } |
| 792 | |
| 793 | ConverterPtr Config::NewFromFile(const std::string& fileName, |
| 794 | const std::vector<std::string>& paths, |
| 795 | const char* argv0) { |
| 796 | return NewFromFile(fileName, paths, argv0, ConfigLoadOptions()); |
| 797 | } |
| 798 | |
| 799 | ConverterPtr Config::NewFromFile(const std::string& fileName, |
| 800 | const std::vector<std::string>& paths, |
| 801 | const char* argv0, |
| 802 | const ConfigLoadOptions& options) { |
| 803 | ConfigInternal* impl = reinterpret_cast<ConfigInternal*>(internal); |
| 804 | impl->options = options; |
| 805 | impl->paths = paths; |
| 806 | if (argv0 != nullptr) { |
| 807 | std::string parent = GetParentDirectory(argv0); |
| 808 | if (!parent.empty()) { |
| 809 | impl->paths.push_back(parent); |
| 810 | } |
| 811 | } |
| 812 | #if defined(_WIN32) || defined(_WIN64) |
| 813 | if (argv0 != nullptr) { |
| 814 | AppendWindowsPortableSearchPaths(impl->paths, argv0); |
| 815 | } |
| 816 | AppendWindowsPortableSearchPaths(impl->paths, GetCurrentProcessModulePath()); |
| 817 | AppendWindowsPortableSearchPaths(impl->paths, GetCurrentLibraryModulePath()); |
| 818 | #endif |
| 819 | if (PACKAGE_DATA_DIRECTORY != "") { |
| 820 | impl->paths.push_back(PACKAGE_DATA_DIRECTORY); |
| 821 | } |
| 822 | std::string prefixedFileName = impl->FindConfigFile(fileName); |
| 823 | if (!isRegularFile(prefixedFileName)) { |
| 824 | throw FileNotFound(prefixedFileName); |
| 825 | } |
| 826 | std::string content = ReadFileUtf8(prefixedFileName); |
| 827 | |
| 828 | #if defined(_WIN32) || defined(_WIN64) |
| 829 | UTF8Util::ReplaceAll(prefixedFileName, "\\", "/"); |
| 830 | #endif // if defined(_WIN32) || defined(_WIN64) |
| 831 | size_t slashPos = prefixedFileName.rfind("/"); |
| 832 | std::string configDirectory = ""; |
| 833 | if (slashPos != std::string::npos) { |
| 834 | configDirectory = prefixedFileName.substr(0, slashPos) + "/"; |
| 835 | } |
| 836 | if (!configDirectory.empty()) { |
| 837 | impl->paths.push_back(configDirectory); |
| 838 | } |
| 839 | impl->configDirectory = configDirectory; |
| 840 | impl->resourceProvider = |
| 841 | NewFilesystemResourceProvider(configDirectory, impl->paths); |
| 842 | return NewFromString(content, impl->resourceProvider, options); |
| 843 | } |
| 844 | |
| 845 | ConverterPtr Config::NewFromString(const std::string& json, |
| 846 | const std::string& configDirectory) { |
| 847 | std::vector<std::string> paths; |
| 848 | if (!configDirectory.empty()) { |
| 849 | if (configDirectory.back() == '/' || configDirectory.back() == '\\') { |
| 850 | paths.push_back(configDirectory); |
| 851 | } else { |
| 852 | paths.push_back(configDirectory + '/'); |
| 853 | } |
| 854 | } |
| 855 | return NewFromString(json, paths); |
| 856 | } |
| 857 | |
| 858 | ConverterPtr Config::NewFromString(const std::string& json, |
| 859 | const std::vector<std::string>& paths) { |
| 860 | return NewFromString(json, paths, ConfigLoadOptions()); |
| 861 | } |
| 862 | |
| 863 | ConverterPtr Config::NewFromString(const std::string& json, |
| 864 | const std::vector<std::string>& paths, |
| 865 | const ConfigLoadOptions& options) { |
| 866 | ConfigInternal* impl = reinterpret_cast<ConfigInternal*>(internal); |
| 867 | impl->paths = paths; |
| 868 | impl->configDirectory = paths.empty() ? "" : paths.front(); |
| 869 | impl->resourceProvider = |
| 870 | NewFilesystemResourceProvider(impl->configDirectory, paths); |
| 871 | return NewFromString(json, impl->resourceProvider, options); |
| 872 | } |
| 873 | |
| 874 | ConverterPtr |
| 875 | Config::NewFromString(const std::string& json, |
| 876 | std::shared_ptr<ResourceProvider> provider) { |
| 877 | return NewFromString(json, provider, ConfigLoadOptions()); |
| 878 | } |
| 879 | |
| 880 | ConverterPtr |
| 881 | Config::NewFromString(const std::string& json, |
| 882 | std::shared_ptr<ResourceProvider> provider, |
| 883 | const ConfigLoadOptions& options) { |
| 884 | rapidjson::Document doc; |
| 885 | |
| 886 | doc.Parse<rapidjson::kParseCommentsFlag | |
| 887 | rapidjson::kParseTrailingCommasFlag>(json.c_str()); |
| 888 | if (doc.HasParseError()) { |
| 889 | throw InvalidFormat("Error parsing JSON"); // doc.GetErrorOffset() |
| 890 | } |
| 891 | if (!doc.IsObject()) { |
| 892 | throw InvalidFormat("Root of configuration must be an object"); |
| 893 | } |
| 894 | |
| 895 | // Schema validation: warn on violations but continue parsing. |
| 896 | { |
| 897 | rapidjson::Document schemaDoc; |
| 898 | schemaDoc.Parse(kConfigSchemaJson); |
| 899 | if (!schemaDoc.HasParseError() && schemaDoc.IsObject()) { |
| 900 | rapidjson::SchemaDocument schema(schemaDoc); |
| 901 | rapidjson::SchemaValidator validator(schema); |
| 902 | if (!doc.Accept(validator)) { |
| 903 | rapidjson::StringBuffer docPath; |
| 904 | validator.GetInvalidDocumentPointer().Stringify(docPath); |
| 905 | rapidjson::StringBuffer schemaPath; |
| 906 | validator.GetInvalidSchemaPointer().Stringify(schemaPath); |
| 907 | fprintf(stderr, |
| 908 | "warning: config does not conform to schema: " |
| 909 | "document path \"%s\", schema path \"%s\", keyword \"%s\"\n", |
| 910 | docPath.GetString(), schemaPath.GetString(), |
| 911 | validator.GetInvalidSchemaKeyword() |
| 912 | ? validator.GetInvalidSchemaKeyword() |
| 913 | : ""); |
| 914 | } |
| 915 | } |
| 916 | } |
| 917 | |
| 918 | // Optional: name |
| 919 | std::string name; |
| 920 | if (doc.HasMember("name") && doc["name"].IsString()) { |
| 921 | name = doc["name"].GetString(); |
| 922 | } |
| 923 | |
| 924 | ConfigInternal* impl = reinterpret_cast<ConfigInternal*>(internal); |
| 925 | impl->options = options; |
| 926 | impl->resourceProvider = provider; |
| 927 | |
| 928 | // Optional: segmentation |
| 929 | SegmentationPtr segmentation; |
| 930 | if (doc.HasMember("segmentation")) { |
| 931 | segmentation = |
| 932 | impl->ParseSegmentation(impl->GetObjectProperty(doc, "segmentation")); |
| 933 | } |
| 934 | |
| 935 | // Required: conversion_chain |
| 936 | ConversionChainPtr chain = impl->ParseConversionChain( |
| 937 | impl->GetArrayProperty(doc, "conversion_chain")); |
| 938 | ConverterPtr mainConverter(new SingleStageConverter(segmentation, chain)); |
| 939 | |
| 940 | // Optional: normalization — a conversion chain applied before segmentation |
| 941 | if (doc.HasMember("normalization")) { |
| 942 | ConversionChainPtr normChain = impl->ParseConversionChain( |
| 943 | impl->GetArrayProperty(doc, "normalization")); |
| 944 | ConverterPtr normConverter(new SingleStageConverter(nullptr, normChain)); |
| 945 | return ConverterPtr( |
| 946 | new ConfigBasedConverter(std::move(normConverter), std::move(mainConverter))); |
| 947 | } |
| 948 | return mainConverter; |
| 949 | } |
| 950 | |
| 951 | }; // namespace opencc |