WallpaperBackupHelper.java revision 31f25696d950dd54e8b339074b98ad6335738f2f
1/*
2 * Copyright (C) 2010 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
17package android.app.backup;
18
19import android.app.WallpaperManager;
20import android.content.Context;
21import android.graphics.BitmapFactory;
22import android.graphics.Point;
23import android.os.Environment;
24import android.os.ParcelFileDescriptor;
25import android.os.UserHandle;
26import android.util.Slog;
27import android.view.Display;
28import android.view.WindowManager;
29
30import java.io.File;
31
32/**
33 * Helper for backing up / restoring wallpapers.  Basically an AbsoluteFileBackupHelper,
34 * but with logic for deciding what to do with restored wallpaper images.
35 *
36 * @hide
37 */
38public class WallpaperBackupHelper extends FileBackupHelperBase implements BackupHelper {
39    private static final String TAG = "WallpaperBackupHelper";
40    private static final boolean DEBUG = false;
41
42    // If 'true', then apply an acceptable-size heuristic at restore time, dropping back
43    // to the factory default wallpaper if the restored one differs "too much" from the
44    // device's preferred wallpaper image dimensions.
45    private static final boolean REJECT_OUTSIZED_RESTORE = true;
46
47    // When outsized restore rejection is enabled, this is the maximum ratio between the
48    // source and target image heights that will be permitted.  The ratio is checked both
49    // ways (i.e. >= MAX, or <= 1/MAX) to validate restores from both largeer-than-target
50    // and smaller-than-target sources.
51    private static final double MAX_HEIGHT_RATIO = 1.35;
52
53    // The height ratio check when applying larger images on smaller screens is separate;
54    // in current policy we accept any such restore regardless of the relative dimensions.
55    private static final double MIN_HEIGHT_RATIO = 0;
56
57    // This path must match what the WallpaperManagerService uses
58    // TODO: Will need to change if backing up non-primary user's wallpaper
59    public static final String WALLPAPER_IMAGE =
60            new File(Environment.getUserSystemDirectory(UserHandle.USER_OWNER),
61                    "wallpaper").getAbsolutePath();
62    public static final String WALLPAPER_INFO =
63            new File(Environment.getUserSystemDirectory(UserHandle.USER_OWNER),
64                    "wallpaper_info.xml").getAbsolutePath();
65    // Use old keys to keep legacy data compatibility and avoid writing two wallpapers
66    public static final String WALLPAPER_IMAGE_KEY =
67            "/data/data/com.android.settings/files/wallpaper";
68    public static final String WALLPAPER_INFO_KEY = "/data/system/wallpaper_info.xml";
69
70    // Stage file - should be adjacent to the WALLPAPER_IMAGE location.  The wallpapers
71    // will be saved to this file from the restore stream, then renamed to the proper
72    // location if it's deemed suitable.
73    // TODO: Will need to change if backing up non-primary user's wallpaper
74    private static final String STAGE_FILE =
75            new File(Environment.getUserSystemDirectory(UserHandle.USER_OWNER),
76                    "wallpaper-tmp").getAbsolutePath();
77
78    Context mContext;
79    String[] mFiles;
80    String[] mKeys;
81    double mDesiredMinWidth;
82    double mDesiredMinHeight;
83
84    /**
85     * Construct a helper for backing up / restoring the files at the given absolute locations
86     * within the file system.
87     *
88     * @param context
89     * @param files
90     */
91    public WallpaperBackupHelper(Context context, String[] files, String[] keys) {
92        super(context);
93
94        mContext = context;
95        mFiles = files;
96        mKeys = keys;
97
98        final WindowManager wm =
99                (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
100        final WallpaperManager wpm =
101                (WallpaperManager) context.getSystemService(Context.WALLPAPER_SERVICE);
102        final Display d = wm.getDefaultDisplay();
103        final Point size = new Point();
104        d.getSize(size);
105        mDesiredMinWidth = Math.min(size.x, size.y);
106        mDesiredMinHeight = (double) wpm.getDesiredMinimumHeight();
107        if (mDesiredMinHeight <= 0) {
108            mDesiredMinHeight = size.y;
109        }
110
111        if (DEBUG) {
112            Slog.d(TAG, "dmW=" + mDesiredMinWidth + " dmH=" + mDesiredMinHeight);
113        }
114    }
115
116    /**
117     * Based on oldState, determine which of the files from the application's data directory
118     * need to be backed up, write them to the data stream, and fill in newState with the
119     * state as it exists now.
120     */
121    public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
122            ParcelFileDescriptor newState) {
123        performBackup_checked(oldState, data, newState, mFiles, mKeys);
124    }
125
126    /**
127     * Restore one absolute file entity from the restore stream.  If we're restoring the
128     * magic wallpaper file, take specific action to determine whether it is suitable for
129     * the current device.
130     */
131    public void restoreEntity(BackupDataInputStream data) {
132        final String key = data.getKey();
133        if (isKeyInList(key, mKeys)) {
134            if (key.equals(WALLPAPER_IMAGE_KEY)) {
135                // restore the file to the stage for inspection
136                File f = new File(STAGE_FILE);
137                if (writeFile(f, data)) {
138
139                    // Preflight the restored image's dimensions without loading it
140                    BitmapFactory.Options options = new BitmapFactory.Options();
141                    options.inJustDecodeBounds = true;
142                    BitmapFactory.decodeFile(STAGE_FILE, options);
143
144                    if (DEBUG) Slog.d(TAG, "Restoring wallpaper image w=" + options.outWidth
145                            + " h=" + options.outHeight);
146
147                    if (REJECT_OUTSIZED_RESTORE) {
148                        // We accept any wallpaper that is at least as wide as our preference
149                        // (i.e. wide enough to fill the screen), and is within a comfortable
150                        // factor of the target height, to avoid significant clipping/scaling/
151                        // letterboxing.  At this point we know that mDesiredMinWidth is the
152                        // smallest dimension, regardless of current orientation, so we can
153                        // safely require that the candidate's width and height both exceed
154                        // that hard minimum.
155                        final double heightRatio = mDesiredMinHeight / options.outHeight;
156                        if (options.outWidth < mDesiredMinWidth
157                                || options.outHeight < mDesiredMinWidth
158                                || heightRatio >= MAX_HEIGHT_RATIO
159                                || heightRatio <= MIN_HEIGHT_RATIO) {
160                            // Not wide enough for the screen, or too short/tall to be a good fit
161                            // for the height of the screen, broken image file, or the system's
162                            // desires for wallpaper size are in a bad state.  Probably one of the
163                            // first two.
164                            Slog.i(TAG, "Restored image dimensions (w="
165                                    + options.outWidth + ", h=" + options.outHeight
166                                    + ") too far off target (tw="
167                                    + mDesiredMinWidth + ", th=" + mDesiredMinHeight
168                                    + "); falling back to default wallpaper.");
169                            f.delete();
170                            return;
171                        }
172                    }
173
174                    // We passed the acceptable-dimensions test (if any), so we're going to
175                    // use the restored image.
176                    // TODO: spin a service to copy the restored image to sd/usb storage,
177                    // since it does not exist anywhere other than the private wallpaper
178                    // file.
179                    Slog.d(TAG, "Applying restored wallpaper image.");
180                    f.renameTo(new File(WALLPAPER_IMAGE));
181                }
182            } else if (key.equals(WALLPAPER_INFO_KEY)) {
183                // XML file containing wallpaper info
184                File f = new File(WALLPAPER_INFO);
185                writeFile(f, data);
186            }
187        }
188    }
189}
190