Suppress tabs permission warning if there is already a browsingHistory warning.
[chromium-blink-merge.git] / base / prefs / json_pref_store.cc
blobb0a16cc11431e01fd8661949388c11cdc972f156
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 "base/prefs/json_pref_store.h"
7 #include <algorithm>
9 #include "base/bind.h"
10 #include "base/callback.h"
11 #include "base/file_util.h"
12 #include "base/json/json_file_value_serializer.h"
13 #include "base/json/json_string_value_serializer.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/message_loop/message_loop_proxy.h"
16 #include "base/prefs/pref_filter.h"
17 #include "base/sequenced_task_runner.h"
18 #include "base/threading/sequenced_worker_pool.h"
19 #include "base/values.h"
21 namespace {
23 // Some extensions we'll tack on to copies of the Preferences files.
24 const base::FilePath::CharType* kBadExtension = FILE_PATH_LITERAL("bad");
26 // Differentiates file loading between origin thread and passed
27 // (aka file) thread.
28 class FileThreadDeserializer
29 : public base::RefCountedThreadSafe<FileThreadDeserializer> {
30 public:
31 FileThreadDeserializer(JsonPrefStore* delegate,
32 base::SequencedTaskRunner* sequenced_task_runner)
33 : no_dir_(false),
34 error_(PersistentPrefStore::PREF_READ_ERROR_NONE),
35 delegate_(delegate),
36 sequenced_task_runner_(sequenced_task_runner),
37 origin_loop_proxy_(base::MessageLoopProxy::current()) {
40 void Start(const base::FilePath& path) {
41 DCHECK(origin_loop_proxy_->BelongsToCurrentThread());
42 sequenced_task_runner_->PostTask(
43 FROM_HERE,
44 base::Bind(&FileThreadDeserializer::ReadFileAndReport,
45 this, path));
48 // Deserializes JSON on the sequenced task runner.
49 void ReadFileAndReport(const base::FilePath& path) {
50 DCHECK(sequenced_task_runner_->RunsTasksOnCurrentThread());
52 value_.reset(DoReading(path, &error_, &no_dir_));
54 origin_loop_proxy_->PostTask(
55 FROM_HERE,
56 base::Bind(&FileThreadDeserializer::ReportOnOriginThread, this));
59 // Reports deserialization result on the origin thread.
60 void ReportOnOriginThread() {
61 DCHECK(origin_loop_proxy_->BelongsToCurrentThread());
62 delegate_->OnFileRead(value_.release(), error_, no_dir_);
65 static base::Value* DoReading(const base::FilePath& path,
66 PersistentPrefStore::PrefReadError* error,
67 bool* no_dir) {
68 int error_code;
69 std::string error_msg;
70 JSONFileValueSerializer serializer(path);
71 base::Value* value = serializer.Deserialize(&error_code, &error_msg);
72 HandleErrors(value, path, error_code, error_msg, error);
73 *no_dir = !base::PathExists(path.DirName());
74 return value;
77 static void HandleErrors(const base::Value* value,
78 const base::FilePath& path,
79 int error_code,
80 const std::string& error_msg,
81 PersistentPrefStore::PrefReadError* error);
83 private:
84 friend class base::RefCountedThreadSafe<FileThreadDeserializer>;
85 ~FileThreadDeserializer() {}
87 bool no_dir_;
88 PersistentPrefStore::PrefReadError error_;
89 scoped_ptr<base::Value> value_;
90 const scoped_refptr<JsonPrefStore> delegate_;
91 const scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner_;
92 const scoped_refptr<base::MessageLoopProxy> origin_loop_proxy_;
95 // static
96 void FileThreadDeserializer::HandleErrors(
97 const base::Value* value,
98 const base::FilePath& path,
99 int error_code,
100 const std::string& error_msg,
101 PersistentPrefStore::PrefReadError* error) {
102 *error = PersistentPrefStore::PREF_READ_ERROR_NONE;
103 if (!value) {
104 DVLOG(1) << "Error while loading JSON file: " << error_msg
105 << ", file: " << path.value();
106 switch (error_code) {
107 case JSONFileValueSerializer::JSON_ACCESS_DENIED:
108 *error = PersistentPrefStore::PREF_READ_ERROR_ACCESS_DENIED;
109 break;
110 case JSONFileValueSerializer::JSON_CANNOT_READ_FILE:
111 *error = PersistentPrefStore::PREF_READ_ERROR_FILE_OTHER;
112 break;
113 case JSONFileValueSerializer::JSON_FILE_LOCKED:
114 *error = PersistentPrefStore::PREF_READ_ERROR_FILE_LOCKED;
115 break;
116 case JSONFileValueSerializer::JSON_NO_SUCH_FILE:
117 *error = PersistentPrefStore::PREF_READ_ERROR_NO_FILE;
118 break;
119 default:
120 *error = PersistentPrefStore::PREF_READ_ERROR_JSON_PARSE;
121 // JSON errors indicate file corruption of some sort.
122 // Since the file is corrupt, move it to the side and continue with
123 // empty preferences. This will result in them losing their settings.
124 // We keep the old file for possible support and debugging assistance
125 // as well as to detect if they're seeing these errors repeatedly.
126 // TODO(erikkay) Instead, use the last known good file.
127 base::FilePath bad = path.ReplaceExtension(kBadExtension);
129 // If they've ever had a parse error before, put them in another bucket.
130 // TODO(erikkay) if we keep this error checking for very long, we may
131 // want to differentiate between recent and long ago errors.
132 if (base::PathExists(bad))
133 *error = PersistentPrefStore::PREF_READ_ERROR_JSON_REPEAT;
134 base::Move(path, bad);
135 break;
137 } else if (!value->IsType(base::Value::TYPE_DICTIONARY)) {
138 *error = PersistentPrefStore::PREF_READ_ERROR_JSON_TYPE;
142 } // namespace
144 scoped_refptr<base::SequencedTaskRunner> JsonPrefStore::GetTaskRunnerForFile(
145 const base::FilePath& filename,
146 base::SequencedWorkerPool* worker_pool) {
147 std::string token("json_pref_store-");
148 token.append(filename.AsUTF8Unsafe());
149 return worker_pool->GetSequencedTaskRunnerWithShutdownBehavior(
150 worker_pool->GetNamedSequenceToken(token),
151 base::SequencedWorkerPool::BLOCK_SHUTDOWN);
154 JsonPrefStore::JsonPrefStore(const base::FilePath& filename,
155 base::SequencedTaskRunner* sequenced_task_runner,
156 scoped_ptr<PrefFilter> pref_filter)
157 : path_(filename),
158 sequenced_task_runner_(sequenced_task_runner),
159 prefs_(new base::DictionaryValue()),
160 read_only_(false),
161 writer_(filename, sequenced_task_runner),
162 pref_filter_(pref_filter.Pass()),
163 initialized_(false),
164 read_error_(PREF_READ_ERROR_OTHER) {}
166 bool JsonPrefStore::GetValue(const std::string& key,
167 const base::Value** result) const {
168 base::Value* tmp = NULL;
169 if (!prefs_->Get(key, &tmp))
170 return false;
172 if (result)
173 *result = tmp;
174 return true;
177 void JsonPrefStore::AddObserver(PrefStore::Observer* observer) {
178 observers_.AddObserver(observer);
181 void JsonPrefStore::RemoveObserver(PrefStore::Observer* observer) {
182 observers_.RemoveObserver(observer);
185 bool JsonPrefStore::HasObservers() const {
186 return observers_.might_have_observers();
189 bool JsonPrefStore::IsInitializationComplete() const {
190 return initialized_;
193 bool JsonPrefStore::GetMutableValue(const std::string& key,
194 base::Value** result) {
195 return prefs_->Get(key, result);
198 void JsonPrefStore::SetValue(const std::string& key, base::Value* value) {
199 DCHECK(value);
200 scoped_ptr<base::Value> new_value(value);
201 base::Value* old_value = NULL;
202 prefs_->Get(key, &old_value);
203 if (!old_value || !value->Equals(old_value)) {
204 prefs_->Set(key, new_value.release());
205 ReportValueChanged(key);
209 void JsonPrefStore::SetValueSilently(const std::string& key,
210 base::Value* value) {
211 DCHECK(value);
212 scoped_ptr<base::Value> new_value(value);
213 base::Value* old_value = NULL;
214 prefs_->Get(key, &old_value);
215 if (!old_value || !value->Equals(old_value)) {
216 prefs_->Set(key, new_value.release());
217 if (!read_only_)
218 writer_.ScheduleWrite(this);
222 void JsonPrefStore::RemoveValue(const std::string& key) {
223 if (prefs_->RemovePath(key, NULL))
224 ReportValueChanged(key);
227 bool JsonPrefStore::ReadOnly() const {
228 return read_only_;
231 PersistentPrefStore::PrefReadError JsonPrefStore::GetReadError() const {
232 return read_error_;
235 PersistentPrefStore::PrefReadError JsonPrefStore::ReadPrefs() {
236 if (path_.empty()) {
237 OnFileRead(NULL, PREF_READ_ERROR_FILE_NOT_SPECIFIED, false);
238 return PREF_READ_ERROR_FILE_NOT_SPECIFIED;
241 PrefReadError error;
242 bool no_dir;
243 base::Value* value =
244 FileThreadDeserializer::DoReading(path_, &error, &no_dir);
245 OnFileRead(value, error, no_dir);
246 return error;
249 void JsonPrefStore::ReadPrefsAsync(ReadErrorDelegate *error_delegate) {
250 initialized_ = false;
251 error_delegate_.reset(error_delegate);
252 if (path_.empty()) {
253 OnFileRead(NULL, PREF_READ_ERROR_FILE_NOT_SPECIFIED, false);
254 return;
257 // Start async reading of the preferences file. It will delete itself
258 // in the end.
259 scoped_refptr<FileThreadDeserializer> deserializer(
260 new FileThreadDeserializer(this, sequenced_task_runner_.get()));
261 deserializer->Start(path_);
264 void JsonPrefStore::CommitPendingWrite() {
265 if (writer_.HasPendingWrite() && !read_only_)
266 writer_.DoScheduledWrite();
269 void JsonPrefStore::ReportValueChanged(const std::string& key) {
270 if (pref_filter_)
271 pref_filter_->FilterUpdate(key);
273 FOR_EACH_OBSERVER(PrefStore::Observer, observers_, OnPrefValueChanged(key));
275 if (!read_only_)
276 writer_.ScheduleWrite(this);
279 void JsonPrefStore::OnFileRead(base::Value* value_owned,
280 PersistentPrefStore::PrefReadError error,
281 bool no_dir) {
282 scoped_ptr<base::Value> value(value_owned);
283 read_error_ = error;
285 if (no_dir) {
286 FOR_EACH_OBSERVER(PrefStore::Observer,
287 observers_,
288 OnInitializationCompleted(false));
289 return;
292 initialized_ = true;
294 switch (error) {
295 case PREF_READ_ERROR_ACCESS_DENIED:
296 case PREF_READ_ERROR_FILE_OTHER:
297 case PREF_READ_ERROR_FILE_LOCKED:
298 case PREF_READ_ERROR_JSON_TYPE:
299 case PREF_READ_ERROR_FILE_NOT_SPECIFIED:
300 read_only_ = true;
301 break;
302 case PREF_READ_ERROR_NONE:
303 DCHECK(value.get());
304 prefs_.reset(static_cast<base::DictionaryValue*>(value.release()));
305 break;
306 case PREF_READ_ERROR_NO_FILE:
307 // If the file just doesn't exist, maybe this is first run. In any case
308 // there's no harm in writing out default prefs in this case.
309 break;
310 case PREF_READ_ERROR_JSON_PARSE:
311 case PREF_READ_ERROR_JSON_REPEAT:
312 break;
313 default:
314 NOTREACHED() << "Unknown error: " << error;
317 if (pref_filter_ && pref_filter_->FilterOnLoad(prefs_.get()))
318 writer_.ScheduleWrite(this);
320 if (error_delegate_.get() && error != PREF_READ_ERROR_NONE)
321 error_delegate_->OnError(error);
323 FOR_EACH_OBSERVER(PrefStore::Observer,
324 observers_,
325 OnInitializationCompleted(true));
328 JsonPrefStore::~JsonPrefStore() {
329 CommitPendingWrite();
332 bool JsonPrefStore::SerializeData(std::string* output) {
333 if (pref_filter_)
334 pref_filter_->FilterSerializeData(prefs_.get());
336 JSONStringValueSerializer serializer(output);
337 serializer.set_pretty_print(true);
338 return serializer.Serialize(*prefs_);