OLD | NEW |
(Empty) | |
| 1 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #include "content/browser/hyphenation/hyphenation_impl.h" |
| 6 |
| 7 #include <algorithm> |
| 8 #include <map> |
| 9 #include <utility> |
| 10 |
| 11 #include "base/files/file.h" |
| 12 #include "base/files/file_path.h" |
| 13 #include "base/strings/stringprintf.h" |
| 14 #include "mojo/public/cpp/system/platform_handle.h" |
| 15 |
| 16 namespace { |
| 17 |
| 18 using DictionaryFileMap = std::unordered_map<std::string, base::File>; |
| 19 |
| 20 static bool IsValidLocale(const std::string& locale) { |
| 21 return std::all_of(locale.cbegin(), locale.cend(), |
| 22 [](const char ch) { return isalpha(ch) || ch == '-'; }); |
| 23 } |
| 24 |
| 25 static base::File& GetDictionaryFile(const std::string& locale) { |
| 26 // Keep Files open in the cache for subsequent calls. |
| 27 CR_DEFINE_STATIC_LOCAL(DictionaryFileMap, cache, ()); |
| 28 |
| 29 const auto& it = cache.find(locale); |
| 30 if (it != cache.end()) |
| 31 return it->second; |
| 32 const auto& inserted = cache.insert(std::make_pair(locale, base::File())); |
| 33 base::File& file = inserted.first->second; |
| 34 DCHECK(!file.IsValid()); |
| 35 |
| 36 #if defined(OS_ANDROID) |
| 37 base::FilePath dir("/system/usr/hyphen-data"); |
| 38 #else |
| 39 #error "This configuration is not supported." |
| 40 #endif |
| 41 std::string filename = base::StringPrintf("hyph-%s.hyb", locale.c_str()); |
| 42 base::FilePath path = dir.AppendASCII(filename); |
| 43 file.Initialize(path, base::File::FLAG_OPEN | base::File::FLAG_READ); |
| 44 return file; |
| 45 } |
| 46 |
| 47 } // namespace |
| 48 |
| 49 namespace hyphenation { |
| 50 |
| 51 HyphenationImpl::HyphenationImpl(blink::mojom::HyphenationRequest request) |
| 52 : binding_(this, std::move(request)) {} |
| 53 |
| 54 HyphenationImpl::~HyphenationImpl() {} |
| 55 |
| 56 // static |
| 57 void HyphenationImpl::Create(blink::mojom::HyphenationRequest request) { |
| 58 new HyphenationImpl(std::move(request)); |
| 59 } |
| 60 |
| 61 void HyphenationImpl::OpenDictionary(const mojo::String& locale, |
| 62 const OpenDictionaryCallback& callback) { |
| 63 mojo::ScopedHandle handle; |
| 64 if (IsValidLocale(locale)) { |
| 65 base::File& file = GetDictionaryFile(locale); |
| 66 if (file.IsValid()) |
| 67 handle = mojo::WrapPlatformFile(file.Duplicate().TakePlatformFile()); |
| 68 } |
| 69 callback.Run(std::move(handle)); |
| 70 } |
| 71 |
| 72 } // namespace hyphenation |
OLD | NEW |