1 // Copyright 2013 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 "chrome/browser/prefs/synced_pref_change_registrar.h"
6
7 #include "base/bind.h"
8
9 namespace {
10
InvokeUnnamedCallback(const SyncedPrefChangeRegistrar::ChangeCallback & callback,const std::string & path,bool from_sync)11 void InvokeUnnamedCallback(
12 const SyncedPrefChangeRegistrar::ChangeCallback& callback,
13 const std::string& path,
14 bool from_sync) {
15 callback.Run(from_sync);
16 }
17
18 } // namespace
19
SyncedPrefChangeRegistrar(PrefServiceSyncable * pref_service)20 SyncedPrefChangeRegistrar::SyncedPrefChangeRegistrar(
21 PrefServiceSyncable* pref_service) {
22 pref_service_ = pref_service;
23 }
24
~SyncedPrefChangeRegistrar()25 SyncedPrefChangeRegistrar::~SyncedPrefChangeRegistrar() {
26 RemoveAll();
27 }
28
Add(const char * path,const ChangeCallback & callback)29 void SyncedPrefChangeRegistrar::Add(const char *path,
30 const ChangeCallback& callback) {
31 Add(path, base::Bind(InvokeUnnamedCallback, callback));
32 }
33
Add(const char * path,const NamedChangeCallback & callback)34 void SyncedPrefChangeRegistrar::Add(const char *path,
35 const NamedChangeCallback& callback) {
36 DCHECK(!IsObserved(path));
37 observers_[path] = callback;
38 pref_service_->AddSyncedPrefObserver(path, this);
39 }
40
Remove(const char * path)41 void SyncedPrefChangeRegistrar::Remove(const char *path) {
42 observers_.erase(path);
43 pref_service_->RemoveSyncedPrefObserver(path, this);
44 }
45
RemoveAll()46 void SyncedPrefChangeRegistrar::RemoveAll() {
47 for (ObserverMap::iterator iter = observers_.begin();
48 iter != observers_.end(); ++iter) {
49 pref_service_->RemoveSyncedPrefObserver(iter->first, this);
50 }
51 observers_.clear();
52 }
53
IsObserved(const char * path) const54 bool SyncedPrefChangeRegistrar::IsObserved(const char* path) const {
55 return observers_.find(path) != observers_.end();
56 }
57
OnSyncedPrefChanged(const std::string & path,bool from_sync)58 void SyncedPrefChangeRegistrar::OnSyncedPrefChanged(const std::string& path,
59 bool from_sync) {
60 if (pref_service_->IsManagedPreference(path.c_str()))
61 return;
62 ObserverMap::const_iterator iter = observers_.find(path);
63 if (iter == observers_.end())
64 return;
65 iter->second.Run(path, from_sync);
66 }
67