Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(148)

Side by Side Diff: chrome/renderer/translate/translate_helper.cc

Issue 187393005: Make it possible to read CLD data from a file (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Address Marcus' comments Created 6 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/renderer/translate/translate_helper.h" 5 #include "chrome/renderer/translate/translate_helper.h"
6 6
7 #include "base/bind.h" 7 #include "base/bind.h"
8 #include "base/compiler_specific.h" 8 #include "base/compiler_specific.h"
9 #include "base/files/memory_mapped_file.h"
9 #include "base/logging.h" 10 #include "base/logging.h"
10 #include "base/message_loop/message_loop.h" 11 #include "base/message_loop/message_loop.h"
11 #include "base/strings/string16.h" 12 #include "base/strings/string16.h"
12 #include "base/strings/string_util.h" 13 #include "base/strings/string_util.h"
13 #include "base/strings/utf_string_conversions.h" 14 #include "base/strings/utf_string_conversions.h"
14 #include "chrome/common/render_messages.h" 15 #include "chrome/common/render_messages.h"
15 #include "chrome/renderer/extensions/extension_groups.h" 16 #include "chrome/renderer/extensions/extension_groups.h"
16 #include "chrome/renderer/isolated_world_ids.h" 17 #include "chrome/renderer/isolated_world_ids.h"
17 #include "components/translate/core/common/translate_constants.h" 18 #include "components/translate/core/common/translate_constants.h"
18 #include "components/translate/core/common/translate_metrics.h" 19 #include "components/translate/core/common/translate_metrics.h"
19 #include "components/translate/core/common/translate_util.h" 20 #include "components/translate/core/common/translate_util.h"
20 #include "components/translate/language_detection/language_detection_util.h" 21 #include "components/translate/language_detection/language_detection_util.h"
21 #include "content/public/renderer/render_view.h" 22 #include "content/public/renderer/render_view.h"
23 #include "extensions/common/constants.h"
24 #include "ipc/ipc_platform_file.h"
25 #if defined(CLD2_DYNAMIC_MODE)
26 #include "content/public/common/url_constants.h"
27 #include "third_party/cld_2/src/public/compact_lang_det.h"
28 #endif
22 #include "third_party/WebKit/public/web/WebDocument.h" 29 #include "third_party/WebKit/public/web/WebDocument.h"
23 #include "third_party/WebKit/public/web/WebElement.h" 30 #include "third_party/WebKit/public/web/WebElement.h"
24 #include "third_party/WebKit/public/web/WebFrame.h" 31 #include "third_party/WebKit/public/web/WebFrame.h"
25 #include "third_party/WebKit/public/web/WebNode.h" 32 #include "third_party/WebKit/public/web/WebNode.h"
26 #include "third_party/WebKit/public/web/WebNodeList.h" 33 #include "third_party/WebKit/public/web/WebNodeList.h"
27 #include "third_party/WebKit/public/web/WebScriptSource.h" 34 #include "third_party/WebKit/public/web/WebScriptSource.h"
28 #include "third_party/WebKit/public/web/WebView.h" 35 #include "third_party/WebKit/public/web/WebView.h"
29 #include "third_party/WebKit/public/web/WebWidget.h" 36 #include "third_party/WebKit/public/web/WebWidget.h"
30 #include "url/gurl.h" 37 #include "url/gurl.h"
31 #include "v8/include/v8.h" 38 #include "v8/include/v8.h"
(...skipping 25 matching lines...) Expand all
57 const int kTranslateStatusCheckDelayMs = 400; 64 const int kTranslateStatusCheckDelayMs = 400;
58 65
59 // Language name passed to the Translate element for it to detect the language. 66 // Language name passed to the Translate element for it to detect the language.
60 const char kAutoDetectionLanguage[] = "auto"; 67 const char kAutoDetectionLanguage[] = "auto";
61 68
62 // Isolated world sets following content-security-policy. 69 // Isolated world sets following content-security-policy.
63 const char kContentSecurityPolicy[] = "script-src 'self' 'unsafe-eval'"; 70 const char kContentSecurityPolicy[] = "script-src 'self' 'unsafe-eval'";
64 71
65 } // namespace 72 } // namespace
66 73
74 // The mmap for the CLD2 data must be held forever once it is available in the
75 // process. This is declared static in the translate_helper.h.
76 base::MemoryMappedFile* TranslateHelper::s_cld2_data_file_mmap_ = NULL;
77
67 //////////////////////////////////////////////////////////////////////////////// 78 ////////////////////////////////////////////////////////////////////////////////
68 // TranslateHelper, public: 79 // TranslateHelper, public:
69 // 80 //
70 TranslateHelper::TranslateHelper(content::RenderView* render_view) 81 TranslateHelper::TranslateHelper(content::RenderView* render_view)
71 : content::RenderViewObserver(render_view), 82 : content::RenderViewObserver(render_view),
72 page_id_(-1), 83 page_id_(-1),
73 translation_pending_(false), 84 translation_pending_(false),
74 weak_method_factory_(this) { 85 weak_method_factory_(this)
86 #if defined(CLD2_DYNAMIC_MODE)
87 ,cld2_data_file_polling_started_(false),
88 cld2_data_file_polling_canceled_(false),
89 deferred_page_capture_(false),
90 deferred_page_id_(-1),
91 deferred_contents_(ASCIIToUTF16(""))
92 #endif
93 {
75 } 94 }
76 95
77 TranslateHelper::~TranslateHelper() { 96 TranslateHelper::~TranslateHelper() {
78 CancelPendingTranslation(); 97 CancelPendingTranslation();
98 #if defined(CLD2_DYNAMIC_MODE)
99 CancelCLD2DataFilePolling();
100 #endif
79 } 101 }
80 102
103 void TranslateHelper::PrepareForUrl(const GURL& url) {
104 #if defined(CLD2_DYNAMIC_MODE)
105 deferred_page_capture_ = false;
106 deferred_contents_.clear();
107 if (cld2_data_file_polling_started_)
108 return;
109
110 // TODO(andrewhayden): Refactor translate_manager.cc's IsTranslatableURL to
111 // components/translate/core/common/translate_util.cc, and ignore any URL
112 // that fails that check. This will require moving unit tests and rewiring
113 // other function calls as well, so for now replicate the logic here.
114 if (url.is_empty())
115 return;
116 if (url.SchemeIs(content::kChromeUIScheme))
117 return;
118 if (url.SchemeIs(content::kChromeDevToolsScheme))
119 return;
120 if (url.SchemeIs(content::kFtpScheme))
121 return;
122 #if defined(OS_CHROMEOS)
123 if (url.SchemeIs(extensions::kExtensionScheme)
124 && url.DomainIs(file_manager::kFileManagerAppId))
bulach 2014/03/25 09:29:26 nit: && in the previous line
Andrew Hayden (chromium.org) 2014/03/26 15:34:11 Done.
125 return;
126 #endif
127
128 // Start polling for CLD data.
129 cld2_data_file_polling_started_ = true;
130 TranslateHelper::SendCLD2DataFileRequest(0, 1000);
131 #endif
132 }
133
134 #if defined(CLD2_DYNAMIC_MODE)
135 void TranslateHelper::DeferPageCaptured(const int page_id,
136 const base::string16& contents) {
137 deferred_page_capture_ = true;
138 deferred_page_id_ = page_id;
139 deferred_contents_ = contents;
140 }
141 #endif
142
81 void TranslateHelper::PageCaptured(int page_id, 143 void TranslateHelper::PageCaptured(int page_id,
82 const base::string16& contents) { 144 const base::string16& contents) {
83 // Get the document language as set by WebKit from the http-equiv 145 // Get the document language as set by WebKit from the http-equiv
84 // meta tag for "content-language". This may or may not also 146 // meta tag for "content-language". This may or may not also
85 // have a value derived from the actual Content-Language HTTP 147 // have a value derived from the actual Content-Language HTTP
86 // header. The two actually have different meanings (despite the 148 // header. The two actually have different meanings (despite the
87 // original intent of http-equiv to be an equivalent) with the former 149 // original intent of http-equiv to be an equivalent) with the former
88 // being the language of the document and the latter being the 150 // being the language of the document and the latter being the
89 // language of the intended audience (a distinction really only 151 // language of the intended audience (a distinction really only
90 // relevant for things like langauge textbooks). This distinction 152 // relevant for things like langauge textbooks). This distinction
91 // shouldn't affect translation. 153 // shouldn't affect translation.
92 WebFrame* main_frame = GetMainFrame(); 154 WebFrame* main_frame = GetMainFrame();
93 if (!main_frame || render_view()->GetPageId() != page_id) 155 if (!main_frame || render_view()->GetPageId() != page_id)
94 return; 156 return;
157
158 // TODO(andrewhayden): UMA insertion point here: Track if data is available.
159 // TODO(andrewhayden): Retry insertion point here, retry till data available.
160 #if defined(CLD2_DYNAMIC_MODE)
161 if (!CLD2::isDataLoaded()) {
162 // We're in dynamic mode and CLD data isn't loaded. Retry when CLD data
163 // is loaded, if ever.
164 TranslateHelper::DeferPageCaptured(page_id, contents);
165 return;
166 }
167 #endif
95 page_id_ = page_id; 168 page_id_ = page_id;
96 WebDocument document = main_frame->document(); 169 WebDocument document = main_frame->document();
97 std::string content_language = document.contentLanguage().utf8(); 170 std::string content_language = document.contentLanguage().utf8();
98 WebElement html_element = document.documentElement(); 171 WebElement html_element = document.documentElement();
99 std::string html_lang; 172 std::string html_lang;
100 // |html_element| can be null element, e.g. in 173 // |html_element| can be null element, e.g. in
101 // BrowserTest.WindowOpenClose. 174 // BrowserTest.WindowOpenClose.
102 if (!html_element.isNull()) 175 if (!html_element.isNull())
103 html_lang = html_element.getAttribute("lang").utf8(); 176 html_lang = html_element.getAttribute("lang").utf8();
104 std::string cld_language; 177 std::string cld_language;
(...skipping 24 matching lines...) Expand all
129 routing_id(), 202 routing_id(),
130 details, 203 details,
131 IsTranslationAllowed(&document) && !language.empty())); 204 IsTranslationAllowed(&document) && !language.empty()));
132 } 205 }
133 206
134 void TranslateHelper::CancelPendingTranslation() { 207 void TranslateHelper::CancelPendingTranslation() {
135 weak_method_factory_.InvalidateWeakPtrs(); 208 weak_method_factory_.InvalidateWeakPtrs();
136 translation_pending_ = false; 209 translation_pending_ = false;
137 source_lang_.clear(); 210 source_lang_.clear();
138 target_lang_.clear(); 211 target_lang_.clear();
212 #if defined(CLD2_DYNAMIC_MODE)
213 CancelCLD2DataFilePolling();
214 #endif
139 } 215 }
140 216
141 //////////////////////////////////////////////////////////////////////////////// 217 ////////////////////////////////////////////////////////////////////////////////
142 // TranslateHelper, protected: 218 // TranslateHelper, protected:
143 // 219 //
144 bool TranslateHelper::IsTranslateLibAvailable() { 220 bool TranslateHelper::IsTranslateLibAvailable() {
145 return ExecuteScriptAndGetBoolResult( 221 return ExecuteScriptAndGetBoolResult(
146 "typeof cr != 'undefined' && typeof cr.googleTranslate != 'undefined' && " 222 "typeof cr != 'undefined' && typeof cr.googleTranslate != 'undefined' && "
147 "typeof cr.googleTranslate.translate == 'function'", false); 223 "typeof cr.googleTranslate.translate == 'function'", false);
148 } 224 }
(...skipping 154 matching lines...) Expand 10 before | Expand all | Expand 10 after
303 return false; 379 return false;
304 } 380 }
305 return true; 381 return true;
306 } 382 }
307 383
308 bool TranslateHelper::OnMessageReceived(const IPC::Message& message) { 384 bool TranslateHelper::OnMessageReceived(const IPC::Message& message) {
309 bool handled = true; 385 bool handled = true;
310 IPC_BEGIN_MESSAGE_MAP(TranslateHelper, message) 386 IPC_BEGIN_MESSAGE_MAP(TranslateHelper, message)
311 IPC_MESSAGE_HANDLER(ChromeViewMsg_TranslatePage, OnTranslatePage) 387 IPC_MESSAGE_HANDLER(ChromeViewMsg_TranslatePage, OnTranslatePage)
312 IPC_MESSAGE_HANDLER(ChromeViewMsg_RevertTranslation, OnRevertTranslation) 388 IPC_MESSAGE_HANDLER(ChromeViewMsg_RevertTranslation, OnRevertTranslation)
389 #if defined(CLD2_DYNAMIC_MODE)
390 IPC_MESSAGE_HANDLER(ChromeViewMsg_CLDDataAvailable, OnCLDDataAvailable);
391 #endif
313 IPC_MESSAGE_UNHANDLED(handled = false) 392 IPC_MESSAGE_UNHANDLED(handled = false)
314 IPC_END_MESSAGE_MAP() 393 IPC_END_MESSAGE_MAP()
315 return handled; 394 return handled;
316 } 395 }
317 396
318 void TranslateHelper::OnTranslatePage(int page_id, 397 void TranslateHelper::OnTranslatePage(int page_id,
319 const std::string& translate_script, 398 const std::string& translate_script,
320 const std::string& source_lang, 399 const std::string& source_lang,
321 const std::string& target_lang) { 400 const std::string& target_lang) {
322 WebFrame* main_frame = GetMainFrame(); 401 WebFrame* main_frame = GetMainFrame();
(...skipping 169 matching lines...) Expand 10 before | Expand all | Expand 10 after
492 571
493 WebFrame* TranslateHelper::GetMainFrame() { 572 WebFrame* TranslateHelper::GetMainFrame() {
494 WebView* web_view = render_view()->GetWebView(); 573 WebView* web_view = render_view()->GetWebView();
495 574
496 // When the tab is going to be closed, the web_view can be NULL. 575 // When the tab is going to be closed, the web_view can be NULL.
497 if (!web_view) 576 if (!web_view)
498 return NULL; 577 return NULL;
499 578
500 return web_view->mainFrame(); 579 return web_view->mainFrame();
501 } 580 }
581
582 #if defined(CLD2_DYNAMIC_MODE)
583 void TranslateHelper::CancelCLD2DataFilePolling() {
584 cld2_data_file_polling_canceled_ = true;
585 }
586
587 void TranslateHelper::SendCLD2DataFileRequest(int delay_millis,
588 int next_delay_millis) {
589 // Terminate immediately if told to stop polling
palmer 2014/03/24 19:01:47 Nit: Punctuate.
Andrew Hayden (chromium.org) 2014/03/26 15:34:11 Done.
590 if (cld2_data_file_polling_canceled_)
591 return;
592
593 // Terminate immediately if data is already loaded.
594 if (CLD2::isDataLoaded())
595 return;
596
597 // Else, send the IPC message to the browser process requesting the data...
598 Send(new ChromeViewHostMsg_NeedCLDData(routing_id()));
599
600 // ... and enqueue another delayed task to call again. This will start a
601 // chain of polling that will last until the pointer stops being null,
palmer 2014/03/24 19:01:47 Nit: NULL
Andrew Hayden (chromium.org) 2014/03/26 15:34:11 Done.
602 // which is the right thing to do.
603 // NB: In the great majority of cases, the data file will be available and
604 // the very first delayed task will be a no-op that terminates the chain.
605 // It's only while downloading the file that we expect this to chain for a
Andrew Hayden (chromium.org) 2014/03/26 15:34:11 Grammar police, don't use pronouns in comments.
606 // nontrivial amount of time.
607 // Use a weak pointer to avoid keeping this helper object around forever.
608 base::MessageLoop::current()->PostDelayedTask(
609 FROM_HERE,
610 base::Bind(&TranslateHelper::SendCLD2DataFileRequest,
611 weak_method_factory_.GetWeakPtr(),
612 next_delay_millis, next_delay_millis),
613 base::TimeDelta::FromMilliseconds(delay_millis));
614 }
615
616 void TranslateHelper::OnCLDDataAvailable(
617 IPC::PlatformFileForTransit ipc_file_handle) {
618 LoadCLDDData(ipc_file_handle);
619 if (deferred_page_capture_ && CLD2::isDataLoaded()) {
620 // Data is available now, and there was previously a deferred request to
621 // start translation. Finish that request up and clear state.
622 // The real situation this translates to is as follows:
623 // The user loaded a page before the CLD data was available - either
624 // because the browser process took too long to respond to our CLD data
625 // request, or because the data truly hasn't been available;
626 // The data is now available, so get that language check done and post the
627 // message back to the browser ASAP.
628 deferred_page_capture_ = false; // Don't do this a second time.
629 PageCaptured(deferred_page_id_, deferred_contents_);
630 deferred_page_id_ = -1; // Clean up for sanity
palmer 2014/03/24 19:01:47 Nit: punctuation, but really these comments are su
Andrew Hayden (chromium.org) 2014/03/26 15:34:11 Deleted.
631 deferred_contents_.clear(); // Clean up for sanity
632 }
633 }
634
635 void TranslateHelper::LoadCLDDData(
636 IPC::PlatformFileForTransit ipc_file_handle) {
637 // Terminate immediately if told to stop polling
palmer 2014/03/24 19:01:47 Nit: Punctuate.
Andrew Hayden (chromium.org) 2014/03/26 15:34:11 Done.
638 if (cld2_data_file_polling_canceled_)
639 return;
640
641 // Terminate immediately if data is already loaded.
642 if (CLD2::isDataLoaded())
643 return;
644
645 // Grab the file handle
646 base::PlatformFile platform_file =
647 IPC::PlatformFileForTransitToPlatformFile(ipc_file_handle);
648 DCHECK(platform_file != base::kInvalidPlatformFileValue)
palmer 2014/03/24 19:01:47 This should be a production, run-time check, not a
Andrew Hayden (chromium.org) 2014/03/26 15:34:11 Done.
649 << "Can't find the CLD data file!";
650 base::File basic_file(platform_file);
651
652 // mmap the file
653 static base::MemoryMappedFile* mmap = new base::MemoryMappedFile();
654 bool initialized = mmap->Initialize(basic_file.Pass());
655 DCHECK(initialized) << "Failed to initialize CLD data mmap";
656 if (!initialized) {
657 delete mmap;
658 mmap = NULL;
659 return;
660 }
661
662 // Retain the reference forever, so the data doesn't get unmapped by the
663 // mmap destructor.
664 s_cld2_data_file_mmap_ = mmap;
665
666 // Initialize the CLD subsystem... and it's all done!
667 CLD2::loadDataFromRawAddress(mmap->data(), mmap->length());
668 DCHECK(CLD2::isDataLoaded()) << "Failed to load CLD data from mmap";
669 }
670 #endif
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698