1 // Copyright (c) 2012 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/spellchecker/spelling_service_client.h"
9 #include "base/json/json_reader.h"
10 #include "base/json/string_escape.h"
11 #include "base/logging.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/stl_util.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/values.h"
18 #include "chrome/common/pref_names.h"
19 #include "chrome/common/spellcheck_common.h"
20 #include "chrome/common/spellcheck_result.h"
21 #include "components/user_prefs/user_prefs.h"
22 #include "content/public/browser/browser_context.h"
23 #include "google_apis/google_api_keys.h"
24 #include "net/base/load_flags.h"
25 #include "net/url_request/url_fetcher.h"
30 // The URL for requesting spell checking and sending user feedback.
31 const char kSpellingServiceURL
[] = "https://www.googleapis.com/rpc";
33 // The location of spellcheck suggestions in JSON response from spelling
35 const char kMisspellingsPath
[] = "result.spellingCheckResponse.misspellings";
37 // The location of error messages in JSON response from spelling service.
38 const char kErrorPath
[] = "error";
40 // Languages currently supported by SPELLCHECK.
41 const char* const kValidLanguages
[] = {"en", "es", "fi", "da"};
45 SpellingServiceClient::SpellingServiceClient() {
48 SpellingServiceClient::~SpellingServiceClient() {
49 STLDeleteContainerPairPointers(spellcheck_fetchers_
.begin(),
50 spellcheck_fetchers_
.end());
53 bool SpellingServiceClient::RequestTextCheck(
54 content::BrowserContext
* context
,
56 const base::string16
& text
,
57 const TextCheckCompleteCallback
& callback
) {
58 DCHECK(type
== SUGGEST
|| type
== SPELLCHECK
);
59 if (!context
|| !IsAvailable(context
, type
)) {
60 callback
.Run(false, text
, std::vector
<SpellCheckResult
>());
64 const PrefService
* pref
= user_prefs::UserPrefs::Get(context
);
67 std::string dictionary
;
68 pref
->GetList(prefs::kSpellCheckDictionaries
)->GetString(0, &dictionary
);
70 std::string language_code
;
71 std::string country_code
;
72 chrome::spellcheck_common::GetISOLanguageCountryCodeFromLocale(
73 dictionary
, &language_code
, &country_code
);
75 // Replace typographical apostrophes with typewriter apostrophes, so that
76 // server word breaker behaves correctly.
77 const base::char16 kApostrophe
= 0x27;
78 const base::char16 kRightSingleQuotationMark
= 0x2019;
79 base::string16 text_copy
= text
;
80 std::replace(text_copy
.begin(), text_copy
.end(), kRightSingleQuotationMark
,
83 // Format the JSON request to be sent to the Spelling service.
84 std::string encoded_text
= base::GetQuotedJSONString(text_copy
);
86 static const char kSpellingRequest
[] =
88 "\"method\":\"spelling.check\","
89 "\"apiVersion\":\"v%d\","
92 "\"language\":\"%s\","
93 "\"originCountry\":\"%s\","
97 std::string api_key
= base::GetQuotedJSONString(google_apis::GetAPIKey());
98 std::string request
= base::StringPrintf(
101 encoded_text
.c_str(),
102 language_code
.c_str(),
103 country_code
.c_str(),
106 GURL url
= GURL(kSpellingServiceURL
);
107 net::URLFetcher
* fetcher
= CreateURLFetcher(url
).release();
108 fetcher
->SetRequestContext(context
->GetRequestContext());
109 fetcher
->SetUploadData("application/json", request
);
110 fetcher
->SetLoadFlags(
111 net::LOAD_DO_NOT_SEND_COOKIES
| net::LOAD_DO_NOT_SAVE_COOKIES
);
112 spellcheck_fetchers_
[fetcher
] = new TextCheckCallbackData(callback
, text
);
117 bool SpellingServiceClient::IsAvailable(
118 content::BrowserContext
* context
,
120 const PrefService
* pref
= user_prefs::UserPrefs::Get(context
);
122 // If prefs don't allow spellchecking, if the context is off the record, or if
123 // multilingual spellchecking is enabled the spelling service should be
125 if (!pref
->GetBoolean(prefs::kEnableContinuousSpellcheck
) ||
126 !pref
->GetBoolean(prefs::kSpellCheckUseSpellingService
) ||
127 context
->IsOffTheRecord())
130 // If the locale for spelling has not been set, the user has not decided to
131 // use spellcheck so we don't do anything remote (suggest or spelling).
133 pref
->GetList(prefs::kSpellCheckDictionaries
)->GetString(0, &locale
);
137 // Finally, if all options are available, we only enable only SUGGEST
138 // if SPELLCHECK is not available for our language because SPELLCHECK results
139 // are a superset of SUGGEST results.
140 for (const char* language
: kValidLanguages
) {
141 if (!locale
.compare(0, 2, language
))
142 return type
== SPELLCHECK
;
145 // Only SUGGEST is allowed.
146 return type
== SUGGEST
;
149 bool SpellingServiceClient::ParseResponse(
150 const std::string
& data
,
151 std::vector
<SpellCheckResult
>* results
) {
152 // When this JSON-RPC call finishes successfully, the Spelling service returns
153 // an JSON object listed below.
154 // * result - an envelope object representing the result from the APIARY
155 // server, which is the JSON-API front-end for the Spelling service. This
156 // object consists of the following variable:
157 // - spellingCheckResponse (SpellingCheckResponse).
158 // * SpellingCheckResponse - an object representing the result from the
159 // Spelling service. This object consists of the following variable:
160 // - misspellings (optional array of Misspelling)
161 // * Misspelling - an object representing a misspelling region and its
162 // suggestions. This object consists of the following variables:
163 // - charStart (number) - the beginning of the misspelled region;
164 // - charLength (number) - the length of the misspelled region;
165 // - suggestions (array of string) - the suggestions for the misspelling
167 // - canAutoCorrect (optional boolean) - whether we can use the first
168 // suggestion for auto-correction.
169 // For example, the Spelling service returns the following JSON when we send a
170 // spelling request for "duck goes quisk" as of 16 August, 2011.
173 // "spellingCheckResponse": {
174 // "misspellings": [{
177 // "suggestions": [{ "suggestion": "quack" }],
178 // "canAutoCorrect": false
183 // If the service is not available, the Spelling service returns JSON with an
188 // "message": "Bad Request",
192 scoped_ptr
<base::DictionaryValue
> value(
193 static_cast<base::DictionaryValue
*>(base::JSONReader::DeprecatedRead(
194 data
, base::JSON_ALLOW_TRAILING_COMMAS
)));
195 if (!value
.get() || !value
->IsType(base::Value::TYPE_DICTIONARY
))
198 // Check for errors from spelling service.
199 base::DictionaryValue
* error
= NULL
;
200 if (value
->GetDictionary(kErrorPath
, &error
))
203 // Retrieve the array of Misspelling objects. When the input text does not
204 // have misspelled words, it returns an empty JSON. (In this case, its HTTP
205 // status is 200.) We just return true for this case.
206 base::ListValue
* misspellings
= NULL
;
207 if (!value
->GetList(kMisspellingsPath
, &misspellings
))
210 for (size_t i
= 0; i
< misspellings
->GetSize(); ++i
) {
211 // Retrieve the i-th misspelling region and put it to the given vector. When
212 // the Spelling service sends two or more suggestions, we read only the
213 // first one because SpellCheckResult can store only one suggestion.
214 base::DictionaryValue
* misspelling
= NULL
;
215 if (!misspellings
->GetDictionary(i
, &misspelling
))
220 base::ListValue
* suggestions
= NULL
;
221 if (!misspelling
->GetInteger("charStart", &start
) ||
222 !misspelling
->GetInteger("charLength", &length
) ||
223 !misspelling
->GetList("suggestions", &suggestions
)) {
227 base::DictionaryValue
* suggestion
= NULL
;
228 base::string16 replacement
;
229 if (!suggestions
->GetDictionary(0, &suggestion
) ||
230 !suggestion
->GetString("suggestion", &replacement
)) {
233 SpellCheckResult
result(
234 SpellCheckResult::SPELLING
, start
, length
, replacement
);
235 results
->push_back(result
);
240 SpellingServiceClient::TextCheckCallbackData::TextCheckCallbackData(
241 TextCheckCompleteCallback callback
,
243 : callback(callback
),
247 SpellingServiceClient::TextCheckCallbackData::~TextCheckCallbackData() {
250 void SpellingServiceClient::OnURLFetchComplete(
251 const net::URLFetcher
* source
) {
252 DCHECK(spellcheck_fetchers_
[source
]);
253 scoped_ptr
<const net::URLFetcher
> fetcher(source
);
254 scoped_ptr
<TextCheckCallbackData
>
255 callback_data(spellcheck_fetchers_
[fetcher
.get()]);
256 bool success
= false;
257 std::vector
<SpellCheckResult
> results
;
258 if (fetcher
->GetResponseCode() / 100 == 2) {
260 fetcher
->GetResponseAsString(&data
);
261 success
= ParseResponse(data
, &results
);
263 spellcheck_fetchers_
.erase(fetcher
.get());
265 // The callback may release the last (transitive) dependency on |this|. It
266 // MUST be the last function called.
267 callback_data
->callback
.Run(success
, callback_data
->text
, results
);
270 scoped_ptr
<net::URLFetcher
> SpellingServiceClient::CreateURLFetcher(
272 return net::URLFetcher::Create(url
, net::URLFetcher::POST
, this);