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 10PrefChangeRegistrar::PrefChangeRegistrar() : service_(NULL) {} 11 12PrefChangeRegistrar::~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 20void PrefChangeRegistrar::Init(PrefService* service) { 21 DCHECK(IsEmpty() || service_ == service); 22 service_ = service; 23} 24 25void 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 39void 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 55void 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 65bool PrefChangeRegistrar::IsEmpty() const { 66 return observers_.empty(); 67} 68