blob: f3bd776dce11acb11d5dda4a116f3ce9ae683929 [file] [log] [blame]
[email protected]3826fed2011-03-25 10:59:561// Copyright (c) 2011 The Chromium Authors. All rights reserved.
[email protected]277404c22010-04-22 13:09:452// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]ea587b02010-05-21 15:01:355#include "chrome/common/json_pref_store.h"
[email protected]277404c22010-04-22 13:09:456
7#include <algorithm>
8
[email protected]844a1002011-04-19 11:37:219#include "base/bind.h"
10#include "base/callback.h"
[email protected]277404c22010-04-22 13:09:4511#include "base/file_util.h"
[email protected]844a1002011-04-19 11:37:2112#include "base/memory/ref_counted.h"
[email protected]845b43a82011-05-11 10:14:4313#include "base/message_loop_proxy.h"
[email protected]277404c22010-04-22 13:09:4514#include "base/values.h"
[email protected]c3113022011-04-16 03:26:3015#include "content/common/json_value_serializer.h"
[email protected]277404c22010-04-22 13:09:4516
17namespace {
18
19// Some extensions we'll tack on to copies of the Preferences files.
20const FilePath::CharType* kBadExtension = FILE_PATH_LITERAL("bad");
21
[email protected]845b43a82011-05-11 10:14:4322// Differentiates file loading between origin thread and passed
23// (aka file) thread.
[email protected]844a1002011-04-19 11:37:2124class FileThreadDeserializer
25 : public base::RefCountedThreadSafe<FileThreadDeserializer> {
26 public:
[email protected]e7e38032011-07-26 17:25:2527 FileThreadDeserializer(JsonPrefStore* delegate,
28 base::MessageLoopProxy* file_loop_proxy)
[email protected]68e83602011-06-14 13:09:2829 : no_dir_(false),
30 error_(PersistentPrefStore::PREF_READ_ERROR_NONE),
31 delegate_(delegate),
[email protected]845b43a82011-05-11 10:14:4332 file_loop_proxy_(file_loop_proxy),
[email protected]edd685f2011-08-15 20:33:4633 origin_loop_proxy_(base::MessageLoopProxy::current()) {
[email protected]844a1002011-04-19 11:37:2134 }
35
36 void Start(const FilePath& path) {
[email protected]845b43a82011-05-11 10:14:4337 DCHECK(origin_loop_proxy_->BelongsToCurrentThread());
38 file_loop_proxy_->PostTask(
[email protected]844a1002011-04-19 11:37:2139 FROM_HERE,
40 NewRunnableMethod(this,
41 &FileThreadDeserializer::ReadFileAndReport,
42 path));
43 }
44
[email protected]845b43a82011-05-11 10:14:4345 // Deserializes JSON on the file thread.
[email protected]844a1002011-04-19 11:37:2146 void ReadFileAndReport(const FilePath& path) {
[email protected]845b43a82011-05-11 10:14:4347 DCHECK(file_loop_proxy_->BelongsToCurrentThread());
[email protected]844a1002011-04-19 11:37:2148
[email protected]845b43a82011-05-11 10:14:4349 value_.reset(DoReading(path, &error_, &no_dir_));
50
51 origin_loop_proxy_->PostTask(
52 FROM_HERE,
53 NewRunnableMethod(this, &FileThreadDeserializer::ReportOnOriginThread));
54 }
55
56 // Reports deserialization result on the origin thread.
57 void ReportOnOriginThread() {
58 DCHECK(origin_loop_proxy_->BelongsToCurrentThread());
59 delegate_->OnFileRead(value_.release(), error_, no_dir_);
60 }
61
62 static Value* DoReading(const FilePath& path,
63 PersistentPrefStore::PrefReadError* error,
64 bool* no_dir) {
[email protected]844a1002011-04-19 11:37:2165 int error_code;
66 std::string error_msg;
67 JSONFileValueSerializer serializer(path);
[email protected]845b43a82011-05-11 10:14:4368 Value* value = serializer.Deserialize(&error_code, &error_msg);
69 HandleErrors(value, path, error_code, error_msg, error);
70 *no_dir = !file_util::PathExists(path.DirName());
71 return value;
[email protected]844a1002011-04-19 11:37:2172 }
73
74 static void HandleErrors(const Value* value,
75 const FilePath& path,
76 int error_code,
77 const std::string& error_msg,
78 PersistentPrefStore::PrefReadError* error);
79
80 private:
81 friend class base::RefCountedThreadSafe<FileThreadDeserializer>;
82
83 bool no_dir_;
84 PersistentPrefStore::PrefReadError error_;
85 scoped_ptr<Value> value_;
86 scoped_refptr<JsonPrefStore> delegate_;
[email protected]845b43a82011-05-11 10:14:4387 scoped_refptr<base::MessageLoopProxy> file_loop_proxy_;
88 scoped_refptr<base::MessageLoopProxy> origin_loop_proxy_;
[email protected]844a1002011-04-19 11:37:2189};
90
91// static
92void FileThreadDeserializer::HandleErrors(
93 const Value* value,
94 const FilePath& path,
95 int error_code,
96 const std::string& error_msg,
97 PersistentPrefStore::PrefReadError* error) {
98 *error = PersistentPrefStore::PREF_READ_ERROR_NONE;
99 if (!value) {
[email protected]2f030662011-05-09 21:31:16100 VLOG(1) << "Error while loading JSON file: " << error_msg;
[email protected]844a1002011-04-19 11:37:21101 switch (error_code) {
102 case JSONFileValueSerializer::JSON_ACCESS_DENIED:
103 *error = PersistentPrefStore::PREF_READ_ERROR_ACCESS_DENIED;
104 break;
105 case JSONFileValueSerializer::JSON_CANNOT_READ_FILE:
106 *error = PersistentPrefStore::PREF_READ_ERROR_FILE_OTHER;
107 break;
108 case JSONFileValueSerializer::JSON_FILE_LOCKED:
109 *error = PersistentPrefStore::PREF_READ_ERROR_FILE_LOCKED;
110 break;
111 case JSONFileValueSerializer::JSON_NO_SUCH_FILE:
112 *error = PersistentPrefStore::PREF_READ_ERROR_NO_FILE;
113 break;
114 default:
115 *error = PersistentPrefStore::PREF_READ_ERROR_JSON_PARSE;
116 // JSON errors indicate file corruption of some sort.
117 // Since the file is corrupt, move it to the side and continue with
118 // empty preferences. This will result in them losing their settings.
119 // We keep the old file for possible support and debugging assistance
120 // as well as to detect if they're seeing these errors repeatedly.
121 // TODO(erikkay) Instead, use the last known good file.
122 FilePath bad = path.ReplaceExtension(kBadExtension);
123
124 // If they've ever had a parse error before, put them in another bucket.
125 // TODO(erikkay) if we keep this error checking for very long, we may
126 // want to differentiate between recent and long ago errors.
127 if (file_util::PathExists(bad))
128 *error = PersistentPrefStore::PREF_READ_ERROR_JSON_REPEAT;
129 file_util::Move(path, bad);
130 break;
131 }
132 } else if (!value->IsType(Value::TYPE_DICTIONARY)) {
133 *error = PersistentPrefStore::PREF_READ_ERROR_JSON_TYPE;
134 }
135}
136
[email protected]277404c22010-04-22 13:09:45137} // namespace
138
[email protected]ea587b02010-05-21 15:01:35139JsonPrefStore::JsonPrefStore(const FilePath& filename,
140 base::MessageLoopProxy* file_message_loop_proxy)
[email protected]277404c22010-04-22 13:09:45141 : path_(filename),
[email protected]845b43a82011-05-11 10:14:43142 file_message_loop_proxy_(file_message_loop_proxy),
[email protected]277404c22010-04-22 13:09:45143 prefs_(new DictionaryValue()),
144 read_only_(false),
[email protected]845b43a82011-05-11 10:14:43145 writer_(filename, file_message_loop_proxy),
146 error_delegate_(NULL),
147 initialized_(false) {
[email protected]6658ca82010-05-20 18:20:29148}
[email protected]277404c22010-04-22 13:09:45149
150JsonPrefStore::~JsonPrefStore() {
[email protected]3826fed2011-03-25 10:59:56151 CommitPendingWrite();
[email protected]277404c22010-04-22 13:09:45152}
153
[email protected]f2d1f612010-12-09 15:10:17154PrefStore::ReadResult JsonPrefStore::GetValue(const std::string& key,
[email protected]68bf41a2011-03-25 16:38:31155 const Value** result) const {
156 Value* tmp = NULL;
157 if (prefs_->Get(key, &tmp)) {
[email protected]a78e9482011-07-14 19:22:29158 if (result)
159 *result = tmp;
[email protected]68bf41a2011-03-25 16:38:31160 return READ_OK;
161 }
162 return READ_NO_VALUE;
[email protected]f2d1f612010-12-09 15:10:17163}
164
165void JsonPrefStore::AddObserver(PrefStore::Observer* observer) {
166 observers_.AddObserver(observer);
167}
168
169void JsonPrefStore::RemoveObserver(PrefStore::Observer* observer) {
170 observers_.RemoveObserver(observer);
171}
172
[email protected]845b43a82011-05-11 10:14:43173bool JsonPrefStore::IsInitializationComplete() const {
174 return initialized_;
175}
176
[email protected]68bf41a2011-03-25 16:38:31177PrefStore::ReadResult JsonPrefStore::GetMutableValue(const std::string& key,
178 Value** result) {
179 return prefs_->Get(key, result) ? READ_OK : READ_NO_VALUE;
180}
181
[email protected]f2d1f612010-12-09 15:10:17182void JsonPrefStore::SetValue(const std::string& key, Value* value) {
[email protected]9b5f56b42011-08-24 21:17:59183 DCHECK(value);
184 scoped_ptr<Value> new_value(value);
185 Value* old_value = NULL;
186 prefs_->Get(key, &old_value);
187 if (!old_value || !value->Equals(old_value)) {
188 prefs_->Set(key, new_value.release());
189 FOR_EACH_OBSERVER(PrefStore::Observer, observers_, OnPrefValueChanged(key));
190 }
[email protected]f2d1f612010-12-09 15:10:17191}
192
193void JsonPrefStore::SetValueSilently(const std::string& key, Value* value) {
[email protected]9b5f56b42011-08-24 21:17:59194 DCHECK(value);
195 scoped_ptr<Value> new_value(value);
196 Value* old_value = NULL;
197 prefs_->Get(key, &old_value);
198 if (!old_value || !value->Equals(old_value))
199 prefs_->Set(key, new_value.release());
[email protected]f2d1f612010-12-09 15:10:17200}
201
202void JsonPrefStore::RemoveValue(const std::string& key) {
[email protected]9b5f56b42011-08-24 21:17:59203 if (prefs_->Remove(key, NULL)) {
[email protected]f2d1f612010-12-09 15:10:17204 FOR_EACH_OBSERVER(PrefStore::Observer, observers_, OnPrefValueChanged(key));
[email protected]9b5f56b42011-08-24 21:17:59205 }
[email protected]f2d1f612010-12-09 15:10:17206}
207
[email protected]ddb1e5a2010-12-13 20:10:45208bool JsonPrefStore::ReadOnly() const {
209 return read_only_;
210}
211
[email protected]844a1002011-04-19 11:37:21212void JsonPrefStore::OnFileRead(Value* value_owned,
213 PersistentPrefStore::PrefReadError error,
214 bool no_dir) {
215 scoped_ptr<Value> value(value_owned);
[email protected]845b43a82011-05-11 10:14:43216 initialized_ = true;
217
218 if (no_dir) {
219 FOR_EACH_OBSERVER(PrefStore::Observer,
220 observers_,
221 OnInitializationCompleted(false));
222 return;
223 }
224
[email protected]844a1002011-04-19 11:37:21225 switch (error) {
226 case PREF_READ_ERROR_ACCESS_DENIED:
227 case PREF_READ_ERROR_FILE_OTHER:
228 case PREF_READ_ERROR_FILE_LOCKED:
229 case PREF_READ_ERROR_JSON_TYPE:
[email protected]845b43a82011-05-11 10:14:43230 case PREF_READ_ERROR_FILE_NOT_SPECIFIED:
[email protected]844a1002011-04-19 11:37:21231 read_only_ = true;
232 break;
233 case PREF_READ_ERROR_NONE:
234 DCHECK(value.get());
235 prefs_.reset(static_cast<DictionaryValue*>(value.release()));
236 break;
237 case PREF_READ_ERROR_NO_FILE:
238 // If the file just doesn't exist, maybe this is first run. In any case
239 // there's no harm in writing out default prefs in this case.
240 break;
241 case PREF_READ_ERROR_JSON_PARSE:
242 case PREF_READ_ERROR_JSON_REPEAT:
243 break;
244 default:
245 NOTREACHED() << "Unknown error: " << error;
246 }
247
[email protected]845b43a82011-05-11 10:14:43248 if (error_delegate_.get() && error != PREF_READ_ERROR_NONE)
249 error_delegate_->OnError(error);
250
251 FOR_EACH_OBSERVER(PrefStore::Observer,
252 observers_,
253 OnInitializationCompleted(true));
[email protected]844a1002011-04-19 11:37:21254}
255
[email protected]845b43a82011-05-11 10:14:43256void JsonPrefStore::ReadPrefsAsync(ReadErrorDelegate *error_delegate) {
257 initialized_ = false;
258 error_delegate_.reset(error_delegate);
[email protected]844a1002011-04-19 11:37:21259 if (path_.empty()) {
[email protected]845b43a82011-05-11 10:14:43260 OnFileRead(NULL, PREF_READ_ERROR_FILE_NOT_SPECIFIED, false);
[email protected]844a1002011-04-19 11:37:21261 return;
262 }
263
[email protected]844a1002011-04-19 11:37:21264 // Start async reading of the preferences file. It will delete itself
265 // in the end.
266 scoped_refptr<FileThreadDeserializer> deserializer(
[email protected]845b43a82011-05-11 10:14:43267 new FileThreadDeserializer(this, file_message_loop_proxy_.get()));
[email protected]844a1002011-04-19 11:37:21268 deserializer->Start(path_);
269}
270
[email protected]f2d1f612010-12-09 15:10:17271PersistentPrefStore::PrefReadError JsonPrefStore::ReadPrefs() {
[email protected]fd6159a2010-09-03 09:38:39272 if (path_.empty()) {
[email protected]845b43a82011-05-11 10:14:43273 OnFileRead(NULL, PREF_READ_ERROR_FILE_NOT_SPECIFIED, false);
[email protected]fd6159a2010-09-03 09:38:39274 return PREF_READ_ERROR_FILE_NOT_SPECIFIED;
275 }
[email protected]277404c22010-04-22 13:09:45276
[email protected]845b43a82011-05-11 10:14:43277 PrefReadError error;
278 bool no_dir;
279 Value* value = FileThreadDeserializer::DoReading(path_, &error, &no_dir);
280 OnFileRead(value, error, no_dir);
[email protected]844a1002011-04-19 11:37:21281 return error;
[email protected]277404c22010-04-22 13:09:45282}
283
284bool JsonPrefStore::WritePrefs() {
285 std::string data;
286 if (!SerializeData(&data))
287 return false;
288
289 // Lie about our ability to save.
290 if (read_only_)
291 return true;
292
293 writer_.WriteNow(data);
294 return true;
295}
296
297void JsonPrefStore::ScheduleWritePrefs() {
298 if (read_only_)
299 return;
300
301 writer_.ScheduleWrite(this);
302}
303
[email protected]3826fed2011-03-25 10:59:56304void JsonPrefStore::CommitPendingWrite() {
305 if (writer_.HasPendingWrite() && !read_only_)
306 writer_.DoScheduledWrite();
307}
308
[email protected]f89ee342011-03-07 09:28:27309void JsonPrefStore::ReportValueChanged(const std::string& key) {
310 FOR_EACH_OBSERVER(PrefStore::Observer, observers_, OnPrefValueChanged(key));
311}
312
[email protected]277404c22010-04-22 13:09:45313bool JsonPrefStore::SerializeData(std::string* output) {
314 // TODO(tc): Do we want to prune webkit preferences that match the default
315 // value?
316 JSONStringValueSerializer serializer(output);
317 serializer.set_pretty_print(true);
318 scoped_ptr<DictionaryValue> copy(prefs_->DeepCopyWithoutEmptyChildren());
319 return serializer.Serialize(*(copy.get()));
320}