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.
4
5 #include "chrome/browser/translate/chrome_translate_client.h"
6
7 #include <memory>
8 #include <vector>
9
10 #include "base/check.h"
11 #include "base/feature_list.h"
12 #include "base/notreached.h"
13 #include "base/path_service.h"
14 #include "base/strings/string_split.h"
15 #include "build/build_config.h"
16 #include "chrome/browser/browser_process.h"
17 #include "chrome/browser/chrome_notification_types.h"
18 #include "chrome/browser/infobars/infobar_service.h"
19 #include "chrome/browser/language/language_model_manager_factory.h"
20 #include "chrome/browser/language/url_language_histogram_factory.h"
21 #include "chrome/browser/profiles/profile.h"
22 #include "chrome/browser/translate/translate_accept_languages_factory.h"
23 #include "chrome/browser/translate/translate_ranker_factory.h"
24 #include "chrome/browser/translate/translate_service.h"
25 #include "chrome/browser/ui/translate/translate_bubble_factory.h"
26 #include "chrome/common/chrome_paths.h"
27 #include "chrome/common/pref_names.h"
28 #include "chrome/grit/theme_resources.h"
29 #include "components/autofill_assistant/browser/public/runtime_manager.h"
30 #include "components/language/core/browser/language_model_manager.h"
31 #include "components/language/core/browser/pref_names.h"
32 #include "components/prefs/pref_service.h"
33 #include "components/translate/core/browser/language_state.h"
34 #include "components/translate/core/browser/page_translated_details.h"
35 #include "components/translate/core/browser/translate_accept_languages.h"
36 #include "components/translate/core/browser/translate_browser_metrics.h"
37 #include "components/translate/core/browser/translate_download_manager.h"
38 #include "components/translate/core/browser/translate_infobar_delegate.h"
39 #include "components/translate/core/browser/translate_manager.h"
40 #include "components/translate/core/browser/translate_metrics_logger.h"
41 #include "components/translate/core/browser/translate_prefs.h"
42 #include "components/translate/core/common/language_detection_details.h"
43 #include "components/translate/core/common/translate_util.h"
44 #include "components/variations/service/variations_service.h"
45 #include "content/public/browser/navigation_entry.h"
46 #include "content/public/browser/notification_service.h"
47 #include "content/public/browser/web_contents.h"
48 #include "third_party/metrics_proto/translate_event.pb.h"
49 #include "ui/base/ui_base_features.h"
50 #include "url/gurl.h"
51
52 #if defined(OS_ANDROID)
53 #include "chrome/browser/android/android_theme_resources.h"
54 #else
55 #include "chrome/browser/ui/browser.h"
56 #include "chrome/browser/ui/browser_finder.h"
57 #include "chrome/browser/ui/browser_tabstrip.h"
58 #include "chrome/browser/ui/browser_window.h"
59 #include "chrome/browser/ui/tabs/tab_strip_model.h"
60 #endif
61
62 namespace {
63 using base::FeatureList;
64 using metrics::TranslateEventProto;
65
66 #if !defined(OS_ANDROID)
BubbleResultToTranslateEvent(ShowTranslateBubbleResult result)67 TranslateEventProto::EventType BubbleResultToTranslateEvent(
68 ShowTranslateBubbleResult result) {
69 switch (result) {
70 case ShowTranslateBubbleResult::BROWSER_WINDOW_NOT_VALID:
71 return TranslateEventProto::BROWSER_WINDOW_IS_INVALID;
72 case ShowTranslateBubbleResult::BROWSER_WINDOW_MINIMIZED:
73 return TranslateEventProto::BROWSER_WINDOW_IS_MINIMIZED;
74 case ShowTranslateBubbleResult::BROWSER_WINDOW_NOT_ACTIVE:
75 return TranslateEventProto::BROWSER_WINDOW_NOT_ACTIVE;
76 case ShowTranslateBubbleResult::WEB_CONTENTS_NOT_ACTIVE:
77 return TranslateEventProto::WEB_CONTENTS_NOT_ACTIVE;
78 case ShowTranslateBubbleResult::EDITABLE_FIELD_IS_ACTIVE:
79 return TranslateEventProto::EDITABLE_FIELD_IS_ACTIVE;
80 default:
81 NOTREACHED();
82 return metrics::TranslateEventProto::UNKNOWN;
83 }
84 }
85 #endif
86
87 } // namespace
88
ChromeTranslateClient(content::WebContents * web_contents)89 ChromeTranslateClient::ChromeTranslateClient(content::WebContents* web_contents)
90 : content::WebContentsObserver(web_contents) {
91 if (translate::IsSubFrameTranslationEnabled()) {
92 per_frame_translate_driver_ =
93 std::make_unique<translate::PerFrameContentTranslateDriver>(
94 &web_contents->GetController(),
95 UrlLanguageHistogramFactory::GetForBrowserContext(
96 web_contents->GetBrowserContext()));
97 } else {
98 translate_driver_ = std::make_unique<translate::ContentTranslateDriver>(
99 &web_contents->GetController(),
100 UrlLanguageHistogramFactory::GetForBrowserContext(
101 web_contents->GetBrowserContext()));
102 }
103 translate_manager_ = std::make_unique<translate::TranslateManager>(
104 this,
105 translate::TranslateRankerFactory::GetForBrowserContext(
106 web_contents->GetBrowserContext()),
107 LanguageModelManagerFactory::GetForBrowserContext(
108 web_contents->GetBrowserContext())
109 ->GetPrimaryModel());
110 if (translate_driver_) {
111 translate_driver_->AddObserver(this);
112 translate_driver_->set_translate_manager(translate_manager_.get());
113 }
114 if (per_frame_translate_driver_) {
115 per_frame_translate_driver_->AddObserver(this);
116 per_frame_translate_driver_->set_translate_manager(
117 translate_manager_.get());
118 }
119
120 auto* assistant_runtime_manager =
121 autofill_assistant::RuntimeManager::GetOrCreateForWebContents(
122 web_contents);
123 assistant_runtime_manager->AddObserver(this);
124 }
125
~ChromeTranslateClient()126 ChromeTranslateClient::~ChromeTranslateClient() {
127 if (translate_driver_) {
128 translate_driver_->RemoveObserver(this);
129 translate_driver_->set_translate_manager(nullptr);
130 }
131 if (per_frame_translate_driver_) {
132 per_frame_translate_driver_->RemoveObserver(this);
133 per_frame_translate_driver_->set_translate_manager(nullptr);
134 }
135 }
136
GetLanguageState()137 const translate::LanguageState& ChromeTranslateClient::GetLanguageState() {
138 return *translate_manager_->GetLanguageState();
139 }
140
translate_driver()141 translate::ContentTranslateDriver* ChromeTranslateClient::translate_driver() {
142 if (translate_driver_) {
143 DCHECK(!translate::IsSubFrameTranslationEnabled());
144 return translate_driver_.get();
145 }
146
147 return per_frame_translate_driver();
148 }
149
150 translate::PerFrameContentTranslateDriver*
per_frame_translate_driver()151 ChromeTranslateClient::per_frame_translate_driver() {
152 DCHECK(translate::IsSubFrameTranslationEnabled());
153 return per_frame_translate_driver_.get();
154 }
155
156 // static
157 std::unique_ptr<translate::TranslatePrefs>
CreateTranslatePrefs(PrefService * prefs)158 ChromeTranslateClient::CreateTranslatePrefs(PrefService* prefs) {
159 #if defined(OS_CHROMEOS)
160 const char* preferred_languages_prefs = language::prefs::kPreferredLanguages;
161 #else
162 const char* preferred_languages_prefs = NULL;
163 #endif
164 std::unique_ptr<translate::TranslatePrefs> translate_prefs(
165 new translate::TranslatePrefs(prefs, language::prefs::kAcceptLanguages,
166 preferred_languages_prefs));
167
168 // We need to obtain the country here, since it comes from VariationsService.
169 // components/ does not have access to that.
170 DCHECK(g_browser_process);
171 variations::VariationsService* variations_service =
172 g_browser_process->variations_service();
173 if (variations_service) {
174 translate_prefs->SetCountry(
175 variations_service->GetStoredPermanentCountry());
176 }
177
178 return translate_prefs;
179 }
180
181 // static
182 translate::TranslateAcceptLanguages*
GetTranslateAcceptLanguages(content::BrowserContext * browser_context)183 ChromeTranslateClient::GetTranslateAcceptLanguages(
184 content::BrowserContext* browser_context) {
185 return TranslateAcceptLanguagesFactory::GetForBrowserContext(browser_context);
186 }
187
188 // static
GetManagerFromWebContents(content::WebContents * web_contents)189 translate::TranslateManager* ChromeTranslateClient::GetManagerFromWebContents(
190 content::WebContents* web_contents) {
191 ChromeTranslateClient* chrome_translate_client =
192 FromWebContents(web_contents);
193 if (!chrome_translate_client)
194 return NULL;
195 return chrome_translate_client->GetTranslateManager();
196 }
197
GetTranslateLanguages(content::WebContents * web_contents,std::string * source,std::string * target)198 void ChromeTranslateClient::GetTranslateLanguages(
199 content::WebContents* web_contents,
200 std::string* source,
201 std::string* target) {
202 DCHECK(source != NULL);
203 DCHECK(target != NULL);
204
205 *source = translate::TranslateDownloadManager::GetLanguageCode(
206 GetLanguageState().original_language());
207
208 Profile* profile =
209 Profile::FromBrowserContext(web_contents->GetBrowserContext());
210 std::unique_ptr<translate::TranslatePrefs> translate_prefs =
211 CreateTranslatePrefs(profile->GetPrefs());
212 if (!profile->IsOffTheRecord()) {
213 std::string auto_translate_language =
214 translate::TranslateManager::GetAutoTargetLanguage(
215 *source, translate_prefs.get());
216 if (!auto_translate_language.empty()) {
217 *target = auto_translate_language;
218 return;
219 }
220 }
221
222 *target = translate::TranslateManager::GetTargetLanguage(
223 translate_prefs.get(), LanguageModelManagerFactory::GetInstance()
224 ->GetForBrowserContext(profile)
225 ->GetPrimaryModel());
226 }
227
GetTranslateManager()228 translate::TranslateManager* ChromeTranslateClient::GetTranslateManager() {
229 return translate_manager_.get();
230 }
231
ShowTranslateUI(translate::TranslateStep step,const std::string & source_language,const std::string & target_language,translate::TranslateErrors::Type error_type,bool triggered_from_menu)232 bool ChromeTranslateClient::ShowTranslateUI(
233 translate::TranslateStep step,
234 const std::string& source_language,
235 const std::string& target_language,
236 translate::TranslateErrors::Type error_type,
237 bool triggered_from_menu) {
238 DCHECK(web_contents());
239 DCHECK(translate_manager_);
240
241 if (error_type != translate::TranslateErrors::NONE)
242 step = translate::TRANSLATE_STEP_TRANSLATE_ERROR;
243
244 // Translate uses a bubble UI on desktop and an infobar on Android (here)
245 // and iOS (in ios/chrome/browser/translate/chrome_ios_translate_client.mm).
246 #if defined(OS_ANDROID)
247 // Infobar UI.
248 DCHECK(!TranslateService::IsTranslateBubbleEnabled());
249 translate::TranslateInfoBarDelegate::Create(
250 step != translate::TRANSLATE_STEP_BEFORE_TRANSLATE,
251 translate_manager_->GetWeakPtr(),
252 InfoBarService::FromWebContents(web_contents()),
253 web_contents()->GetBrowserContext()->IsOffTheRecord(), step,
254 source_language, target_language, error_type, triggered_from_menu);
255
256 translate_manager_->GetActiveTranslateMetricsLogger()->LogUIChange(true);
257 #else
258 DCHECK(TranslateService::IsTranslateBubbleEnabled());
259 // Bubble UI.
260 if (step == translate::TRANSLATE_STEP_BEFORE_TRANSLATE &&
261 translate_manager_->ShouldSuppressBubbleUI(triggered_from_menu,
262 source_language)) {
263 return false;
264 }
265
266 ShowTranslateBubbleResult result =
267 ShowBubble(step, source_language, target_language, error_type);
268 if (result != ShowTranslateBubbleResult::SUCCESS &&
269 step == translate::TRANSLATE_STEP_BEFORE_TRANSLATE) {
270 translate_manager_->RecordTranslateEvent(
271 BubbleResultToTranslateEvent(result));
272 }
273 #endif
274
275 return true;
276 }
277
GetTranslateDriver()278 translate::TranslateDriver* ChromeTranslateClient::GetTranslateDriver() {
279 return translate_driver();
280 }
281
GetPrefs()282 PrefService* ChromeTranslateClient::GetPrefs() {
283 DCHECK(web_contents());
284 Profile* profile =
285 Profile::FromBrowserContext(web_contents()->GetBrowserContext());
286 return profile->GetPrefs();
287 }
288
289 std::unique_ptr<translate::TranslatePrefs>
GetTranslatePrefs()290 ChromeTranslateClient::GetTranslatePrefs() {
291 return CreateTranslatePrefs(GetPrefs());
292 }
293
294 translate::TranslateAcceptLanguages*
GetTranslateAcceptLanguages()295 ChromeTranslateClient::GetTranslateAcceptLanguages() {
296 DCHECK(web_contents());
297 return GetTranslateAcceptLanguages(web_contents()->GetBrowserContext());
298 }
299
300 #if defined(OS_ANDROID)
GetInfobarIconID() const301 int ChromeTranslateClient::GetInfobarIconID() const {
302 return IDR_ANDROID_INFOBAR_TRANSLATE;
303 }
304
ManualTranslateWhenReady()305 void ChromeTranslateClient::ManualTranslateWhenReady() {
306 if (GetLanguageState().original_language().empty()) {
307 manual_translate_on_ready_ = true;
308 } else {
309 translate::TranslateManager* manager = GetTranslateManager();
310 manager->InitiateManualTranslation(true);
311 }
312 }
313 #endif
314
SetPredefinedTargetLanguage(const std::string & translate_language_code)315 void ChromeTranslateClient::SetPredefinedTargetLanguage(
316 const std::string& translate_language_code) {
317 translate::TranslateManager* manager = GetTranslateManager();
318 manager->SetPredefinedTargetLanguage(translate_language_code);
319 }
320
IsTranslatableURL(const GURL & url)321 bool ChromeTranslateClient::IsTranslatableURL(const GURL& url) {
322 return TranslateService::IsTranslatableURL(url);
323 }
324
IsAutofillAssistantRunning() const325 bool ChromeTranslateClient::IsAutofillAssistantRunning() const {
326 auto* assistant_runtime_manager =
327 autofill_assistant::RuntimeManager::GetForWebContents(web_contents());
328 return assistant_runtime_manager && assistant_runtime_manager->GetState() ==
329 autofill_assistant::UIState::kShown;
330 }
331
OnStateChanged(autofill_assistant::UIState state)332 void ChromeTranslateClient::OnStateChanged(autofill_assistant::UIState state) {
333 if (state == autofill_assistant::UIState::kNotShown) {
334 GetTranslateManager()->OnAutofillAssistantFinished();
335 }
336 }
337
ShowReportLanguageDetectionErrorUI(const GURL & report_url)338 void ChromeTranslateClient::ShowReportLanguageDetectionErrorUI(
339 const GURL& report_url) {
340 #if defined(OS_ANDROID)
341 // Android does not support reporting language detection errors.
342 NOTREACHED();
343 #else
344 // We'll open the URL in a new tab so that the user can tell us more.
345 Browser* browser = chrome::FindBrowserWithWebContents(web_contents());
346 if (!browser) {
347 NOTREACHED();
348 return;
349 }
350
351 chrome::AddSelectedTabWithURL(browser, report_url,
352 ui::PAGE_TRANSITION_AUTO_BOOKMARK);
353 #endif // defined(OS_ANDROID)
354 }
355
WebContentsDestroyed()356 void ChromeTranslateClient::WebContentsDestroyed() {
357 // Translation process can be interrupted.
358 // Destroying the TranslateManager now guarantees that it never has to deal
359 // with NULL WebContents.
360 translate_manager_.reset();
361
362 auto* assistant_runtime_manager =
363 autofill_assistant::RuntimeManager::GetForWebContents(web_contents());
364 if (assistant_runtime_manager) {
365 assistant_runtime_manager->RemoveObserver(this);
366 }
367 }
368
369 // ContentTranslateDriver::Observer implementation.
370
OnLanguageDetermined(const translate::LanguageDetectionDetails & details)371 void ChromeTranslateClient::OnLanguageDetermined(
372 const translate::LanguageDetectionDetails& details) {
373 translate::TranslateBrowserMetrics::ReportLanguageDetectionContentLength(
374 details.contents.size());
375
376 // TODO(268984): Remove translate notifications and have the clients be
377 // ContentTranslateDriver::Observer directly instead.
378 content::NotificationService::current()->Notify(
379 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
380 content::Source<content::WebContents>(web_contents()),
381 content::Details<const translate::LanguageDetectionDetails>(&details));
382
383 #if defined(OS_ANDROID)
384 // See ChromeTranslateClient::ManualTranslateOnReady
385 if (manual_translate_on_ready_) {
386 GetTranslateManager()->InitiateManualTranslation(true);
387 manual_translate_on_ready_ = false;
388 }
389 #endif
390 }
391
392 // The bubble is implemented only on the desktop platforms.
393 #if !defined(OS_ANDROID)
ShowBubble(translate::TranslateStep step,const std::string & source_language,const std::string & target_language,translate::TranslateErrors::Type error_type)394 ShowTranslateBubbleResult ChromeTranslateClient::ShowBubble(
395 translate::TranslateStep step,
396 const std::string& source_language,
397 const std::string& target_language,
398 translate::TranslateErrors::Type error_type) {
399 DCHECK(translate_manager_);
400 Browser* browser = chrome::FindBrowserWithWebContents(web_contents());
401
402 // |browser| might be NULL when testing. In this case, Show(...) should be
403 // called because the implementation for testing is used.
404 if (!browser) {
405 return TranslateBubbleFactory::Show(NULL, web_contents(), step,
406 source_language, target_language,
407 error_type);
408 }
409
410 if (web_contents() != browser->tab_strip_model()->GetActiveWebContents())
411 return ShowTranslateBubbleResult::WEB_CONTENTS_NOT_ACTIVE;
412
413 // This ShowBubble function is also used for updating the existing bubble.
414 // However, with the bubble shown, any browser windows are NOT activated
415 // because the bubble takes the focus from the other widgets including the
416 // browser windows. So it is checked that |browser| is the last activated
417 // browser, not is now activated.
418 if (browser != chrome::FindLastActive())
419 return ShowTranslateBubbleResult::BROWSER_WINDOW_NOT_ACTIVE;
420
421 // During auto-translating, the bubble should not be shown.
422 if (step == translate::TRANSLATE_STEP_TRANSLATING ||
423 step == translate::TRANSLATE_STEP_AFTER_TRANSLATE) {
424 if (GetLanguageState().InTranslateNavigation())
425 return ShowTranslateBubbleResult::SUCCESS;
426 }
427
428 return TranslateBubbleFactory::Show(browser->window(), web_contents(), step,
429 source_language, target_language,
430 error_type);
431 }
432 #endif
433
434 WEB_CONTENTS_USER_DATA_KEY_IMPL(ChromeTranslateClient)
435