Roll src/third_party/WebKit eac3800:0237a66 (svn 202606:202607)
[chromium-blink-merge.git] / components / translate / core / browser / translate_accept_languages.cc
blobe65d92f1940dc5b3bc886d12ab0cc3874657a538
1 // Copyright 2014 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.
5 #include "components/translate/core/browser/translate_accept_languages.h"
7 #include "base/bind.h"
8 #include "base/prefs/pref_service.h"
9 #include "base/strings/string_split.h"
10 #include "base/strings/string_util.h"
11 #include "components/translate/core/browser/translate_download_manager.h"
12 #include "components/translate/core/common/translate_util.h"
13 #include "ui/base/l10n/l10n_util.h"
15 namespace translate {
17 TranslateAcceptLanguages::TranslateAcceptLanguages(
18 PrefService* prefs,
19 const char* accept_languages_pref)
20 : accept_languages_pref_(accept_languages_pref) {
21 InitAcceptLanguages(prefs);
23 // Also start listening for changes in the accept languages.
24 pref_change_registrar_.Init(prefs);
25 pref_change_registrar_.Add(
26 accept_languages_pref,
27 base::Bind(&TranslateAcceptLanguages::InitAcceptLanguages,
28 base::Unretained(this),
29 prefs));
32 TranslateAcceptLanguages::~TranslateAcceptLanguages() {
35 // static
36 bool TranslateAcceptLanguages::CanBeAcceptLanguage(
37 const std::string& language) {
38 std::string accept_language = language;
39 translate::ToChromeLanguageSynonym(&accept_language);
41 const std::string locale =
42 TranslateDownloadManager::GetInstance()->application_locale();
43 std::vector<std::string> accept_language_codes;
44 l10n_util::GetAcceptLanguagesForLocale(locale, &accept_language_codes);
46 if (std::find(accept_language_codes.begin(),
47 accept_language_codes.end(),
48 accept_language) != accept_language_codes.end()) {
49 return true;
52 return false;
55 bool TranslateAcceptLanguages::IsAcceptLanguage(const std::string& language) {
56 std::string accept_language = language;
57 translate::ToChromeLanguageSynonym(&accept_language);
58 return accept_languages_.find(accept_language) != accept_languages_.end();
61 void TranslateAcceptLanguages::InitAcceptLanguages(PrefService* prefs) {
62 DCHECK(prefs);
63 // Build the languages.
64 accept_languages_.clear();
65 std::string accept_languages_pref = prefs->GetString(accept_languages_pref_);
66 for (const base::StringPiece& lang : base::SplitStringPiece(
67 accept_languages_pref, ",",
68 base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
69 // Get rid of the locale extension if any (ex: en-US -> en), but for Chinese
70 // for which the CLD reports zh-CN and zh-TW.
71 size_t index = lang.find('-');
72 if (index != base::StringPiece::npos && lang != "zh-CN" && lang != "zh-TW")
73 accept_languages_.insert(lang.substr(0, index).as_string());
74 accept_languages_.insert(lang.as_string());
78 } // namespace translate