summaryrefslogtreecommitdiffstats
path: root/chrome/browser/prefs/pref_change_registrar.cc
blob: 05372b1fe2a377f64e8e9686fdfeb00ef7fb461e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/prefs/pref_change_registrar.h"

#include "chrome/browser/prefs/pref_service.h"

PrefChangeRegistrar::PrefChangeRegistrar() : service_(NULL) {}

PrefChangeRegistrar::~PrefChangeRegistrar() {
  RemoveAll();
}

void PrefChangeRegistrar::Init(PrefService* service) {
  DCHECK(IsEmpty() || service_ == service);
  service_ = service;
}

void PrefChangeRegistrar::Add(const char* path, NotificationObserver* obs) {
  if (!service_) {
    NOTREACHED();
    return;
  }
  ObserverRegistration registration(path, obs);
  if (observers_.find(registration) != observers_.end()) {
    NOTREACHED();
    return;
  }
  observers_.insert(registration);
  service_->AddPrefObserver(path, obs);
}

void PrefChangeRegistrar::Remove(const char* path, NotificationObserver* obs) {
  if (!service_) {
    NOTREACHED();
    return;
  }
  ObserverRegistration registration(path, obs);
  std::set<ObserverRegistration>::iterator it =
       observers_.find(registration);
  if (it == observers_.end()) {
    NOTREACHED();
    return;
  }
  service_->RemovePrefObserver(it->first.c_str(), it->second);
  observers_.erase(it);
}

void PrefChangeRegistrar::RemoveAll() {
  if (service_) {
    for (std::set<ObserverRegistration>::const_iterator it = observers_.begin();
         it != observers_.end(); ++it) {
      service_->RemovePrefObserver(it->first.c_str(), it->second);
    }
    observers_.clear();
  }
}

bool PrefChangeRegistrar::IsEmpty() const {
  return observers_.empty();
}