Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / translate / translate_tab_helper.cc
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.
4
5 #include "chrome/browser/translate/translate_tab_helper.h"
6
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"
35 #include "url/gurl.h"
36
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"
45 #endif
46
47 #if defined(CLD2_IS_COMPONENT)
48 #include "chrome/browser/component_updater/cld_component_installer.h"
49 #endif
50
51 namespace {
52
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;
56
57 }  // namespace
58
59 DEFINE_WEB_CONTENTS_USER_DATA_KEY(TranslateTabHelper);
60
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;
68 #endif
69
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) {}
76
77 TranslateTabHelper::~TranslateTabHelper() {
78 }
79
80 LanguageState& TranslateTabHelper::GetLanguageState() {
81   return translate_driver_.GetLanguageState();
82 }
83
84 // static
85 scoped_ptr<TranslatePrefs> TranslateTabHelper::CreateTranslatePrefs(
86     PrefService* prefs) {
87 #if defined(OS_CHROMEOS)
88   const char* preferred_languages_prefs = prefs::kLanguagePreferredLanguages;
89 #else
90   const char* preferred_languages_prefs = NULL;
91 #endif
92   return scoped_ptr<TranslatePrefs>(new TranslatePrefs(
93       prefs, prefs::kAcceptLanguages, preferred_languages_prefs));
94 }
95
96 // static
97 TranslateAcceptLanguages* TranslateTabHelper::GetTranslateAcceptLanguages(
98     content::BrowserContext* browser_context) {
99   return TranslateAcceptLanguagesFactory::GetForBrowserContext(browser_context);
100 }
101
102 // static
103 TranslateManager* TranslateTabHelper::GetManagerFromWebContents(
104     content::WebContents* web_contents) {
105   TranslateTabHelper* translate_tab_helper = FromWebContents(web_contents);
106   if (!translate_tab_helper)
107     return NULL;
108   return translate_tab_helper->GetTranslateManager();
109 }
110
111 // static
112 void TranslateTabHelper::GetTranslateLanguages(
113     content::WebContents* web_contents,
114     std::string* source,
115     std::string* target) {
116   DCHECK(source != NULL);
117   DCHECK(target != NULL);
118
119   TranslateTabHelper* translate_tab_helper = FromWebContents(web_contents);
120   if (!translate_tab_helper)
121     return;
122
123   *source = translate_tab_helper->GetLanguageState().original_language();
124
125   Profile* profile =
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;
135       return;
136     }
137   }
138
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);
143 }
144
145 TranslateManager* TranslateTabHelper::GetTranslateManager() {
146   return translate_manager_.get();
147 }
148
149 content::WebContents* TranslateTabHelper::GetWebContents() {
150   return web_contents();
151 }
152
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;
161
162   if (TranslateService::IsTranslateBubbleEnabled()) {
163     // Bubble UI.
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())
168         return;
169     }
170     ShowBubble(step, error_type);
171     return;
172   }
173
174   // Infobar UI.
175   Profile* profile =
176       Profile::FromBrowserContext(web_contents()->GetBrowserContext());
177   Profile* original_profile = profile->GetOriginalProfile();
178   TranslateInfoBarDelegate::Create(
179       step != translate::TRANSLATE_STEP_BEFORE_TRANSLATE,
180       web_contents(),
181       step,
182       source_language,
183       target_language,
184       error_type,
185       original_profile->GetPrefs(),
186       triggered_from_menu);
187 }
188
189 TranslateDriver* TranslateTabHelper::GetTranslateDriver() {
190   return &translate_driver_;
191 }
192
193 PrefService* TranslateTabHelper::GetPrefs() {
194   DCHECK(web_contents());
195   Profile* profile =
196       Profile::FromBrowserContext(web_contents()->GetBrowserContext());
197   return profile->GetOriginalProfile()->GetPrefs();
198 }
199
200 scoped_ptr<TranslatePrefs> TranslateTabHelper::GetTranslatePrefs() {
201   DCHECK(web_contents());
202   Profile* profile =
203       Profile::FromBrowserContext(web_contents()->GetBrowserContext());
204   return CreateTranslatePrefs(profile->GetPrefs());
205 }
206
207 TranslateAcceptLanguages* TranslateTabHelper::GetTranslateAcceptLanguages() {
208   DCHECK(web_contents());
209   return GetTranslateAcceptLanguages(web_contents()->GetBrowserContext());
210 }
211
212 bool TranslateTabHelper::IsTranslatableURL(const GURL& url) {
213   return TranslateService::IsTranslatableURL(url);
214 }
215
216 void TranslateTabHelper::ShowReportLanguageDetectionErrorUI(
217     const GURL& report_url) {
218 #if defined(OS_ANDROID)
219   // Android does not support reporting language detection errors.
220   NOTREACHED();
221 #else
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());
224   if (!browser) {
225     NOTREACHED();
226     return;
227   }
228
229   chrome::AddSelectedTabWithURL(
230       browser, report_url, content::PAGE_TRANSITION_AUTO_BOOKMARK);
231 #endif  // defined(OS_ANDROID)
232 }
233
234 bool TranslateTabHelper::OnMessageReceived(const IPC::Message& message) {
235   bool handled = true;
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)
242 #endif
243     IPC_MESSAGE_UNHANDLED(handled = false)
244   IPC_END_MESSAGE_MAP()
245
246   return handled;
247 }
248
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.
254
255   content::NavigationEntry* entry =
256       web_contents()->GetController().GetActiveEntry();
257   if (!entry) {
258     NOTREACHED();
259     return;
260   }
261
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) {
266     return;
267   }
268
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.
274     return;
275   }
276
277   // If not a reload, return.
278   if (entry->GetTransitionType() != content::PAGE_TRANSITION_RELOAD &&
279       load_details.type != content::NAVIGATION_TYPE_SAME_PAGE) {
280     return;
281   }
282
283   if (!translate_driver_.GetLanguageState().page_needs_translation())
284     return;
285
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(
291       FROM_HERE,
292       base::Bind(&TranslateTabHelper::InitiateTranslation,
293                  weak_pointer_factory_.GetWeakPtr(),
294                  translate_driver_.GetLanguageState().original_language(),
295                  0));
296 }
297
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);
303 }
304
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();
310 }
311
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
316   // blocking pool.
317   base::File* handle = NULL;
318   uint64 data_offset = 0;
319   uint64 data_length = 0;
320   {
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_;
325   }
326
327   if (handle && handle->IsValid()) {
328     // Cached data available. Respond to the request.
329     SendCLDDataAvailable(handle, data_offset, data_length);
330     return;
331   }
332
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(
340       FROM_HERE,
341       base::Bind(&TranslateTabHelper::HandleCLDDataRequest),
342       base::Bind(&TranslateTabHelper::MaybeSendCLDDataAvailable,
343                  weak_pointer_factory_.GetWeakPtr()));
344 }
345
346 void TranslateTabHelper::MaybeSendCLDDataAvailable() {
347   base::File* handle = NULL;
348   uint64 data_offset = 0;
349   uint64 data_length = 0;
350   {
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_;
355   }
356
357   if (handle && handle->IsValid())
358     SendCLDDataAvailable(handle, data_offset, data_length);
359 }
360
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(),
369           false);
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
375   // safe.
376   Send(new ChromeViewMsg_CLDDataAvailable(
377       GetWebContents()->GetRenderViewHost()->GetRoutingID(),
378       ipc_platform_file, data_offset, data_length));
379 }
380
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));
386
387   {
388     base::AutoLock lock(s_file_lock_.Get());
389     if (s_cached_file_)
390       return; // Already done, duplicate request
391   }
392
393   base::FilePath path;
394 #if defined(CLD2_IS_COMPONENT)
395   if (!component_updater::GetLatestCldDataFile(&path))
396     return;
397 #else
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.
401   }
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))
406     return;
407 #endif
408
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";
414     return;
415   }
416
417   base::File::Info file_info;
418   if (!file->GetInfo(&file_info)) {
419     LOG(WARNING) << "CLD data file exists but cannot be inspected";
420     return;
421   }
422
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;
428
429   {
430     base::AutoLock lock(s_file_lock_.Get());
431     if (s_cached_file_) {
432       // Idempotence: Racing another request on the blocking pool, abort.
433     } else {
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;
438     }
439   }
440 }
441 #endif // defined(CLD2_DYNAMIC_MODE)
442
443 void TranslateTabHelper::InitiateTranslation(const std::string& page_lang,
444                                              int attempt) {
445   if (translate_driver_.GetLanguageState().translation_pending())
446     return;
447
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
451   // has finished.
452   if (web_contents()->IsLoading() && attempt < max_reload_check_attempts_) {
453     int backoff = attempt * kMaxTranslateLoadCheckAttempts;
454     base::MessageLoop::current()->PostDelayedTask(
455         FROM_HERE,
456         base::Bind(&TranslateTabHelper::InitiateTranslation,
457                    weak_pointer_factory_.GetWeakPtr(),
458                    page_lang,
459                    ++attempt),
460         base::TimeDelta::FromMilliseconds(backoff));
461     return;
462   }
463
464   translate_manager_->InitiateTranslation(
465       TranslateDownloadManager::GetLanguageCode(page_lang));
466 }
467
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);
473
474   if (web_contents())
475     translate_manager_->InitiateTranslation(details.adopted_language);
476
477   content::NotificationService::current()->Notify(
478       chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
479       content::Source<content::WebContents>(web_contents()),
480       content::Details<const LanguageDetectionDetails>(&details));
481 }
482
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);
490
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));
499 }
500
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());
506
507   // |browser| might be NULL when testing. In this case, Show(...) should be
508   // called because the implementation for testing is used.
509   if (!browser) {
510     TranslateBubbleFactory::Show(NULL, web_contents(), step, error_type);
511     return;
512   }
513
514   if (web_contents() != browser->tab_strip_model()->GetActiveWebContents())
515     return;
516
517   content::RenderViewHost* rvh = web_contents()->GetRenderViewHost();
518   if (rvh->IsFocusedElementEditable())
519     return;
520
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.
526   if (browser !=
527       chrome::FindLastActiveWithHostDesktopType(browser->host_desktop_type())) {
528     return;
529   }
530
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())
535       return;
536   }
537
538   TranslateBubbleFactory::Show(
539       browser->window(), web_contents(), step, error_type);
540 #else
541   NOTREACHED();
542 #endif
543 }