File: theme_service.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1016 lines) | stat: -rw-r--r-- 36,043 bytes parent folder | download | duplicates (5)
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
// Copyright 2012 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/themes/theme_service.h"

#include <stddef.h>

#include <algorithm>
#include <memory>
#include <optional>

#include "base/auto_reset.h"
#include "base/command_line.h"
#include "base/containers/fixed_flat_map.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted_memory.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/user_metrics.h"
#include "base/observer_list.h"
#include "base/one_shot_event.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include "chrome/browser/new_tab_page/chrome_colors/chrome_colors_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/themes/browser_theme_pack.h"
#include "chrome/browser/themes/custom_theme_supplier.h"
#include "chrome/browser/themes/theme_properties.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/browser/themes/theme_service_observer.h"
#include "chrome/browser/themes/theme_service_utils.h"
#include "chrome/browser/themes/theme_syncable_service.h"
#include "chrome/browser/ui/color/chrome_color_id.h"
#include "chrome/common/buildflags.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "components/infobars/content/content_infobar_manager.h"
#include "components/prefs/pref_service.h"
#include "extensions/browser/extension_file_task_runner.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_registrar.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/uninstall_reason.h"
#include "extensions/buildflags/buildflags.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_set.h"
#include "third_party/abseil-cpp/absl/cleanup/cleanup.h"
#include "ui/base/mojom/themes.mojom.h"
#include "ui/base/resource/resource_scale_factor.h"
#include "ui/base/ui_base_features.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/color/color_provider_manager.h"
#include "ui/native_theme/native_theme.h"

#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "base/scoped_observation.h"
#include "extensions/browser/extension_registry_observer.h"
#endif

#if BUILDFLAG(IS_LINUX)
#include "ui/linux/linux_ui.h"
#include "ui/ozone/public/ozone_platform.h"  // nogncheck
#endif

using TP = ThemeProperties;

// Helpers --------------------------------------------------------------------

namespace {

// Wait this many seconds after startup to garbage collect unused themes.
// Removing unused themes is done after a delay because there is no
// reason to do it at startup.
// ExtensionService::GarbageCollectExtensions() does something similar.
constexpr base::TimeDelta kRemoveUnusedThemesStartupDelay = base::Seconds(30);

bool g_dont_write_theme_pack_for_testing = false;

// Writes the theme pack to disk on a separate thread.
void WritePackToDiskCallback(BrowserThemePack* pack,
                             const base::FilePath& directory) {
  if (g_dont_write_theme_pack_for_testing) {
    return;
  }

  pack->WriteToDisk(directory.Append(chrome::kThemePackFilename));
}

}  // namespace

// ThemeService::ThemeObserver ------------------------------------------------

#if BUILDFLAG(ENABLE_EXTENSIONS)
class ThemeService::ThemeObserver
    : public extensions::ExtensionRegistryObserver {
 public:
  explicit ThemeObserver(ThemeService* service) : theme_service_(service) {
    extension_registry_observation_.Observe(
        extensions::ExtensionRegistry::Get(theme_service_->profile_));
  }

  ThemeObserver(const ThemeObserver&) = delete;
  ThemeObserver& operator=(const ThemeObserver&) = delete;

  ~ThemeObserver() override = default;

 private:
  // extensions::ExtensionRegistryObserver:
  void OnExtensionWillBeInstalled(content::BrowserContext* browser_context,
                                  const extensions::Extension* extension,
                                  bool is_update,
                                  const std::string& old_name) override {
    if (extension->is_theme()) {
      // Remember ID of the newly installed theme.
      theme_service_->installed_pending_load_id_ = extension->id();
    }
  }

  void OnExtensionLoaded(content::BrowserContext* browser_context,
                         const extensions::Extension* extension) override {
    if (!extension->is_theme() || theme_service_->UsingPolicyTheme()) {
      return;
    }

    bool is_new_version =
        theme_service_->installed_pending_load_id_ !=
            ThemeHelper::kDefaultThemeID &&
        theme_service_->installed_pending_load_id_ == extension->id();
    theme_service_->installed_pending_load_id_ = ThemeHelper::kDefaultThemeID;

    // Do not load already loaded theme.
    if (!is_new_version && extension->id() == theme_service_->GetThemeID()) {
      return;
    }

    // Set the new theme during extension load:
    // This includes: a) installing a new theme, b) enabling a disabled theme.
    // We shouldn't get here for the update of a disabled theme.
    theme_service_->DoSetTheme(extension, !is_new_version);
  }

  void OnExtensionUnloaded(
      content::BrowserContext* browser_context,
      const extensions::Extension* extension,
      extensions::UnloadedExtensionReason reason) override {
    if (reason != extensions::UnloadedExtensionReason::UPDATE &&
        reason != extensions::UnloadedExtensionReason::LOCK_ALL &&
        extension->is_theme() &&
        extension->id() == theme_service_->GetThemeID()) {
      theme_service_->UseDefaultTheme();
    }
  }

  raw_ptr<ThemeService> theme_service_;

  base::ScopedObservation<extensions::ExtensionRegistry,
                          extensions::ExtensionRegistryObserver>
      extension_registry_observation_{this};
};
#endif  // BUILDFLAG(ENABLE_EXTENSIONS)

// ThemeService::ThemeReinstaller -----------------------------------------

ThemeService::ThemeReinstaller::ThemeReinstaller(Profile* profile,
                                                 base::OnceClosure installer)
    : theme_service_(ThemeServiceFactory::GetForProfile(profile)) {
  theme_service_->number_of_reinstallers_++;
  installer_ = std::move(installer);
}

ThemeService::ThemeReinstaller::~ThemeReinstaller() {
  theme_service_->number_of_reinstallers_--;
  theme_service_->RemoveUnusedThemes();
}

void ThemeService::ThemeReinstaller::Reinstall() {
  if (!installer_.is_null()) {
    std::move(installer_).Run();
  }
}

// ThemeService::BrowserThemeProvider ------------------------------------------

ThemeService::BrowserThemeProvider::BrowserThemeProvider(
    const ThemeHelper& theme_helper,
    bool incognito,
    const BrowserThemeProviderDelegate* delegate)
    : theme_helper_(theme_helper), incognito_(incognito), delegate_(delegate) {
  DCHECK(delegate_);
}

ThemeService::BrowserThemeProvider::~BrowserThemeProvider() = default;

gfx::ImageSkia* ThemeService::BrowserThemeProvider::GetImageSkiaNamed(
    int id) const {
  return theme_helper_->GetImageSkiaNamed(id, incognito_, GetThemeSupplier());
}

color_utils::HSL ThemeService::BrowserThemeProvider::GetTint(int id) const {
  return theme_helper_->GetTint(id, incognito_, GetThemeSupplier());
}

int ThemeService::BrowserThemeProvider::GetDisplayProperty(int id) const {
  return theme_helper_->GetDisplayProperty(id, GetThemeSupplier());
}

bool ThemeService::BrowserThemeProvider::ShouldUseNativeFrame() const {
  return theme_helper_->ShouldUseNativeFrame(GetThemeSupplier());
}

bool ThemeService::BrowserThemeProvider::HasCustomImage(int id) const {
  return theme_helper_->HasCustomImage(id, GetThemeSupplier());
}

base::RefCountedMemory* ThemeService::BrowserThemeProvider::GetRawData(
    int id,
    ui::ResourceScaleFactor scale_factor) const {
  return theme_helper_->GetRawData(id, GetThemeSupplier(), scale_factor);
}

CustomThemeSupplier* ThemeService::BrowserThemeProvider::GetThemeSupplier()
    const {
  return incognito_ ? nullptr : delegate_->GetThemeSupplier();
}

// ThemeService ---------------------------------------------------------------

const char ThemeService::kAutogeneratedThemeID[] = "autogenerated_theme_id";
const char ThemeService::kUserColorThemeID[] = "user_color_theme_id";

// static
std::unique_ptr<ui::ThemeProvider> ThemeService::CreateBoundThemeProvider(
    Profile* profile,
    BrowserThemeProviderDelegate* delegate) {
  return std::make_unique<BrowserThemeProvider>(
      *ThemeServiceFactory::GetForProfile(profile)->theme_helper_, false,
      delegate);
}

ThemeService::ThemeService(Profile* profile, const ThemeHelper& theme_helper)
    : profile_(profile),
      theme_helper_(theme_helper),
      original_theme_provider_(*theme_helper_, false, this),
      incognito_theme_provider_(*theme_helper_, true, this) {}

ThemeService::~ThemeService() = default;

void ThemeService::Init() {
  theme_helper_->DCheckCalledOnValidSequence();

  InitFromPrefs();

  // ThemeObserver should be constructed before calling
  // OnExtensionServiceReady. Otherwise, the ThemeObserver won't be
  // constructed in time to observe the corresponding events.
#if BUILDFLAG(ENABLE_EXTENSIONS)
  theme_observer_ = std::make_unique<ThemeObserver>(this);

  extensions::ExtensionSystem::Get(profile_)->ready().Post(
      FROM_HERE, base::BindOnce(&ThemeService::OnExtensionServiceReady,
                                weak_ptr_factory_.GetWeakPtr()));
#endif
  theme_syncable_service_ =
      std::make_unique<ThemeSyncableService>(profile_, this);

  // TODO(gayane): Temporary entry point for Chrome Colors. Remove once UI is
  // there.
  const base::CommandLine* command_line =
      base::CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kInstallAutogeneratedTheme)) {
    std::string value =
        command_line->GetSwitchValueASCII(switches::kInstallAutogeneratedTheme);
    std::vector<std::string> rgb = base::SplitString(
        value, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
    if (rgb.size() != 3) {
      return;
    }
    int r, g, b;
    base::StringToInt(rgb[0], &r);
    base::StringToInt(rgb[1], &g);
    base::StringToInt(rgb[2], &b);
    BuildAutogeneratedThemeFromColor(SkColorSetRGB(r, g, b));
  }

  pref_change_registrar_.Init(profile_->GetPrefs());
  pref_change_registrar_.Add(
      prefs::kPolicyThemeColor,
      base::BindRepeating(&ThemeService::HandlePolicyColorUpdate,
                          base::Unretained(this)));
  pref_change_registrar_.Add(
      prefs::kBrowserColorScheme,
      base::BindRepeating(&ThemeService::NotifyThemeChanged,
                          base::Unretained(this)));
  pref_change_registrar_.Add(
      prefs::kBrowserColorVariant,
      base::BindRepeating(&ThemeService::NotifyThemeChanged,
                          base::Unretained(this)));
  pref_change_registrar_.Add(
      prefs::kGrayscaleThemeEnabled,
      base::BindRepeating(&ThemeService::NotifyThemeChanged,
                          base::Unretained(this)));
  pref_change_registrar_.Add(
      prefs::kUserColor, base::BindRepeating(&ThemeService::NotifyThemeChanged,
                                             base::Unretained(this)));
}

void ThemeService::Shutdown() {
#if BUILDFLAG(ENABLE_EXTENSIONS)
  theme_observer_.reset();
#endif
  theme_syncable_service_.reset();
}

CustomThemeSupplier* ThemeService::GetThemeSupplier() const {
  return theme_supplier_.get();
}

bool ThemeService::ShouldUseCustomFrame() const {
#if BUILDFLAG(IS_LINUX)
  if (!ui::OzonePlatform::GetInstance()
           ->GetPlatformRuntimeProperties()
           .supports_server_side_window_decorations) {
    return true;
  }

  return profile_->GetPrefs()->GetBoolean(prefs::kUseCustomChromeFrame);
#else
  return true;
#endif
}

void ThemeService::SetTheme(const extensions::Extension* extension) {
  DoSetTheme(extension, true);
}

void ThemeService::RevertToExtensionTheme(const std::string& extension_id) {
  const auto* extension = extensions::ExtensionRegistry::Get(profile_)
                              ->disabled_extensions()
                              .GetByID(extension_id);
  if (extension && extension->is_theme()) {
    auto* registrar = extensions::ExtensionRegistrar::Get(profile_);
    DCHECK(!registrar->IsExtensionEnabled(extension->id()));
    // |extension| is disabled when reverting to the previous theme via an
    // infobar.
    registrar->EnableExtension(extension->id());
    // Enabling the extension will call back to SetTheme().
  }
}

void ThemeService::UseTheme(ui::SystemTheme system_theme) {
  UseDefaultTheme();
}

void ThemeService::UseDefaultTheme() {
  if (UsingPolicyTheme()) {
    DVLOG(1)
        << "Default theme was not applied because a policy theme has been set.";
    return;
  }

  if (ready_) {
    base::RecordAction(base::UserMetricsAction("Themes_Reset"));
  }

  ClearThemeData(/*clear_ntp_background=*/true);
  NotifyThemeChanged();
}

void ThemeService::UseSystemTheme() {
  UseDefaultTheme();
}

void ThemeService::UseDeviceTheme(bool follow) {
#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_WIN)
  // This toggle is currently supported on ChromeOS and Windows and we only want
  // platforms to set the value if they have a visible toggle.
  profile_->GetPrefs()->SetBoolean(prefs::kBrowserFollowsSystemThemeColors,
                                   follow);
  NotifyThemeChanged();
#endif
}

bool ThemeService::UsingDeviceTheme() const {
#if BUILDFLAG(IS_CHROMEOS)
  const PrefService::Preference* pref = profile_->GetPrefs()->FindPreference(
      prefs::kBrowserFollowsSystemThemeColors);
  // Ensure we respect previous theme settings for an unset follow theme
  // value.
  if (pref->IsDefaultValue()) {
    return GetIsBaseline() && !UsingExtensionTheme();
  }
  return pref->GetValue()->GetBool();
#elif BUILDFLAG(IS_WIN)
  // Always respect the profile preference on Windows. In the default case the
  // preference starts disabled.
  return profile_->GetPrefs()
      ->FindPreference(prefs::kBrowserFollowsSystemThemeColors)
      ->GetValue()
      ->GetBool();
#else
  // Only ChromeOS and Windows have this toggle.
  return false;
#endif
}

bool ThemeService::IsSystemThemeDistinctFromDefaultTheme() const {
  return false;
}

bool ThemeService::UsingDefaultTheme() const {
  return ThemeHelper::IsDefaultTheme(GetThemeSupplier());
}

bool ThemeService::UsingSystemTheme() const {
  return UsingDefaultTheme();
}

bool ThemeService::UsingExtensionTheme() const {
  return ThemeHelper::IsExtensionTheme(GetThemeSupplier());
}

bool ThemeService::UsingAutogeneratedTheme() const {
  return ThemeHelper::IsAutogeneratedTheme(GetThemeSupplier());
}

std::string ThemeService::GetThemeID() const {
  return profile_->GetPrefs()->GetString(prefs::kCurrentThemeID);
}

bool ThemeService::UsingPolicyTheme() const {
  return profile_->GetPrefs()->IsManagedPreference(prefs::kPolicyThemeColor);
}

void ThemeService::RemoveUnusedThemes() {
  // We do not want to garbage collect themes on startup (|ready_| is false).
  // Themes will get garbage collected after |kRemoveUnusedThemesStartupDelay|.
  if (!profile_ || !ready_) {
    return;
  }
  if (number_of_reinstallers_ != 0 || !building_extension_id_.empty()) {
    return;
  }

  auto* extension_registrar = extensions::ExtensionRegistrar::Get(profile_);
  if (!extension_registrar) {
    return;
  }

  std::string current_theme = GetThemeID();
  std::vector<std::string> remove_list;
  const extensions::ExtensionSet extensions =
      extensions::ExtensionRegistry::Get(profile_)
          ->GenerateInstalledExtensionsSet();
  extensions::ExtensionPrefs* prefs = extensions::ExtensionPrefs::Get(profile_);
  for (const auto& extension : extensions) {
    if (extension->is_theme() && extension->id() != current_theme) {
      // Only uninstall themes which are not disabled or are disabled with
      // reason DISABLE_USER_ACTION. We cannot blanket uninstall all disabled
      // themes because externally installed themes are initially disabled.
      bool is_disabled_by_user = prefs->HasOnlyDisableReason(
          extension->id(), extensions::disable_reason::DISABLE_USER_ACTION);
      if (!prefs->IsExtensionDisabled(extension->id()) || is_disabled_by_user) {
        remove_list.push_back(extension->id());
      }
    }
  }
  // TODO: Garbage collect all unused themes. This method misses themes which
  // are installed but not loaded because they are blocked by a management
  // policy provider.

  for (const auto& i : remove_list) {
    extension_registrar->UninstallExtension(
        i, extensions::UNINSTALL_REASON_ORPHANED_THEME, nullptr);
  }
}

ThemeSyncableService* ThemeService::GetThemeSyncableService() const {
  return theme_syncable_service_.get();
}

// static
const ui::ThemeProvider& ThemeService::GetThemeProviderForProfile(
    Profile* profile) {
  ThemeService* service = ThemeServiceFactory::GetForProfile(profile);
  return profile->IsIncognitoProfile() ? service->incognito_theme_provider_
                                       : service->original_theme_provider_;
}

// static
CustomThemeSupplier* ThemeService::GetThemeSupplierForProfile(
    Profile* profile) {
  return ThemeServiceFactory::GetForProfile(profile)->GetThemeSupplier();
}

ui::ColorProvider* ThemeService::GetColorProvider() {
  // Device theme overrides custom themes.
  auto* theme_supplier = UsingDeviceTheme() ? nullptr : GetThemeSupplier();
  return ui::ColorProviderManager::Get().GetColorProviderFor(
      ui::NativeTheme::GetInstanceForNativeUi()->GetColorProviderKey(
          theme_supplier));
}

void ThemeService::BuildAutogeneratedThemeFromColor(SkColor color) {
  if (UsingPolicyTheme()) {
    DVLOG(1) << "Autogenerated theme was not applied because a policy theme"
                " has been set.";
    return;
  }
  BuildAutogeneratedThemeFromColor(color, /*store_user_prefs*/ true);
}

void ThemeService::BuildAutogeneratedThemeFromColor(SkColor color,
                                                    bool store_in_prefs) {
  std::optional<std::string> previous_theme_id;
  if (UsingExtensionTheme()) {
    previous_theme_id = GetThemeID();
  }

  auto pack = base::MakeRefCounted<BrowserThemePack>(
      ui::ColorProviderKey::ThemeInitializerSupplier::ThemeType::
          kAutogenerated);
  BrowserThemePack::BuildFromColor(color, pack.get());
  SwapThemeSupplier(std::move(pack));
  if (theme_supplier_) {
    if (store_in_prefs) {
      SetThemePrefsForColor(color);
      // Only disable previous extension theme if new theme is saved to prefs,
      // otherwise there may be issues (ex. when unsetting managed theme).
      if (previous_theme_id.has_value()) {
        DisableExtension(previous_theme_id.value());
      }
    }
    NotifyThemeChanged();
  }
}

SkColor ThemeService::GetAutogeneratedThemeColor() const {
  return profile_->GetPrefs()->GetInteger(prefs::kAutogeneratedThemeColor);
}

void ThemeService::BuildAutogeneratedPolicyTheme() {
  BuildAutogeneratedThemeFromColor(GetPolicyThemeColor(),
                                   /*store_user_prefs*/ false);
}

SkColor ThemeService::GetPolicyThemeColor() const {
  DCHECK(UsingPolicyTheme());
  return profile_->GetPrefs()->GetInteger(prefs::kPolicyThemeColor);
}

void ThemeService::SetBrowserColorScheme(
    ThemeService::BrowserColorScheme color_scheme) {
  {
    base::AutoReset<bool> resetter(&should_suppress_theme_updates_, true);
    profile_->GetPrefs()->SetInteger(prefs::kBrowserColorScheme,
                                     static_cast<int>(color_scheme));
  }
  NotifyThemeChanged();
}

ThemeService::BrowserColorScheme ThemeService::GetBrowserColorScheme() const {
  return static_cast<BrowserColorScheme>(
      profile_->GetPrefs()->GetInteger(prefs::kBrowserColorScheme));
}

void ThemeService::SetUserColor(std::optional<SkColor> user_color) {
  {
    base::AutoReset<bool> resetter(&should_suppress_theme_updates_, true);
    ClearThemeData(/*clear_ntp_background=*/false);
    profile_->GetPrefs()->SetInteger(prefs::kUserColor,
                                     user_color.value_or(SK_ColorTRANSPARENT));
    profile_->GetPrefs()->SetString(prefs::kCurrentThemeID, kUserColorThemeID);
  }
  NotifyThemeChanged();
}

std::optional<SkColor> ThemeService::GetUserColor() const {
  return CurrentThemeUserColor(profile_->GetPrefs());
}

void ThemeService::SetBrowserColorVariant(
    ui::mojom::BrowserColorVariant color_variant) {
  {
    base::AutoReset<bool> resetter(&should_suppress_theme_updates_, true);
    profile_->GetPrefs()->SetInteger(prefs::kBrowserColorVariant,
                                     static_cast<int>(color_variant));
  }
  NotifyThemeChanged();
}

ui::mojom::BrowserColorVariant ThemeService::GetBrowserColorVariant() const {
  return static_cast<ui::mojom::BrowserColorVariant>(
      profile_->GetPrefs()->GetInteger(prefs::kBrowserColorVariant));
}

void ThemeService::SetUserColorAndBrowserColorVariant(
    SkColor user_color,
    ui::mojom::BrowserColorVariant color_variant) {
  {
    base::AutoReset<bool> resetter(&should_suppress_theme_updates_, true);
    ClearThemeData(/*clear_ntp_background=*/false);
    profile_->GetPrefs()->SetInteger(prefs::kUserColor, user_color);
    profile_->GetPrefs()->SetString(prefs::kCurrentThemeID, kUserColorThemeID);
    profile_->GetPrefs()->SetInteger(prefs::kBrowserColorVariant,
                                     static_cast<int>(color_variant));
  }
  NotifyThemeChanged();
}

void ThemeService::SetIsGrayscale(bool is_grayscale) {
  {
    base::AutoReset<bool> resetter(&should_suppress_theme_updates_, true);
    ClearThemeData(/*clear_ntp_background=*/false);
    profile_->GetPrefs()->SetBoolean(prefs::kGrayscaleThemeEnabled,
                                     is_grayscale);
  }
  NotifyThemeChanged();
}

bool ThemeService::GetIsGrayscale() const {
  return CurrentThemeIsGrayscale(profile_->GetPrefs());
}

bool ThemeService::GetIsBaseline() const {
  // Baseline is defined by the absence of a user color set by the corresponding
  // profile pref or the autogenerated theme.
  return !GetUserColor().has_value() && !UsingAutogeneratedTheme();
}

// static
void ThemeService::DisableThemePackForTesting() {
  g_dont_write_theme_pack_for_testing = true;
}

std::unique_ptr<ThemeService::ThemeReinstaller>
ThemeService::BuildReinstallerForCurrentTheme() {
  std::string current_id = GetThemeID();
  if (UsingExtensionTheme()) {
    return std::make_unique<ThemeReinstaller>(
        profile_, base::BindOnce(&ThemeService::RevertToExtensionTheme,
                                 weak_ptr_factory_.GetWeakPtr(), current_id));
  }
  // TODO(crbug.com/352471699): Also restore the NTP background image.
  if (UsingAutogeneratedTheme()) {
    return std::make_unique<ThemeReinstaller>(
        profile_,
        base::BindOnce(static_cast<void (ThemeService::*)(SkColor)>(
                           &ThemeService::BuildAutogeneratedThemeFromColor),
                       weak_ptr_factory_.GetWeakPtr(),
                       GetAutogeneratedThemeColor()));
  }
  if (current_id == kUserColorThemeID) {
    if (const std::optional<SkColor> user_color = GetUserColor()) {
      return std::make_unique<ThemeReinstaller>(
          profile_,
          base::BindOnce(&ThemeService::SetUserColorAndBrowserColorVariant,
                         weak_ptr_factory_.GetWeakPtr(), user_color.value(),
                         GetBrowserColorVariant()));
    }
  }

  auto system_theme = ui::SystemTheme::kDefault;
  if (auto* theme_supplier = GetThemeSupplier()) {
    if (auto* native_theme = theme_supplier->GetNativeTheme()) {
      system_theme = native_theme->system_theme();
    }
  }
  return std::make_unique<ThemeReinstaller>(
      profile_, base::BindOnce(&ThemeService::UseTheme,
                               weak_ptr_factory_.GetWeakPtr(), system_theme));
}

void ThemeService::AddObserver(ThemeServiceObserver* observer) {
  observers_.AddObserver(observer);
}

void ThemeService::RemoveObserver(ThemeServiceObserver* observer) {
  observers_.RemoveObserver(observer);
}

void ThemeService::SetCustomDefaultTheme(
    scoped_refptr<CustomThemeSupplier> theme_supplier) {
  if (UsingPolicyTheme()) {
    DVLOG(1) << "Custom default theme was not applied because a policy "
                "theme has been set.";
    return;
  }

  ClearThemeData(/*clear_ntp_background=*/true);
  SwapThemeSupplier(std::move(theme_supplier));
  NotifyThemeChanged();
}

ui::SystemTheme ThemeService::GetDefaultSystemTheme() const {
  return ui::SystemTheme::kDefault;
}

void ThemeService::ClearThemeData(bool clear_ntp_background) {
  if (!ready_) {
    return;
  }

  std::optional<std::string> previous_theme_id;
  if (UsingExtensionTheme()) {
    previous_theme_id = GetThemeID();
  }

  SwapThemeSupplier(nullptr);
  ClearThemePrefs();
  if (clear_ntp_background) {
    // Redraw and notify sync that theme has changed.
    for (auto& observer : observers_) {
      observer.OnCustomNtpBackgroundObsolete();
    }
  }

  // Disable extension after modifying the prefs so that unloading the extension
  // doesn't trigger |ClearThemeData| again.
  if (previous_theme_id.has_value()) {
    DisableExtension(previous_theme_id.value());
  }
}

void ThemeService::InitFromPrefs() {
  FixInconsistentPreferencesIfNeeded();
  absl::Cleanup set_ready_cleanup = [this] { this->set_ready(); };

  // If theme color policy was set while browser was off, apply it now.
  if (UsingPolicyTheme()) {
    BuildAutogeneratedPolicyTheme();
    return;
  }

  std::string current_id = GetThemeID();
  if (current_id == ThemeHelper::kDefaultThemeID) {
    if (GetIsGrayscale()) {
      chrome_colors::RecordDynamicColorOnLoadHistogramForGrayscale();
    }
    UseTheme(GetDefaultSystemTheme());
    return;
  }

  if (current_id == kAutogeneratedThemeID) {
    SkColor color = GetAutogeneratedThemeColor();
    BuildAutogeneratedThemeFromColor(color);
    chrome_colors::RecordColorOnLoadHistogram(color);
    return;
  }

  if (current_id == kUserColorThemeID) {
    const auto user_color = GetUserColor();
    if (user_color.has_value()) {
      chrome_colors::RecordDynamicColorOnLoadHistogram(
          *user_color, GetBrowserColorVariant());
    }
    return;
  }

  PrefService* prefs = profile_->GetPrefs();
  base::FilePath path = prefs->GetFilePath(prefs::kCurrentThemePackFilename);
  // If we don't have a file pack, we're updating from an old version.
  if (!path.empty()) {
    path = path.Append(chrome::kThemePackFilename);
    SwapThemeSupplier(BrowserThemePack::BuildFromDataPack(path, current_id));
    if (theme_supplier_) {
      base::RecordAction(base::UserMetricsAction("Themes.Loaded"));
      return;
    }
  }
  // Else: wait for the extension service to be ready so that the theme pack
  // can be recreated from the extension.
  std::move(set_ready_cleanup).Cancel();
}

void ThemeService::NotifyThemeChanged() {
  if (!ready_ || should_suppress_theme_updates_) {
    return;
  }

  // Redraw and notify sync that theme has changed.
  for (auto& observer : observers_) {
    observer.OnThemeChanged();
  }
}

void ThemeService::FixInconsistentPreferencesIfNeeded() {}

void ThemeService::DoSetTheme(const extensions::Extension* extension,
                              bool suppress_infobar) {
  DCHECK(extension->is_theme());
  DCHECK(!UsingPolicyTheme());
  DCHECK(extensions::ExtensionRegistrar::Get(profile_)->IsExtensionEnabled(
      extension->id()));
  BuildFromExtension(extension, suppress_infobar);
}

void ThemeService::OnExtensionServiceReady() {
  if (!ready_) {
    // If the ThemeService is not ready yet, the custom theme data pack needs to
    // be recreated from the extension.
    MigrateTheme();
    set_ready();
  }

  base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&ThemeService::RemoveUnusedThemes,
                     weak_ptr_factory_.GetWeakPtr()),
      kRemoveUnusedThemesStartupDelay);
}

void ThemeService::MigrateTheme() {
  TRACE_EVENT0("browser", "ThemeService::MigrateTheme");

  extensions::ExtensionRegistry* registry =
      extensions::ExtensionRegistry::Get(profile_);
  const extensions::Extension* extension =
      registry ? registry->enabled_extensions().GetByID(GetThemeID()) : nullptr;
  if (extension) {
    // Theme migration is done on the UI thread. Blocking the UI from appearing
    // until it's ready is deemed better than showing a blip of the default
    // theme.
    TRACE_EVENT0("browser", "ThemeService::MigrateTheme - BuildFromExtension");
    DLOG(ERROR) << "Migrating theme";

    scoped_refptr<BrowserThemePack> pack(new BrowserThemePack(
        ui::ColorProviderKey::ThemeInitializerSupplier::ThemeType::kExtension));
    BrowserThemePack::BuildFromExtension(extension, pack.get());
    OnThemeBuiltFromExtension(extension->id(), pack.get(), true);
    base::RecordAction(base::UserMetricsAction("Themes.Migrated"));
  } else {
    DLOG(ERROR) << "Theme is mysteriously gone.";
    ClearThemeData(/*clear_ntp_background=*/true);
    base::RecordAction(base::UserMetricsAction("Themes.Gone"));
  }
}

void ThemeService::SwapThemeSupplier(
    scoped_refptr<CustomThemeSupplier> theme_supplier) {
  if (theme_supplier_) {
    theme_supplier_->StopUsingTheme();
  }
  theme_supplier_ = theme_supplier;
  if (theme_supplier_) {
    theme_supplier_->StartUsingTheme();
  }
}

void ThemeService::BuildFromExtension(const extensions::Extension* extension,
                                      bool suppress_infobar) {
  build_extension_task_tracker_.TryCancelAll();
  building_extension_id_ = extension->id();
  scoped_refptr<BrowserThemePack> pack(new BrowserThemePack(
      ui::ColorProviderKey::ThemeInitializerSupplier::ThemeType::kExtension));
  auto task_runner = base::ThreadPool::CreateTaskRunner(
      {base::MayBlock(), base::TaskPriority::USER_BLOCKING});
  build_extension_task_tracker_.PostTaskAndReply(
      task_runner.get(), FROM_HERE,
      base::BindOnce(&BrowserThemePack::BuildFromExtension,
                     base::RetainedRef(extension),
                     base::RetainedRef(pack.get())),
      base::BindOnce(&ThemeService::OnThemeBuiltFromExtension,
                     weak_ptr_factory_.GetWeakPtr(), extension->id(), pack,
                     suppress_infobar));
}

void ThemeService::OnThemeBuiltFromExtension(
    const extensions::ExtensionId& extension_id,
    scoped_refptr<BrowserThemePack> pack,
    bool suppress_infobar) {
  if (UsingPolicyTheme()) {
    DVLOG(1) << "Extension theme was not applied because a policy theme has "
                "been set.";
    return;
  }

  if (!pack->is_valid()) {
    // TODO(erg): We've failed to install the theme; perhaps we should tell the
    // user? http://crbug.com/34780
    LOG(ERROR) << "Could not load theme.";
    return;
  }

  extensions::ExtensionService* service =
      extensions::ExtensionSystem::Get(profile_)->extension_service();
  if (!service) {
    return;
  }
  const auto* extension = extensions::ExtensionRegistry::Get(profile_)
                              ->enabled_extensions()
                              .GetByID(extension_id);
  if (!extension) {
    return;
  }

  // Schedule the writing of the packed file to disk.
  extensions::GetExtensionFileTaskRunner()->PostTask(
      FROM_HERE, base::BindOnce(&WritePackToDiskCallback,
                                base::RetainedRef(pack), extension->path()));
  std::unique_ptr<ThemeService::ThemeReinstaller> reinstaller =
      BuildReinstallerForCurrentTheme();
  std::optional<std::string> previous_theme_id;
  if (UsingExtensionTheme()) {
    previous_theme_id = GetThemeID();
  }

  SwapThemeSupplier(std::move(pack));
  SetThemePrefsForExtension(extension);
  NotifyThemeChanged();
  building_extension_id_.clear();

  // Same old theme, but the theme has changed (migrated) or auto-updated.
  if (previous_theme_id.has_value() &&
      previous_theme_id.value() == extension->id()) {
    return;
  }

  base::RecordAction(base::UserMetricsAction("Themes_Installed"));

  bool can_revert_theme = true;
  if (previous_theme_id.has_value()) {
    can_revert_theme = DisableExtension(previous_theme_id.value());
  }

  // Offer to revert to the old theme.
  if (can_revert_theme && !suppress_infobar && extension->is_theme()) {
    ThemeInstalledInfoBarDelegate::CreateForLastActiveTab(
        profile_, extension->name(), extension->id(), std::move(reinstaller));
  }
}

void ThemeService::HandlePolicyColorUpdate() {
  if (UsingPolicyTheme()) {
    BuildAutogeneratedPolicyTheme();
  } else {
    // If a policy theme is unset, load the previous theme from prefs.
    InitFromPrefs();

    // NotifyThemeChanged() isn't triggered in InitFromPrefs() for extension
    // themes, so it's called here to make sure the browser's theme is updated.
    if (UsingExtensionTheme()) {
      NotifyThemeChanged();
    }
  }
}

void ThemeService::ClearThemePrefs() {
  profile_->GetPrefs()->ClearPref(prefs::kCurrentThemePackFilename);
  profile_->GetPrefs()->ClearPref(prefs::kAutogeneratedThemeColor);
  profile_->GetPrefs()->ClearPref(prefs::kUserColor);
  profile_->GetPrefs()->ClearPref(prefs::kGrayscaleThemeEnabled);
  profile_->GetPrefs()->ClearPref(prefs::kBrowserColorVariant);
  profile_->GetPrefs()->SetString(prefs::kCurrentThemeID,
                                  ThemeHelper::kDefaultThemeID);
}

void ThemeService::SetThemePrefsForExtension(
    const extensions::Extension* extension) {
  ClearThemePrefs();
  // Redraw and notify sync that theme has changed.
  for (auto& observer : observers_) {
    observer.OnCustomNtpBackgroundObsolete();
  }
  // Extensions are incompatible with device themes so turn them off.
  // TODO(crbug.com/40280173): Remove this if we can otherwise separate
  // extension and device themes from attempting to apply at the same time.
  profile_->GetPrefs()->SetBoolean(prefs::kBrowserFollowsSystemThemeColors,
                                   false);

  profile_->GetPrefs()->SetString(prefs::kCurrentThemeID, extension->id());

  // Save only the extension path. The packed file will be loaded via
  // InitFromPrefs().
  profile_->GetPrefs()->SetFilePath(prefs::kCurrentThemePackFilename,
                                    extension->path());
}

void ThemeService::SetThemePrefsForColor(SkColor color) {
  ClearThemePrefs();
  profile_->GetPrefs()->SetInteger(prefs::kAutogeneratedThemeColor, color);
  profile_->GetPrefs()->SetString(prefs::kCurrentThemeID,
                                  kAutogeneratedThemeID);
}

bool ThemeService::DisableExtension(const std::string& extension_id) {
  auto* registry = extensions::ExtensionRegistry::Get(profile_);
  if (registry->GetInstalledExtension(extension_id)) {
    // Do not disable the previous theme if it is already uninstalled. Sending
    // |ThemeServiceObserver::OnThemeChanged()| causes the previous theme to be
    // uninstalled when the notification causes the remaining infobar to close
    // and does not open any new infobars. See crbug.com/468280.
    extensions::ExtensionRegistrar::Get(profile_)->DisableExtension(
        extension_id, {extensions::disable_reason::DISABLE_USER_ACTION});
    return true;
  }
  return false;
}

void ThemeService::ResetThemeSyncableServiceForTest() {
  theme_syncable_service_.reset();
}