Fix random lint warnings in chrome/android/shell
[chromium-blink-merge.git] / chrome / browser / renderer_context_menu / spelling_menu_observer.cc
blob80dc0973dc4bacdc78a11a0845cf0029189c0325
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.
5 #include "chrome/browser/renderer_context_menu/spelling_menu_observer.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/i18n/case_conversion.h"
10 #include "base/prefs/pref_service.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "chrome/app/chrome_command_ids.h"
13 #include "chrome/browser/profiles/profile.h"
14 #include "chrome/browser/renderer_context_menu/render_view_context_menu.h"
15 #include "chrome/browser/renderer_context_menu/spelling_bubble_model.h"
16 #include "chrome/browser/spellchecker/spellcheck_factory.h"
17 #include "chrome/browser/spellchecker/spellcheck_host_metrics.h"
18 #include "chrome/browser/spellchecker/spellcheck_platform_mac.h"
19 #include "chrome/browser/spellchecker/spellcheck_service.h"
20 #include "chrome/browser/spellchecker/spelling_service_client.h"
21 #include "chrome/browser/ui/confirm_bubble.h"
22 #include "chrome/common/chrome_switches.h"
23 #include "chrome/common/pref_names.h"
24 #include "chrome/common/spellcheck_result.h"
25 #include "chrome/grit/generated_resources.h"
26 #include "content/public/browser/render_view_host.h"
27 #include "content/public/browser/render_widget_host_view.h"
28 #include "content/public/browser/web_contents.h"
29 #include "content/public/common/context_menu_params.h"
30 #include "extensions/browser/view_type_utils.h"
31 #include "ui/base/l10n/l10n_util.h"
32 #include "ui/gfx/geometry/rect.h"
34 using content::BrowserThread;
36 SpellingMenuObserver::SpellingMenuObserver(RenderViewContextMenuProxy* proxy)
37 : proxy_(proxy),
38 loading_frame_(0),
39 succeeded_(false),
40 client_(new SpellingServiceClient) {
41 if (proxy_ && proxy_->GetBrowserContext()) {
42 Profile* profile = Profile::FromBrowserContext(proxy_->GetBrowserContext());
43 integrate_spelling_service_.Init(prefs::kSpellCheckUseSpellingService,
44 profile->GetPrefs());
45 autocorrect_spelling_.Init(prefs::kEnableAutoSpellCorrect,
46 profile->GetPrefs());
50 SpellingMenuObserver::~SpellingMenuObserver() {
53 void SpellingMenuObserver::InitMenu(const content::ContextMenuParams& params) {
54 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
55 DCHECK(!params.misspelled_word.empty() ||
56 params.dictionary_suggestions.empty());
58 // Exit if we are not in an editable element because we add a menu item only
59 // for editable elements.
60 content::BrowserContext* browser_context = proxy_->GetBrowserContext();
61 if (!params.is_editable || !browser_context)
62 return;
64 // Exit if there is no misspelled word.
65 if (params.misspelled_word.empty())
66 return;
68 suggestions_ = params.dictionary_suggestions;
69 misspelled_word_ = params.misspelled_word;
71 bool use_suggestions = SpellingServiceClient::IsAvailable(
72 browser_context, SpellingServiceClient::SUGGEST);
74 if (!suggestions_.empty() || use_suggestions)
75 proxy_->AddSeparator();
77 // Append Dictionary spell check suggestions.
78 for (size_t i = 0; i < params.dictionary_suggestions.size() &&
79 IDC_SPELLCHECK_SUGGESTION_0 + i <= IDC_SPELLCHECK_SUGGESTION_LAST;
80 ++i) {
81 proxy_->AddMenuItem(IDC_SPELLCHECK_SUGGESTION_0 + static_cast<int>(i),
82 params.dictionary_suggestions[i]);
85 // The service types |SpellingServiceClient::SPELLCHECK| and
86 // |SpellingServiceClient::SUGGEST| are mutually exclusive. Only one is
87 // available at at time.
89 // When |SpellingServiceClient::SPELLCHECK| is available, the contextual
90 // suggestions from |SpellingServiceClient| are already stored in
91 // |params.dictionary_suggestions|. |SpellingMenuObserver| places these
92 // suggestions in the slots |IDC_SPELLCHECK_SUGGESTION_[0-LAST]|. If
93 // |SpellingMenuObserver| queried |SpellingServiceClient| again, then quality
94 // of suggestions would be reduced by lack of context around the misspelled
95 // word.
97 // When |SpellingServiceClient::SUGGEST| is available,
98 // |params.dictionary_suggestions| contains suggestions only from Hunspell
99 // dictionary. |SpellingMenuObserver| queries |SpellingServiceClient| with the
100 // misspelled word without the surrounding context. Spellcheck suggestions
101 // from |SpellingServiceClient::SUGGEST| are not available until
102 // |SpellingServiceClient| responds to the query. While |SpellingMenuObserver|
103 // waits for |SpellingServiceClient|, it shows a placeholder text "Loading
104 // suggestion..." in the |IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION| slot. After
105 // |SpellingServiceClient| responds to the query, |SpellingMenuObserver|
106 // replaces the placeholder text with either the spelling suggestion or the
107 // message "No more suggestions from Google." The "No more suggestions"
108 // message is there when |SpellingServiceClient| returned the same suggestion
109 // as Hunspell.
110 if (use_suggestions) {
111 // Append a placeholder item for the suggestion from the Spelling service
112 // and send a request to the service if we can retrieve suggestions from it.
113 // Also, see if we can use the spelling service to get an ideal suggestion.
114 // Otherwise, we'll fall back to the set of suggestions. Initialize
115 // variables used in OnTextCheckComplete(). We copy the input text to the
116 // result text so we can replace its misspelled regions with suggestions.
117 succeeded_ = false;
118 result_ = params.misspelled_word;
120 // Add a placeholder item. This item will be updated when we receive a
121 // response from the Spelling service. (We do not have to disable this
122 // item now since Chrome will call IsCommandIdEnabled() and disable it.)
123 loading_message_ =
124 l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_SPELLING_CHECKING);
125 proxy_->AddMenuItem(IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION,
126 loading_message_);
127 // Invoke a JSON-RPC call to the Spelling service in the background so we
128 // can update the placeholder item when we receive its response. It also
129 // starts the animation timer so we can show animation until we receive
130 // it.
131 bool result = client_->RequestTextCheck(
132 browser_context,
133 SpellingServiceClient::SUGGEST,
134 params.misspelled_word,
135 base::Bind(&SpellingMenuObserver::OnTextCheckComplete,
136 base::Unretained(this),
137 SpellingServiceClient::SUGGEST));
138 if (result) {
139 loading_frame_ = 0;
140 animation_timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(1),
141 this, &SpellingMenuObserver::OnAnimationTimerExpired);
145 if (params.dictionary_suggestions.empty()) {
146 proxy_->AddMenuItem(
147 IDC_CONTENT_CONTEXT_NO_SPELLING_SUGGESTIONS,
148 l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_NO_SPELLING_SUGGESTIONS));
149 bool use_spelling_service = SpellingServiceClient::IsAvailable(
150 browser_context, SpellingServiceClient::SPELLCHECK);
151 if (use_suggestions || use_spelling_service)
152 proxy_->AddSeparator();
153 } else {
154 proxy_->AddSeparator();
156 // |spellcheck_service| can be null when the suggested word is
157 // provided by Web SpellCheck API.
158 SpellcheckService* spellcheck_service =
159 SpellcheckServiceFactory::GetForContext(browser_context);
160 if (spellcheck_service && spellcheck_service->GetMetrics())
161 spellcheck_service->GetMetrics()->RecordSuggestionStats(1);
164 // If word is misspelled, give option for "Add to dictionary" and a check item
165 // "Ask Google for suggestions".
166 proxy_->AddMenuItem(IDC_SPELLCHECK_ADD_TO_DICTIONARY,
167 l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_ADD_TO_DICTIONARY));
169 proxy_->AddCheckItem(IDC_CONTENT_CONTEXT_SPELLING_TOGGLE,
170 l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_SPELLING_ASK_GOOGLE));
172 const base::CommandLine* command_line =
173 base::CommandLine::ForCurrentProcess();
174 if (command_line->HasSwitch(switches::kEnableSpellingAutoCorrect)) {
175 proxy_->AddCheckItem(IDC_CONTENT_CONTEXT_AUTOCORRECT_SPELLING_TOGGLE,
176 l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_SPELLING_AUTOCORRECT));
179 proxy_->AddSeparator();
182 bool SpellingMenuObserver::IsCommandIdSupported(int command_id) {
183 if (command_id >= IDC_SPELLCHECK_SUGGESTION_0 &&
184 command_id <= IDC_SPELLCHECK_SUGGESTION_LAST)
185 return true;
187 switch (command_id) {
188 case IDC_SPELLCHECK_ADD_TO_DICTIONARY:
189 case IDC_CONTENT_CONTEXT_NO_SPELLING_SUGGESTIONS:
190 case IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION:
191 case IDC_CONTENT_CONTEXT_SPELLING_TOGGLE:
192 case IDC_CONTENT_CONTEXT_AUTOCORRECT_SPELLING_TOGGLE:
193 return true;
195 default:
196 return false;
200 bool SpellingMenuObserver::IsCommandIdChecked(int command_id) {
201 DCHECK(IsCommandIdSupported(command_id));
202 Profile* profile = Profile::FromBrowserContext(proxy_->GetBrowserContext());
204 if (command_id == IDC_CONTENT_CONTEXT_SPELLING_TOGGLE)
205 return integrate_spelling_service_.GetValue() && !profile->IsOffTheRecord();
206 if (command_id == IDC_CONTENT_CONTEXT_AUTOCORRECT_SPELLING_TOGGLE)
207 return autocorrect_spelling_.GetValue() && !profile->IsOffTheRecord();
208 return false;
211 bool SpellingMenuObserver::IsCommandIdEnabled(int command_id) {
212 DCHECK(IsCommandIdSupported(command_id));
214 if (command_id >= IDC_SPELLCHECK_SUGGESTION_0 &&
215 command_id <= IDC_SPELLCHECK_SUGGESTION_LAST)
216 return true;
218 Profile* profile = Profile::FromBrowserContext(proxy_->GetBrowserContext());
219 switch (command_id) {
220 case IDC_SPELLCHECK_ADD_TO_DICTIONARY:
221 return !misspelled_word_.empty();
223 case IDC_CONTENT_CONTEXT_NO_SPELLING_SUGGESTIONS:
224 return false;
226 case IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION:
227 return succeeded_;
229 case IDC_CONTENT_CONTEXT_SPELLING_TOGGLE:
230 return integrate_spelling_service_.IsUserModifiable() &&
231 !profile->IsOffTheRecord();
233 case IDC_CONTENT_CONTEXT_AUTOCORRECT_SPELLING_TOGGLE:
234 return integrate_spelling_service_.IsUserModifiable() &&
235 !profile->IsOffTheRecord();
237 default:
238 return false;
242 void SpellingMenuObserver::ExecuteCommand(int command_id) {
243 DCHECK(IsCommandIdSupported(command_id));
245 if (command_id >= IDC_SPELLCHECK_SUGGESTION_0 &&
246 command_id <= IDC_SPELLCHECK_SUGGESTION_LAST) {
247 int suggestion_index = command_id - IDC_SPELLCHECK_SUGGESTION_0;
248 proxy_->GetWebContents()->ReplaceMisspelling(
249 suggestions_[suggestion_index]);
250 // GetSpellCheckHost() can return null when the suggested word is provided
251 // by Web SpellCheck API.
252 content::BrowserContext* browser_context = proxy_->GetBrowserContext();
253 if (browser_context) {
254 SpellcheckService* spellcheck =
255 SpellcheckServiceFactory::GetForContext(browser_context);
256 if (spellcheck) {
257 if (spellcheck->GetMetrics())
258 spellcheck->GetMetrics()->RecordReplacedWordStats(1);
261 return;
264 // When we choose the suggestion sent from the Spelling service, we replace
265 // the misspelled word with the suggestion and add it to our custom-word
266 // dictionary so this word is not marked as misspelled any longer.
267 if (command_id == IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION) {
268 proxy_->GetWebContents()->ReplaceMisspelling(result_);
269 misspelled_word_ = result_;
272 if (command_id == IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION ||
273 command_id == IDC_SPELLCHECK_ADD_TO_DICTIONARY) {
274 // GetHostForProfile() can return null when the suggested word is provided
275 // by Web SpellCheck API.
276 content::BrowserContext* browser_context = proxy_->GetBrowserContext();
277 if (browser_context) {
278 SpellcheckService* spellcheck =
279 SpellcheckServiceFactory::GetForContext(browser_context);
280 if (spellcheck) {
281 spellcheck->GetCustomDictionary()->AddWord(base::UTF16ToUTF8(
282 misspelled_word_));
285 #if defined(OS_MACOSX)
286 spellcheck_mac::AddWord(misspelled_word_);
287 #endif
290 Profile* profile = Profile::FromBrowserContext(proxy_->GetBrowserContext());
292 // The spelling service can be toggled by the user only if it is not managed.
293 if (command_id == IDC_CONTENT_CONTEXT_SPELLING_TOGGLE &&
294 integrate_spelling_service_.IsUserModifiable()) {
295 // When a user enables the "Ask Google for spelling suggestions" item, we
296 // show a bubble to confirm it. On the other hand, when a user disables this
297 // item, we directly update/ the profile and stop integrating the spelling
298 // service immediately.
299 if (!integrate_spelling_service_.GetValue()) {
300 content::RenderViewHost* rvh = proxy_->GetRenderViewHost();
301 gfx::Rect rect = rvh->GetView()->GetViewBounds();
302 scoped_ptr<SpellingBubbleModel> model(
303 new SpellingBubbleModel(profile, proxy_->GetWebContents(), false));
304 chrome::ShowConfirmBubble(
305 proxy_->GetWebContents()->GetTopLevelNativeWindow(),
306 rvh->GetView()->GetNativeView(),
307 gfx::Point(rect.CenterPoint().x(), rect.y()),
308 model.Pass());
309 } else {
310 if (profile) {
311 profile->GetPrefs()->SetBoolean(prefs::kSpellCheckUseSpellingService,
312 false);
313 profile->GetPrefs()->SetBoolean(prefs::kEnableAutoSpellCorrect,
314 false);
318 // Autocorrect requires use of the spelling service and the spelling service
319 // can be toggled by the user only if it is not managed.
320 if (command_id == IDC_CONTENT_CONTEXT_AUTOCORRECT_SPELLING_TOGGLE &&
321 integrate_spelling_service_.IsUserModifiable()) {
322 // When the user enables autocorrect, we'll need to make sure that we can
323 // ask Google for suggestions since that service is required. So we show
324 // the bubble and just make sure to enable autocorrect as well.
325 if (!integrate_spelling_service_.GetValue()) {
326 content::RenderViewHost* rvh = proxy_->GetRenderViewHost();
327 gfx::Rect rect = rvh->GetView()->GetViewBounds();
328 scoped_ptr<SpellingBubbleModel> model(
329 new SpellingBubbleModel(profile, proxy_->GetWebContents(), true));
330 chrome::ShowConfirmBubble(
331 proxy_->GetWebContents()->GetTopLevelNativeWindow(),
332 rvh->GetView()->GetNativeView(),
333 gfx::Point(rect.CenterPoint().x(), rect.y()),
334 model.Pass());
335 } else {
336 if (profile) {
337 bool current_value = autocorrect_spelling_.GetValue();
338 profile->GetPrefs()->SetBoolean(prefs::kEnableAutoSpellCorrect,
339 !current_value);
345 void SpellingMenuObserver::OnTextCheckComplete(
346 SpellingServiceClient::ServiceType type,
347 bool success,
348 const base::string16& text,
349 const std::vector<SpellCheckResult>& results) {
350 animation_timer_.Stop();
352 // Scan the text-check results and replace the misspelled regions with
353 // suggested words. If the replaced text is included in the suggestion list
354 // provided by the local spellchecker, we show a "No suggestions from Google"
355 // message.
356 succeeded_ = success;
357 if (results.empty()) {
358 succeeded_ = false;
359 } else {
360 typedef std::vector<SpellCheckResult> SpellCheckResults;
361 for (SpellCheckResults::const_iterator it = results.begin();
362 it != results.end(); ++it) {
363 result_.replace(it->location, it->length, it->replacement);
365 base::string16 result = base::i18n::ToLower(result_);
366 for (std::vector<base::string16>::const_iterator it = suggestions_.begin();
367 it != suggestions_.end(); ++it) {
368 if (result == base::i18n::ToLower(*it)) {
369 succeeded_ = false;
370 break;
374 if (type != SpellingServiceClient::SPELLCHECK) {
375 if (!succeeded_) {
376 result_ = l10n_util::GetStringUTF16(
377 IDS_CONTENT_CONTEXT_SPELLING_NO_SUGGESTIONS_FROM_GOOGLE);
380 // Update the menu item with the result text. We disable this item and hide
381 // it when the spelling service does not provide valid suggestions.
382 proxy_->UpdateMenuItem(IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION, succeeded_,
383 false, result_);
387 void SpellingMenuObserver::OnAnimationTimerExpired() {
388 // Append '.' characters to the end of "Checking".
389 loading_frame_ = (loading_frame_ + 1) & 3;
390 base::string16 loading_message =
391 loading_message_ + base::string16(loading_frame_,'.');
393 // Update the menu item with the text. We disable this item to prevent users
394 // from selecting it.
395 proxy_->UpdateMenuItem(IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION, false, false,
396 loading_message);