• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2010 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/pref_change_registrar.h"
6 
7 #include "base/logging.h"
8 #include "chrome/browser/prefs/pref_service.h"
9 
PrefChangeRegistrar()10 PrefChangeRegistrar::PrefChangeRegistrar() : service_(NULL) {}
11 
~PrefChangeRegistrar()12 PrefChangeRegistrar::~PrefChangeRegistrar() {
13   // If you see an invalid memory access in this destructor, this
14   // PrefChangeRegistrar might be subscribed to an OffTheRecordProfileImpl that
15   // has been destroyed. This should not happen any more but be warned.
16   // Feel free to contact battre@chromium.org in case this happens.
17   RemoveAll();
18 }
19 
Init(PrefService * service)20 void PrefChangeRegistrar::Init(PrefService* service) {
21   DCHECK(IsEmpty() || service_ == service);
22   service_ = service;
23 }
24 
Add(const char * path,NotificationObserver * obs)25 void PrefChangeRegistrar::Add(const char* path, NotificationObserver* obs) {
26   if (!service_) {
27     NOTREACHED();
28     return;
29   }
30   ObserverRegistration registration(path, obs);
31   if (observers_.find(registration) != observers_.end()) {
32     NOTREACHED();
33     return;
34   }
35   observers_.insert(registration);
36   service_->AddPrefObserver(path, obs);
37 }
38 
Remove(const char * path,NotificationObserver * obs)39 void PrefChangeRegistrar::Remove(const char* path, NotificationObserver* obs) {
40   if (!service_) {
41     NOTREACHED();
42     return;
43   }
44   ObserverRegistration registration(path, obs);
45   std::set<ObserverRegistration>::iterator it =
46        observers_.find(registration);
47   if (it == observers_.end()) {
48     NOTREACHED();
49     return;
50   }
51   service_->RemovePrefObserver(it->first.c_str(), it->second);
52   observers_.erase(it);
53 }
54 
RemoveAll()55 void PrefChangeRegistrar::RemoveAll() {
56   if (service_) {
57     for (std::set<ObserverRegistration>::const_iterator it = observers_.begin();
58          it != observers_.end(); ++it) {
59       service_->RemovePrefObserver(it->first.c_str(), it->second);
60     }
61     observers_.clear();
62   }
63 }
64 
IsEmpty() const65 bool PrefChangeRegistrar::IsEmpty() const {
66   return observers_.empty();
67 }
68