1 // Copyright 2013 The Chromium Authors
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 "components/prefs/scoped_user_pref_update.h"
6
7 #include <string_view>
8
9 #include "base/check_deref.h"
10 #include "base/check_op.h"
11 #include "components/prefs/pref_notifier.h"
12 #include "components/prefs/pref_service.h"
13
14 // TODO(crbug.com/40895218): The following two can be removed after resolving
15 // the problem.
16 #include "base/debug/crash_logging.h"
17 #include "base/debug/dump_without_crashing.h"
18 #include "base/types/cxx23_to_underlying.h"
19
20 namespace subtle {
21
ScopedUserPrefUpdateBase(PrefService * service,std::string_view path)22 ScopedUserPrefUpdateBase::ScopedUserPrefUpdateBase(PrefService* service,
23 std::string_view path)
24 : service_(CHECK_DEREF(service)), path_(path) {
25 DCHECK_CALLED_ON_VALID_SEQUENCE(service_->sequence_checker_);
26 }
27
~ScopedUserPrefUpdateBase()28 ScopedUserPrefUpdateBase::~ScopedUserPrefUpdateBase() {
29 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
30 Notify();
31 }
32
GetValueOfType(base::Value::Type type)33 base::Value* ScopedUserPrefUpdateBase::GetValueOfType(base::Value::Type type) {
34 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
35 if (!value_)
36 value_ = service_->GetMutableUserPref(path_, type);
37 if (!value_) {
38 // TODO(crbug.com/40895218) This is unexpected, so let's collect some data.
39 const PrefService::Preference* pref = service_->FindPreference(path_);
40 SCOPED_CRASH_KEY_NUMBER(
41 "ScopedUserPrefUpdate", "PrevServiceStatus",
42 base::to_underlying(service_->GetInitializationStatus()));
43 SCOPED_CRASH_KEY_STRING32("ScopedUserPrefUpdate", "FindPreference",
44 pref ? "Yes" : "No");
45 SCOPED_CRASH_KEY_NUMBER("ScopedUserPrefUpdate", "Type",
46 pref ? base::to_underlying(pref->GetType()) : -1);
47 base::debug::DumpWithoutCrashing();
48 }
49 return value_;
50 }
51
Notify()52 void ScopedUserPrefUpdateBase::Notify() {
53 if (value_) {
54 service_->ReportUserPrefChanged(path_);
55 value_ = nullptr;
56 }
57 }
58
59 } // namespace subtle
60
Get()61 base::Value::Dict& ScopedDictPrefUpdate::Get() {
62 return GetValueOfType(base::Value::Type::DICT)->GetDict();
63 }
64
Get()65 base::Value::List& ScopedListPrefUpdate::Get() {
66 return GetValueOfType(base::Value::Type::LIST)->GetList();
67 }
68