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.
4
5#include "base/prefs/pref_member.h"
6
7#include "base/callback.h"
8#include "base/callback_helpers.h"
9#include "base/location.h"
10#include "base/message_loop/message_loop_proxy.h"
11#include "base/prefs/pref_service.h"
12#include "base/value_conversions.h"
13
14using base::MessageLoopProxy;
15using base::SingleThreadTaskRunner;
16
17namespace subtle {
18
19PrefMemberBase::PrefMemberBase()
20    : prefs_(NULL),
21      setting_value_(false) {
22}
23
24PrefMemberBase::~PrefMemberBase() {
25  Destroy();
26}
27
28void PrefMemberBase::Init(const char* pref_name,
29                          PrefService* prefs,
30                          const NamedChangeCallback& observer) {
31  observer_ = observer;
32  Init(pref_name, prefs);
33}
34
35void PrefMemberBase::Init(const char* pref_name,
36                          PrefService* prefs) {
37  DCHECK(pref_name);
38  DCHECK(prefs);
39  DCHECK(pref_name_.empty());  // Check that Init is only called once.
40  prefs_ = prefs;
41  pref_name_ = pref_name;
42  // Check that the preference is registered.
43  DCHECK(prefs_->FindPreference(pref_name_.c_str()))
44      << pref_name << " not registered.";
45
46  // Add ourselves as a pref observer so we can keep our local value in sync.
47  prefs_->AddPrefObserver(pref_name, this);
48}
49
50void PrefMemberBase::Destroy() {
51  if (prefs_ && !pref_name_.empty()) {
52    prefs_->RemovePrefObserver(pref_name_.c_str(), this);
53    prefs_ = NULL;
54  }
55}
56
57void PrefMemberBase::MoveToThread(
58    const scoped_refptr<SingleThreadTaskRunner>& task_runner) {
59  VerifyValuePrefName();
60  // Load the value from preferences if it hasn't been loaded so far.
61  if (!internal())
62    UpdateValueFromPref(base::Closure());
63  internal()->MoveToThread(task_runner);
64}
65
66void PrefMemberBase::OnPreferenceChanged(PrefService* service,
67                                         const std::string& pref_name) {
68  VerifyValuePrefName();
69  UpdateValueFromPref((!setting_value_ && !observer_.is_null()) ?
70      base::Bind(observer_, pref_name) : base::Closure());
71}
72
73void PrefMemberBase::UpdateValueFromPref(const base::Closure& callback) const {
74  VerifyValuePrefName();
75  const PrefService::Preference* pref =
76      prefs_->FindPreference(pref_name_.c_str());
77  DCHECK(pref);
78  if (!internal())
79    CreateInternal();
80  internal()->UpdateValue(pref->GetValue()->DeepCopy(),
81                          pref->IsManaged(),
82                          pref->IsUserModifiable(),
83                          callback);
84}
85
86void PrefMemberBase::VerifyPref() const {
87  VerifyValuePrefName();
88  if (!internal())
89    UpdateValueFromPref(base::Closure());
90}
91
92void PrefMemberBase::InvokeUnnamedCallback(const base::Closure& callback,
93                                           const std::string& pref_name) {
94  callback.Run();
95}
96
97PrefMemberBase::Internal::Internal()
98    : thread_loop_(MessageLoopProxy::current()),
99      is_managed_(false),
100      is_user_modifiable_(false) {
101}
102PrefMemberBase::Internal::~Internal() { }
103
104bool PrefMemberBase::Internal::IsOnCorrectThread() const {
105  // In unit tests, there may not be a message loop.
106  return thread_loop_.get() == NULL || thread_loop_->BelongsToCurrentThread();
107}
108
109void PrefMemberBase::Internal::UpdateValue(
110    base::Value* v,
111    bool is_managed,
112    bool is_user_modifiable,
113    const base::Closure& callback) const {
114  scoped_ptr<base::Value> value(v);
115  base::ScopedClosureRunner closure_runner(callback);
116  if (IsOnCorrectThread()) {
117    bool rv = UpdateValueInternal(*value);
118    DCHECK(rv);
119    is_managed_ = is_managed;
120    is_user_modifiable_ = is_user_modifiable;
121  } else {
122    bool may_run = thread_loop_->PostTask(
123        FROM_HERE,
124        base::Bind(&PrefMemberBase::Internal::UpdateValue, this,
125                   value.release(), is_managed, is_user_modifiable,
126                   closure_runner.Release()));
127    DCHECK(may_run);
128  }
129}
130
131void PrefMemberBase::Internal::MoveToThread(
132    const scoped_refptr<SingleThreadTaskRunner>& task_runner) {
133  CheckOnCorrectThread();
134  thread_loop_ = task_runner;
135}
136
137bool PrefMemberVectorStringUpdate(const base::Value& value,
138                                  std::vector<std::string>* string_vector) {
139  if (!value.IsType(base::Value::TYPE_LIST))
140    return false;
141  const base::ListValue* list = static_cast<const base::ListValue*>(&value);
142
143  std::vector<std::string> local_vector;
144  for (base::ListValue::const_iterator it = list->begin();
145       it != list->end(); ++it) {
146    std::string string_value;
147    if (!(*it)->GetAsString(&string_value))
148      return false;
149
150    local_vector.push_back(string_value);
151  }
152
153  string_vector->swap(local_vector);
154  return true;
155}
156
157}  // namespace subtle
158
159template <>
160void PrefMember<bool>::UpdatePref(const bool& value) {
161  prefs()->SetBoolean(pref_name().c_str(), value);
162}
163
164template <>
165bool PrefMember<bool>::Internal::UpdateValueInternal(
166    const base::Value& value) const {
167  return value.GetAsBoolean(&value_);
168}
169
170template <>
171void PrefMember<int>::UpdatePref(const int& value) {
172  prefs()->SetInteger(pref_name().c_str(), value);
173}
174
175template <>
176bool PrefMember<int>::Internal::UpdateValueInternal(
177    const base::Value& value) const {
178  return value.GetAsInteger(&value_);
179}
180
181template <>
182void PrefMember<double>::UpdatePref(const double& value) {
183  prefs()->SetDouble(pref_name().c_str(), value);
184}
185
186template <>
187bool PrefMember<double>::Internal::UpdateValueInternal(const base::Value& value)
188    const {
189  return value.GetAsDouble(&value_);
190}
191
192template <>
193void PrefMember<std::string>::UpdatePref(const std::string& value) {
194  prefs()->SetString(pref_name().c_str(), value);
195}
196
197template <>
198bool PrefMember<std::string>::Internal::UpdateValueInternal(
199    const base::Value& value)
200    const {
201  return value.GetAsString(&value_);
202}
203
204template <>
205void PrefMember<base::FilePath>::UpdatePref(const base::FilePath& value) {
206  prefs()->SetFilePath(pref_name().c_str(), value);
207}
208
209template <>
210bool PrefMember<base::FilePath>::Internal::UpdateValueInternal(
211    const base::Value& value)
212    const {
213  return base::GetValueAsFilePath(value, &value_);
214}
215
216template <>
217void PrefMember<std::vector<std::string> >::UpdatePref(
218    const std::vector<std::string>& value) {
219  base::ListValue list_value;
220  list_value.AppendStrings(value);
221  prefs()->Set(pref_name().c_str(), list_value);
222}
223
224template <>
225bool PrefMember<std::vector<std::string> >::Internal::UpdateValueInternal(
226    const base::Value& value) const {
227  return subtle::PrefMemberVectorStringUpdate(value, &value_);
228}
229