1 // Copyright 2011 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 "chrome/browser/translate/translate_tab_helper.h"
7 #include "base/logging.h"
8 #include "base/prefs/pref_service.h"
9 #include "base/strings/string_split.h"
10 #include "chrome/browser/chrome_notification_types.h"
11 #include "chrome/browser/profiles/profile.h"
12 #include "chrome/browser/translate/translate_accept_languages_factory.h"
13 #include "chrome/browser/translate/translate_infobar_delegate.h"
14 #include "chrome/browser/translate/translate_service.h"
15 #include "chrome/browser/ui/browser.h"
16 #include "chrome/browser/ui/browser_finder.h"
17 #include "chrome/browser/ui/browser_tabstrip.h"
18 #include "chrome/browser/ui/browser_window.h"
19 #include "chrome/browser/ui/tabs/tab_strip_model.h"
20 #include "chrome/browser/ui/translate/translate_bubble_factory.h"
21 #include "chrome/common/pref_names.h"
22 #include "components/translate/content/common/translate_messages.h"
23 #include "components/translate/core/browser/page_translated_details.h"
24 #include "components/translate/core/browser/translate_accept_languages.h"
25 #include "components/translate/core/browser/translate_download_manager.h"
26 #include "components/translate/core/browser/translate_manager.h"
27 #include "components/translate/core/browser/translate_prefs.h"
28 #include "components/translate/core/common/language_detection_details.h"
29 #include "content/public/browser/navigation_details.h"
30 #include "content/public/browser/navigation_entry.h"
31 #include "content/public/browser/notification_service.h"
32 #include "content/public/browser/render_view_host.h"
33 #include "content/public/browser/web_contents.h"
34 #include "net/http/http_status_code.h"
37 #if defined(CLD2_DYNAMIC_MODE)
38 #include "base/files/file.h"
39 #include "base/path_service.h"
40 #include "chrome/common/chrome_constants.h"
41 #include "chrome/common/chrome_paths.h"
42 #include "content/public/browser/browser_thread.h"
43 #include "content/public/browser/render_process_host.h"
44 #include "content/public/browser/render_view_host.h"
47 #if defined(CLD2_IS_COMPONENT)
48 #include "chrome/browser/component_updater/cld_component_installer.h"
53 // The maximum number of attempts we'll do to see if the page has finshed
54 // loading before giving up the translation
55 const int kMaxTranslateLoadCheckAttempts = 20;
59 DEFINE_WEB_CONTENTS_USER_DATA_KEY(TranslateTabHelper);
61 #if defined(CLD2_DYNAMIC_MODE)
62 // Statics defined in the .h file:
63 base::File* TranslateTabHelper::s_cached_file_ = NULL;
64 uint64 TranslateTabHelper::s_cached_data_offset_ = 0;
65 uint64 TranslateTabHelper::s_cached_data_length_ = 0;
66 base::LazyInstance<base::Lock> TranslateTabHelper::s_file_lock_ =
67 LAZY_INSTANCE_INITIALIZER;
70 TranslateTabHelper::TranslateTabHelper(content::WebContents* web_contents)
71 : content::WebContentsObserver(web_contents),
72 max_reload_check_attempts_(kMaxTranslateLoadCheckAttempts),
73 translate_driver_(&web_contents->GetController()),
74 translate_manager_(new TranslateManager(this, prefs::kAcceptLanguages)),
75 weak_pointer_factory_(this) {}
77 TranslateTabHelper::~TranslateTabHelper() {
80 LanguageState& TranslateTabHelper::GetLanguageState() {
81 return translate_driver_.GetLanguageState();
85 scoped_ptr<TranslatePrefs> TranslateTabHelper::CreateTranslatePrefs(
87 #if defined(OS_CHROMEOS)
88 const char* preferred_languages_prefs = prefs::kLanguagePreferredLanguages;
90 const char* preferred_languages_prefs = NULL;
92 return scoped_ptr<TranslatePrefs>(new TranslatePrefs(
93 prefs, prefs::kAcceptLanguages, preferred_languages_prefs));
97 TranslateAcceptLanguages* TranslateTabHelper::GetTranslateAcceptLanguages(
98 content::BrowserContext* browser_context) {
99 return TranslateAcceptLanguagesFactory::GetForBrowserContext(browser_context);
103 TranslateManager* TranslateTabHelper::GetManagerFromWebContents(
104 content::WebContents* web_contents) {
105 TranslateTabHelper* translate_tab_helper = FromWebContents(web_contents);
106 if (!translate_tab_helper)
108 return translate_tab_helper->GetTranslateManager();
112 void TranslateTabHelper::GetTranslateLanguages(
113 content::WebContents* web_contents,
115 std::string* target) {
116 DCHECK(source != NULL);
117 DCHECK(target != NULL);
119 TranslateTabHelper* translate_tab_helper = FromWebContents(web_contents);
120 if (!translate_tab_helper)
123 *source = translate_tab_helper->GetLanguageState().original_language();
126 Profile::FromBrowserContext(web_contents->GetBrowserContext());
127 Profile* original_profile = profile->GetOriginalProfile();
128 PrefService* prefs = original_profile->GetPrefs();
129 scoped_ptr<TranslatePrefs> translate_prefs = CreateTranslatePrefs(prefs);
130 if (!web_contents->GetBrowserContext()->IsOffTheRecord()) {
131 std::string auto_translate_language =
132 TranslateManager::GetAutoTargetLanguage(*source, translate_prefs.get());
133 if (!auto_translate_language.empty()) {
134 *target = auto_translate_language;
139 std::string accept_languages_str = prefs->GetString(prefs::kAcceptLanguages);
140 std::vector<std::string> accept_languages_list;
141 base::SplitString(accept_languages_str, ',', &accept_languages_list);
142 *target = TranslateManager::GetTargetLanguage(accept_languages_list);
145 TranslateManager* TranslateTabHelper::GetTranslateManager() {
146 return translate_manager_.get();
149 content::WebContents* TranslateTabHelper::GetWebContents() {
150 return web_contents();
153 void TranslateTabHelper::ShowTranslateUI(translate::TranslateStep step,
154 const std::string source_language,
155 const std::string target_language,
156 TranslateErrors::Type error_type,
157 bool triggered_from_menu) {
158 DCHECK(web_contents());
159 if (error_type != TranslateErrors::NONE)
160 step = translate::TRANSLATE_STEP_TRANSLATE_ERROR;
162 if (TranslateService::IsTranslateBubbleEnabled()) {
164 if (step == translate::TRANSLATE_STEP_BEFORE_TRANSLATE) {
165 // TODO: Move this logic out of UI code.
166 GetLanguageState().SetTranslateEnabled(true);
167 if (!GetLanguageState().HasLanguageChanged())
170 ShowBubble(step, error_type);
176 Profile::FromBrowserContext(web_contents()->GetBrowserContext());
177 Profile* original_profile = profile->GetOriginalProfile();
178 TranslateInfoBarDelegate::Create(
179 step != translate::TRANSLATE_STEP_BEFORE_TRANSLATE,
185 original_profile->GetPrefs(),
186 triggered_from_menu);
189 TranslateDriver* TranslateTabHelper::GetTranslateDriver() {
190 return &translate_driver_;
193 PrefService* TranslateTabHelper::GetPrefs() {
194 DCHECK(web_contents());
196 Profile::FromBrowserContext(web_contents()->GetBrowserContext());
197 return profile->GetOriginalProfile()->GetPrefs();
200 scoped_ptr<TranslatePrefs> TranslateTabHelper::GetTranslatePrefs() {
201 DCHECK(web_contents());
203 Profile::FromBrowserContext(web_contents()->GetBrowserContext());
204 return CreateTranslatePrefs(profile->GetPrefs());
207 TranslateAcceptLanguages* TranslateTabHelper::GetTranslateAcceptLanguages() {
208 DCHECK(web_contents());
209 return GetTranslateAcceptLanguages(web_contents()->GetBrowserContext());
212 bool TranslateTabHelper::IsTranslatableURL(const GURL& url) {
213 return TranslateService::IsTranslatableURL(url);
216 void TranslateTabHelper::ShowReportLanguageDetectionErrorUI(
217 const GURL& report_url) {
218 #if defined(OS_ANDROID)
219 // Android does not support reporting language detection errors.
222 // We'll open the URL in a new tab so that the user can tell us more.
223 Browser* browser = chrome::FindBrowserWithWebContents(web_contents());
229 chrome::AddSelectedTabWithURL(
230 browser, report_url, content::PAGE_TRANSITION_AUTO_BOOKMARK);
231 #endif // defined(OS_ANDROID)
234 bool TranslateTabHelper::OnMessageReceived(const IPC::Message& message) {
236 IPC_BEGIN_MESSAGE_MAP(TranslateTabHelper, message)
237 IPC_MESSAGE_HANDLER(ChromeViewHostMsg_TranslateLanguageDetermined,
238 OnLanguageDetermined)
239 IPC_MESSAGE_HANDLER(ChromeViewHostMsg_PageTranslated, OnPageTranslated)
240 #if defined(CLD2_DYNAMIC_MODE)
241 IPC_MESSAGE_HANDLER(ChromeViewHostMsg_NeedCLDData, OnCLDDataRequested)
243 IPC_MESSAGE_UNHANDLED(handled = false)
244 IPC_END_MESSAGE_MAP()
249 void TranslateTabHelper::NavigationEntryCommitted(
250 const content::LoadCommittedDetails& load_details) {
251 // Check whether this is a reload: When doing a page reload, the
252 // TranslateLanguageDetermined IPC is not sent so the translation needs to be
253 // explicitly initiated.
255 content::NavigationEntry* entry =
256 web_contents()->GetController().GetActiveEntry();
262 // If the navigation happened while offline don't show the translate
263 // bar since there will be nothing to translate.
264 if (load_details.http_status_code == 0 ||
265 load_details.http_status_code == net::HTTP_INTERNAL_SERVER_ERROR) {
269 if (!load_details.is_main_frame &&
270 translate_driver_.GetLanguageState().translation_declined()) {
271 // Some sites (such as Google map) may trigger sub-frame navigations
272 // when the user interacts with the page. We don't want to show a new
273 // infobar if the user already dismissed one in that case.
277 // If not a reload, return.
278 if (entry->GetTransitionType() != content::PAGE_TRANSITION_RELOAD &&
279 load_details.type != content::NAVIGATION_TYPE_SAME_PAGE) {
283 if (!translate_driver_.GetLanguageState().page_needs_translation())
286 // Note that we delay it as the ordering of the processing of this callback
287 // by WebContentsObservers is undefined and might result in the current
288 // infobars being removed. Since the translation initiation process might add
289 // an infobar, it must be done after that.
290 base::MessageLoop::current()->PostTask(
292 base::Bind(&TranslateTabHelper::InitiateTranslation,
293 weak_pointer_factory_.GetWeakPtr(),
294 translate_driver_.GetLanguageState().original_language(),
298 void TranslateTabHelper::DidNavigateAnyFrame(
299 const content::LoadCommittedDetails& details,
300 const content::FrameNavigateParams& params) {
301 // Let the LanguageState clear its state.
302 translate_driver_.DidNavigate(details);
305 void TranslateTabHelper::WebContentsDestroyed() {
306 // Translation process can be interrupted.
307 // Destroying the TranslateManager now guarantees that it never has to deal
308 // with NULL WebContents.
309 translate_manager_.reset();
312 #if defined(CLD2_DYNAMIC_MODE)
313 void TranslateTabHelper::OnCLDDataRequested() {
314 // Quickly try to read s_cached_file_. If valid, the file handle is
315 // cached and can be used immediately. Else, queue the caching task to the
317 base::File* handle = NULL;
318 uint64 data_offset = 0;
319 uint64 data_length = 0;
321 base::AutoLock lock(s_file_lock_.Get());
322 handle = s_cached_file_;
323 data_offset = s_cached_data_offset_;
324 data_length = s_cached_data_length_;
327 if (handle && handle->IsValid()) {
328 // Cached data available. Respond to the request.
329 SendCLDDataAvailable(handle, data_offset, data_length);
333 // Else, we don't have the data file yet. Queue a caching attempt.
334 // The caching attempt happens in the blocking pool because it may involve
335 // arbitrary filesystem access.
336 // After the caching attempt is made, we call MaybeSendCLDDataAvailable
337 // to pass the file handle to the renderer. This only results in an IPC
338 // message if the caching attempt was successful.
339 content::BrowserThread::PostBlockingPoolTaskAndReply(
341 base::Bind(&TranslateTabHelper::HandleCLDDataRequest),
342 base::Bind(&TranslateTabHelper::MaybeSendCLDDataAvailable,
343 weak_pointer_factory_.GetWeakPtr()));
346 void TranslateTabHelper::MaybeSendCLDDataAvailable() {
347 base::File* handle = NULL;
348 uint64 data_offset = 0;
349 uint64 data_length = 0;
351 base::AutoLock lock(s_file_lock_.Get());
352 handle = s_cached_file_;
353 data_offset = s_cached_data_offset_;
354 data_length = s_cached_data_length_;
357 if (handle && handle->IsValid())
358 SendCLDDataAvailable(handle, data_offset, data_length);
361 void TranslateTabHelper::SendCLDDataAvailable(const base::File* handle,
362 const uint64 data_offset,
363 const uint64 data_length) {
364 // Data available, respond to the request.
365 IPC::PlatformFileForTransit ipc_platform_file =
366 IPC::GetFileHandleForProcess(
367 handle->GetPlatformFile(),
368 GetWebContents()->GetRenderViewHost()->GetProcess()->GetHandle(),
370 // In general, sending a response from within the code path that is processing
371 // a request is discouraged because there is potential for deadlock (if the
372 // methods are sent synchronously) or loops (if the response can trigger a
373 // new request). Neither of these concerns is relevant in this code, so
374 // sending the response from within the code path of the request handler is
376 Send(new ChromeViewMsg_CLDDataAvailable(
377 GetWebContents()->GetRenderViewHost()->GetRoutingID(),
378 ipc_platform_file, data_offset, data_length));
381 void TranslateTabHelper::HandleCLDDataRequest() {
382 // Because this function involves arbitrary file system access, it must run
383 // on the blocking pool.
384 DCHECK(!content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
385 DCHECK(!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
388 base::AutoLock lock(s_file_lock_.Get());
390 return; // Already done, duplicate request
394 #if defined(CLD2_IS_COMPONENT)
395 if (!component_updater::GetLatestCldDataFile(&path))
398 if (!PathService::Get(chrome::DIR_USER_DATA, &path)) {
399 LOG(WARNING) << "Unable to locate user data directory";
400 return; // Chrome isn't properly installed.
402 // If the file exists, we can send an IPC-safe construct back to the
403 // renderer process immediately.
404 path = path.Append(chrome::kCLDDataFilename);
405 if (!base::PathExists(path))
409 // Attempt to open the file for reading.
410 scoped_ptr<base::File> file(
411 new base::File(path, base::File::FLAG_OPEN | base::File::FLAG_READ));
412 if (!file->IsValid()) {
413 LOG(WARNING) << "CLD data file exists but cannot be opened";
417 base::File::Info file_info;
418 if (!file->GetInfo(&file_info)) {
419 LOG(WARNING) << "CLD data file exists but cannot be inspected";
423 // For now, our offset and length are simply 0 and the length of the file,
424 // respectively. If we later decide to include the CLD2 data file inside of
425 // a larger binary context, these params can be twiddled appropriately.
426 const uint64 data_offset = 0;
427 const uint64 data_length = file_info.size;
430 base::AutoLock lock(s_file_lock_.Get());
431 if (s_cached_file_) {
432 // Idempotence: Racing another request on the blocking pool, abort.
434 // Else, this request has taken care of it all. Cache all info.
435 s_cached_file_ = file.release();
436 s_cached_data_offset_ = data_offset;
437 s_cached_data_length_ = data_length;
441 #endif // defined(CLD2_DYNAMIC_MODE)
443 void TranslateTabHelper::InitiateTranslation(const std::string& page_lang,
445 if (translate_driver_.GetLanguageState().translation_pending())
448 // During a reload we need web content to be available before the
449 // translate script is executed. Otherwise we will run the translate script on
450 // an empty DOM which will fail. Therefore we wait a bit to see if the page
452 if (web_contents()->IsLoading() && attempt < max_reload_check_attempts_) {
453 int backoff = attempt * kMaxTranslateLoadCheckAttempts;
454 base::MessageLoop::current()->PostDelayedTask(
456 base::Bind(&TranslateTabHelper::InitiateTranslation,
457 weak_pointer_factory_.GetWeakPtr(),
460 base::TimeDelta::FromMilliseconds(backoff));
464 translate_manager_->InitiateTranslation(
465 TranslateDownloadManager::GetLanguageCode(page_lang));
468 void TranslateTabHelper::OnLanguageDetermined(
469 const LanguageDetectionDetails& details,
470 bool page_needs_translation) {
471 translate_driver_.GetLanguageState().LanguageDetermined(
472 details.adopted_language, page_needs_translation);
475 translate_manager_->InitiateTranslation(details.adopted_language);
477 content::NotificationService::current()->Notify(
478 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
479 content::Source<content::WebContents>(web_contents()),
480 content::Details<const LanguageDetectionDetails>(&details));
483 void TranslateTabHelper::OnPageTranslated(int32 page_id,
484 const std::string& original_lang,
485 const std::string& translated_lang,
486 TranslateErrors::Type error_type) {
487 DCHECK(web_contents());
488 translate_manager_->PageTranslated(
489 original_lang, translated_lang, error_type);
491 PageTranslatedDetails details;
492 details.source_language = original_lang;
493 details.target_language = translated_lang;
494 details.error_type = error_type;
495 content::NotificationService::current()->Notify(
496 chrome::NOTIFICATION_PAGE_TRANSLATED,
497 content::Source<content::WebContents>(web_contents()),
498 content::Details<PageTranslatedDetails>(&details));
501 void TranslateTabHelper::ShowBubble(translate::TranslateStep step,
502 TranslateErrors::Type error_type) {
503 // The bubble is implemented only on the desktop platforms.
504 #if !defined(OS_ANDROID) && !defined(OS_IOS)
505 Browser* browser = chrome::FindBrowserWithWebContents(web_contents());
507 // |browser| might be NULL when testing. In this case, Show(...) should be
508 // called because the implementation for testing is used.
510 TranslateBubbleFactory::Show(NULL, web_contents(), step, error_type);
514 if (web_contents() != browser->tab_strip_model()->GetActiveWebContents())
517 content::RenderViewHost* rvh = web_contents()->GetRenderViewHost();
518 if (rvh->IsFocusedElementEditable())
521 // This ShowBubble function is also used for upating the existing bubble.
522 // However, with the bubble shown, any browser windows are NOT activated
523 // because the bubble takes the focus from the other widgets including the
524 // browser windows. So it is checked that |browser| is the last activated
525 // browser, not is now activated.
527 chrome::FindLastActiveWithHostDesktopType(browser->host_desktop_type())) {
531 // During auto-translating, the bubble should not be shown.
532 if (step == translate::TRANSLATE_STEP_TRANSLATING ||
533 step == translate::TRANSLATE_STEP_AFTER_TRANSLATE) {
534 if (GetLanguageState().InTranslateNavigation())
538 TranslateBubbleFactory::Show(
539 browser->window(), web_contents(), step, error_type);