chrome_translate_client.h revision 46d4c2bc3267f3f028f39e7e311b0f89aba2e4fd
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#ifndef CHROME_BROWSER_TRANSLATE_CHROME_TRANSLATE_CLIENT_H_
6#define CHROME_BROWSER_TRANSLATE_CHROME_TRANSLATE_CLIENT_H_
7
8#include <string>
9
10#include "base/memory/scoped_ptr.h"
11#include "base/memory/weak_ptr.h"
12#include "chrome/browser/ui/translate/translate_bubble_model.h"
13#include "components/translate/content/browser/content_translate_driver.h"
14#include "components/translate/core/browser/translate_client.h"
15#include "components/translate/core/browser/translate_step.h"
16#include "components/translate/core/common/translate_errors.h"
17#include "content/public/browser/web_contents_observer.h"
18#include "content/public/browser/web_contents_user_data.h"
19
20#if defined(CLD2_DYNAMIC_MODE)
21#include "base/basictypes.h"
22#include "base/lazy_instance.h"
23#include "base/synchronization/lock.h"
24#include "base/task_runner.h"
25#endif
26
27namespace base {
28class File;
29}  // namespace base
30
31namespace content {
32class BrowserContext;
33class WebContents;
34}  // namespace content
35
36namespace test {
37class ScopedCLDDynamicDataHarness;
38}  // namespace test
39
40struct LanguageDetectionDetails;
41class PrefService;
42class TranslateAcceptLanguages;
43class TranslatePrefs;
44class TranslateManager;
45
46class ChromeTranslateClient
47    : public TranslateClient,
48      public content::WebContentsObserver,
49      public content::WebContentsUserData<ChromeTranslateClient> {
50 public:
51  virtual ~ChromeTranslateClient();
52
53  // Gets the LanguageState associated with the page.
54  LanguageState& GetLanguageState();
55
56  // Returns the ContentTranslateDriver instance associated with this
57  // WebContents.
58  ContentTranslateDriver& translate_driver() { return translate_driver_; }
59
60  // Helper method to return a new TranslatePrefs instance.
61  static scoped_ptr<TranslatePrefs> CreateTranslatePrefs(PrefService* prefs);
62
63  // Helper method to return the TranslateAcceptLanguages instance associated
64  // with |browser_context|.
65  static TranslateAcceptLanguages* GetTranslateAcceptLanguages(
66      content::BrowserContext* browser_context);
67
68  // Helper method to return the TranslateManager instance associated with
69  // |web_contents|, or NULL if there is no such associated instance.
70  static TranslateManager* GetManagerFromWebContents(
71      content::WebContents* web_contents);
72
73  // Gets |source| and |target| language for translation.
74  static void GetTranslateLanguages(content::WebContents* web_contents,
75                                    std::string* source,
76                                    std::string* target);
77
78  // Gets the associated TranslateManager.
79  TranslateManager* GetTranslateManager();
80
81  // Gets the associated WebContents. Returns NULL if the WebContents is being
82  // destroyed.
83  content::WebContents* GetWebContents();
84
85  // Number of attempts before waiting for a page to be fully reloaded.
86  void set_translate_max_reload_attempts(int attempts) {
87    max_reload_check_attempts_ = attempts;
88  }
89
90  // TranslateClient implementation.
91  virtual TranslateDriver* GetTranslateDriver() OVERRIDE;
92  virtual PrefService* GetPrefs() OVERRIDE;
93  virtual scoped_ptr<TranslatePrefs> GetTranslatePrefs() OVERRIDE;
94  virtual TranslateAcceptLanguages* GetTranslateAcceptLanguages() OVERRIDE;
95  virtual int GetInfobarIconID() const OVERRIDE;
96  virtual scoped_ptr<infobars::InfoBar> CreateInfoBar(
97      scoped_ptr<TranslateInfoBarDelegate> delegate) const OVERRIDE;
98  virtual void ShowTranslateUI(translate::TranslateStep step,
99                               const std::string source_language,
100                               const std::string target_language,
101                               TranslateErrors::Type error_type,
102                               bool triggered_from_menu) OVERRIDE;
103  virtual bool IsTranslatableURL(const GURL& url) OVERRIDE;
104  virtual void ShowReportLanguageDetectionErrorUI(
105      const GURL& report_url) OVERRIDE;
106
107 private:
108  explicit ChromeTranslateClient(content::WebContents* web_contents);
109  friend class content::WebContentsUserData<ChromeTranslateClient>;
110  friend class test::ScopedCLDDynamicDataHarness;  // For cleaning static state.
111
112  // content::WebContentsObserver implementation.
113  virtual void NavigationEntryCommitted(
114      const content::LoadCommittedDetails& load_details) OVERRIDE;
115  virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
116  virtual void DidNavigateAnyFrame(
117      const content::LoadCommittedDetails& details,
118      const content::FrameNavigateParams& params) OVERRIDE;
119  virtual void WebContentsDestroyed() OVERRIDE;
120
121  // Initiates translation once the page is finished loading.
122  void InitiateTranslation(const std::string& page_lang, int attempt);
123  void OnLanguageDetermined(const LanguageDetectionDetails& details,
124                            bool page_needs_translation);
125  void OnPageTranslated(int32 page_id,
126                        const std::string& original_lang,
127                        const std::string& translated_lang,
128                        TranslateErrors::Type error_type);
129
130#if defined(CLD2_DYNAMIC_MODE)
131  // Called when we receive ChromeViewHostMsg_NeedCLDData from a renderer.
132  // If we have already cached the data, responds immediately; else, enqueues
133  // a HandleCLDDataRequest on the blocking pool to cache the data.
134  // Acquires and releases s_file_lock_ in a non-blocking manner; queries
135  // handled while the file is being cached will gracefully and immediately
136  // fail.
137  // It is up to the originator of the message to poll again later if required;
138  // no "negative response" will be generated.
139  void OnCLDDataRequested();
140
141  // Invoked on the blocking pool in order to cache the data. When successful,
142  // immediately responds to the request that initiated OnCLDDataRequested.
143  // Holds s_file_lock_ while the file is being cached.
144  static void HandleCLDDataRequest();
145
146  // If the CLD data is ready, send it to the renderer. Briefly checks the lock.
147  void MaybeSendCLDDataAvailable();
148
149  // Sends the renderer a response containing the data file handle. No locking.
150  void SendCLDDataAvailable(const base::File* handle,
151                            const uint64 data_offset,
152                            const uint64 data_length);
153
154  // The data file,  cached as long as the process stays alive.
155  // We also track the offset at which the data starts, and its length.
156  static base::File* s_cached_file_;    // guarded by file_lock_
157  static uint64 s_cached_data_offset_;  // guarded by file_lock_
158  static uint64 s_cached_data_length_;  // guarded by file_lock_
159
160  // Guards s_cached_file_
161  static base::LazyInstance<base::Lock> s_file_lock_;
162
163#endif
164
165  // Shows the translate bubble.
166  void ShowBubble(translate::TranslateStep step,
167                  TranslateErrors::Type error_type);
168
169  // Max number of attempts before checking if a page has been reloaded.
170  int max_reload_check_attempts_;
171
172  ContentTranslateDriver translate_driver_;
173  scoped_ptr<TranslateManager> translate_manager_;
174
175  // Necessary for binding the callback to HandleCLDDataRequest on the blocking
176  // pool and for delaying translation initialization until the page has
177  // finished loading on a reload.
178  base::WeakPtrFactory<ChromeTranslateClient> weak_pointer_factory_;
179
180  DISALLOW_COPY_AND_ASSIGN(ChromeTranslateClient);
181};
182
183#endif  // CHROME_BROWSER_TRANSLATE_CHROME_TRANSLATE_CLIENT_H_
184