blob: ac4a78020a7ddf69c15043a743cbd3ba249eaedf [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]005bab02011-10-07 18:36:0012#include "base/json/json_value_serializer.h"
[email protected]844a1002011-04-19 11:37:2113#include "base/memory/ref_counted.h"
[email protected]845b43a82011-05-11 10:14:4314#include "base/message_loop_proxy.h"
[email protected]277404c22010-04-22 13:09:4515#include "base/values.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());
[email protected]25308672011-10-10 17:22:50189 ReportValueChanged(key);
[email protected]9b5f56b42011-08-24 21:17:59190 }
[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);
[email protected]25308672011-10-10 17:22:50198 if (!old_value || !value->Equals(old_value)) {
[email protected]9b5f56b42011-08-24 21:17:59199 prefs_->Set(key, new_value.release());
[email protected]25308672011-10-10 17:22:50200 if (!read_only_)
201 writer_.ScheduleWrite(this);
202 }
[email protected]f2d1f612010-12-09 15:10:17203}
204
205void JsonPrefStore::RemoveValue(const std::string& key) {
[email protected]25308672011-10-10 17:22:50206 if (prefs_->Remove(key, NULL))
207 ReportValueChanged(key);
[email protected]f2d1f612010-12-09 15:10:17208}
209
[email protected]ddb1e5a2010-12-13 20:10:45210bool JsonPrefStore::ReadOnly() const {
211 return read_only_;
212}
213
[email protected]844a1002011-04-19 11:37:21214void JsonPrefStore::OnFileRead(Value* value_owned,
215 PersistentPrefStore::PrefReadError error,
216 bool no_dir) {
217 scoped_ptr<Value> value(value_owned);
[email protected]845b43a82011-05-11 10:14:43218 initialized_ = true;
219
220 if (no_dir) {
221 FOR_EACH_OBSERVER(PrefStore::Observer,
222 observers_,
223 OnInitializationCompleted(false));
224 return;
225 }
226
[email protected]844a1002011-04-19 11:37:21227 switch (error) {
228 case PREF_READ_ERROR_ACCESS_DENIED:
229 case PREF_READ_ERROR_FILE_OTHER:
230 case PREF_READ_ERROR_FILE_LOCKED:
231 case PREF_READ_ERROR_JSON_TYPE:
[email protected]845b43a82011-05-11 10:14:43232 case PREF_READ_ERROR_FILE_NOT_SPECIFIED:
[email protected]844a1002011-04-19 11:37:21233 read_only_ = true;
234 break;
235 case PREF_READ_ERROR_NONE:
236 DCHECK(value.get());
237 prefs_.reset(static_cast<DictionaryValue*>(value.release()));
238 break;
239 case PREF_READ_ERROR_NO_FILE:
240 // If the file just doesn't exist, maybe this is first run. In any case
241 // there's no harm in writing out default prefs in this case.
242 break;
243 case PREF_READ_ERROR_JSON_PARSE:
244 case PREF_READ_ERROR_JSON_REPEAT:
245 break;
246 default:
247 NOTREACHED() << "Unknown error: " << error;
248 }
249
[email protected]845b43a82011-05-11 10:14:43250 if (error_delegate_.get() && error != PREF_READ_ERROR_NONE)
251 error_delegate_->OnError(error);
252
253 FOR_EACH_OBSERVER(PrefStore::Observer,
254 observers_,
255 OnInitializationCompleted(true));
[email protected]844a1002011-04-19 11:37:21256}
257
[email protected]845b43a82011-05-11 10:14:43258void JsonPrefStore::ReadPrefsAsync(ReadErrorDelegate *error_delegate) {
259 initialized_ = false;
260 error_delegate_.reset(error_delegate);
[email protected]844a1002011-04-19 11:37:21261 if (path_.empty()) {
[email protected]845b43a82011-05-11 10:14:43262 OnFileRead(NULL, PREF_READ_ERROR_FILE_NOT_SPECIFIED, false);
[email protected]844a1002011-04-19 11:37:21263 return;
264 }
265
[email protected]844a1002011-04-19 11:37:21266 // Start async reading of the preferences file. It will delete itself
267 // in the end.
268 scoped_refptr<FileThreadDeserializer> deserializer(
[email protected]845b43a82011-05-11 10:14:43269 new FileThreadDeserializer(this, file_message_loop_proxy_.get()));
[email protected]844a1002011-04-19 11:37:21270 deserializer->Start(path_);
271}
272
[email protected]f2d1f612010-12-09 15:10:17273PersistentPrefStore::PrefReadError JsonPrefStore::ReadPrefs() {
[email protected]fd6159a2010-09-03 09:38:39274 if (path_.empty()) {
[email protected]845b43a82011-05-11 10:14:43275 OnFileRead(NULL, PREF_READ_ERROR_FILE_NOT_SPECIFIED, false);
[email protected]fd6159a2010-09-03 09:38:39276 return PREF_READ_ERROR_FILE_NOT_SPECIFIED;
277 }
[email protected]277404c22010-04-22 13:09:45278
[email protected]845b43a82011-05-11 10:14:43279 PrefReadError error;
280 bool no_dir;
281 Value* value = FileThreadDeserializer::DoReading(path_, &error, &no_dir);
282 OnFileRead(value, error, no_dir);
[email protected]844a1002011-04-19 11:37:21283 return error;
[email protected]277404c22010-04-22 13:09:45284}
285
286bool JsonPrefStore::WritePrefs() {
287 std::string data;
288 if (!SerializeData(&data))
289 return false;
290
[email protected]25308672011-10-10 17:22:50291 // Don't actually write prefs if we're read-only or don't have any pending
292 // writes.
293 // TODO(bauerb): Make callers of this method call CommitPendingWrite directly.
294 if (writer_.HasPendingWrite() && !read_only_)
295 writer_.WriteNow(data);
[email protected]277404c22010-04-22 13:09:45296
[email protected]277404c22010-04-22 13:09:45297 return true;
298}
299
300void JsonPrefStore::ScheduleWritePrefs() {
[email protected]25308672011-10-10 17:22:50301 // Writing prefs should be scheduled automatically, so this is a no-op
302 // for now.
303 // TODO(bauerb): Remove calls to this method.
[email protected]277404c22010-04-22 13:09:45304}
305
[email protected]3826fed2011-03-25 10:59:56306void JsonPrefStore::CommitPendingWrite() {
307 if (writer_.HasPendingWrite() && !read_only_)
308 writer_.DoScheduledWrite();
309}
310
[email protected]f89ee342011-03-07 09:28:27311void JsonPrefStore::ReportValueChanged(const std::string& key) {
312 FOR_EACH_OBSERVER(PrefStore::Observer, observers_, OnPrefValueChanged(key));
[email protected]25308672011-10-10 17:22:50313 if (!read_only_)
314 writer_.ScheduleWrite(this);
[email protected]f89ee342011-03-07 09:28:27315}
316
[email protected]277404c22010-04-22 13:09:45317bool JsonPrefStore::SerializeData(std::string* output) {
318 // TODO(tc): Do we want to prune webkit preferences that match the default
319 // value?
320 JSONStringValueSerializer serializer(output);
321 serializer.set_pretty_print(true);
322 scoped_ptr<DictionaryValue> copy(prefs_->DeepCopyWithoutEmptyChildren());
323 return serializer.Serialize(*(copy.get()));
324}