Brett Wilson | 21cf626a | 2017-09-07 00:30:20 | [diff] [blame] | 1 | // Copyright 2017 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/font_pref_change_notifier.h" |
| 6 | |
| 7 | #include "base/bind.h" |
Hans Wennborg | 1790e6b | 2020-04-24 19:10:33 | [diff] [blame] | 8 | #include "base/check.h" |
Brett Wilson | 21cf626a | 2017-09-07 00:30:20 | [diff] [blame] | 9 | #include "base/strings/string_util.h" |
| 10 | #include "chrome/common/pref_names_util.h" |
| 11 | #include "components/prefs/pref_service.h" |
| 12 | |
| 13 | FontPrefChangeNotifier::Registrar::Registrar() {} |
| 14 | FontPrefChangeNotifier::Registrar::~Registrar() { |
| 15 | if (is_registered()) |
| 16 | Unregister(); |
| 17 | } |
| 18 | |
| 19 | void FontPrefChangeNotifier::Registrar::Register( |
| 20 | FontPrefChangeNotifier* notifier, |
| 21 | FontPrefChangeNotifier::Callback cb) { |
| 22 | DCHECK(!is_registered()); |
| 23 | notifier_ = notifier; |
| 24 | callback_ = std::move(cb); |
| 25 | |
| 26 | notifier_->AddRegistrar(this); |
| 27 | } |
| 28 | |
| 29 | void FontPrefChangeNotifier::Registrar::Unregister() { |
| 30 | DCHECK(is_registered()); |
| 31 | notifier_->RemoveRegistrar(this); |
| 32 | |
| 33 | notifier_ = nullptr; |
| 34 | callback_ = FontPrefChangeNotifier::Callback(); |
| 35 | } |
| 36 | |
| 37 | FontPrefChangeNotifier::FontPrefChangeNotifier(PrefService* pref_service) |
| 38 | : pref_service_(pref_service) { |
| 39 | pref_service_->AddPrefObserverAllPrefs(this); |
| 40 | } |
| 41 | |
| 42 | FontPrefChangeNotifier::~FontPrefChangeNotifier() { |
| 43 | pref_service_->RemovePrefObserverAllPrefs(this); |
| 44 | |
| 45 | // There could be a shutdown race between this class and the objects |
| 46 | // registered with it. We don't want the registrars to call back into us |
| 47 | // when we're deleted, so tell them to unregister now. |
| 48 | for (auto& reg : registrars_) |
| 49 | reg.Unregister(); |
| 50 | } |
| 51 | |
| 52 | void FontPrefChangeNotifier::AddRegistrar(Registrar* registrar) { |
| 53 | registrars_.AddObserver(registrar); |
| 54 | } |
| 55 | |
| 56 | void FontPrefChangeNotifier::RemoveRegistrar(Registrar* registrar) { |
| 57 | registrars_.RemoveObserver(registrar); |
| 58 | } |
| 59 | |
| 60 | void FontPrefChangeNotifier::OnPreferenceChanged(PrefService* pref_service, |
| 61 | const std::string& pref_name) { |
| 62 | if (base::StartsWith(pref_name, pref_names_util::kWebKitFontPrefPrefix, |
| 63 | base::CompareCase::SENSITIVE)) { |
| 64 | for (auto& reg : registrars_) |
| 65 | reg.callback_.Run(pref_name); |
| 66 | } |
| 67 | } |