ozone: fix HDPMLegacy - do the PF after overlays, also clear old overlays
[chromium-blink-merge.git] / base / prefs / json_pref_store.cc
blobe35ed295d699b68ffe50d707d1864b8dcc046125
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/files/file_path.h"
12 #include "base/files/file_util.h"
13 #include "base/json/json_file_value_serializer.h"
14 #include "base/json/json_string_value_serializer.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/metrics/histogram.h"
17 #include "base/prefs/pref_filter.h"
18 #include "base/sequenced_task_runner.h"
19 #include "base/strings/string_util.h"
20 #include "base/task_runner_util.h"
21 #include "base/threading/sequenced_worker_pool.h"
22 #include "base/values.h"
24 // Result returned from internal read tasks.
25 struct JsonPrefStore::ReadResult {
26 public:
27 ReadResult();
28 ~ReadResult();
30 scoped_ptr<base::Value> value;
31 PrefReadError error;
32 bool no_dir;
34 private:
35 DISALLOW_COPY_AND_ASSIGN(ReadResult);
38 JsonPrefStore::ReadResult::ReadResult()
39 : error(PersistentPrefStore::PREF_READ_ERROR_NONE), no_dir(false) {
42 JsonPrefStore::ReadResult::~ReadResult() {
45 namespace {
47 // Some extensions we'll tack on to copies of the Preferences files.
48 const base::FilePath::CharType kBadExtension[] = FILE_PATH_LITERAL("bad");
50 PersistentPrefStore::PrefReadError HandleReadErrors(
51 const base::Value* value,
52 const base::FilePath& path,
53 int error_code,
54 const std::string& error_msg) {
55 if (!value) {
56 DVLOG(1) << "Error while loading JSON file: " << error_msg
57 << ", file: " << path.value();
58 switch (error_code) {
59 case JSONFileValueSerializer::JSON_ACCESS_DENIED:
60 return PersistentPrefStore::PREF_READ_ERROR_ACCESS_DENIED;
61 break;
62 case JSONFileValueSerializer::JSON_CANNOT_READ_FILE:
63 return PersistentPrefStore::PREF_READ_ERROR_FILE_OTHER;
64 break;
65 case JSONFileValueSerializer::JSON_FILE_LOCKED:
66 return PersistentPrefStore::PREF_READ_ERROR_FILE_LOCKED;
67 break;
68 case JSONFileValueSerializer::JSON_NO_SUCH_FILE:
69 return PersistentPrefStore::PREF_READ_ERROR_NO_FILE;
70 break;
71 default:
72 // JSON errors indicate file corruption of some sort.
73 // Since the file is corrupt, move it to the side and continue with
74 // empty preferences. This will result in them losing their settings.
75 // We keep the old file for possible support and debugging assistance
76 // as well as to detect if they're seeing these errors repeatedly.
77 // TODO(erikkay) Instead, use the last known good file.
78 base::FilePath bad = path.ReplaceExtension(kBadExtension);
80 // If they've ever had a parse error before, put them in another bucket.
81 // TODO(erikkay) if we keep this error checking for very long, we may
82 // want to differentiate between recent and long ago errors.
83 bool bad_existed = base::PathExists(bad);
84 base::Move(path, bad);
85 return bad_existed ? PersistentPrefStore::PREF_READ_ERROR_JSON_REPEAT
86 : PersistentPrefStore::PREF_READ_ERROR_JSON_PARSE;
88 } else if (!value->IsType(base::Value::TYPE_DICTIONARY)) {
89 return PersistentPrefStore::PREF_READ_ERROR_JSON_TYPE;
91 return PersistentPrefStore::PREF_READ_ERROR_NONE;
94 scoped_ptr<JsonPrefStore::ReadResult> ReadPrefsFromDisk(
95 const base::FilePath& path,
96 const base::FilePath& alternate_path) {
97 if (!base::PathExists(path) && !alternate_path.empty() &&
98 base::PathExists(alternate_path)) {
99 base::Move(alternate_path, path);
102 int error_code;
103 std::string error_msg;
104 scoped_ptr<JsonPrefStore::ReadResult> read_result(
105 new JsonPrefStore::ReadResult);
106 JSONFileValueSerializer serializer(path);
107 read_result->value.reset(serializer.Deserialize(&error_code, &error_msg));
108 read_result->error =
109 HandleReadErrors(read_result->value.get(), path, error_code, error_msg);
110 read_result->no_dir = !base::PathExists(path.DirName());
111 return read_result.Pass();
114 } // namespace
116 // static
117 scoped_refptr<base::SequencedTaskRunner> JsonPrefStore::GetTaskRunnerForFile(
118 const base::FilePath& filename,
119 base::SequencedWorkerPool* worker_pool) {
120 std::string token("json_pref_store-");
121 token.append(filename.AsUTF8Unsafe());
122 return worker_pool->GetSequencedTaskRunnerWithShutdownBehavior(
123 worker_pool->GetNamedSequenceToken(token),
124 base::SequencedWorkerPool::BLOCK_SHUTDOWN);
127 JsonPrefStore::JsonPrefStore(
128 const base::FilePath& filename,
129 const scoped_refptr<base::SequencedTaskRunner>& sequenced_task_runner,
130 scoped_ptr<PrefFilter> pref_filter)
131 : path_(filename),
132 sequenced_task_runner_(sequenced_task_runner),
133 prefs_(new base::DictionaryValue()),
134 read_only_(false),
135 writer_(filename, sequenced_task_runner),
136 pref_filter_(pref_filter.Pass()),
137 initialized_(false),
138 filtering_in_progress_(false),
139 read_error_(PREF_READ_ERROR_NONE) {
140 DCHECK(!path_.empty());
143 JsonPrefStore::JsonPrefStore(
144 const base::FilePath& filename,
145 const base::FilePath& alternate_filename,
146 const scoped_refptr<base::SequencedTaskRunner>& sequenced_task_runner,
147 scoped_ptr<PrefFilter> pref_filter)
148 : path_(filename),
149 alternate_path_(alternate_filename),
150 sequenced_task_runner_(sequenced_task_runner),
151 prefs_(new base::DictionaryValue()),
152 read_only_(false),
153 writer_(filename, sequenced_task_runner),
154 pref_filter_(pref_filter.Pass()),
155 initialized_(false),
156 filtering_in_progress_(false),
157 read_error_(PREF_READ_ERROR_NONE) {
158 DCHECK(!path_.empty());
161 bool JsonPrefStore::GetValue(const std::string& key,
162 const base::Value** result) const {
163 DCHECK(CalledOnValidThread());
165 base::Value* tmp = NULL;
166 if (!prefs_->Get(key, &tmp))
167 return false;
169 if (result)
170 *result = tmp;
171 return true;
174 void JsonPrefStore::AddObserver(PrefStore::Observer* observer) {
175 DCHECK(CalledOnValidThread());
177 observers_.AddObserver(observer);
180 void JsonPrefStore::RemoveObserver(PrefStore::Observer* observer) {
181 DCHECK(CalledOnValidThread());
183 observers_.RemoveObserver(observer);
186 bool JsonPrefStore::HasObservers() const {
187 DCHECK(CalledOnValidThread());
189 return observers_.might_have_observers();
192 bool JsonPrefStore::IsInitializationComplete() const {
193 DCHECK(CalledOnValidThread());
195 return initialized_;
198 bool JsonPrefStore::GetMutableValue(const std::string& key,
199 base::Value** result) {
200 DCHECK(CalledOnValidThread());
202 return prefs_->Get(key, result);
205 void JsonPrefStore::SetValue(const std::string& key, base::Value* value) {
206 DCHECK(CalledOnValidThread());
208 DCHECK(value);
209 scoped_ptr<base::Value> new_value(value);
210 base::Value* old_value = NULL;
211 prefs_->Get(key, &old_value);
212 if (!old_value || !value->Equals(old_value)) {
213 prefs_->Set(key, new_value.release());
214 ReportValueChanged(key);
218 void JsonPrefStore::SetValueSilently(const std::string& key,
219 base::Value* value) {
220 DCHECK(CalledOnValidThread());
222 DCHECK(value);
223 scoped_ptr<base::Value> new_value(value);
224 base::Value* old_value = NULL;
225 prefs_->Get(key, &old_value);
226 if (!old_value || !value->Equals(old_value)) {
227 prefs_->Set(key, new_value.release());
228 if (!read_only_)
229 writer_.ScheduleWrite(this);
233 void JsonPrefStore::RemoveValue(const std::string& key) {
234 DCHECK(CalledOnValidThread());
236 if (prefs_->RemovePath(key, NULL))
237 ReportValueChanged(key);
240 void JsonPrefStore::RemoveValueSilently(const std::string& key) {
241 DCHECK(CalledOnValidThread());
243 prefs_->RemovePath(key, NULL);
244 if (!read_only_)
245 writer_.ScheduleWrite(this);
248 bool JsonPrefStore::ReadOnly() const {
249 DCHECK(CalledOnValidThread());
251 return read_only_;
254 PersistentPrefStore::PrefReadError JsonPrefStore::GetReadError() const {
255 DCHECK(CalledOnValidThread());
257 return read_error_;
260 PersistentPrefStore::PrefReadError JsonPrefStore::ReadPrefs() {
261 DCHECK(CalledOnValidThread());
263 OnFileRead(ReadPrefsFromDisk(path_, alternate_path_));
264 return filtering_in_progress_ ? PREF_READ_ERROR_ASYNCHRONOUS_TASK_INCOMPLETE
265 : read_error_;
268 void JsonPrefStore::ReadPrefsAsync(ReadErrorDelegate* error_delegate) {
269 DCHECK(CalledOnValidThread());
271 initialized_ = false;
272 error_delegate_.reset(error_delegate);
274 // Weakly binds the read task so that it doesn't kick in during shutdown.
275 base::PostTaskAndReplyWithResult(
276 sequenced_task_runner_.get(),
277 FROM_HERE,
278 base::Bind(&ReadPrefsFromDisk, path_, alternate_path_),
279 base::Bind(&JsonPrefStore::OnFileRead, AsWeakPtr()));
282 void JsonPrefStore::CommitPendingWrite() {
283 DCHECK(CalledOnValidThread());
285 if (writer_.HasPendingWrite() && !read_only_)
286 writer_.DoScheduledWrite();
289 void JsonPrefStore::ReportValueChanged(const std::string& key) {
290 DCHECK(CalledOnValidThread());
292 if (pref_filter_)
293 pref_filter_->FilterUpdate(key);
295 FOR_EACH_OBSERVER(PrefStore::Observer, observers_, OnPrefValueChanged(key));
297 if (!read_only_)
298 writer_.ScheduleWrite(this);
301 void JsonPrefStore::RegisterOnNextSuccessfulWriteCallback(
302 const base::Closure& on_next_successful_write) {
303 DCHECK(CalledOnValidThread());
305 writer_.RegisterOnNextSuccessfulWriteCallback(on_next_successful_write);
308 void JsonPrefStore::OnFileRead(scoped_ptr<ReadResult> read_result) {
309 DCHECK(CalledOnValidThread());
311 DCHECK(read_result);
313 scoped_ptr<base::DictionaryValue> unfiltered_prefs(new base::DictionaryValue);
315 read_error_ = read_result->error;
317 bool initialization_successful = !read_result->no_dir;
319 if (initialization_successful) {
320 switch (read_error_) {
321 case PREF_READ_ERROR_ACCESS_DENIED:
322 case PREF_READ_ERROR_FILE_OTHER:
323 case PREF_READ_ERROR_FILE_LOCKED:
324 case PREF_READ_ERROR_JSON_TYPE:
325 case PREF_READ_ERROR_FILE_NOT_SPECIFIED:
326 read_only_ = true;
327 break;
328 case PREF_READ_ERROR_NONE:
329 DCHECK(read_result->value.get());
330 unfiltered_prefs.reset(
331 static_cast<base::DictionaryValue*>(read_result->value.release()));
332 break;
333 case PREF_READ_ERROR_NO_FILE:
334 // If the file just doesn't exist, maybe this is first run. In any case
335 // there's no harm in writing out default prefs in this case.
336 break;
337 case PREF_READ_ERROR_JSON_PARSE:
338 case PREF_READ_ERROR_JSON_REPEAT:
339 break;
340 case PREF_READ_ERROR_ASYNCHRONOUS_TASK_INCOMPLETE:
341 // This is a special error code to be returned by ReadPrefs when it
342 // can't complete synchronously, it should never be returned by the read
343 // operation itself.
344 NOTREACHED();
345 break;
346 case PREF_READ_ERROR_LEVELDB_IO:
347 case PREF_READ_ERROR_LEVELDB_CORRUPTION_READ_ONLY:
348 case PREF_READ_ERROR_LEVELDB_CORRUPTION:
349 // These are specific to LevelDBPrefStore.
350 NOTREACHED();
351 case PREF_READ_ERROR_MAX_ENUM:
352 NOTREACHED();
353 break;
357 if (pref_filter_) {
358 filtering_in_progress_ = true;
359 const PrefFilter::PostFilterOnLoadCallback post_filter_on_load_callback(
360 base::Bind(
361 &JsonPrefStore::FinalizeFileRead, AsWeakPtr(),
362 initialization_successful));
363 pref_filter_->FilterOnLoad(post_filter_on_load_callback,
364 unfiltered_prefs.Pass());
365 } else {
366 FinalizeFileRead(initialization_successful, unfiltered_prefs.Pass(), false);
370 JsonPrefStore::~JsonPrefStore() {
371 CommitPendingWrite();
374 bool JsonPrefStore::SerializeData(std::string* output) {
375 DCHECK(CalledOnValidThread());
377 if (pref_filter_)
378 pref_filter_->FilterSerializeData(prefs_.get());
380 JSONStringValueSerializer serializer(output);
381 serializer.set_pretty_print(true);
382 bool result = serializer.Serialize(*prefs_);
384 if (result) {
385 std::string spaceless_basename;
386 base::ReplaceChars(path_.BaseName().MaybeAsASCII(), " ", "_",
387 &spaceless_basename);
389 // The histogram below is an expansion of the UMA_HISTOGRAM_COUNTS_10000
390 // macro adapted to allow for a dynamically suffixed histogram name.
391 // Note: The factory creates and owns the histogram.
392 base::HistogramBase* histogram =
393 base::LinearHistogram::FactoryGet(
394 "Settings.JsonDataSizeKilobytes." + spaceless_basename,
396 10000,
398 base::HistogramBase::kUmaTargetedHistogramFlag);
399 histogram->Add(static_cast<int>(output->size()) / 1024);
402 return result;
405 void JsonPrefStore::FinalizeFileRead(bool initialization_successful,
406 scoped_ptr<base::DictionaryValue> prefs,
407 bool schedule_write) {
408 DCHECK(CalledOnValidThread());
410 filtering_in_progress_ = false;
412 if (!initialization_successful) {
413 FOR_EACH_OBSERVER(PrefStore::Observer,
414 observers_,
415 OnInitializationCompleted(false));
416 return;
419 prefs_ = prefs.Pass();
421 initialized_ = true;
423 if (schedule_write && !read_only_)
424 writer_.ScheduleWrite(this);
426 if (error_delegate_ && read_error_ != PREF_READ_ERROR_NONE)
427 error_delegate_->OnError(read_error_);
429 FOR_EACH_OBSERVER(PrefStore::Observer,
430 observers_,
431 OnInitializationCompleted(true));
433 return;