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

Side by Side Diff: chrome/browser/spellchecker/spellcheck_custom_dictionary.cc

Issue 11445002: Sync user's custom spellcheck dictionary (Closed) Base URL: http://git.chromium.org/chromium/src.git@master
Patch Set: Add server-side size limit tests Created 7 years, 11 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
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/spellchecker/spellcheck_custom_dictionary.h" 5 #include "chrome/browser/spellchecker/spellcheck_custom_dictionary.h"
6 6
7 #include <functional> 7 #include <functional>
8 8
9 #include "base/file_util.h" 9 #include "base/file_util.h"
10 #include "base/files/important_file_writer.h" 10 #include "base/files/important_file_writer.h"
11 #include "base/md5.h" 11 #include "base/md5.h"
12 #include "base/string_number_conversions.h"
12 #include "base/string_split.h" 13 #include "base/string_split.h"
13 #include "chrome/browser/profiles/profile.h" 14 #include "chrome/browser/profiles/profile.h"
14 #include "chrome/common/chrome_constants.h" 15 #include "chrome/common/chrome_constants.h"
15 #include "chrome/common/spellcheck_messages.h" 16 #include "chrome/common/spellcheck_messages.h"
16 #include "content/public/browser/browser_thread.h" 17 #include "content/public/browser/browser_thread.h"
17 #include "content/public/browser/render_process_host.h" 18 #include "sync/api/sync_change.h"
19 #include "sync/api/sync_data.h"
20 #include "sync/api/sync_error_factory.h"
21 #include "sync/protocol/sync.pb.h"
22 #include "third_party/hunspell/src/hunspell/hunspell.hxx"
groby-ooo-7-16 2013/01/10 22:04:44 We probably shouldn't include hunspell here - tech
please use gerrit instead 2013/01/12 02:50:46 Defined a chrome::spellcheck_common::MAX_CUSTOM_DI
18 23
19 using content::BrowserThread; 24 using content::BrowserThread;
20 using chrome::spellcheck_common::WordList; 25 using chrome::spellcheck_common::WordList;
21 26
27 namespace custom_dictionary {
22 namespace { 28 namespace {
23 29
30 // Filename extension for backup dictionary file.
24 const FilePath::CharType BACKUP_EXTENSION[] = FILE_PATH_LITERAL("backup"); 31 const FilePath::CharType BACKUP_EXTENSION[] = FILE_PATH_LITERAL("backup");
32
33 // Prefix for the checksum in the dictionary file.
25 const char CHECKSUM_PREFIX[] = "checksum_v1 = "; 34 const char CHECKSUM_PREFIX[] = "checksum_v1 = ";
26 35
36 // The status of the checksum in a custom spellcheck dictionary.
37 enum ChecksumStatus {
38 VALID_CHECKSUM,
39 INVALID_CHECKSUM,
40 };
41
27 // Loads the lines from the file at |file_path| into the |lines| container. If 42 // Loads the lines from the file at |file_path| into the |lines| container. If
28 // the file has a valid checksum, then returns |true|. If the file has an 43 // the file has a valid checksum, then returns ChecksumStatus::VALID. If the
29 // invalid checksum, then returns |false| and clears |lines|. 44 // file has an invalid checksum, then returns ChecksumStatus::INVALID and clears
30 bool LoadFile(FilePath file_path, std::vector<std::string>* lines) { 45 // |lines|. Must be called on the file thread.
46 ChecksumStatus LoadFile(FilePath file_path, std::vector<std::string>* lines) {
47 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
31 lines->clear(); 48 lines->clear();
32 std::string contents; 49 std::string contents;
33 file_util::ReadFileToString(file_path, &contents); 50 file_util::ReadFileToString(file_path, &contents);
34 size_t pos = contents.rfind(CHECKSUM_PREFIX); 51 size_t pos = contents.rfind(CHECKSUM_PREFIX);
35 if (pos != std::string::npos) { 52 if (pos != std::string::npos) {
36 std::string checksum = contents.substr(pos + strlen(CHECKSUM_PREFIX)); 53 std::string checksum = contents.substr(pos + strlen(CHECKSUM_PREFIX));
37 contents = contents.substr(0, pos); 54 contents = contents.substr(0, pos);
38 if (checksum != base::MD5String(contents)) 55 if (checksum != base::MD5String(contents))
39 return false; 56 return INVALID_CHECKSUM;
40 } 57 }
41 TrimWhitespaceASCII(contents, TRIM_ALL, &contents); 58 TrimWhitespaceASCII(contents, TRIM_ALL, &contents);
42 base::SplitString(contents, '\n', lines); 59 base::SplitString(contents, '\n', lines);
43 return true; 60 return VALID_CHECKSUM;
44 } 61 }
45 62
46 bool IsValidWord(const std::string& word) { 63 // Returns true for invalid words and false for valid words. Useful for
47 return IsStringUTF8(word) && word.length() <= 128 && word.length() > 0 && 64 // std::remove_if() calls.
48 std::string::npos == word.find_first_of(kWhitespaceASCII); 65 bool IsInvalidWord(const std::string& word) {
66 return !IsStringUTF8(word) || word.length() >= MAXWORDLEN || word.empty() ||
67 word.find_first_of(kWhitespaceASCII) != std::string::npos;
49 } 68 }
50 69
51 bool IsInvalidWord(const std::string& word) { 70 // Loads the custom spellcheck dictionary from |path| into |custom_words|. If
52 return !IsValidWord(word); 71 // the dictionary checksum is not valid, but backup checksum is valid, then
72 // restores the backup and loads that into |custom_words| instead. If the backup
73 // is invalid too, then clears |custom_words|. Must be called on the file
74 // thread.
75 void LoadDictionaryFileReliably(WordList* custom_words, const FilePath& path) {
76 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
77
78 // Load the contents and verify the checksum.
79 if (LoadFile(path, custom_words) == VALID_CHECKSUM)
80 return;
81
82 // Checksum is not valid. See if there's a backup.
83 FilePath backup = path.AddExtension(BACKUP_EXTENSION);
84 if (!file_util::PathExists(backup))
85 return;
86
87 // Load the backup and verify its checksum.
88 if (LoadFile(backup, custom_words) != VALID_CHECKSUM)
89 return;
90
91 // Backup checksum is valid. Restore the backup.
92 file_util::CopyFile(backup, path);
93 }
94
95 // Backs up the original dictionary, saves |custom_words| and its checksum into
96 // the custom spellcheck dictionary at |path|. Does not take ownership of
97 // |custom_words|. Must be called on the file thread.
98 void SaveDictionaryFileReliably(
99 const WordList* custom_words,
100 const FilePath& path) {
101 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
102 DCHECK(custom_words);
103
104 std::stringstream content;
105 for (WordList::const_iterator it = custom_words->begin();
106 it != custom_words->end();
107 ++it) {
108 content << *it << '\n';
109 }
110 std::string checksum = base::MD5String(content.str());
111 content << CHECKSUM_PREFIX << checksum;
112
113 file_util::CopyFile(path, path.AddExtension(BACKUP_EXTENSION));
114 base::ImportantFileWriter::WriteFileAtomically(path, content.str());
115 }
116
117 // Applies the change in |dictionary_change| to the custom spellcheck dictionary
118 // at |path|. Assumes that |dictionary_change| has already been processed to
119 // clean the words that cannot be added or removed. Deletes |dictionary_change|
120 // when done. Must be called on the file thread.
121 void WriteAndEraseWordsInCustomDictionary(
122 scoped_ptr<SpellcheckCustomDictionary::Change> dictionary_change,
123 const FilePath& path) {
124 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
125 DCHECK(dictionary_change.get());
126
127 WordList custom_words;
128 LoadDictionaryFileReliably(&custom_words, path);
129
130 // Add words.
131 custom_words.insert(custom_words.end(),
132 dictionary_change->to_add().begin(),
133 dictionary_change->to_add().end());
134
135 // Remove words.
136 std::sort(custom_words.begin(), custom_words.end());
137 std::sort(dictionary_change->to_remove().begin(),
138 dictionary_change->to_remove().end());
139 WordList remaining;
140 std::set_difference(custom_words.begin(),
141 custom_words.end(),
142 dictionary_change->to_remove().begin(),
143 dictionary_change->to_remove().end(),
144 std::back_inserter(remaining));
145 std::swap(custom_words, remaining);
146
147 SaveDictionaryFileReliably(&custom_words, path);
53 } 148 }
54 149
55 } // namespace 150 } // namespace
56 151
57 SpellcheckCustomDictionary::SpellcheckCustomDictionary(Profile* profile) 152 scoped_ptr<WordList> LoadDictionary(const FilePath& path) {
58 : SpellcheckDictionary(profile),
59 custom_dictionary_path_(),
60 weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
61 DCHECK(profile);
62 custom_dictionary_path_ =
63 profile_->GetPath().Append(chrome::kCustomDictionaryFileName);
64 }
65
66 SpellcheckCustomDictionary::~SpellcheckCustomDictionary() {
67 }
68
69 void SpellcheckCustomDictionary::Load() {
70 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
71
72 BrowserThread::PostTaskAndReplyWithResult<WordList*>(
73 BrowserThread::FILE,
74 FROM_HERE,
75 base::Bind(&SpellcheckCustomDictionary::LoadDictionary,
76 base::Unretained(this)),
77 base::Bind(&SpellcheckCustomDictionary::SetCustomWordListAndDelete,
78 weak_ptr_factory_.GetWeakPtr()));
79 }
80
81 const WordList& SpellcheckCustomDictionary::GetWords() const {
82 return words_;
83 }
84
85 void SpellcheckCustomDictionary::LoadDictionaryIntoCustomWordList(
86 WordList* custom_words) {
87 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); 153 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
88 154
89 LoadDictionaryFileReliably(custom_words); 155 scoped_ptr<WordList> custom_words(new WordList);
156 LoadDictionaryFileReliably(custom_words.get(), path);
90 if (custom_words->empty()) 157 if (custom_words->empty())
91 return; 158 return custom_words.Pass();
92 159
93 // Clean up the dictionary file contents by removing duplicates and invalid 160 // Clean up the dictionary file contents by removing duplicates and invalid
94 // words. 161 // words.
95 std::sort(custom_words->begin(), custom_words->end()); 162 std::sort(custom_words->begin(), custom_words->end());
96 custom_words->erase(std::unique(custom_words->begin(), custom_words->end()), 163 custom_words->erase(std::unique(custom_words->begin(), custom_words->end()),
97 custom_words->end()); 164 custom_words->end());
98 custom_words->erase(std::remove_if(custom_words->begin(), 165 custom_words->erase(std::remove_if(custom_words->begin(),
99 custom_words->end(), 166 custom_words->end(),
100 IsInvalidWord), 167 custom_dictionary::IsInvalidWord),
101 custom_words->end()); 168 custom_words->end());
102 169
103 SaveDictionaryFileReliably(*custom_words); 170 SaveDictionaryFileReliably(custom_words.get(), path);
171
172 return custom_words.Pass();
104 } 173 }
105 174
106 void SpellcheckCustomDictionary::SetCustomWordList(WordList* custom_words) { 175 void WriteWordToCustomDictionary(
176 const std::string& word,
177 const FilePath& path) {
178 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
179 scoped_ptr<SpellcheckCustomDictionary::Change> dictionary_change(
180 new SpellcheckCustomDictionary::Change);
181 dictionary_change->AddWord(word);
182 WriteAndEraseWordsInCustomDictionary(dictionary_change.Pass(), path);
183 }
184
185 void EraseWordFromCustomDictionary(
186 const std::string& word,
187 const FilePath& path) {
188 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
189 scoped_ptr<SpellcheckCustomDictionary::Change> dictionary_change(
190 new SpellcheckCustomDictionary::Change);
191 dictionary_change->RemoveWord(word);
192 WriteAndEraseWordsInCustomDictionary(dictionary_change.Pass(), path);
193 }
194
195 } // namespace custom_dictionary
196
197 SpellcheckCustomDictionary::Change::Result::Result()
198 : invalid_(false),
199 duplicate_(false),
200 missing_(false) {
201 }
202
203 SpellcheckCustomDictionary::Change::Result::Result(
204 const SpellcheckCustomDictionary::Change::Result& other)
205 : invalid_(other.detected_invalid_words()),
206 duplicate_(other.detected_duplicate_words()),
207 missing_(other.detected_missing_words()) {
208 }
209
210 SpellcheckCustomDictionary::Change::Result::~Result() {
211 }
212
213 SpellcheckCustomDictionary::Change::Change() {
214 }
215
216 SpellcheckCustomDictionary::Change::Change(
groby-ooo-7-16 2013/01/10 22:04:44 Why pointer magic, and not just a copy ctor? (In f
please use gerrit instead 2013/01/12 02:50:46 No longer used, removed.
217 const SpellcheckCustomDictionary::Change* other) {
218 DCHECK(other);
219
220 AddWords(&other->to_add());
221 RemoveWords(&other->to_remove());
222 }
223
224 SpellcheckCustomDictionary::Change::~Change() {
225 }
226
227 void SpellcheckCustomDictionary::Change::AddWord(const std::string& word) {
228 to_add_.push_back(word);
229 }
230
231 void SpellcheckCustomDictionary::Change::RemoveWord(const std::string& word) {
232 to_remove_.push_back(word);
233 }
234
235 void SpellcheckCustomDictionary::Change::AddWords(const WordList* words) {
236 to_add_.insert(to_add_.end(), words->begin(), words->end());
237 }
238
239 void SpellcheckCustomDictionary::Change::RemoveWords(const WordList* words) {
240 to_remove_.insert(to_remove_.end(), words->begin(), words->end());
241 }
242
243 SpellcheckCustomDictionary::SpellcheckCustomDictionary(Profile* profile)
244 : SpellcheckDictionary(profile),
245 custom_dictionary_path_(),
246 weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
247 is_loaded_(false) {
248 DCHECK(profile);
249
groby-ooo-7-16 2013/01/10 22:04:44 Kill a newline, save some space :)
please use gerrit instead 2013/01/12 02:50:46 Killed newlines after all dchecks.
250 custom_dictionary_path_ =
251 profile_->GetPath().Append(chrome::kCustomDictionaryFileName);
252 }
253
254 SpellcheckCustomDictionary::~SpellcheckCustomDictionary() {
255 }
256
257 const WordList& SpellcheckCustomDictionary::GetWords() const {
107 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 258 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
108 259
109 words_.clear(); 260 return words_;
110 if (custom_words)
111 std::swap(words_, *custom_words);
112
113 FOR_EACH_OBSERVER(Observer, observers_, OnCustomDictionaryLoaded());
114 } 261 }
115 262
116 bool SpellcheckCustomDictionary::AddWord(const std::string& word) { 263 SpellcheckCustomDictionary::Change::Result SpellcheckCustomDictionary::AddWord(
264 const std::string& word) {
117 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 265 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
118 if (!IsValidWord(word))
119 return false;
120 266
121 if (!CustomWordAddedLocally(word)) 267 scoped_ptr<Change> dictionary_change(new Change);
122 return false; 268 dictionary_change->AddWord(word);
123 269 Apply(dictionary_change.get());
124 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, 270 Change::Result result(dictionary_change->result());
125 base::Bind(&SpellcheckCustomDictionary::WriteWordToCustomDictionary, 271 Notify(dictionary_change.get());
126 base::Unretained(this), word)); 272 Sync(dictionary_change.get());
127 273 Save(dictionary_change.Pass());
128 for (content::RenderProcessHost::iterator i( 274 return result;
129 content::RenderProcessHost::AllHostsIterator());
130 !i.IsAtEnd(); i.Advance()) {
131 i.GetCurrentValue()->Send(new SpellCheckMsg_WordAdded(word));
132 }
133
134 FOR_EACH_OBSERVER(Observer, observers_, OnCustomDictionaryWordAdded(word));
135
136 return true;
137 } 275 }
138 276
139 bool SpellcheckCustomDictionary::CustomWordAddedLocally( 277 SpellcheckCustomDictionary::Change::Result
140 const std::string& word) { 278 SpellcheckCustomDictionary::CustomWordAddedLocally(
141 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 279 const std::string& word) {
142 DCHECK(IsValidWord(word)); 280 scoped_ptr<Change> dictionary_change(new Change);
143 281 dictionary_change->AddWord(word);
144 WordList::iterator it = std::find(words_.begin(), words_.end(), word); 282 Apply(dictionary_change.get());
145 if (it == words_.end()) { 283 Notify(dictionary_change.get());
146 words_.push_back(word); 284 Sync(dictionary_change.get());
147 return true; 285 return dictionary_change->result();
148 }
149 return false;
150 // TODO(rlp): record metrics on custom word size
151 } 286 }
152 287
153 void SpellcheckCustomDictionary::WriteWordToCustomDictionary( 288 SpellcheckCustomDictionary::Change::Result
154 const std::string& word) { 289 SpellcheckCustomDictionary::RemoveWord(const std::string& word) {
155 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); 290 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
156 DCHECK(IsValidWord(word));
157 291
158 WordList custom_words; 292 scoped_ptr<Change> dictionary_change(new Change);
159 LoadDictionaryFileReliably(&custom_words); 293 dictionary_change->RemoveWord(word);
160 custom_words.push_back(word); 294 Apply(dictionary_change.get());
161 SaveDictionaryFileReliably(custom_words); 295 Change::Result result(dictionary_change->result());
groby-ooo-7-16 2013/01/10 22:04:44 Why doesn't this just call RemoveWordLocally?
please use gerrit instead 2013/01/12 02:50:46 I deleted RemoveWordLocally and AddWordLocally com
296 Notify(dictionary_change.get());
297 Sync(dictionary_change.get());
298 Save(dictionary_change.Pass());
299 return result;
162 } 300 }
163 301
164 bool SpellcheckCustomDictionary::RemoveWord(const std::string& word) { 302 SpellcheckCustomDictionary::Change::Result
groby-ooo-7-16 2013/01/10 19:53:03 Oy. I apologize for the confusion - in my previous
please use gerrit instead 2013/01/12 02:50:46 I moved the public API back to bool. SpellcheckCus
303 SpellcheckCustomDictionary::CustomWordRemovedLocally(
304 const std::string& word) {
165 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 305 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
166 if (!IsValidWord(word))
167 return false;
168 306
169 if (!CustomWordRemovedLocally(word)) 307 scoped_ptr<Change> dictionary_change(new Change);
170 return false; 308 dictionary_change->RemoveWord(word);
171 309 Apply(dictionary_change.get());
172 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, 310 Notify(dictionary_change.get());
173 base::Bind(&SpellcheckCustomDictionary::EraseWordFromCustomDictionary, 311 Sync(dictionary_change.get());
174 base::Unretained(this), word)); 312 return dictionary_change->result();
175
176 for (content::RenderProcessHost::iterator i(
177 content::RenderProcessHost::AllHostsIterator());
178 !i.IsAtEnd(); i.Advance()) {
179 i.GetCurrentValue()->Send(new SpellCheckMsg_WordRemoved(word));
180 }
181
182 FOR_EACH_OBSERVER(Observer, observers_, OnCustomDictionaryWordRemoved(word));
183
184 return true;
185 }
186
187 bool SpellcheckCustomDictionary::CustomWordRemovedLocally(
188 const std::string& word) {
189 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
190 DCHECK(IsValidWord(word));
191
192 WordList::iterator it = std::find(words_.begin(), words_.end(), word);
193 if (it != words_.end()) {
194 words_.erase(it);
195 return true;
196 }
197 return false;
198 }
199
200 void SpellcheckCustomDictionary::EraseWordFromCustomDictionary(
201 const std::string& word) {
202 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
203 DCHECK(IsValidWord(word));
204
205 WordList custom_words;
206 LoadDictionaryFileReliably(&custom_words);
207 if (custom_words.empty())
208 return;
209
210 WordList::iterator it = std::find(custom_words.begin(),
211 custom_words.end(),
212 word);
213 if (it != custom_words.end())
214 custom_words.erase(it);
215
216 SaveDictionaryFileReliably(custom_words);
217 } 313 }
218 314
219 void SpellcheckCustomDictionary::AddObserver(Observer* observer) { 315 void SpellcheckCustomDictionary::AddObserver(Observer* observer) {
220 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 316 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
221 317
222 observers_.AddObserver(observer); 318 observers_.AddObserver(observer);
223 } 319 }
224 320
225 void SpellcheckCustomDictionary::RemoveObserver(Observer* observer) { 321 void SpellcheckCustomDictionary::RemoveObserver(Observer* observer) {
226 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 322 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
227 323
228 observers_.RemoveObserver(observer); 324 observers_.RemoveObserver(observer);
229 } 325 }
230 326
231 WordList* SpellcheckCustomDictionary::LoadDictionary() { 327 bool SpellcheckCustomDictionary::IsLoaded() {
232 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); 328 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
233 329
234 WordList* custom_words = new WordList; 330 return is_loaded_;
235 LoadDictionaryIntoCustomWordList(custom_words); 331 }
236 return custom_words; 332
237 } 333 bool SpellcheckCustomDictionary::IsSyncing() {
238 334 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
239 void SpellcheckCustomDictionary::SetCustomWordListAndDelete( 335
240 WordList* custom_words) { 336 return !!sync_processor_.get();
241 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 337 }
242 338
243 SetCustomWordList(custom_words); 339 void SpellcheckCustomDictionary::OnLoaded(scoped_ptr<WordList> custom_words) {
244 delete custom_words; 340 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
245 } 341 DCHECK(custom_words.get());
246 342
247 void SpellcheckCustomDictionary::LoadDictionaryFileReliably( 343 scoped_ptr<Change> dictionary_change(new Change);
248 WordList* custom_words) { 344 dictionary_change->AddWords(custom_words.get());
249 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); 345 Apply(dictionary_change.get());
groby-ooo-7-16 2013/01/10 22:04:44 Hm. It seems every Apply causes a Sync. Why not ca
please use gerrit instead 2013/01/12 02:50:46 We cannot call Sync from Apply because ProcessSync
250 346 Sync(dictionary_change.get());
251 // Load the contents and verify the checksum. 347
252 if (LoadFile(custom_dictionary_path_, custom_words)) 348 is_loaded_ = true;
349 FOR_EACH_OBSERVER(Observer, observers_, OnCustomDictionaryLoaded());
350 }
351
352 void SpellcheckCustomDictionary::Load() {
353 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
354
355 BrowserThread::PostTaskAndReplyWithResult<scoped_ptr<WordList> >(
356 BrowserThread::FILE,
357 FROM_HERE,
358 base::Bind(&custom_dictionary::LoadDictionary,
359 custom_dictionary_path_),
360 base::Bind(&SpellcheckCustomDictionary::OnLoaded,
361 weak_ptr_factory_.GetWeakPtr()));
362 }
363
364 syncer::SyncMergeResult SpellcheckCustomDictionary::MergeDataAndStartSyncing(
365 syncer::ModelType type,
366 const syncer::SyncDataList& initial_sync_data,
367 scoped_ptr<syncer::SyncChangeProcessor> sync_processor,
368 scoped_ptr<syncer::SyncErrorFactory> sync_error_handler) {
369 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
370 DCHECK(!sync_processor_.get());
371 DCHECK(!sync_error_handler_.get());
372 DCHECK(sync_processor.get());
373 DCHECK(sync_error_handler.get());
374 DCHECK_EQ(syncer::DICTIONARY, type);
375
376 sync_processor_ = sync_processor.Pass();
377 sync_error_handler_ = sync_error_handler.Pass();
378
379 // Add remote words locally.
380 WordList sync_words;
381 std::string word;
382 for (syncer::SyncDataList::const_iterator it = initial_sync_data.begin();
383 it != initial_sync_data.end();
384 ++it) {
385 DCHECK_EQ(syncer::DICTIONARY, it->GetDataType());
386 sync_words.push_back(it->GetSpecifics().dictionary().word());
387 }
388 scoped_ptr<Change> to_change_locally(new Change);
389 to_change_locally->AddWords(&sync_words);
390 Apply(to_change_locally.get());
391 Notify(to_change_locally.get());
392 Save(to_change_locally.Pass());
393
394 // Add as many as possible local words remotely.
395 std::sort(words_.begin(), words_.end());
396 std::sort(sync_words.begin(), sync_words.end());
397 Change to_change_remotely;
398 std::set_difference(words_.begin(),
399 words_.end(),
400 sync_words.begin(),
401 sync_words.end(),
402 std::back_inserter(to_change_remotely.to_add()));
403 syncer::SyncMergeResult result(type);
404 result.set_error(Sync(&to_change_remotely));
405 return result;
406 }
407
408 void SpellcheckCustomDictionary::StopSyncing(syncer::ModelType type) {
409 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
410 DCHECK_EQ(syncer::DICTIONARY, type);
411
412 sync_processor_.reset();
413 sync_error_handler_.reset();
414 }
415
416 syncer::SyncDataList SpellcheckCustomDictionary::GetAllSyncData(
417 syncer::ModelType type) const {
418 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
419 DCHECK_EQ(syncer::DICTIONARY, type);
420
421 syncer::SyncDataList data;
422 std::string word;
423 size_t i = 0;
424 for (WordList::const_iterator it = words_.begin();
425 it != words_.end() &&
426 i < chrome::spellcheck_common::MAX_SYNCABLE_DICTIONARY_SIZE_IN_WORDS;
427 ++it, ++i) {
428 word = *it;
429 sync_pb::EntitySpecifics specifics;
430 specifics.mutable_dictionary()->set_word(word);
431 data.push_back(syncer::SyncData::CreateLocalData(word, word, specifics));
432 }
433 return data;
434 }
435
436 syncer::SyncError SpellcheckCustomDictionary::ProcessSyncChanges(
437 const tracked_objects::Location& from_here,
438 const syncer::SyncChangeList& change_list) {
439 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
440
441 scoped_ptr<Change> dictionary_change(new Change);
442 for (syncer::SyncChangeList::const_iterator it = change_list.begin();
443 it != change_list.end();
444 ++it) {
445 DCHECK(it->IsValid());
446 std::string word = it->sync_data().GetSpecifics().dictionary().word();
447 switch (it->change_type()) {
448 case syncer::SyncChange::ACTION_ADD:
449 dictionary_change->AddWord(word);
450 break;
451 case syncer::SyncChange::ACTION_DELETE:
452 dictionary_change->RemoveWord(word);
453 break;
454 default:
455 return sync_error_handler_->CreateAndUploadError(
456 FROM_HERE,
457 "Processing sync changes failed on change type " +
458 syncer::SyncChange::ChangeTypeToString(it->change_type()));
459 }
460 }
461
462 Apply(dictionary_change.get());
463 Notify(dictionary_change.get());
464 Save(dictionary_change.Pass());
465
466 return syncer::SyncError();
467 }
468
469 // TODO(rlp): record metrics on custom word size
470 void SpellcheckCustomDictionary::Apply(
471 SpellcheckCustomDictionary::Change* dictionary_change) {
472 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
473 DCHECK(dictionary_change);
474
475 if (!dictionary_change->to_add().empty()) {
476 // Do not add duplicate words.
477 std::sort(dictionary_change->to_add().begin(),
478 dictionary_change->to_add().end());
479 std::sort(words_.begin(), words_.end());
480 WordList to_add;
481 std::set_difference(dictionary_change->to_add().begin(),
groby-ooo-7-16 2013/01/10 22:04:44 That's similar to the sanitizing code at load time
please use gerrit instead 2013/01/12 02:50:46 Good idea! Done.
482 dictionary_change->to_add().end(),
483 words_.begin(),
484 words_.end(),
485 std::back_inserter(to_add));
486 to_add.erase(std::unique(to_add.begin(), to_add.end()),
487 to_add.end());
488 if (dictionary_change->to_add().size() != to_add.size())
489 dictionary_change->result().set_detected_duplicate_words();
490
491 // Do not add invalid words.
492 size_t size = to_add.size();
493 to_add.erase(std::remove_if(to_add.begin(),
494 to_add.end(),
495 custom_dictionary::IsInvalidWord),
496 to_add.end());
497 if (size != to_add.size())
498 dictionary_change->result().set_detected_invalid_words();
499
500 // Add the words to the dictionary.
501 words_.insert(words_.end(), to_add.begin(), to_add.end());
502
503 // Clean up the dictionary change by removing duplicates and invalid words.
504 std::swap(dictionary_change->to_add(), to_add);
505 }
506
507 if (!dictionary_change->to_remove().empty()) {
508 // Do not remove words that are missing from the dictionary.
509 std::sort(dictionary_change->to_remove().begin(),
510 dictionary_change->to_remove().end());
511 std::sort(words_.begin(), words_.end());
512 WordList to_remove;
513 std::set_intersection(words_.begin(),
514 words_.end(),
515 dictionary_change->to_remove().begin(),
516 dictionary_change->to_remove().end(),
517 std::back_inserter(to_remove));
518 if (dictionary_change->to_remove().size() > to_remove.size())
519 dictionary_change->result().set_detected_missing_words();
520
521 // Remove the words from the dictionary.
522 WordList updated_words;
523 std::set_difference(words_.begin(),
524 words_.end(),
525 to_remove.begin(),
526 to_remove.end(),
527 std::back_inserter(updated_words));
528 std::swap(words_, updated_words);
529
530 // Clean up the dictionary change by removing missing words.
531 std::swap(dictionary_change->to_remove(), to_remove);
532 }
533 }
534
535 void SpellcheckCustomDictionary::Save(
536 scoped_ptr<SpellcheckCustomDictionary::Change> dictionary_change) {
537 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
538 DCHECK(dictionary_change.get());
539
540 BrowserThread::PostTask(
541 BrowserThread::FILE,
542 FROM_HERE,
543 base::Bind(
544 &custom_dictionary::WriteAndEraseWordsInCustomDictionary,
545 base::Passed(dictionary_change.Pass()),
546 custom_dictionary_path_));
547 }
548
549 syncer::SyncError SpellcheckCustomDictionary::Sync(
550 const SpellcheckCustomDictionary::Change* dictionary_change) {
551 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
552 DCHECK(dictionary_change);
553
554 syncer::SyncError error;
555 if (!IsSyncing() || dictionary_change->empty())
556 return error;
557
558 // The number of words on the sync server should not exceed the limits.
559 int server_size = static_cast<int>(words_.size()) -
560 static_cast<int>(dictionary_change->to_add().size());
561 int max_upload_size = std::max(
562 0,
563 static_cast<int>(
564 chrome::spellcheck_common::MAX_SYNCABLE_DICTIONARY_SIZE_IN_WORDS) -
565 server_size);
566 int upload_size = std::min(
567 static_cast<int>(dictionary_change->to_add().size()),
568 max_upload_size);
569
570 syncer::SyncChangeList sync_change_list;
571 std::string word;
572 int i = 0;
573
574 for (WordList::const_iterator it = dictionary_change->to_add().begin();
575 it != dictionary_change->to_add().end() && i < upload_size;
576 ++it, ++i) {
577 word = *it;
578 sync_pb::EntitySpecifics specifics;
579 specifics.mutable_dictionary()->set_word(word);
580 sync_change_list.push_back(syncer::SyncChange(
581 FROM_HERE,
582 syncer::SyncChange::ACTION_ADD,
583 syncer::SyncData::CreateLocalData(word, word, specifics)));
584 }
585
586 for (WordList::const_iterator it = dictionary_change->to_remove().begin();
587 it != dictionary_change->to_remove().end();
588 ++it) {
589 word = *it;
590 sync_pb::EntitySpecifics specifics;
591 specifics.mutable_dictionary()->set_word(word);
592 sync_change_list.push_back(syncer::SyncChange(
593 FROM_HERE,
594 syncer::SyncChange::ACTION_DELETE,
595 syncer::SyncData::CreateLocalData(word, word, specifics)));
596 }
597
598 // Send the changes to the sync processor.
599 error = sync_processor_->ProcessSyncChanges(FROM_HERE, sync_change_list);
600 if (error.IsSet())
601 return error;
602
603 // Turn off syncing of this dictionary if the server already has the maximum
604 // number of words.
605 if (words_.size() >
606 chrome::spellcheck_common::MAX_SYNCABLE_DICTIONARY_SIZE_IN_WORDS)
607 StopSyncing(syncer::DICTIONARY);
608
609 return error;
610 }
611
612 void SpellcheckCustomDictionary::Notify(
613 const SpellcheckCustomDictionary::Change* dictionary_change) {
614 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
615 DCHECK(dictionary_change);
616
617 if (!IsLoaded() || dictionary_change->empty())
253 return; 618 return;
254 619
255 // Checksum is not valid. See if there's a backup. 620 FOR_EACH_OBSERVER(Observer,
256 FilePath backup = custom_dictionary_path_.AddExtension(BACKUP_EXTENSION); 621 observers_,
257 if (!file_util::PathExists(backup)) 622 OnCustomDictionaryChanged(dictionary_change));
258 return; 623 }
259
260 // Load the backup and verify its checksum.
261 if (!LoadFile(backup, custom_words))
262 return;
263
264 // Backup checksum is valid. Restore the backup.
265 file_util::CopyFile(backup, custom_dictionary_path_);
266 }
267
268 void SpellcheckCustomDictionary::SaveDictionaryFileReliably(
269 const WordList& custom_words) {
270 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
271
272 std::stringstream content;
273 for (WordList::const_iterator it = custom_words.begin();
274 it != custom_words.end();
275 ++it) {
276 content << *it << '\n';
277 }
278 std::string checksum = base::MD5String(content.str());
279 content << CHECKSUM_PREFIX << checksum;
280
281 file_util::CopyFile(custom_dictionary_path_,
282 custom_dictionary_path_.AddExtension(BACKUP_EXTENSION));
283 base::ImportantFileWriter::WriteFileAtomically(custom_dictionary_path_,
284 content.str());
285 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698