Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(398)

Side by Side Diff: chrome/browser/tab_contents/spelling_menu_observer.cc

Issue 7713033: Integrate the Spelling service to Chrome. (Closed) Base URL: svn://chrome-svn/chrome/trunk/src/
Patch Set: '' Created 9 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
Property Changes:
Added: svn:eol-style
+ LF
OLDNEW
(Empty)
1 // Copyright (c) 2011 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.
4
5 #include "chrome/browser/tab_contents/spelling_menu_observer.h"
6
7 #include <string>
8
9 #include "base/json/json_reader.h"
10 #include "base/json/string_escape.h"
11 #include "base/stringprintf.h"
12 #include "base/utf_string_conversions.h"
13 #include "base/values.h"
14 #include "chrome/app/chrome_command_ids.h"
15 #include "chrome/browser/prefs/pref_service.h"
16 #include "chrome/browser/profiles/profile.h"
17 #include "chrome/browser/tab_contents/render_view_context_menu.h"
18 #include "chrome/common/pref_names.h"
19 #include "content/browser/renderer_host/render_view_host.h"
20 #include "googleurl/src/gurl.h"
21 #include "grit/generated_resources.h"
22 #include "ui/base/l10n/l10n_util.h"
23 #include "unicode/uloc.h"
24 #include "webkit/glue/context_menu.h"
25
26 #if defined(GOOGLE_CHROME_BUILD)
27 #include "chrome/browser/spellchecker/internal/spellcheck_internal.h"
28 #else
29 // Use a dummy URL and a key on Chromium to avoid build breaks until the
30 // Spelling API is released. These dummy parameters just cause a timeout and
31 // show 'no suggestions found'.
32 #define SPELLING_SERVICE_KEY
33 #define SPELLING_SERVICE_URL "http://127.0.0.1/rpc"
34 #endif
35
36 SpellingMenuObserver::SpellingMenuObserver(RenderViewContextMenuProxy* proxy)
37 : proxy_(proxy),
38 loading_frame_(0),
39 succeeded_(false) {
40 }
41
42 SpellingMenuObserver::~SpellingMenuObserver() {
43 }
44
45 void SpellingMenuObserver::InitMenu(const ContextMenuParams& params) {
46 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
47
48 // Exit if we are not in an editable element because we add a menu item only
49 // for editable elements.
50 if (!params.is_editable)
51 return;
52
53 Profile* profile = proxy_->GetProfile();
54 if (!profile || !profile->GetRequestContext())
55 return;
56
57 // Retrieve the misspelled word to be sent to the Spelling service.
58 string16 text = params.misspelled_word;
59 if (text.empty())
60 return;
61
62 // Initialize variables used in OnURLFetchComplete(). We copy the input text
63 // to the result text so we can replace its misspelled regions with
64 // suggestions.
65 loading_frame_ = 0;
66 succeeded_ = false;
67 result_ = text;
68
69 // Add a placeholder item. This item will be updated when we receive a
70 // response from the Spelling service. (We do not have to disable this item
71 // now since Chrome will call IsCommandIdEnabled() and disable it.)
72 loading_message_ =
73 l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_SPELLING_CHECKING);
74 proxy_->AddMenuItem(IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION,
75 loading_message_);
76
77 // Invoke a JSON-RPC call to the Spelling service in the background so we can
78 // update the placeholder item when we receive its response. It also starts
79 // the animation timer so we can show animation until we receive it.
80 const PrefService* pref = profile->GetPrefs();
81 std::string language =
82 pref ? pref->GetString(prefs::kSpellCheckDictionary) : "en-US";
83 Invoke(text, language, profile->GetRequestContext());
84 }
85
86 bool SpellingMenuObserver::IsCommandIdSupported(int command_id) {
87 return command_id == IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION;
88 }
89
90 bool SpellingMenuObserver::IsCommandIdEnabled(int command_id) {
91 return command_id == IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION && succeeded_;
92 }
93
94 void SpellingMenuObserver::ExecuteCommand(int command_id) {
95 if (IsCommandIdEnabled(command_id))
96 proxy_->GetRenderViewHost()->Replace(result_);
97 }
98
99 bool SpellingMenuObserver::Invoke(const string16& text,
100 const std::string& locale,
101 net::URLRequestContextGetter* context) {
102 // Create the parameters needed by Spelling API. Spelling API needs three
103 // parameters: ISO language code, ISO3 country code, and text to be checked by
104 // the service. On the other hand, Chrome uses an ISO locale ID and it may
105 // not include a country ID, e.g. "fr", "de", etc. To create the input
106 // parameters, we convert the UI locale to a full locale ID, and convert the
107 // full locale ID to an ISO language code and and ISO3 country code. Also, we
108 // convert the given text to a JSON string, i.e. quote all its non-ASCII
109 // characters.
110 UErrorCode error = U_ZERO_ERROR;
111 char id[ULOC_LANG_CAPACITY + ULOC_SCRIPT_CAPACITY + ULOC_COUNTRY_CAPACITY];
112 uloc_addLikelySubtags(locale.c_str(), id, arraysize(id), &error);
113
114 error = U_ZERO_ERROR;
115 char language[ULOC_LANG_CAPACITY];
116 uloc_getLanguage(id, language, arraysize(language), &error);
117
118 const char* country = uloc_getISO3Country(id);
119
120 std::string encoded_text;
121 base::JsonDoubleQuote(text, false, &encoded_text);
122
123 // Format the JSON request to be sent to the Spelling service.
124 static const char kSpellingRequest[] =
125 "{"
126 "\"method\":\"spelling.check\","
127 "\"apiVersion\":\"v1\","
128 "\"params\":{"
129 "\"text\":\"%s\","
130 "\"language\":\"%s\","
131 "\"origin_country\":\"%s\","
132 "\"key\":\"" SPELLING_SERVICE_KEY "\""
133 "}"
134 "}";
135 std::string request = base::StringPrintf(kSpellingRequest,
136 encoded_text.c_str(),
137 language, country);
138
139 static const char kSpellingServiceURL[] = SPELLING_SERVICE_URL;
140 GURL url = GURL(kSpellingServiceURL);
141 fetcher_.reset(new URLFetcher(url, URLFetcher::POST, this));
142 fetcher_->set_request_context(context);
143 fetcher_->set_upload_data("application/json", request);
144 fetcher_->Start();
145
146 animation_timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(1),
147 this, &SpellingMenuObserver::OnAnimationTimerExpired);
148
149 return true;
150 }
151
152 void SpellingMenuObserver::OnURLFetchComplete(
153 const URLFetcher* source,
154 const GURL& url,
155 const net::URLRequestStatus& status,
156 int response,
157 const net::ResponseCookies& cookies,
158 const std::string& data) {
159 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
160
161 fetcher_.reset();
162 animation_timer_.Stop();
163
164 // Parse the response JSON and replace misspelled words in the |result_| text
165 // with their suggestions.
166 succeeded_ = ParseResponse(response, data);
167 if (!succeeded_)
168 result_ = l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_SPELLING_CORRECT);
169
170 // Update the menu item with the result text. We enable this item only when
171 // the request text has misspelled words. (We disable this item not only when
172 // we receive a server error but also when the input text consists only of
173 // well-spelled words. For either case, we do not need to replace the input
174 // text.)
175 proxy_->UpdateMenuItem(IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION, succeeded_,
176 result_);
177 }
178
179 bool SpellingMenuObserver::ParseResponse(int response,
180 const std::string& data) {
181 // When this JSON-RPC call finishes successfully, the Spelling service returns
182 // an JSON object listed below.
183 // * result - an envelope object representing the result from the APIARY
184 // server, which is the JSON-API front-end for the Spelling service. This
185 // object consists of the following variable:
186 // - spellingCheckResponse (SpellingCheckResponse).
187 // * SpellingCheckResponse - an object representing the result from the
188 // Spelling service. This object consists of the following variable:
189 // - misspellings (optional array of Misspelling)
190 // * Misspelling - an object representing a misspelling region and its
191 // suggestions. This object consists of the following variables:
192 // - charStart (number) - the beginning of the misspelled region;
193 // - charLength (number) - the length of the misspelled region;
194 // - suggestions (array of string) - the suggestions for the misspelling
195 // text, and;
196 // - canAutoCorrect (optional boolean) - whether we can use the first
197 // suggestion for auto-correction.
198 // For example, the Spelling service returns the following JSON when we send a
199 // spelling request for "duck goes quisk" as of 16 August, 2011.
200 // {
201 // "result": {
202 // "spellingCheckResponse": {
203 // "misspellings": [{
204 // "charStart": 10,
205 // "charLength": 5,
206 // "suggestions": [{ "suggestion": "quack" }],
207 // "canAutoCorrect": false
208 // }]
209 // }
210 // }
211
212 // When a server error happened in the APIARY server (including when we cannot
213 // get any responses from the server), it returns an HTTP error.
214 if ((response / 100) != 2)
215 return false;
216
217 scoped_ptr<DictionaryValue> value(
218 static_cast<DictionaryValue*>(base::JSONReader::Read(data, true)));
219 if (!value.get() || !value->IsType(base::Value::TYPE_DICTIONARY))
220 return false;
221
222 // Retrieve the array of Misspelling objects. When the APIARY service failed
223 // calling the Spelling service, it returns a JSON representing the service
224 // error. (In this case, its HTTP status is 200.) We just return false for
225 // this case.
226 ListValue* misspellings = NULL;
227 const char kMisspellings[] = "result.spellingCheckResponse.misspellings";
228 if (!value->GetList(kMisspellings, &misspellings))
229 return false;
230
231 // For each misspelled region, we replace it with its first suggestion.
232 for (size_t i = 0; i < misspellings->GetSize(); ++i) {
233 // Retrieve the i-th misspelling region, which represents misspelling text
234 // in the request text and its alternative.
235 DictionaryValue* misspelling = NULL;
236 if (!misspellings->GetDictionary(i, &misspelling))
237 return false;
238
239 int start = 0;
240 int length = 0;
241 ListValue* suggestions = NULL;
242 if (!misspelling->GetInteger("charStart", &start) ||
243 !misspelling->GetInteger("charLength", &length) ||
244 !misspelling->GetList("suggestions", &suggestions)) {
245 return false;
246 }
247
248 // Retrieve the alternative text and replace the misspelling region with the
249 // alternative.
250 DictionaryValue* suggestion = NULL;
251 string16 text;
252 if (!suggestions->GetDictionary(0, &suggestion) ||
253 !suggestion->GetString("suggestion", &text)) {
254 return false;
255 }
256 result_.replace(start, length, text);
257 }
258
259 return true;
260 }
261
262 void SpellingMenuObserver::OnAnimationTimerExpired() {
263 if (!fetcher_.get())
264 return;
265
266 // Append '.' characters to the end of "Checking".
267 loading_frame_ = (loading_frame_ + 1) & 3;
268 string16 loading_message = loading_message_;
269 for (int i = 0; i < loading_frame_; ++i)
270 loading_message.push_back('.');
271
272 // Update the menu item with the text. We disable this item to prevent users
273 // from selecting it.
274 proxy_->UpdateMenuItem(IDC_CONTENT_CONTEXT_SPELLING_SUGGESTION, false,
275 loading_message);
276 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698