1 // Copyright 2010 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/prefs/pref_change_registrar.h"
9 #include "base/check.h"
10 #include "base/functional/bind.h"
11 #include "base/notreached.h"
12 #include "components/prefs/pref_service.h"
14 PrefChangeRegistrar::PrefChangeRegistrar() : service_(nullptr) {}
16 PrefChangeRegistrar::~PrefChangeRegistrar() {
17 // If you see an invalid memory access in this destructor, this
18 // PrefChangeRegistrar might be subscribed to an OffTheRecordProfileImpl that
19 // has been destroyed. This should not happen any more but be warned.
20 // Feel free to contact battre@chromium.org in case this happens.
22 // This can also happen for non-OTR profiles, when the
23 // DestroyProfileOnBrowserClose flag is enabled. In that case, contact
24 // nicolaso@chromium.org.
28 void PrefChangeRegistrar::Init(PrefService* service) {
29 DCHECK(IsEmpty() || service_ == service);
33 void PrefChangeRegistrar::Add(const std::string& path,
34 const base::RepeatingClosure& obs) {
36 base::BindRepeating(&PrefChangeRegistrar::InvokeUnnamedCallback, obs));
39 void PrefChangeRegistrar::Add(const std::string& path,
40 const NamedChangeCallback& obs) {
45 DCHECK(!IsObserved(path)) << "Already had pref, \"" << path
48 service_->AddPrefObserver(path, this);
49 observers_[path] = obs;
52 void PrefChangeRegistrar::Remove(const std::string& path) {
53 DCHECK(IsObserved(path));
55 observers_.erase(path);
56 service_->RemovePrefObserver(path, this);
59 void PrefChangeRegistrar::RemoveAll() {
60 for (ObserverMap::const_iterator it = observers_.begin();
61 it != observers_.end(); ++it) {
62 service_->RemovePrefObserver(it->first, this);
68 bool PrefChangeRegistrar::IsEmpty() const {
69 return observers_.empty();
72 bool PrefChangeRegistrar::IsObserved(const std::string& pref) {
73 return observers_.find(pref) != observers_.end();
76 void PrefChangeRegistrar::OnPreferenceChanged(PrefService* service,
77 const std::string& pref) {
79 observers_[pref].Run(pref);
82 void PrefChangeRegistrar::InvokeUnnamedCallback(
83 const base::RepeatingClosure& callback,
84 const std::string& pref_name) {
88 PrefService* PrefChangeRegistrar::prefs() {
92 const PrefService* PrefChangeRegistrar::prefs() const {