Componentize AccountReconcilor.
[chromium-blink-merge.git] / chrome / browser / renderer_context_menu / spelling_menu_observer.cc
blob16ee4e76a2fd9f938291c9e4e7e3ad80c6312657
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 "content/public/browser/render_view_host.h"
26 #include "content/public/browser/render_widget_host_view.h"
27 #include "content/public/browser/web_contents.h"
28 #include "content/public/browser/web_contents_view.h"
29 #include "content/public/common/context_menu_params.h"
30 #include "extensions/browser/view_type_utils.h"
31 #include "grit/generated_resources.h"
32 #include "ui/base/l10n/l10n_util.h"
33 #include "ui/gfx/rect.h"
35 using content::BrowserThread;
37 SpellingMenuObserver::SpellingMenuObserver(RenderViewContextMenuProxy* proxy)
38 : proxy_(proxy),
39 loading_frame_(0),
40 succeeded_(false),
41 misspelling_hash_(0),
42 client_(new SpellingServiceClient) {
43 if (proxy && proxy->GetProfile()) {
44 integrate_spelling_service_.Init(prefs::kSpellCheckUseSpellingService,
45 proxy->GetProfile()->GetPrefs());
46 autocorrect_spelling_.Init(prefs::kEnableAutoSpellCorrect,
47 proxy->GetProfile()->GetPrefs());
51 SpellingMenuObserver::~SpellingMenuObserver() {
54 void SpellingMenuObserver::InitMenu(const content::ContextMenuParams& params) {
55 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
56 DCHECK(!params.misspelled_word.empty() ||
57 params.dictionary_suggestions.empty());
59 // Exit if we are not in an editable element because we add a menu item only
60 // for editable elements.
61 Profile* profile = proxy_->GetProfile();
62 if (!params.is_editable || !profile)
63 return;
65 // Exit if there is no misspelled word.
66 if (params.misspelled_word.empty())
67 return;
69 suggestions_ = params.dictionary_suggestions;
70 misspelled_word_ = params.misspelled_word;
71 misspelling_hash_ = params.misspelling_hash;
73 bool use_suggestions = SpellingServiceClient::IsAvailable(
74 profile, SpellingServiceClient::SUGGEST);
76 if (!suggestions_.empty() || use_suggestions)
77 proxy_->AddSeparator();
79 // Append Dictionary spell check suggestions.
80 for (size_t i = 0; i < params.dictionary_suggestions.size() &&
81 IDC_SPELLCHECK_SUGGESTION_0 + i <= IDC_SPELLCHECK_SUGGESTION_LAST;
82 ++i) {
83 proxy_->AddMenuItem(IDC_SPELLCHECK_SUGGESTION_0 + static_cast<int>(i),
84 params.dictionary_suggestions[i]);
87 // The service types |SpellingServiceClient::SPELLCHECK| and
88 // |SpellingServiceClient::SUGGEST| are mutually exclusive. Only one is
89 // available at at time.
91 // When |SpellingServiceClient::SPELLCHECK| is available, the contextual
92 // suggestions from |SpellingServiceClient| are already stored in
93 // |params.dictionary_suggestions|. |SpellingMenuObserver| places these
94 // suggestions in the slots |IDC_SPELLCHECK_SUGGESTION_[0-LAST]|. If
95 // |SpellingMenuObserver| queried |SpellingServiceClient| again, then quality
96 // of suggestions would be reduced by lack of context around the misspelled
97 // word.
99 // When |SpellingServiceClient::SUGGEST| is available,
100 // |params.dictionary_suggestions| contains suggestions only from Hunspell
101 // dictionary. |SpellingMenuObserver| queries |SpellingServiceClient| with the
102 // misspelled word without the surrounding context. Spellcheck suggestions
103 // from |SpellingServiceClient::SUGGEST| are not available until
104 // |SpellingServiceClient| responds to the query. While |SpellingMenuObserver|
105 // waits for |SpellingServiceClient|, it shows a placeholder text "Loading
106 // suggestion..." in the |IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION| slot. After
107 // |SpellingServiceClient| responds to the query, |SpellingMenuObserver|
108 // replaces the placeholder text with either the spelling suggestion or the
109 // message "No more suggestions from Google." The "No more suggestions"
110 // message is there when |SpellingServiceClient| returned the same suggestion
111 // as Hunspell.
112 if (use_suggestions) {
113 // Append a placeholder item for the suggestion from the Spelling service
114 // and send a request to the service if we can retrieve suggestions from it.
115 // Also, see if we can use the spelling service to get an ideal suggestion.
116 // Otherwise, we'll fall back to the set of suggestions. Initialize
117 // variables used in OnTextCheckComplete(). We copy the input text to the
118 // result text so we can replace its misspelled regions with suggestions.
119 succeeded_ = false;
120 result_ = params.misspelled_word;
122 // Add a placeholder item. This item will be updated when we receive a
123 // response from the Spelling service. (We do not have to disable this
124 // item now since Chrome will call IsCommandIdEnabled() and disable it.)
125 loading_message_ =
126 l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_SPELLING_CHECKING);
127 proxy_->AddMenuItem(IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION,
128 loading_message_);
129 // Invoke a JSON-RPC call to the Spelling service in the background so we
130 // can update the placeholder item when we receive its response. It also
131 // starts the animation timer so we can show animation until we receive
132 // it.
133 bool result = client_->RequestTextCheck(
134 profile, SpellingServiceClient::SUGGEST, params.misspelled_word,
135 base::Bind(&SpellingMenuObserver::OnTextCheckComplete,
136 base::Unretained(this), SpellingServiceClient::SUGGEST));
137 if (result) {
138 loading_frame_ = 0;
139 animation_timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(1),
140 this, &SpellingMenuObserver::OnAnimationTimerExpired);
144 if (params.dictionary_suggestions.empty()) {
145 proxy_->AddMenuItem(
146 IDC_CONTENT_CONTEXT_NO_SPELLING_SUGGESTIONS,
147 l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_NO_SPELLING_SUGGESTIONS));
148 bool use_spelling_service = SpellingServiceClient::IsAvailable(
149 profile, SpellingServiceClient::SPELLCHECK);
150 if (use_suggestions || use_spelling_service)
151 proxy_->AddSeparator();
152 } else {
153 proxy_->AddSeparator();
155 // |spellcheck_service| can be null when the suggested word is
156 // provided by Web SpellCheck API.
157 SpellcheckService* spellcheck_service =
158 SpellcheckServiceFactory::GetForContext(profile);
159 if (spellcheck_service && spellcheck_service->GetMetrics())
160 spellcheck_service->GetMetrics()->RecordSuggestionStats(1);
163 // If word is misspelled, give option for "Add to dictionary" and a check item
164 // "Ask Google for suggestions".
165 proxy_->AddMenuItem(IDC_SPELLCHECK_ADD_TO_DICTIONARY,
166 l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_ADD_TO_DICTIONARY));
168 #if defined(TOOLKIT_GTK)
169 extensions::ViewType view_type =
170 extensions::GetViewType(proxy_->GetWebContents());
171 if (view_type != extensions::VIEW_TYPE_PANEL) {
172 #endif
173 proxy_->AddCheckItem(IDC_CONTENT_CONTEXT_SPELLING_TOGGLE,
174 l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_SPELLING_ASK_GOOGLE));
175 #if defined(TOOLKIT_GTK)
177 #endif
179 const CommandLine* command_line = CommandLine::ForCurrentProcess();
180 if (command_line->HasSwitch(switches::kEnableSpellingAutoCorrect)) {
181 proxy_->AddCheckItem(IDC_CONTENT_CONTEXT_AUTOCORRECT_SPELLING_TOGGLE,
182 l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_SPELLING_AUTOCORRECT));
185 proxy_->AddSeparator();
188 bool SpellingMenuObserver::IsCommandIdSupported(int command_id) {
189 if (command_id >= IDC_SPELLCHECK_SUGGESTION_0 &&
190 command_id <= IDC_SPELLCHECK_SUGGESTION_LAST)
191 return true;
193 switch (command_id) {
194 case IDC_SPELLCHECK_ADD_TO_DICTIONARY:
195 case IDC_CONTENT_CONTEXT_NO_SPELLING_SUGGESTIONS:
196 case IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION:
197 case IDC_CONTENT_CONTEXT_SPELLING_TOGGLE:
198 case IDC_CONTENT_CONTEXT_AUTOCORRECT_SPELLING_TOGGLE:
199 return true;
201 default:
202 return false;
206 bool SpellingMenuObserver::IsCommandIdChecked(int command_id) {
207 DCHECK(IsCommandIdSupported(command_id));
209 if (command_id == IDC_CONTENT_CONTEXT_SPELLING_TOGGLE)
210 return integrate_spelling_service_.GetValue() &&
211 !proxy_->GetProfile()->IsOffTheRecord();
212 if (command_id == IDC_CONTENT_CONTEXT_AUTOCORRECT_SPELLING_TOGGLE)
213 return autocorrect_spelling_.GetValue() &&
214 !proxy_->GetProfile()->IsOffTheRecord();
215 return false;
218 bool SpellingMenuObserver::IsCommandIdEnabled(int command_id) {
219 DCHECK(IsCommandIdSupported(command_id));
221 if (command_id >= IDC_SPELLCHECK_SUGGESTION_0 &&
222 command_id <= IDC_SPELLCHECK_SUGGESTION_LAST)
223 return true;
225 switch (command_id) {
226 case IDC_SPELLCHECK_ADD_TO_DICTIONARY:
227 return !misspelled_word_.empty();
229 case IDC_CONTENT_CONTEXT_NO_SPELLING_SUGGESTIONS:
230 return false;
232 case IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION:
233 return succeeded_;
235 case IDC_CONTENT_CONTEXT_SPELLING_TOGGLE:
236 return integrate_spelling_service_.IsUserModifiable() &&
237 !proxy_->GetProfile()->IsOffTheRecord();
239 case IDC_CONTENT_CONTEXT_AUTOCORRECT_SPELLING_TOGGLE:
240 return integrate_spelling_service_.IsUserModifiable() &&
241 !proxy_->GetProfile()->IsOffTheRecord();
243 default:
244 return false;
248 void SpellingMenuObserver::ExecuteCommand(int command_id) {
249 DCHECK(IsCommandIdSupported(command_id));
251 if (command_id >= IDC_SPELLCHECK_SUGGESTION_0 &&
252 command_id <= IDC_SPELLCHECK_SUGGESTION_LAST) {
253 int suggestion_index = command_id - IDC_SPELLCHECK_SUGGESTION_0;
254 proxy_->GetWebContents()->ReplaceMisspelling(
255 suggestions_[suggestion_index]);
256 // GetSpellCheckHost() can return null when the suggested word is provided
257 // by Web SpellCheck API.
258 Profile* profile = proxy_->GetProfile();
259 if (profile) {
260 SpellcheckService* spellcheck =
261 SpellcheckServiceFactory::GetForContext(profile);
262 if (spellcheck) {
263 if (spellcheck->GetMetrics())
264 spellcheck->GetMetrics()->RecordReplacedWordStats(1);
265 spellcheck->GetFeedbackSender()->SelectedSuggestion(
266 misspelling_hash_, suggestion_index);
269 return;
272 // When we choose the suggestion sent from the Spelling service, we replace
273 // the misspelled word with the suggestion and add it to our custom-word
274 // dictionary so this word is not marked as misspelled any longer.
275 if (command_id == IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION) {
276 proxy_->GetWebContents()->ReplaceMisspelling(result_);
277 misspelled_word_ = result_;
280 if (command_id == IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION ||
281 command_id == IDC_SPELLCHECK_ADD_TO_DICTIONARY) {
282 // GetHostForProfile() can return null when the suggested word is provided
283 // by Web SpellCheck API.
284 Profile* profile = proxy_->GetProfile();
285 if (profile) {
286 SpellcheckService* spellcheck =
287 SpellcheckServiceFactory::GetForContext(profile);
288 if (spellcheck) {
289 spellcheck->GetCustomDictionary()->AddWord(base::UTF16ToUTF8(
290 misspelled_word_));
291 spellcheck->GetFeedbackSender()->AddedToDictionary(misspelling_hash_);
294 #if defined(OS_MACOSX)
295 spellcheck_mac::AddWord(misspelled_word_);
296 #endif
299 // The spelling service can be toggled by the user only if it is not managed.
300 if (command_id == IDC_CONTENT_CONTEXT_SPELLING_TOGGLE &&
301 integrate_spelling_service_.IsUserModifiable()) {
302 // When a user enables the "Ask Google for spelling suggestions" item, we
303 // show a bubble to confirm it. On the other hand, when a user disables this
304 // item, we directly update/ the profile and stop integrating the spelling
305 // service immediately.
306 if (!integrate_spelling_service_.GetValue()) {
307 content::RenderViewHost* rvh = proxy_->GetRenderViewHost();
308 gfx::Rect rect = rvh->GetView()->GetViewBounds();
309 chrome::ShowConfirmBubble(
310 #if defined(TOOLKIT_VIEWS)
311 proxy_->GetWebContents()->GetView()->GetTopLevelNativeWindow(),
312 #else
313 rvh->GetView()->GetNativeView(),
314 #endif
315 gfx::Point(rect.CenterPoint().x(), rect.y()),
316 new SpellingBubbleModel(proxy_->GetProfile(),
317 proxy_->GetWebContents(),
318 false));
319 } else {
320 Profile* profile = proxy_->GetProfile();
321 if (profile)
322 profile->GetPrefs()->SetBoolean(prefs::kSpellCheckUseSpellingService,
323 false);
324 profile->GetPrefs()->SetBoolean(prefs::kEnableAutoSpellCorrect,
325 false);
328 // Autocorrect requires use of the spelling service and the spelling service
329 // can be toggled by the user only if it is not managed.
330 if (command_id == IDC_CONTENT_CONTEXT_AUTOCORRECT_SPELLING_TOGGLE &&
331 integrate_spelling_service_.IsUserModifiable()) {
332 // When the user enables autocorrect, we'll need to make sure that we can
333 // ask Google for suggestions since that service is required. So we show
334 // the bubble and just make sure to enable autocorrect as well.
335 if (!integrate_spelling_service_.GetValue()) {
336 content::RenderViewHost* rvh = proxy_->GetRenderViewHost();
337 gfx::Rect rect = rvh->GetView()->GetViewBounds();
338 chrome::ShowConfirmBubble(rvh->GetView()->GetNativeView(),
339 gfx::Point(rect.CenterPoint().x(), rect.y()),
340 new SpellingBubbleModel(
341 proxy_->GetProfile(),
342 proxy_->GetWebContents(),
343 true));
344 } else {
345 Profile* profile = proxy_->GetProfile();
346 if (profile) {
347 bool current_value = autocorrect_spelling_.GetValue();
348 profile->GetPrefs()->SetBoolean(prefs::kEnableAutoSpellCorrect,
349 !current_value);
355 void SpellingMenuObserver::OnMenuCancel() {
356 Profile* profile = proxy_->GetProfile();
357 if (!profile)
358 return;
359 SpellcheckService* spellcheck =
360 SpellcheckServiceFactory::GetForContext(profile);
361 if (!spellcheck)
362 return;
363 spellcheck->GetFeedbackSender()->IgnoredSuggestions(misspelling_hash_);
366 void SpellingMenuObserver::OnTextCheckComplete(
367 SpellingServiceClient::ServiceType type,
368 bool success,
369 const base::string16& text,
370 const std::vector<SpellCheckResult>& results) {
371 animation_timer_.Stop();
373 // Scan the text-check results and replace the misspelled regions with
374 // suggested words. If the replaced text is included in the suggestion list
375 // provided by the local spellchecker, we show a "No suggestions from Google"
376 // message.
377 succeeded_ = success;
378 if (results.empty()) {
379 succeeded_ = false;
380 } else {
381 typedef std::vector<SpellCheckResult> SpellCheckResults;
382 for (SpellCheckResults::const_iterator it = results.begin();
383 it != results.end(); ++it) {
384 result_.replace(it->location, it->length, it->replacement);
386 base::string16 result = base::i18n::ToLower(result_);
387 for (std::vector<base::string16>::const_iterator it = suggestions_.begin();
388 it != suggestions_.end(); ++it) {
389 if (result == base::i18n::ToLower(*it)) {
390 succeeded_ = false;
391 break;
395 if (type != SpellingServiceClient::SPELLCHECK) {
396 if (!succeeded_) {
397 result_ = l10n_util::GetStringUTF16(
398 IDS_CONTENT_CONTEXT_SPELLING_NO_SUGGESTIONS_FROM_GOOGLE);
401 // Update the menu item with the result text. We disable this item and hide
402 // it when the spelling service does not provide valid suggestions.
403 proxy_->UpdateMenuItem(IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION, succeeded_,
404 false, result_);
408 void SpellingMenuObserver::OnAnimationTimerExpired() {
409 // Append '.' characters to the end of "Checking".
410 loading_frame_ = (loading_frame_ + 1) & 3;
411 base::string16 loading_message =
412 loading_message_ + base::string16(loading_frame_,'.');
414 // Update the menu item with the text. We disable this item to prevent users
415 // from selecting it.
416 proxy_->UpdateMenuItem(IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION, false, false,
417 loading_message);