Allow only one bookmark to be added for multiple fast starring
[chromium-blink-merge.git] / chrome / renderer / spellchecker / spellcheck_provider.cc
blob001484ede8d768cdd8c32737dfc2e14482d3c413
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
3 // found in the LICENSE file.
5 #include "chrome/renderer/spellchecker/spellcheck_provider.h"
7 #include "base/command_line.h"
8 #include "base/metrics/histogram.h"
9 #include "chrome/common/chrome_switches.h"
10 #include "chrome/common/spellcheck_marker.h"
11 #include "chrome/common/spellcheck_messages.h"
12 #include "chrome/common/spellcheck_result.h"
13 #include "chrome/renderer/spellchecker/spellcheck.h"
14 #include "chrome/renderer/spellchecker/spellcheck_language.h"
15 #include "content/public/renderer/render_view.h"
16 #include "third_party/WebKit/public/platform/WebVector.h"
17 #include "third_party/WebKit/public/web/WebDocument.h"
18 #include "third_party/WebKit/public/web/WebElement.h"
19 #include "third_party/WebKit/public/web/WebFrame.h"
20 #include "third_party/WebKit/public/web/WebTextCheckingCompletion.h"
21 #include "third_party/WebKit/public/web/WebTextCheckingResult.h"
22 #include "third_party/WebKit/public/web/WebTextDecorationType.h"
23 #include "third_party/WebKit/public/web/WebView.h"
25 using blink::WebElement;
26 using blink::WebFrame;
27 using blink::WebString;
28 using blink::WebTextCheckingCompletion;
29 using blink::WebTextCheckingResult;
30 using blink::WebTextDecorationType;
31 using blink::WebVector;
33 static_assert(int(blink::WebTextDecorationTypeSpelling) ==
34 int(SpellCheckResult::SPELLING), "mismatching enums");
35 static_assert(int(blink::WebTextDecorationTypeGrammar) ==
36 int(SpellCheckResult::GRAMMAR), "mismatching enums");
37 static_assert(int(blink::WebTextDecorationTypeInvisibleSpellcheck) ==
38 int(SpellCheckResult::INVISIBLE), "mismatching enums");
40 SpellCheckProvider::SpellCheckProvider(
41 content::RenderView* render_view,
42 SpellCheck* spellcheck)
43 : content::RenderViewObserver(render_view),
44 content::RenderViewObserverTracker<SpellCheckProvider>(render_view),
45 spelling_panel_visible_(false),
46 spellcheck_(spellcheck) {
47 DCHECK(spellcheck_);
48 if (render_view) { // NULL in unit tests.
49 render_view->GetWebView()->setSpellCheckClient(this);
50 EnableSpellcheck(spellcheck_->is_spellcheck_enabled());
54 SpellCheckProvider::~SpellCheckProvider() {
57 void SpellCheckProvider::RequestTextChecking(
58 const base::string16& text,
59 WebTextCheckingCompletion* completion,
60 const std::vector<SpellCheckMarker>& markers) {
61 // Ignore invalid requests.
62 if (text.empty() || !HasWordCharacters(text, 0)) {
63 completion->didCancelCheckingText();
64 return;
67 // Try to satisfy check from cache.
68 if (SatisfyRequestFromCache(text, completion))
69 return;
71 // Send this text to a browser. A browser checks the user profile and send
72 // this text to the Spelling service only if a user enables this feature.
73 last_request_.clear();
74 last_results_.assign(blink::WebVector<blink::WebTextCheckingResult>());
76 #if defined(USE_BROWSER_SPELLCHECKER)
77 // Text check (unified request for grammar and spell check) is only
78 // available for browser process, so we ask the system spellchecker
79 // over IPC or return an empty result if the checker is not
80 // available.
81 Send(new SpellCheckHostMsg_RequestTextCheck(
82 routing_id(),
83 text_check_completions_.Add(completion),
84 text,
85 markers));
86 #else
87 Send(new SpellCheckHostMsg_CallSpellingService(
88 routing_id(),
89 text_check_completions_.Add(completion),
90 base::string16(text),
91 markers));
92 #endif // !USE_BROWSER_SPELLCHECKER
95 bool SpellCheckProvider::OnMessageReceived(const IPC::Message& message) {
96 bool handled = true;
97 IPC_BEGIN_MESSAGE_MAP(SpellCheckProvider, message)
98 #if !defined(USE_BROWSER_SPELLCHECKER)
99 IPC_MESSAGE_HANDLER(SpellCheckMsg_RespondSpellingService,
100 OnRespondSpellingService)
101 #endif
102 #if defined(USE_BROWSER_SPELLCHECKER)
103 IPC_MESSAGE_HANDLER(SpellCheckMsg_AdvanceToNextMisspelling,
104 OnAdvanceToNextMisspelling)
105 IPC_MESSAGE_HANDLER(SpellCheckMsg_RespondTextCheck, OnRespondTextCheck)
106 IPC_MESSAGE_HANDLER(SpellCheckMsg_ToggleSpellPanel, OnToggleSpellPanel)
107 #endif
108 IPC_MESSAGE_UNHANDLED(handled = false)
109 IPC_END_MESSAGE_MAP()
110 return handled;
113 void SpellCheckProvider::FocusedNodeChanged(const blink::WebNode& unused) {
114 #if defined(USE_BROWSER_SPELLCHECKER)
115 WebFrame* frame = render_view()->GetWebView()->focusedFrame();
116 WebElement element = frame->document().isNull() ? WebElement() :
117 frame->document().focusedElement();
118 bool enabled = !element.isNull() && render_view()->IsEditableNode(element);
120 bool checked = enabled && render_view()->GetWebView() &&
121 frame->isContinuousSpellCheckingEnabled();
123 Send(new SpellCheckHostMsg_ToggleSpellCheck(routing_id(), enabled, checked));
124 #endif // USE_BROWSER_SPELLCHECKER
127 void SpellCheckProvider::spellCheck(
128 const WebString& text,
129 int& offset,
130 int& length,
131 WebVector<WebString>* optional_suggestions) {
132 base::string16 word(text);
133 std::vector<base::string16> suggestions;
134 spellcheck_->SpellCheckWord(
135 word.c_str(), word.size(), routing_id(),
136 &offset, &length, optional_suggestions ? & suggestions : NULL);
137 if (optional_suggestions) {
138 *optional_suggestions = suggestions;
139 UMA_HISTOGRAM_COUNTS("SpellCheck.api.check.suggestions", word.size());
140 } else {
141 UMA_HISTOGRAM_COUNTS("SpellCheck.api.check", word.size());
142 // If optional_suggestions is not requested, the API is called
143 // for marking. So we use this for counting markable words.
144 Send(new SpellCheckHostMsg_NotifyChecked(routing_id(), word, 0 < length));
148 void SpellCheckProvider::checkTextOfParagraph(
149 const blink::WebString& text,
150 blink::WebTextCheckingTypeMask mask,
151 blink::WebVector<blink::WebTextCheckingResult>* results) {
152 if (!results)
153 return;
155 if (!(mask & blink::WebTextCheckingTypeSpelling))
156 return;
158 // TODO(groby): As far as I can tell, this method is never invoked.
159 // UMA results seem to support that. Investigate, clean up if true.
160 NOTREACHED();
161 spellcheck_->SpellCheckParagraph(text, results);
162 UMA_HISTOGRAM_COUNTS("SpellCheck.api.paragraph", text.length());
165 void SpellCheckProvider::requestCheckingOfText(
166 const WebString& text,
167 const WebVector<uint32>& markers,
168 const WebVector<unsigned>& marker_offsets,
169 WebTextCheckingCompletion* completion) {
170 std::vector<SpellCheckMarker> spellcheck_markers;
171 for (size_t i = 0; i < markers.size(); ++i) {
172 spellcheck_markers.push_back(
173 SpellCheckMarker(markers[i], marker_offsets[i]));
175 RequestTextChecking(text, completion, spellcheck_markers);
176 UMA_HISTOGRAM_COUNTS("SpellCheck.api.async", text.length());
179 WebString SpellCheckProvider::autoCorrectWord(const WebString& word) {
180 const base::CommandLine& command_line =
181 *base::CommandLine::ForCurrentProcess();
182 if (command_line.HasSwitch(switches::kEnableSpellingAutoCorrect)) {
183 UMA_HISTOGRAM_COUNTS("SpellCheck.api.autocorrect", word.length());
184 return spellcheck_->GetAutoCorrectionWord(word, routing_id());
186 return base::string16();
189 void SpellCheckProvider::showSpellingUI(bool show) {
190 #if defined(USE_BROWSER_SPELLCHECKER)
191 UMA_HISTOGRAM_BOOLEAN("SpellCheck.api.showUI", show);
192 Send(new SpellCheckHostMsg_ShowSpellingPanel(routing_id(), show));
193 #endif
196 bool SpellCheckProvider::isShowingSpellingUI() {
197 return spelling_panel_visible_;
200 void SpellCheckProvider::updateSpellingUIWithMisspelledWord(
201 const WebString& word) {
202 #if defined(USE_BROWSER_SPELLCHECKER)
203 Send(new SpellCheckHostMsg_UpdateSpellingPanelWithMisspelledWord(routing_id(),
204 word));
205 #endif
208 #if !defined(USE_BROWSER_SPELLCHECKER)
209 void SpellCheckProvider::OnRespondSpellingService(
210 int identifier,
211 bool succeeded,
212 const base::string16& line,
213 const std::vector<SpellCheckResult>& results) {
214 WebTextCheckingCompletion* completion =
215 text_check_completions_.Lookup(identifier);
216 if (!completion)
217 return;
218 text_check_completions_.Remove(identifier);
220 // If |succeeded| is false, we use local spellcheck as a fallback.
221 if (!succeeded) {
222 spellcheck_->RequestTextChecking(line, completion);
223 return;
226 // Double-check the returned spellchecking results with our spellchecker to
227 // visualize the differences between ours and the on-line spellchecker.
228 blink::WebVector<blink::WebTextCheckingResult> textcheck_results;
229 spellcheck_->CreateTextCheckingResults(SpellCheck::USE_NATIVE_CHECKER,
231 line,
232 results,
233 &textcheck_results);
234 completion->didFinishCheckingText(textcheck_results);
236 // Cache the request and the converted results.
237 last_request_ = line;
238 last_results_.swap(textcheck_results);
240 #endif
242 bool SpellCheckProvider::HasWordCharacters(
243 const base::string16& text,
244 int index) const {
245 const base::char16* data = text.data();
246 int length = text.length();
247 while (index < length) {
248 uint32 code = 0;
249 U16_NEXT(data, index, length, code);
250 UErrorCode error = U_ZERO_ERROR;
251 if (uscript_getScript(code, &error) != USCRIPT_COMMON)
252 return true;
254 return false;
257 #if defined(USE_BROWSER_SPELLCHECKER)
258 void SpellCheckProvider::OnAdvanceToNextMisspelling() {
259 if (!render_view()->GetWebView())
260 return;
261 render_view()->GetWebView()->focusedFrame()->executeCommand(
262 WebString::fromUTF8("AdvanceToNextMisspelling"));
265 void SpellCheckProvider::OnRespondTextCheck(
266 int identifier,
267 const base::string16& line,
268 const std::vector<SpellCheckResult>& results) {
269 // TODO(groby): Unify with SpellCheckProvider::OnRespondSpellingService
270 DCHECK(spellcheck_);
271 WebTextCheckingCompletion* completion =
272 text_check_completions_.Lookup(identifier);
273 if (!completion)
274 return;
275 text_check_completions_.Remove(identifier);
276 blink::WebVector<blink::WebTextCheckingResult> textcheck_results;
277 spellcheck_->CreateTextCheckingResults(SpellCheck::DO_NOT_MODIFY,
279 line,
280 results,
281 &textcheck_results);
282 completion->didFinishCheckingText(textcheck_results);
284 // TODO(groby): Add request caching once OSX reports back original request.
285 // (cf. SpellCheckProvider::OnRespondSpellingService)
286 // Cache the request and the converted results.
289 void SpellCheckProvider::OnToggleSpellPanel(bool is_currently_visible) {
290 if (!render_view()->GetWebView())
291 return;
292 // We need to tell the webView whether the spelling panel is visible or not so
293 // that it won't need to make ipc calls later.
294 spelling_panel_visible_ = is_currently_visible;
295 render_view()->GetWebView()->focusedFrame()->executeCommand(
296 WebString::fromUTF8("ToggleSpellPanel"));
298 #endif
300 void SpellCheckProvider::EnableSpellcheck(bool enable) {
301 if (!render_view()->GetWebView())
302 return;
304 WebFrame* frame = render_view()->GetWebView()->focusedFrame();
305 frame->enableContinuousSpellChecking(enable);
306 if (!enable)
307 frame->removeSpellingMarkers();
310 bool SpellCheckProvider::SatisfyRequestFromCache(
311 const base::string16& text,
312 WebTextCheckingCompletion* completion) {
313 size_t last_length = last_request_.length();
315 // Send back the |last_results_| if the |last_request_| is a substring of
316 // |text| and |text| does not have more words to check. Provider cannot cancel
317 // the spellcheck request here, because WebKit might have discarded the
318 // previous spellcheck results and erased the spelling markers in response to
319 // the user editing the text.
320 base::string16 request(text);
321 size_t text_length = request.length();
322 if (text_length >= last_length &&
323 !request.compare(0, last_length, last_request_)) {
324 if (text_length == last_length || !HasWordCharacters(text, last_length)) {
325 completion->didFinishCheckingText(last_results_);
326 return true;
328 int code = 0;
329 int length = static_cast<int>(text_length);
330 U16_PREV(text.data(), 0, length, code);
331 UErrorCode error = U_ZERO_ERROR;
332 if (uscript_getScript(code, &error) != USCRIPT_COMMON) {
333 completion->didCancelCheckingText();
334 return true;
337 // Create a subset of the cached results and return it if the given text is a
338 // substring of the cached text.
339 if (text_length < last_length &&
340 !last_request_.compare(0, text_length, request)) {
341 size_t result_size = 0;
342 for (size_t i = 0; i < last_results_.size(); ++i) {
343 size_t start = last_results_[i].location;
344 size_t end = start + last_results_[i].length;
345 if (start <= text_length && end <= text_length)
346 ++result_size;
348 if (result_size > 0) {
349 blink::WebVector<blink::WebTextCheckingResult> results(result_size);
350 for (size_t i = 0; i < result_size; ++i) {
351 results[i].decoration = last_results_[i].decoration;
352 results[i].location = last_results_[i].location;
353 results[i].length = last_results_[i].length;
354 results[i].replacement = last_results_[i].replacement;
356 completion->didFinishCheckingText(results);
357 return true;
361 return false;