| // Copyright 2017 The Chromium Authors | 
 | // Use of this source code is governed by a BSD-style license that can be | 
 | // found in the LICENSE file. | 
 |  | 
 | #include "chrome/browser/font_pref_change_notifier.h" | 
 |  | 
 | #include "base/check.h" | 
 | #include "base/functional/bind.h" | 
 | #include "base/observer_list.h" | 
 | #include "base/strings/string_util.h" | 
 | #include "chrome/common/pref_names_util.h" | 
 | #include "components/prefs/pref_service.h" | 
 |  | 
 | FontPrefChangeNotifier::Registrar::Registrar() = default; | 
 | FontPrefChangeNotifier::Registrar::~Registrar() { | 
 |   if (is_registered()) | 
 |     Unregister(); | 
 | } | 
 |  | 
 | void FontPrefChangeNotifier::Registrar::Register( | 
 |     FontPrefChangeNotifier* notifier, | 
 |     FontPrefChangeNotifier::Callback cb) { | 
 |   DCHECK(!is_registered()); | 
 |   notifier_ = notifier; | 
 |   callback_ = std::move(cb); | 
 |  | 
 |   notifier_->AddRegistrar(this); | 
 | } | 
 |  | 
 | void FontPrefChangeNotifier::Registrar::Unregister() { | 
 |   DCHECK(is_registered()); | 
 |   notifier_->RemoveRegistrar(this); | 
 |  | 
 |   notifier_ = nullptr; | 
 |   callback_ = FontPrefChangeNotifier::Callback(); | 
 | } | 
 |  | 
 | FontPrefChangeNotifier::FontPrefChangeNotifier(PrefService* pref_service) | 
 |     : pref_service_(pref_service) { | 
 |   pref_service_->AddPrefObserverAllPrefs(this); | 
 | } | 
 |  | 
 | FontPrefChangeNotifier::~FontPrefChangeNotifier() { | 
 |   if (pref_service_) { | 
 |     pref_service_->RemovePrefObserverAllPrefs(this); | 
 |     pref_service_ = nullptr; | 
 |   } | 
 |  | 
 |   // There could be a shutdown race between this class and the objects | 
 |   // registered with it. We don't want the registrars to call back into us | 
 |   // when we're deleted, so tell them to unregister now. | 
 |   for (auto& reg : registrars_) | 
 |     reg.Unregister(); | 
 | } | 
 |  | 
 | void FontPrefChangeNotifier::AddRegistrar(Registrar* registrar) { | 
 |   registrars_.AddObserver(registrar); | 
 | } | 
 |  | 
 | void FontPrefChangeNotifier::RemoveRegistrar(Registrar* registrar) { | 
 |   registrars_.RemoveObserver(registrar); | 
 | } | 
 |  | 
 | void FontPrefChangeNotifier::OnServiceDestroyed(PrefService* service) { | 
 |   pref_service_->RemovePrefObserverAllPrefs(this); | 
 |   pref_service_ = nullptr; | 
 | } | 
 |  | 
 | void FontPrefChangeNotifier::OnPreferenceChanged(PrefService* pref_service, | 
 |                                                  std::string_view pref_name) { | 
 |   if (base::StartsWith(pref_name, pref_names_util::kWebKitFontPrefPrefix, | 
 |                        base::CompareCase::SENSITIVE)) { | 
 |     const std::string pref_name_string(pref_name); | 
 |     for (auto& reg : registrars_) | 
 |       reg.callback_.Run(pref_name_string); | 
 |   } | 
 | } |