1 /* 2 * Copyright (C) 2019 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.customization.model.theme.custom; 17 18 import android.content.Context; 19 import android.content.pm.PackageManager.NameNotFoundException; 20 import android.content.res.Resources; 21 import android.os.UserHandle; 22 23 import com.android.customization.model.CustomizationManager.OptionsFetchedListener; 24 import com.android.customization.model.ResourceConstants; 25 import com.android.customization.model.theme.OverlayManagerCompat; 26 27 import java.util.ArrayList; 28 import java.util.List; 29 30 /** 31 * Base class used to retrieve Custom Theme Component options (eg, different fonts) 32 * from the system. 33 */ 34 public abstract class ThemeComponentOptionProvider<T extends ThemeComponentOption> { 35 36 protected final Context mContext; 37 protected final List<String> mOverlayPackages; 38 protected List<T> mOptions; 39 ThemeComponentOptionProvider(Context context, OverlayManagerCompat manager, String... categories)40 public ThemeComponentOptionProvider(Context context, OverlayManagerCompat manager, 41 String... categories) { 42 mContext = context; 43 mOverlayPackages = new ArrayList<>(); 44 for (String category : categories) { 45 mOverlayPackages.addAll(manager.getOverlayPackagesForCategory(category, 46 UserHandle.myUserId(), ResourceConstants.getPackagesToOverlay(mContext))); 47 } 48 } 49 50 /** 51 * Returns whether there are options for this component available in the current setup. 52 */ isAvailable()53 public boolean isAvailable() { 54 return !mOverlayPackages.isEmpty(); 55 } 56 57 /** 58 * Retrieve the available options for this component. 59 * @param callback called when the themes have been retrieved (or immediately if cached) 60 * @param reload whether to reload themes if they're cached. 61 */ fetch(OptionsFetchedListener<T> callback, boolean reload)62 public void fetch(OptionsFetchedListener<T> callback, boolean reload) { 63 if (mOptions == null || reload) { 64 mOptions = new ArrayList<>(); 65 loadOptions(); 66 } 67 68 if(callback != null) { 69 callback.onOptionsLoaded(mOptions); 70 } 71 } 72 loadOptions()73 protected abstract void loadOptions(); 74 getOverlayResources(String overlayPackage)75 protected Resources getOverlayResources(String overlayPackage) throws NameNotFoundException { 76 return mContext.getPackageManager().getResourcesForApplication(overlayPackage); 77 } 78 } 79