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"
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"
17 TranslateAcceptLanguages::TranslateAcceptLanguages(
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),
32 TranslateAcceptLanguages::~TranslateAcceptLanguages() {
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()) {
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
) {
63 // Build the languages.
64 accept_languages_
.clear();
65 std::string accept_langs_str
= prefs
->GetString(
66 accept_languages_pref_
.c_str());
67 std::vector
<std::string
> accept_langs_list
;
68 base::SplitString(accept_langs_str
, ',', &accept_langs_list
);
69 std::vector
<std::string
>::const_iterator iter
;
71 for (iter
= accept_langs_list
.begin();
72 iter
!= accept_langs_list
.end(); ++iter
) {
73 // Get rid of the locale extension if any (ex: en-US -> en), but for Chinese
74 // for which the CLD reports zh-CN and zh-TW.
75 std::string
accept_lang(*iter
);
76 size_t index
= iter
->find("-");
77 if (index
!= std::string::npos
&& *iter
!= "zh-CN" && *iter
!= "zh-TW")
78 accept_lang
= iter
->substr(0, index
);
80 accept_languages_
.insert(accept_lang
);
84 } // namespace translate