• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
5 #include "chrome/browser/spellchecker/spellcheck_service.h"
6 
7 #include "base/platform_file.h"
8 #include "base/prefs/pref_member.h"
9 #include "base/prefs/pref_service.h"
10 #include "base/strings/string_split.h"
11 #include "base/synchronization/waitable_event.h"
12 #include "chrome/browser/spellchecker/spellcheck_factory.h"
13 #include "chrome/browser/spellchecker/spellcheck_host_metrics.h"
14 #include "chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h"
15 #include "chrome/browser/spellchecker/spellcheck_platform_mac.h"
16 #include "chrome/browser/spellchecker/spelling_service_client.h"
17 #include "chrome/common/pref_names.h"
18 #include "chrome/common/spellcheck_messages.h"
19 #include "components/user_prefs/user_prefs.h"
20 #include "content/public/browser/browser_context.h"
21 #include "content/public/browser/browser_thread.h"
22 #include "content/public/browser/notification_service.h"
23 #include "content/public/browser/notification_types.h"
24 #include "content/public/browser/render_process_host.h"
25 #include "ipc/ipc_platform_file.h"
26 
27 using content::BrowserThread;
28 using chrome::spellcheck_common::WordList;
29 
30 // TODO(rlp): I do not like globals, but keeping these for now during
31 // transition.
32 // An event used by browser tests to receive status events from this class and
33 // its derived classes.
34 base::WaitableEvent* g_status_event = NULL;
35 SpellcheckService::EventType g_status_type =
36     SpellcheckService::BDICT_NOTINITIALIZED;
37 
SpellcheckService(content::BrowserContext * context)38 SpellcheckService::SpellcheckService(content::BrowserContext* context)
39     : context_(context),
40       weak_ptr_factory_(this) {
41   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
42   PrefService* prefs = user_prefs::UserPrefs::Get(context);
43   pref_change_registrar_.Init(prefs);
44 
45   std::string language_code;
46   std::string country_code;
47   chrome::spellcheck_common::GetISOLanguageCountryCodeFromLocale(
48       prefs->GetString(prefs::kSpellCheckDictionary),
49       &language_code,
50       &country_code);
51   feedback_sender_.reset(new spellcheck::FeedbackSender(
52       context->GetRequestContext(), language_code, country_code));
53 
54   pref_change_registrar_.Add(
55       prefs::kEnableAutoSpellCorrect,
56       base::Bind(&SpellcheckService::OnEnableAutoSpellCorrectChanged,
57                  base::Unretained(this)));
58   pref_change_registrar_.Add(
59       prefs::kSpellCheckDictionary,
60       base::Bind(&SpellcheckService::OnSpellCheckDictionaryChanged,
61                  base::Unretained(this)));
62  pref_change_registrar_.Add(
63      prefs::kSpellCheckUseSpellingService,
64      base::Bind(&SpellcheckService::OnUseSpellingServiceChanged,
65                 base::Unretained(this)));
66   pref_change_registrar_.Add(
67       prefs::kEnableContinuousSpellcheck,
68       base::Bind(&SpellcheckService::InitForAllRenderers,
69                  base::Unretained(this)));
70 
71   OnSpellCheckDictionaryChanged();
72 
73   custom_dictionary_.reset(new SpellcheckCustomDictionary(context_->GetPath()));
74   custom_dictionary_->AddObserver(this);
75   custom_dictionary_->Load();
76 
77   registrar_.Add(this,
78                  content::NOTIFICATION_RENDERER_PROCESS_CREATED,
79                  content::NotificationService::AllSources());
80 }
81 
~SpellcheckService()82 SpellcheckService::~SpellcheckService() {
83   // Remove pref observers
84   pref_change_registrar_.RemoveAll();
85 }
86 
87 // static
GetSpellCheckLanguages(content::BrowserContext * context,std::vector<std::string> * languages)88 int SpellcheckService::GetSpellCheckLanguages(
89     content::BrowserContext* context,
90     std::vector<std::string>* languages) {
91   PrefService* prefs = user_prefs::UserPrefs::Get(context);
92   StringPrefMember accept_languages_pref;
93   StringPrefMember dictionary_language_pref;
94   accept_languages_pref.Init(prefs::kAcceptLanguages, prefs);
95   dictionary_language_pref.Init(prefs::kSpellCheckDictionary, prefs);
96   std::string dictionary_language = dictionary_language_pref.GetValue();
97 
98   // Now scan through the list of accept languages, and find possible mappings
99   // from this list to the existing list of spell check languages.
100   std::vector<std::string> accept_languages;
101 
102 #if defined(OS_MACOSX)
103   if (spellcheck_mac::SpellCheckerAvailable())
104     spellcheck_mac::GetAvailableLanguages(&accept_languages);
105   else
106     base::SplitString(accept_languages_pref.GetValue(), ',', &accept_languages);
107 #else
108   base::SplitString(accept_languages_pref.GetValue(), ',', &accept_languages);
109 #endif  // !OS_MACOSX
110 
111   GetSpellCheckLanguagesFromAcceptLanguages(
112       accept_languages, dictionary_language, languages);
113 
114   for (size_t i = 0; i < languages->size(); ++i) {
115     if ((*languages)[i] == dictionary_language)
116       return i;
117   }
118   return -1;
119 }
120 
121 // static
GetSpellCheckLanguagesFromAcceptLanguages(const std::vector<std::string> & accept_languages,const std::string & dictionary_language,std::vector<std::string> * languages)122 void SpellcheckService::GetSpellCheckLanguagesFromAcceptLanguages(
123     const std::vector<std::string>& accept_languages,
124     const std::string& dictionary_language,
125     std::vector<std::string>* languages) {
126   // The current dictionary language should be there.
127   languages->push_back(dictionary_language);
128 
129   for (std::vector<std::string>::const_iterator i = accept_languages.begin();
130        i != accept_languages.end(); ++i) {
131     std::string language =
132         chrome::spellcheck_common::GetCorrespondingSpellCheckLanguage(*i);
133     if (!language.empty() &&
134         std::find(languages->begin(), languages->end(), language) ==
135         languages->end()) {
136       languages->push_back(language);
137     }
138   }
139 }
140 
141 // static
SignalStatusEvent(SpellcheckService::EventType status_type)142 bool SpellcheckService::SignalStatusEvent(
143     SpellcheckService::EventType status_type) {
144   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
145 
146   if (!g_status_event)
147     return false;
148   g_status_type = status_type;
149   g_status_event->Signal();
150   return true;
151 }
152 
StartRecordingMetrics(bool spellcheck_enabled)153 void SpellcheckService::StartRecordingMetrics(bool spellcheck_enabled) {
154   metrics_.reset(new SpellCheckHostMetrics());
155   metrics_->RecordEnabledStats(spellcheck_enabled);
156   OnUseSpellingServiceChanged();
157 }
158 
InitForRenderer(content::RenderProcessHost * process)159 void SpellcheckService::InitForRenderer(content::RenderProcessHost* process) {
160   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
161 
162   content::BrowserContext* context = process->GetBrowserContext();
163   if (SpellcheckServiceFactory::GetForContext(context) != this)
164     return;
165 
166   PrefService* prefs = user_prefs::UserPrefs::Get(context);
167   IPC::PlatformFileForTransit file = IPC::InvalidPlatformFileForTransit();
168 
169   if (hunspell_dictionary_->GetDictionaryFile() !=
170       base::kInvalidPlatformFileValue) {
171 #if defined(OS_POSIX)
172     file = base::FileDescriptor(hunspell_dictionary_->GetDictionaryFile(),
173                                 false);
174 #elif defined(OS_WIN)
175     BOOL ok = ::DuplicateHandle(::GetCurrentProcess(),
176                                 hunspell_dictionary_->GetDictionaryFile(),
177                                 process->GetHandle(),
178                                 &file,
179                                 0,
180                                 false,
181                                 DUPLICATE_SAME_ACCESS);
182     DCHECK(ok) << ::GetLastError();
183 #endif
184   }
185 
186   process->Send(new SpellCheckMsg_Init(
187       file,
188       custom_dictionary_->GetWords(),
189       hunspell_dictionary_->GetLanguage(),
190       prefs->GetBoolean(prefs::kEnableAutoSpellCorrect)));
191   process->Send(new SpellCheckMsg_EnableSpellCheck(
192       prefs->GetBoolean(prefs::kEnableContinuousSpellcheck)));
193 }
194 
GetMetrics() const195 SpellCheckHostMetrics* SpellcheckService::GetMetrics() const {
196   return metrics_.get();
197 }
198 
GetCustomDictionary()199 SpellcheckCustomDictionary* SpellcheckService::GetCustomDictionary() {
200   return custom_dictionary_.get();
201 }
202 
GetHunspellDictionary()203 SpellcheckHunspellDictionary* SpellcheckService::GetHunspellDictionary() {
204   return hunspell_dictionary_.get();
205 }
206 
GetFeedbackSender()207 spellcheck::FeedbackSender* SpellcheckService::GetFeedbackSender() {
208   return feedback_sender_.get();
209 }
210 
LoadExternalDictionary(std::string language,std::string locale,std::string path,DictionaryFormat format)211 bool SpellcheckService::LoadExternalDictionary(std::string language,
212                                                std::string locale,
213                                                std::string path,
214                                                DictionaryFormat format) {
215   return false;
216 }
217 
UnloadExternalDictionary(std::string path)218 bool SpellcheckService::UnloadExternalDictionary(std::string path) {
219   return false;
220 }
221 
Observe(int type,const content::NotificationSource & source,const content::NotificationDetails & details)222 void SpellcheckService::Observe(int type,
223                                 const content::NotificationSource& source,
224                                 const content::NotificationDetails& details) {
225   DCHECK(type == content::NOTIFICATION_RENDERER_PROCESS_CREATED);
226   content::RenderProcessHost* process =
227       content::Source<content::RenderProcessHost>(source).ptr();
228   InitForRenderer(process);
229 }
230 
OnCustomDictionaryLoaded()231 void SpellcheckService::OnCustomDictionaryLoaded() {
232   InitForAllRenderers();
233 }
234 
OnCustomDictionaryChanged(const SpellcheckCustomDictionary::Change & dictionary_change)235 void SpellcheckService::OnCustomDictionaryChanged(
236     const SpellcheckCustomDictionary::Change& dictionary_change) {
237   for (content::RenderProcessHost::iterator i(
238           content::RenderProcessHost::AllHostsIterator());
239        !i.IsAtEnd(); i.Advance()) {
240     i.GetCurrentValue()->Send(new SpellCheckMsg_CustomDictionaryChanged(
241         dictionary_change.to_add(),
242         dictionary_change.to_remove()));
243   }
244 }
245 
OnHunspellDictionaryInitialized()246 void SpellcheckService::OnHunspellDictionaryInitialized() {
247   InitForAllRenderers();
248 }
249 
OnHunspellDictionaryDownloadBegin()250 void SpellcheckService::OnHunspellDictionaryDownloadBegin() {
251 }
252 
OnHunspellDictionaryDownloadSuccess()253 void SpellcheckService::OnHunspellDictionaryDownloadSuccess() {
254 }
255 
OnHunspellDictionaryDownloadFailure()256 void SpellcheckService::OnHunspellDictionaryDownloadFailure() {
257 }
258 
259 // static
AttachStatusEvent(base::WaitableEvent * status_event)260 void SpellcheckService::AttachStatusEvent(base::WaitableEvent* status_event) {
261   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
262 
263   g_status_event = status_event;
264 }
265 
266 // static
GetStatusEvent()267 SpellcheckService::EventType SpellcheckService::GetStatusEvent() {
268   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
269   return g_status_type;
270 }
271 
InitForAllRenderers()272 void SpellcheckService::InitForAllRenderers() {
273   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
274   for (content::RenderProcessHost::iterator i(
275           content::RenderProcessHost::AllHostsIterator());
276        !i.IsAtEnd(); i.Advance()) {
277     content::RenderProcessHost* process = i.GetCurrentValue();
278     if (process && process->GetHandle())
279       InitForRenderer(process);
280   }
281 }
282 
OnEnableAutoSpellCorrectChanged()283 void SpellcheckService::OnEnableAutoSpellCorrectChanged() {
284   bool enabled = pref_change_registrar_.prefs()->GetBoolean(
285       prefs::kEnableAutoSpellCorrect);
286   for (content::RenderProcessHost::iterator i(
287            content::RenderProcessHost::AllHostsIterator());
288        !i.IsAtEnd(); i.Advance()) {
289     content::RenderProcessHost* process = i.GetCurrentValue();
290     process->Send(new SpellCheckMsg_EnableAutoSpellCorrect(enabled));
291   }
292 }
293 
OnSpellCheckDictionaryChanged()294 void SpellcheckService::OnSpellCheckDictionaryChanged() {
295   if (hunspell_dictionary_.get())
296     hunspell_dictionary_->RemoveObserver(this);
297   PrefService* prefs = user_prefs::UserPrefs::Get(context_);
298   DCHECK(prefs);
299 
300   std::string dictionary =
301       prefs->GetString(prefs::kSpellCheckDictionary);
302   hunspell_dictionary_.reset(new SpellcheckHunspellDictionary(
303       dictionary, context_->GetRequestContext(), this));
304   hunspell_dictionary_->AddObserver(this);
305   hunspell_dictionary_->Load();
306   std::string language_code;
307   std::string country_code;
308   chrome::spellcheck_common::GetISOLanguageCountryCodeFromLocale(
309       dictionary, &language_code, &country_code);
310   feedback_sender_->OnLanguageCountryChange(language_code, country_code);
311   UpdateFeedbackSenderState();
312 }
313 
OnUseSpellingServiceChanged()314 void SpellcheckService::OnUseSpellingServiceChanged() {
315   bool enabled = pref_change_registrar_.prefs()->GetBoolean(
316       prefs::kSpellCheckUseSpellingService);
317   if (metrics_)
318     metrics_->RecordSpellingServiceStats(enabled);
319   UpdateFeedbackSenderState();
320 }
321 
UpdateFeedbackSenderState()322 void SpellcheckService::UpdateFeedbackSenderState() {
323   if (SpellingServiceClient::IsAvailable(
324           context_, SpellingServiceClient::SPELLCHECK)) {
325     feedback_sender_->StartFeedbackCollection();
326   } else {
327     feedback_sender_->StopFeedbackCollection();
328   }
329 }
330