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 "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
)
40 client_(new SpellingServiceClient
) {
41 if (proxy_
&& proxy_
->GetBrowserContext()) {
42 Profile
* profile
= Profile::FromBrowserContext(proxy_
->GetBrowserContext());
43 integrate_spelling_service_
.Init(prefs::kSpellCheckUseSpellingService
,
45 autocorrect_spelling_
.Init(prefs::kEnableAutoSpellCorrect
,
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
)
64 // Exit if there is no misspelled word.
65 if (params
.misspelled_word
.empty())
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
;
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
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
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.
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.)
124 l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_SPELLING_CHECKING
);
125 proxy_
->AddMenuItem(IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION
,
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
131 bool result
= client_
->RequestTextCheck(
133 SpellingServiceClient::SUGGEST
,
134 params
.misspelled_word
,
135 base::Bind(&SpellingMenuObserver::OnTextCheckComplete
,
136 base::Unretained(this),
137 SpellingServiceClient::SUGGEST
));
140 animation_timer_
.Start(FROM_HERE
, base::TimeDelta::FromSeconds(1),
141 this, &SpellingMenuObserver::OnAnimationTimerExpired
);
145 if (params
.dictionary_suggestions
.empty()) {
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();
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
)
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
:
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();
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
)
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
:
226 case IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION
:
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();
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
);
257 if (spellcheck
->GetMetrics())
258 spellcheck
->GetMetrics()->RecordReplacedWordStats(1);
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
);
281 spellcheck
->GetCustomDictionary()->AddWord(base::UTF16ToUTF8(
285 #if defined(OS_MACOSX)
286 spellcheck_mac::AddWord(misspelled_word_
);
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()),
311 profile
->GetPrefs()->SetBoolean(prefs::kSpellCheckUseSpellingService
,
313 profile
->GetPrefs()->SetBoolean(prefs::kEnableAutoSpellCorrect
,
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()),
337 bool current_value
= autocorrect_spelling_
.GetValue();
338 profile
->GetPrefs()->SetBoolean(prefs::kEnableAutoSpellCorrect
,
345 void SpellingMenuObserver::OnTextCheckComplete(
346 SpellingServiceClient::ServiceType type
,
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"
356 succeeded_
= success
;
357 if (results
.empty()) {
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
)) {
374 if (type
!= SpellingServiceClient::SPELLCHECK
) {
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_
,
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,