summaryrefslogtreecommitdiff
path: root/partnerconfig/java/com/google/android/setupcompat/partnerconfig/PartnerConfigHelper.java
blob: aca9a07022eeaf93a5854c5146fc6659c2cf442a (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
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
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.android.setupcompat.partnerconfig;

import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.Resources.NotFoundException;
import android.database.ContentObserver;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import com.google.android.setupcompat.partnerconfig.PartnerConfig.ResourceType;
import com.google.android.setupcompat.util.BuildCompatUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;

/** The helper reads and caches the partner configurations from SUW. */
public class PartnerConfigHelper {

  private static final String TAG = PartnerConfigHelper.class.getSimpleName();

  @VisibleForTesting
  public static final String SUW_AUTHORITY = "com.google.android.setupwizard.partner";

  @VisibleForTesting public static final String SUW_GET_PARTNER_CONFIG_METHOD = "getOverlayConfig";

  @VisibleForTesting public static final String KEY_FALLBACK_CONFIG = "fallbackConfig";

  @VisibleForTesting
  public static final String IS_SUW_DAY_NIGHT_ENABLED_METHOD = "isSuwDayNightEnabled";

  @VisibleForTesting
  public static final String IS_EXTENDED_PARTNER_CONFIG_ENABLED_METHOD =
      "isExtendedPartnerConfigEnabled";

  @VisibleForTesting
  public static final String IS_MATERIAL_YOU_STYLE_ENABLED_METHOD = "IsMaterialYouStyleEnabled";

  @VisibleForTesting
  public static final String IS_DYNAMIC_COLOR_ENABLED_METHOD = "isDynamicColorEnabled";

  @VisibleForTesting
  public static final String IS_NEUTRAL_BUTTON_STYLE_ENABLED_METHOD = "isNeutralButtonStyleEnabled";

  @VisibleForTesting public static final String SUW_PACKAGE_NAME = "com.google.android.setupwizard";
  @VisibleForTesting public static final String MATERIAL_YOU_RESOURCE_SUFFIX = "_material_you";

  @VisibleForTesting static Bundle suwDayNightEnabledBundle = null;

  @VisibleForTesting public static Bundle applyExtendedPartnerConfigBundle = null;

  @VisibleForTesting public static Bundle applyMaterialYouConfigBundle = null;

  @VisibleForTesting public static Bundle applyDynamicColorBundle = null;

  @VisibleForTesting public static Bundle applyNeutralButtonStyleBundle = null;

  private static PartnerConfigHelper instance = null;

  @VisibleForTesting Bundle resultBundle = null;

  @VisibleForTesting
  final EnumMap<PartnerConfig, Object> partnerResourceCache = new EnumMap<>(PartnerConfig.class);

  private static ContentObserver contentObserver;

  private static int savedConfigUiMode;

  @VisibleForTesting
  public static int savedOrientation = Configuration.ORIENTATION_PORTRAIT;

  /**
   * When testing related to fake PartnerConfigHelper instance, should sync the following saved
   * config with testing environment.
   */
  @VisibleForTesting public static int savedScreenHeight = Configuration.SCREEN_HEIGHT_DP_UNDEFINED;

  @VisibleForTesting public static int savedScreenWidth = Configuration.SCREEN_WIDTH_DP_UNDEFINED;

  public static synchronized PartnerConfigHelper get(@NonNull Context context) {
    if (!isValidInstance(context)) {
      instance = new PartnerConfigHelper(context);
    }
    return instance;
  }

  private static boolean isValidInstance(@NonNull Context context) {
    Configuration currentConfig = context.getResources().getConfiguration();
    if (instance == null) {
      savedConfigUiMode = currentConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK;
      savedOrientation = currentConfig.orientation;
      savedScreenWidth = currentConfig.screenWidthDp;
      savedScreenHeight = currentConfig.screenHeightDp;
      return false;
    } else {
      boolean uiModeChanged =
          isSetupWizardDayNightEnabled(context)
              && (currentConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK) != savedConfigUiMode;
      if (uiModeChanged
          || currentConfig.orientation != savedOrientation
          || currentConfig.screenWidthDp != savedScreenWidth
          || currentConfig.screenHeightDp != savedScreenHeight) {
        savedConfigUiMode = currentConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK;
        savedOrientation = currentConfig.orientation;
        savedScreenHeight = currentConfig.screenHeightDp;
        savedScreenWidth = currentConfig.screenWidthDp;
        resetInstance();
        return false;
      }
    }
    return true;
  }

  private PartnerConfigHelper(Context context) {
    getPartnerConfigBundle(context);

    registerContentObserver(context);
  }

  /**
   * Returns whether partner customized config values are available. This is true if setup wizard's
   * content provider returns us a non-empty bundle, even if all the values are default, and none
   * are customized by the overlay APK.
   */
  public boolean isAvailable() {
    return resultBundle != null && !resultBundle.isEmpty();
  }

  /**
   * Returns whether the given {@code resourceConfig} are available. This is true if setup wizard's
   * content provider returns us a non-empty bundle, and this result bundle includes the given
   * {@code resourceConfig} even if all the values are default, and none are customized by the
   * overlay APK.
   */
  public boolean isPartnerConfigAvailable(PartnerConfig resourceConfig) {
    return isAvailable() && resultBundle.containsKey(resourceConfig.getResourceName());
  }

  /**
   * Returns the color of given {@code resourceConfig}, or 0 if the given {@code resourceConfig} is
   * not found. If the {@code ResourceType} of the given {@code resourceConfig} is not color,
   * IllegalArgumentException will be thrown.
   *
   * @param context The context of client activity
   * @param resourceConfig The {@link PartnerConfig} of target resource
   */
  @ColorInt
  public int getColor(@NonNull Context context, PartnerConfig resourceConfig) {
    if (resourceConfig.getResourceType() != ResourceType.COLOR) {
      throw new IllegalArgumentException("Not a color resource");
    }

    if (partnerResourceCache.containsKey(resourceConfig)) {
      return (int) partnerResourceCache.get(resourceConfig);
    }

    int result = 0;
    try {
      ResourceEntry resourceEntry =
          getResourceEntryFromKey(context, resourceConfig.getResourceName());
      Resources resource = resourceEntry.getResources();
      int resId = resourceEntry.getResourceId();

      // for @null
      TypedValue outValue = new TypedValue();
      resource.getValue(resId, outValue, true);
      if (outValue.type == TypedValue.TYPE_REFERENCE && outValue.data == 0) {
        return result;
      }

      if (Build.VERSION.SDK_INT >= VERSION_CODES.M) {
        result = resource.getColor(resId, null);
      } else {
        result = resource.getColor(resId);
      }
      partnerResourceCache.put(resourceConfig, result);
    } catch (NullPointerException exception) {
      // fall through
    }
    return result;
  }

  /**
   * Returns the {@code Drawable} of given {@code resourceConfig}, or {@code null} if the given
   * {@code resourceConfig} is not found. If the {@code ResourceType} of the given {@code
   * resourceConfig} is not drawable, IllegalArgumentException will be thrown.
   *
   * @param context The context of client activity
   * @param resourceConfig The {@code PartnerConfig} of target resource
   */
  @Nullable
  public Drawable getDrawable(@NonNull Context context, PartnerConfig resourceConfig) {
    if (resourceConfig.getResourceType() != ResourceType.DRAWABLE) {
      throw new IllegalArgumentException("Not a drawable resource");
    }

    if (partnerResourceCache.containsKey(resourceConfig)) {
      return (Drawable) partnerResourceCache.get(resourceConfig);
    }

    Drawable result = null;
    try {
      ResourceEntry resourceEntry =
          getResourceEntryFromKey(context, resourceConfig.getResourceName());
      Resources resource = resourceEntry.getResources();
      int resId = resourceEntry.getResourceId();

      // for @null
      TypedValue outValue = new TypedValue();
      resource.getValue(resId, outValue, true);
      if (outValue.type == TypedValue.TYPE_REFERENCE && outValue.data == 0) {
        return result;
      }

      if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
        result = resource.getDrawable(resId, null);
      } else {
        result = resource.getDrawable(resId);
      }
      partnerResourceCache.put(resourceConfig, result);
    } catch (NullPointerException | NotFoundException exception) {
      // fall through
    }
    return result;
  }

  /**
   * Returns the string of the given {@code resourceConfig}, or {@code null} if the given {@code
   * resourceConfig} is not found. If the {@code ResourceType} of the given {@code resourceConfig}
   * is not string, IllegalArgumentException will be thrown.
   *
   * @param context The context of client activity
   * @param resourceConfig The {@code PartnerConfig} of target resource
   */
  @Nullable
  public String getString(@NonNull Context context, PartnerConfig resourceConfig) {
    if (resourceConfig.getResourceType() != ResourceType.STRING) {
      throw new IllegalArgumentException("Not a string resource");
    }

    if (partnerResourceCache.containsKey(resourceConfig)) {
      return (String) partnerResourceCache.get(resourceConfig);
    }

    String result = null;
    try {
      ResourceEntry resourceEntry =
          getResourceEntryFromKey(context, resourceConfig.getResourceName());
      Resources resource = resourceEntry.getResources();
      int resId = resourceEntry.getResourceId();

      result = resource.getString(resId);
      partnerResourceCache.put(resourceConfig, result);
    } catch (NullPointerException exception) {
      // fall through
    }
    return result;
  }

  /**
   * Returns the string array of the given {@code resourceConfig}, or {@code null} if the given
   * {@code resourceConfig} is not found. If the {@code ResourceType} of the given {@code
   * resourceConfig} is not string, IllegalArgumentException will be thrown.
   *
   * @param context The context of client activity
   * @param resourceConfig The {@code PartnerConfig} of target resource
   */
  @NonNull
  public List<String> getStringArray(@NonNull Context context, PartnerConfig resourceConfig) {
    if (resourceConfig.getResourceType() != ResourceType.STRING_ARRAY) {
      throw new IllegalArgumentException("Not a string array resource");
    }

    String[] result;
    List<String> listResult = new ArrayList<>();

    try {
      ResourceEntry resourceEntry =
          getResourceEntryFromKey(context, resourceConfig.getResourceName());
      Resources resource = resourceEntry.getResources();
      int resId = resourceEntry.getResourceId();

      result = resource.getStringArray(resId);
      Collections.addAll(listResult, result);
    } catch (NullPointerException exception) {
      // fall through
    }

    return listResult;
  }

  /**
   * Returns the boolean of given {@code resourceConfig}, or {@code defaultValue} if the given
   * {@code resourceName} is not found. If the {@code ResourceType} of the given {@code
   * resourceConfig} is not boolean, IllegalArgumentException will be thrown.
   *
   * @param context The context of client activity
   * @param resourceConfig The {@code PartnerConfig} of target resource
   * @param defaultValue The default value
   */
  public boolean getBoolean(
      @NonNull Context context, PartnerConfig resourceConfig, boolean defaultValue) {
    if (resourceConfig.getResourceType() != ResourceType.BOOL) {
      throw new IllegalArgumentException("Not a bool resource");
    }

    if (partnerResourceCache.containsKey(resourceConfig)) {
      return (boolean) partnerResourceCache.get(resourceConfig);
    }

    boolean result = defaultValue;
    try {
      ResourceEntry resourceEntry =
          getResourceEntryFromKey(context, resourceConfig.getResourceName());
      Resources resource = resourceEntry.getResources();
      int resId = resourceEntry.getResourceId();

      result = resource.getBoolean(resId);
      partnerResourceCache.put(resourceConfig, result);
    } catch (NullPointerException | NotFoundException exception) {
      // fall through
    }
    return result;
  }

  /**
   * Returns the dimension of given {@code resourceConfig}. The default return value is 0.
   *
   * @param context The context of client activity
   * @param resourceConfig The {@code PartnerConfig} of target resource
   */
  public float getDimension(@NonNull Context context, PartnerConfig resourceConfig) {
    return getDimension(context, resourceConfig, 0);
  }

  /**
   * Returns the dimension of given {@code resourceConfig}. If the given {@code resourceConfig} is
   * not found, will return {@code defaultValue}. If the {@code ResourceType} of given {@code
   * resourceConfig} is not dimension, will throw IllegalArgumentException.
   *
   * @param context The context of client activity
   * @param resourceConfig The {@code PartnerConfig} of target resource
   * @param defaultValue The default value
   */
  public float getDimension(
      @NonNull Context context, PartnerConfig resourceConfig, float defaultValue) {
    if (resourceConfig.getResourceType() != ResourceType.DIMENSION) {
      throw new IllegalArgumentException("Not a dimension resource");
    }

    if (partnerResourceCache.containsKey(resourceConfig)) {
      return getDimensionFromTypedValue(
          context, (TypedValue) partnerResourceCache.get(resourceConfig));
    }

    float result = defaultValue;
    try {
      ResourceEntry resourceEntry =
          getResourceEntryFromKey(context, resourceConfig.getResourceName());
      Resources resource = resourceEntry.getResources();
      int resId = resourceEntry.getResourceId();

      result = resource.getDimension(resId);
      TypedValue value = getTypedValueFromResource(resource, resId, TypedValue.TYPE_DIMENSION);
      partnerResourceCache.put(resourceConfig, value);
      result =
          getDimensionFromTypedValue(
              context, (TypedValue) partnerResourceCache.get(resourceConfig));
    } catch (NullPointerException | NotFoundException exception) {
      // fall through
    }
    return result;
  }

  /**
   * Returns the float of given {@code resourceConfig}. The default return value is 0.
   *
   * @param context The context of client activity
   * @param resourceConfig The {@code PartnerConfig} of target resource
   */
  public float getFraction(@NonNull Context context, PartnerConfig resourceConfig) {
    return getFraction(context, resourceConfig, 0.0f);
  }

  /**
   * Returns the float of given {@code resourceConfig}. If the given {@code resourceConfig} not
   * found, will return {@code defaultValue}. If the {@code ResourceType} of given {@code
   * resourceConfig} is not fraction, will throw IllegalArgumentException.
   *
   * @param context The context of client activity
   * @param resourceConfig The {@code PartnerConfig} of target resource
   * @param defaultValue The default value
   */
  public float getFraction(
      @NonNull Context context, PartnerConfig resourceConfig, float defaultValue) {
    if (resourceConfig.getResourceType() != ResourceType.FRACTION) {
      throw new IllegalArgumentException("Not a fraction resource");
    }

    if (partnerResourceCache.containsKey(resourceConfig)) {
      return (float) partnerResourceCache.get(resourceConfig);
    }

    float result = defaultValue;
    try {
      ResourceEntry resourceEntry =
          getResourceEntryFromKey(context, resourceConfig.getResourceName());
      Resources resource = resourceEntry.getResources();
      int resId = resourceEntry.getResourceId();

      result = resource.getFraction(resId, 1, 1);
      partnerResourceCache.put(resourceConfig, result);
    } catch (NullPointerException | NotFoundException exception) {
      // fall through
    }
    return result;
  }

  /**
   * Returns the integer of given {@code resourceConfig}. If the given {@code resourceConfig} is not
   * found, will return {@code defaultValue}. If the {@code ResourceType} of given {@code
   * resourceConfig} is not dimension, will throw IllegalArgumentException.
   *
   * @param context The context of client activity
   * @param resourceConfig The {@code PartnerConfig} of target resource
   * @param defaultValue The default value
   */
  public int getInteger(@NonNull Context context, PartnerConfig resourceConfig, int defaultValue) {
    if (resourceConfig.getResourceType() != ResourceType.INTEGER) {
      throw new IllegalArgumentException("Not a integer resource");
    }

    if (partnerResourceCache.containsKey(resourceConfig)) {
      return (int) partnerResourceCache.get(resourceConfig);
    }

    int result = defaultValue;
    try {
      ResourceEntry resourceEntry =
          getResourceEntryFromKey(context, resourceConfig.getResourceName());
      Resources resource = resourceEntry.getResources();
      int resId = resourceEntry.getResourceId();

      result = resource.getInteger(resId);
      partnerResourceCache.put(resourceConfig, result);
    } catch (NullPointerException | NotFoundException exception) {
      // fall through
    }
    return result;
  }

  /**
   * Returns the {@link ResourceEntry} of given {@code resourceConfig}, or {@code null} if the given
   * {@code resourceConfig} is not found. If the {@link ResourceType} of the given {@code
   * resourceConfig} is not illustration, IllegalArgumentException will be thrown.
   *
   * @param context The context of client activity
   * @param resourceConfig The {@link PartnerConfig} of target resource
   */
  @Nullable
  public ResourceEntry getIllustrationResourceEntry(
      @NonNull Context context, PartnerConfig resourceConfig) {
    if (resourceConfig.getResourceType() != ResourceType.ILLUSTRATION) {
      throw new IllegalArgumentException("Not a illustration resource");
    }

    if (partnerResourceCache.containsKey(resourceConfig)) {
      return (ResourceEntry) partnerResourceCache.get(resourceConfig);
    }

    try {
      ResourceEntry resourceEntry =
          getResourceEntryFromKey(context, resourceConfig.getResourceName());

      Resources resource = resourceEntry.getResources();
      int resId = resourceEntry.getResourceId();

      // TODO: The illustration resource entry validation should validate is it a video
      // resource or not?
      // for @null
      TypedValue outValue = new TypedValue();
      resource.getValue(resId, outValue, true);
      if (outValue.type == TypedValue.TYPE_REFERENCE && outValue.data == 0) {
        return null;
      }

      partnerResourceCache.put(resourceConfig, resourceEntry);
      return resourceEntry;
    } catch (NullPointerException exception) {
      // fall through
    }

    return null;
  }

  private void getPartnerConfigBundle(Context context) {
    if (resultBundle == null || resultBundle.isEmpty()) {
      try {
        resultBundle =
            context
                .getContentResolver()
                .call(
                    getContentUri(),
                    SUW_GET_PARTNER_CONFIG_METHOD,
                    /* arg= */ null,
                    /* extras= */ null);
        partnerResourceCache.clear();
        Log.i(
            TAG, "PartnerConfigsBundle=" + (resultBundle != null ? resultBundle.size() : "(null)"));
      } catch (IllegalArgumentException | SecurityException exception) {
        Log.w(TAG, "Fail to get config from suw provider");
      }
    }
  }

  @Nullable
  @VisibleForTesting
  ResourceEntry getResourceEntryFromKey(Context context, String resourceName) {
    Bundle resourceEntryBundle = resultBundle.getBundle(resourceName);
    Bundle fallbackBundle = resultBundle.getBundle(KEY_FALLBACK_CONFIG);
    if (fallbackBundle != null) {
      resourceEntryBundle.putBundle(KEY_FALLBACK_CONFIG, fallbackBundle.getBundle(resourceName));
    }
    ResourceEntry adjustResourceEntry =
        adjustResourceEntryDefaultValue(
            context, ResourceEntry.fromBundle(context, resourceEntryBundle));
    return adjustResourceEntryDayNightMode(context, adjustResourceEntry);
  }

  /**
   * Force to day mode if setup wizard does not support day/night mode and current system is in
   * night mode.
   */
  private static ResourceEntry adjustResourceEntryDayNightMode(
      Context context, ResourceEntry resourceEntry) {
    Resources resource = resourceEntry.getResources();
    Configuration configuration = resource.getConfiguration();
    if (!isSetupWizardDayNightEnabled(context) && Util.isNightMode(configuration)) {
      if (resourceEntry == null) {
        Log.w(TAG, "resourceEntry is null, skip to force day mode.");
        return resourceEntry;
      }
      configuration.uiMode =
          Configuration.UI_MODE_NIGHT_NO
              | (configuration.uiMode & ~Configuration.UI_MODE_NIGHT_MASK);
      resource.updateConfiguration(configuration, resource.getDisplayMetrics());
    }

    return resourceEntry;
  }

  // Check the MNStyle flag and replace the inputResourceEntry.resourceName &
  // inputResourceEntry.resourceId after T, that means if using Gliv4 before S, will always use
  // glifv3 resources.
  ResourceEntry adjustResourceEntryDefaultValue(Context context, ResourceEntry inputResourceEntry) {
    if (BuildCompatUtils.isAtLeastT() && shouldApplyMaterialYouStyle(context)) {
      // If not overlay resource
      try {
        if (SUW_PACKAGE_NAME.equals(inputResourceEntry.getPackageName())) {
          String resourceTypeName =
              inputResourceEntry
                  .getResources()
                  .getResourceTypeName(inputResourceEntry.getResourceId());
          // try to update resourceName & resourceId
          String materialYouResourceName =
              inputResourceEntry.getResourceName().concat(MATERIAL_YOU_RESOURCE_SUFFIX);
          int materialYouResourceId =
              inputResourceEntry
                  .getResources()
                  .getIdentifier(
                      materialYouResourceName,
                      resourceTypeName,
                      inputResourceEntry.getPackageName());
          if (materialYouResourceId != 0) {
            Log.i(TAG, "use material you resource:" + materialYouResourceName);
            return new ResourceEntry(
                inputResourceEntry.getPackageName(),
                materialYouResourceName,
                materialYouResourceId,
                inputResourceEntry.getResources());
          }
        }
      } catch (NotFoundException ex) {
        // fall through
      }
    }
    return inputResourceEntry;
  }

  @VisibleForTesting
  public static synchronized void resetInstance() {
    instance = null;
    suwDayNightEnabledBundle = null;
    applyExtendedPartnerConfigBundle = null;
    applyMaterialYouConfigBundle = null;
    applyDynamicColorBundle = null;
    applyNeutralButtonStyleBundle = null;
  }

  /**
   * Checks whether SetupWizard supports the DayNight theme during setup flow; if return false setup
   * flow should force to light theme.
   *
   * <p>Returns true if the setupwizard is listening to system DayNight theme setting.
   */
  public static boolean isSetupWizardDayNightEnabled(@NonNull Context context) {
    if (suwDayNightEnabledBundle == null) {
      try {
        suwDayNightEnabledBundle =
            context
                .getContentResolver()
                .call(
                    getContentUri(),
                    IS_SUW_DAY_NIGHT_ENABLED_METHOD,
                    /* arg= */ null,
                    /* extras= */ null);
      } catch (IllegalArgumentException | SecurityException exception) {
        Log.w(TAG, "SetupWizard DayNight supporting status unknown; return as false.");
        suwDayNightEnabledBundle = null;
        return false;
      }
    }

    return (suwDayNightEnabledBundle != null
        && suwDayNightEnabledBundle.getBoolean(IS_SUW_DAY_NIGHT_ENABLED_METHOD, false));
  }

  /** Returns true if the SetupWizard supports the extended partner configs during setup flow. */
  public static boolean shouldApplyExtendedPartnerConfig(@NonNull Context context) {
    if (applyExtendedPartnerConfigBundle == null) {
      try {
        applyExtendedPartnerConfigBundle =
            context
                .getContentResolver()
                .call(
                    getContentUri(),
                    IS_EXTENDED_PARTNER_CONFIG_ENABLED_METHOD,
                    /* arg= */ null,
                    /* extras= */ null);
      } catch (IllegalArgumentException | SecurityException exception) {
        Log.w(
            TAG,
            "SetupWizard extended partner configs supporting status unknown; return as false.");
        applyExtendedPartnerConfigBundle = null;
        return false;
      }
    }

    return (applyExtendedPartnerConfigBundle != null
        && applyExtendedPartnerConfigBundle.getBoolean(
            IS_EXTENDED_PARTNER_CONFIG_ENABLED_METHOD, false));
  }

  /**
   * Returns true if the SetupWizard is flow enabled "Material You(Glifv4)" style, or the result of
   * shouldApplyExtendedPartnerConfig() in SDK S as fallback.
   */
  public static boolean shouldApplyMaterialYouStyle(@NonNull Context context) {
    if (applyMaterialYouConfigBundle == null || applyMaterialYouConfigBundle.isEmpty()) {
      try {
        applyMaterialYouConfigBundle =
            context
                .getContentResolver()
                .call(
                    getContentUri(),
                    IS_MATERIAL_YOU_STYLE_ENABLED_METHOD,
                    /* arg= */ null,
                    /* extras= */ null);
        // The suw version did not support the flag yet, fallback to
        // shouldApplyExtendedPartnerConfig() for SDK S.
        if (applyMaterialYouConfigBundle != null
            && applyMaterialYouConfigBundle.isEmpty()
            && !BuildCompatUtils.isAtLeastT()) {
          return shouldApplyExtendedPartnerConfig(context);
        }
      } catch (IllegalArgumentException | SecurityException exception) {
        Log.w(TAG, "SetupWizard Material You configs supporting status unknown; return as false.");
        applyMaterialYouConfigBundle = null;
        return false;
      }
    }

    return (applyMaterialYouConfigBundle != null
        && applyMaterialYouConfigBundle.getBoolean(IS_MATERIAL_YOU_STYLE_ENABLED_METHOD, false));
  }

  /** Returns true if the SetupWizard supports the dynamic color during setup flow. */
  public static boolean isSetupWizardDynamicColorEnabled(@NonNull Context context) {
    if (applyDynamicColorBundle == null) {
      try {
        applyDynamicColorBundle =
            context
                .getContentResolver()
                .call(
                    getContentUri(),
                    IS_DYNAMIC_COLOR_ENABLED_METHOD,
                    /* arg= */ null,
                    /* extras= */ null);
      } catch (IllegalArgumentException | SecurityException exception) {
        Log.w(TAG, "SetupWizard dynamic color supporting status unknown; return as false.");
        applyDynamicColorBundle = null;
        return false;
      }
    }

    return (applyDynamicColorBundle != null
        && applyDynamicColorBundle.getBoolean(IS_DYNAMIC_COLOR_ENABLED_METHOD, false));
  }

  /** Returns true if the SetupWizard supports the neutral button style during setup flow. */
  public static boolean isNeutralButtonStyleEnabled(@NonNull Context context) {
    if (applyNeutralButtonStyleBundle == null) {
      try {
        applyNeutralButtonStyleBundle =
            context
                .getContentResolver()
                .call(
                    getContentUri(),
                    IS_NEUTRAL_BUTTON_STYLE_ENABLED_METHOD,
                    /* arg= */ null,
                    /* extras= */ null);
      } catch (IllegalArgumentException | SecurityException exception) {
        Log.w(TAG, "Neutral button style supporting status unknown; return as false.");
        applyNeutralButtonStyleBundle = null;
        return false;
      }
    }

    return (applyNeutralButtonStyleBundle != null
        && applyNeutralButtonStyleBundle.getBoolean(IS_NEUTRAL_BUTTON_STYLE_ENABLED_METHOD, false));
  }

  @VisibleForTesting
  static Uri getContentUri() {
    return new Uri.Builder()
        .scheme(ContentResolver.SCHEME_CONTENT)
        .authority(SUW_AUTHORITY)
        .build();
  }

  private static TypedValue getTypedValueFromResource(Resources resource, int resId, int type) {
    TypedValue value = new TypedValue();
    resource.getValue(resId, value, true);
    if (value.type != type) {
      throw new NotFoundException(
          "Resource ID #0x"
              + Integer.toHexString(resId)
              + " type #0x"
              + Integer.toHexString(value.type)
              + " is not valid");
    }
    return value;
  }

  private static float getDimensionFromTypedValue(Context context, TypedValue value) {
    DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
    return value.getDimension(displayMetrics);
  }

  private static void registerContentObserver(Context context) {
    if (isSetupWizardDayNightEnabled(context)) {
      if (contentObserver != null) {
        unregisterContentObserver(context);
      }

      Uri contentUri = getContentUri();
      try {
        contentObserver =
            new ContentObserver(null) {
              @Override
              public void onChange(boolean selfChange) {
                super.onChange(selfChange);
                resetInstance();
              }
            };
        context
            .getContentResolver()
            .registerContentObserver(contentUri, /* notifyForDescendants= */ true, contentObserver);
      } catch (SecurityException | NullPointerException | IllegalArgumentException e) {
        Log.w(TAG, "Failed to register content observer for " + contentUri + ": " + e);
      }
    }
  }

  private static void unregisterContentObserver(Context context) {
    try {
      context.getContentResolver().unregisterContentObserver(contentObserver);
      contentObserver = null;
    } catch (SecurityException | NullPointerException | IllegalArgumentException e) {
      Log.w(TAG, "Failed to unregister content observer: " + e);
    }
  }
}