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"
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
)
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
)
65 // Exit if there is no misspelled word.
66 if (params
.misspelled_word
.empty())
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
;
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
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
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.
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.)
126 l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_SPELLING_CHECKING
);
127 proxy_
->AddMenuItem(IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION
,
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
133 bool result
= client_
->RequestTextCheck(
134 profile
, SpellingServiceClient::SUGGEST
, params
.misspelled_word
,
135 base::Bind(&SpellingMenuObserver::OnTextCheckComplete
,
136 base::Unretained(this), SpellingServiceClient::SUGGEST
));
139 animation_timer_
.Start(FROM_HERE
, base::TimeDelta::FromSeconds(1),
140 this, &SpellingMenuObserver::OnAnimationTimerExpired
);
144 if (params
.dictionary_suggestions
.empty()) {
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();
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
) {
173 proxy_
->AddCheckItem(IDC_CONTENT_CONTEXT_SPELLING_TOGGLE
,
174 l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_SPELLING_ASK_GOOGLE
));
175 #if defined(TOOLKIT_GTK)
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
)
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
:
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();
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
)
225 switch (command_id
) {
226 case IDC_SPELLCHECK_ADD_TO_DICTIONARY
:
227 return !misspelled_word_
.empty();
229 case IDC_CONTENT_CONTEXT_NO_SPELLING_SUGGESTIONS
:
232 case IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION
:
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();
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();
260 SpellcheckService
* spellcheck
=
261 SpellcheckServiceFactory::GetForContext(profile
);
263 if (spellcheck
->GetMetrics())
264 spellcheck
->GetMetrics()->RecordReplacedWordStats(1);
265 spellcheck
->GetFeedbackSender()->SelectedSuggestion(
266 misspelling_hash_
, suggestion_index
);
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();
286 SpellcheckService
* spellcheck
=
287 SpellcheckServiceFactory::GetForContext(profile
);
289 spellcheck
->GetCustomDictionary()->AddWord(base::UTF16ToUTF8(
291 spellcheck
->GetFeedbackSender()->AddedToDictionary(misspelling_hash_
);
294 #if defined(OS_MACOSX)
295 spellcheck_mac::AddWord(misspelled_word_
);
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(),
313 rvh
->GetView()->GetNativeView(),
315 gfx::Point(rect
.CenterPoint().x(), rect
.y()),
316 new SpellingBubbleModel(proxy_
->GetProfile(),
317 proxy_
->GetWebContents(),
320 Profile
* profile
= proxy_
->GetProfile();
322 profile
->GetPrefs()->SetBoolean(prefs::kSpellCheckUseSpellingService
,
324 profile
->GetPrefs()->SetBoolean(prefs::kEnableAutoSpellCorrect
,
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(),
345 Profile
* profile
= proxy_
->GetProfile();
347 bool current_value
= autocorrect_spelling_
.GetValue();
348 profile
->GetPrefs()->SetBoolean(prefs::kEnableAutoSpellCorrect
,
355 void SpellingMenuObserver::OnMenuCancel() {
356 Profile
* profile
= proxy_
->GetProfile();
359 SpellcheckService
* spellcheck
=
360 SpellcheckServiceFactory::GetForContext(profile
);
363 spellcheck
->GetFeedbackSender()->IgnoredSuggestions(misspelling_hash_
);
366 void SpellingMenuObserver::OnTextCheckComplete(
367 SpellingServiceClient::ServiceType type
,
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"
377 succeeded_
= success
;
378 if (results
.empty()) {
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
)) {
395 if (type
!= SpellingServiceClient::SPELLCHECK
) {
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_
,
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,