summaryrefslogtreecommitdiffstats
path: root/src/org/cyanogenmod/themes/provider/ThemePackageHelper.java
blob: 7a6fe42c0acca58e546eddb0fd09aa1a58721e29 (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
/*
 * Copyright (C) 2014 The CyanogenMod 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 org.cyanogenmod.themes.provider;

import android.content.ContentValues;
import android.content.Context;
import android.content.pm.LegacyThemeInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ThemeInfo;
import android.content.res.AssetManager;
import android.content.res.ThemeManager;
import android.database.Cursor;
import android.provider.ThemesContract;
import android.provider.ThemesContract.MixnMatchColumns;
import android.provider.ThemesContract.ThemesColumns;
import android.text.TextUtils;
import android.util.Log;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Helper class to populate the provider with info from the theme.
 */
public class ThemePackageHelper {
    public final static String TAG = ThemePackageHelper.class.getName();

    // Maps the theme component to its folder name in assets.
    public static HashMap<String, String> sComponentToFolderName = new HashMap<String, String>();
    static {
        sComponentToFolderName.put(ThemesColumns.MODIFIES_OVERLAYS, "overlays");
        sComponentToFolderName.put(ThemesColumns.MODIFIES_BOOT_ANIM, "bootanimation");
        sComponentToFolderName.put(ThemesColumns.MODIFIES_FONTS, "fonts");
        sComponentToFolderName.put(ThemesColumns.MODIFIES_ICONS, "icons");
        sComponentToFolderName.put(ThemesColumns.MODIFIES_LAUNCHER, "wallpapers");
        sComponentToFolderName.put(ThemesColumns.MODIFIES_LOCKSCREEN, "lockscreen");
        sComponentToFolderName.put(ThemesColumns.MODIFIES_ALARMS, "alarms");
        sComponentToFolderName.put(ThemesColumns.MODIFIES_NOTIFICATIONS, "notifications");
        sComponentToFolderName.put(ThemesColumns.MODIFIES_RINGTONES, "ringtones");
    }

    public static boolean insertPackage(Context context, String pkgName)
            throws NameNotFoundException {
        PackageInfo pi = context.getPackageManager().getPackageInfo(pkgName, 0);
        if (pi == null)
            return false;

        Map<String, Boolean> capabilities = getCapabilities(context, pkgName);
        if (pi.themeInfos != null && pi.themeInfos.length > 0) {
            insertPackageInternal(context, pi, capabilities);
        } else if (pi.legacyThemeInfos != null && pi.legacyThemeInfos.length > 0) {
            insertLegacyPackageInternal(context, pi, capabilities);
        }
        return true;
    }

    private static void insertPackageInternal(Context context, PackageInfo pi,
            Map<String, Boolean> capabilities) {
        ThemeInfo info = pi.themeInfos[0];
        boolean isPresentableTheme = ThemePackageHelper.isPresentableTheme(capabilities);

        ContentValues values = new ContentValues();
        values.put(ThemesColumns.PKG_NAME, pi.packageName);
        values.put(ThemesColumns.TITLE, info.name);
        values.put(ThemesColumns.AUTHOR, info.author);
        values.put(ThemesColumns.DATE_CREATED, System.currentTimeMillis());
        values.put(ThemesColumns.PRESENT_AS_THEME, isPresentableTheme);
        values.put(ThemesColumns.IS_LEGACY_THEME, pi.isLegacyThemeApk);
        values.put(ThemesColumns.LAST_UPDATE_TIME, pi.lastUpdateTime);

        // Insert theme capabilities
        for (Map.Entry<String, Boolean> entry : capabilities.entrySet()) {
            String component = entry.getKey();
            Boolean isImplemented = entry.getValue();
            values.put(component, isImplemented);
        }

        context.getContentResolver().insert(ThemesColumns.CONTENT_URI, values);
    }

    private static void insertLegacyPackageInternal(Context context, PackageInfo pi,
            Map<String, Boolean> capabilities) {
        LegacyThemeInfo info = pi.legacyThemeInfos[0];
        ContentValues values = new ContentValues();
        values.put(ThemesColumns.PKG_NAME, pi.packageName);
        values.put(ThemesColumns.TITLE, info.name);
        values.put(ThemesColumns.AUTHOR, info.author);
        values.put(ThemesColumns.DATE_CREATED, System.currentTimeMillis());
        values.put(ThemesColumns.PRESENT_AS_THEME, 1);
        values.put(ThemesColumns.IS_LEGACY_THEME, pi.isLegacyThemeApk);
        values.put(ThemesColumns.LAST_UPDATE_TIME, pi.lastUpdateTime);

        // Insert theme capabilities
        for (Map.Entry<String, Boolean> entry : capabilities.entrySet()) {
            String component = entry.getKey();
            Boolean isImplemented = ThemesColumns.MODIFIES_OVERLAYS.equals(component) ? Boolean.TRUE
                    : entry.getValue();
            values.put(component, isImplemented);
        }

        context.getContentResolver().insert(ThemesColumns.CONTENT_URI, values);
    }

    public static void updatePackage(Context context, String pkgName) throws NameNotFoundException {
        PackageInfo pi = context.getPackageManager().getPackageInfo(pkgName, 0);
        Map<String, Boolean> capabilities = getCapabilities(context, pkgName);
        if (pi.themeInfos != null && pi.themeInfos.length > 0) {
            updatePackageInternal(context, pi, capabilities);
        } else if (pi.legacyThemeInfos != null && pi.legacyThemeInfos.length > 0) {
            updateLegacyPackageInternal(context, pi, capabilities);
        }
    }

    private static void updatePackageInternal(Context context, PackageInfo pi,
            Map<String, Boolean> capabilities) {
        ThemeInfo info = pi.themeInfos[0];
        boolean isPresentableTheme = ThemePackageHelper.isPresentableTheme(capabilities);
        ContentValues values = new ContentValues();
        values.put(ThemesColumns.PKG_NAME, pi.packageName);
        values.put(ThemesColumns.TITLE, info.name);
        values.put(ThemesColumns.AUTHOR, info.author);
        values.put(ThemesColumns.DATE_CREATED, System.currentTimeMillis());
        values.put(ThemesColumns.PRESENT_AS_THEME, isPresentableTheme);
        values.put(ThemesColumns.IS_LEGACY_THEME, pi.isLegacyThemeApk);
        values.put(ThemesColumns.LAST_UPDATE_TIME, pi.lastUpdateTime);

        String where = ThemesColumns.PKG_NAME + "=?";
        String[] args = { pi.packageName };
        context.getContentResolver().update(ThemesColumns.CONTENT_URI, values, where, args);
    }

    private static void updateLegacyPackageInternal(Context context, PackageInfo pi,
            Map<String, Boolean> capabilities) {
        LegacyThemeInfo info = pi.legacyThemeInfos[0];
        ContentValues values = new ContentValues();
        values.put(ThemesColumns.PKG_NAME, pi.packageName);
        values.put(ThemesColumns.TITLE, info.name);
        values.put(ThemesColumns.AUTHOR, info.author);
        values.put(ThemesColumns.DATE_CREATED, System.currentTimeMillis());
        values.put(ThemesColumns.PRESENT_AS_THEME, 1);
        values.put(ThemesColumns.IS_LEGACY_THEME, pi.isLegacyThemeApk);
        values.put(ThemesColumns.LAST_UPDATE_TIME, pi.lastUpdateTime);

        String where = ThemesColumns.PKG_NAME + "=?";
        String[] args = { pi.packageName };
        context.getContentResolver().update(ThemesColumns.CONTENT_URI, values, where, args);
    }

    public static void removePackage(Context context, String pkgToRemove) {
        // Check currently applied components (fonts, wallpapers etc) and verify the theme is still
        // installed if it is not installed, we need to set the component back to the default theme
        List<String> moveToDefault = new LinkedList<String>(); // components to move back to default
        Cursor mixnmatch = context.getContentResolver().query(MixnMatchColumns.CONTENT_URI, null,
                null, null, null);
        while (mixnmatch.moveToNext()) {
            String mixnmatchKey = mixnmatch.getString(mixnmatch
                    .getColumnIndex(MixnMatchColumns.COL_KEY));
            String component = ThemesContract.MixnMatchColumns
                    .mixNMatchKeyToComponent(mixnmatchKey);
            String pkg = mixnmatch.getString(mixnmatch.getColumnIndex(MixnMatchColumns.COL_VALUE));
            if (pkgToRemove.equals(pkg)) {
                moveToDefault.add(component);
            }
        }
        ThemeManager manager = (ThemeManager) context.getSystemService(Context.THEME_SERVICE);
        manager.requestThemeChange("default", moveToDefault);

        // Delete the theme from the db
        String selection = ThemesColumns.PKG_NAME + "= ?";
        String[] selectionArgs = { pkgToRemove };
        context.getContentResolver().delete(ThemesColumns.CONTENT_URI, selection, selectionArgs);
    }

    /**
     * Returns a map of components with value of true if the APK themes that component or false
     * otherwise. Example of a theme that handles fonts but not ringtones: (MODIFIES_FONTS -> true,
     * MODIFIES_RINGTONES -> false)
     */
    public static Map<String, Boolean> getCapabilities(Context context, String pkgName) {
        PackageInfo pi = null;
        try {
            pi = context.getPackageManager().getPackageInfo(pkgName, 0);
        } catch (Exception e) {
            Log.e(TAG, "Error getting pi during insert", e);
            return Collections.emptyMap();
        }

        // Determine what this theme is capable of
        Context themeContext = null;
        try {
            themeContext = context.createPackageContext(pkgName, Context.CONTEXT_IGNORE_SECURITY);
        } catch (NameNotFoundException e) {
            Log.e(TAG, "Error getting themeContext during insert", e);
            return Collections.emptyMap();
        }

        // Determine what components the theme implements.
        // TODO: Some sort of verification for valid elements (ex font should have valid ttf files)
        HashMap<String, Boolean> implementMap = new HashMap<String, Boolean>();
        for (Map.Entry<String, String> entry : sComponentToFolderName.entrySet()) {
            String component = entry.getKey();
            String folderName = entry.getValue();
            boolean hasComponent = pi.isLegacyThemeApk ? hasThemeComponentLegacy(pi, component)
                    : hasThemeComponent(themeContext, folderName);
            implementMap.put(component, hasComponent);
        }
        return implementMap;
    }

    private static boolean hasThemeComponentLegacy(PackageInfo pi, String component) {
        if (ThemesColumns.MODIFIES_OVERLAYS.equals(component)) {
            return true;
        } else if (ThemesColumns.MODIFIES_LAUNCHER.equals(component)) {
            if (pi.legacyThemeInfos != null && pi.legacyThemeInfos.length > 0
                    && pi.legacyThemeInfos[0].wallpaperResourceId != 0) {
                return true;
            }
        } else if (ThemesColumns.MODIFIES_RINGTONES.equals(component)) {
            if (pi.legacyThemeInfos != null && pi.legacyThemeInfos.length > 0
                    && !TextUtils.isEmpty(pi.legacyThemeInfos[0].ringtoneFileName)) {
                return true;
            }
        } else if (ThemesColumns.MODIFIES_NOTIFICATIONS.equals(component)) {
            if (pi.legacyThemeInfos != null && pi.legacyThemeInfos.length > 0
                    && !TextUtils.isEmpty(pi.legacyThemeInfos[0].notificationFileName)) {
                return true;
            }
        }
        return false;
    }

    private static boolean hasThemeComponent(Context themeContext, String component) {
        boolean found = false;
        AssetManager assetManager = themeContext.getAssets();
        try {
            String[] assetList = assetManager.list(component);
            if (assetList != null && assetList.length > 0) {
                found = true;
            }
        } catch (IOException e) {
            Log.e(TAG, "There was an error checking for asset " + component, e);
        }
        return found;
    }

    // Presently we are defining a "presentable" theme as any theme
    // which implements 2+ components. Such themes can be shown to the user
    // under the "themes" category.
    public static boolean isPresentableTheme(Map<String, Boolean> implementMap) {
        int count = 0;
        for (Boolean isImplemented : implementMap.values()) {
            count += isImplemented ? 1 : 0;
        }
        return count >= 2;
    }
}