WallpaperBackupHelper.java revision ebadfb17e77c5e297635376dbdbcf1615192620f
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 = false;
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    // http://b/22388012
60    public static final String WALLPAPER_IMAGE =
61            new File(Environment.getUserSystemDirectory(UserHandle.USER_SYSTEM),
62                    "wallpaper").getAbsolutePath();
63    public static final String WALLPAPER_ORIG_IMAGE =
64            new File(Environment.getUserSystemDirectory(UserHandle.USER_SYSTEM),
65                    "wallpaper_orig").getAbsolutePath();
66    public static final String WALLPAPER_INFO =
67            new File(Environment.getUserSystemDirectory(UserHandle.USER_SYSTEM),
68                    "wallpaper_info.xml").getAbsolutePath();
69    // Use old keys to keep legacy data compatibility and avoid writing two wallpapers
70    public static final String WALLPAPER_IMAGE_KEY =
71            "/data/data/com.android.settings/files/wallpaper";
72    public static final String WALLPAPER_INFO_KEY = "/data/system/wallpaper_info.xml";
73
74    // Stage file - should be adjacent to the WALLPAPER_IMAGE location.  The wallpapers
75    // will be saved to this file from the restore stream, then renamed to the proper
76    // location if it's deemed suitable.
77    // TODO: Will need to change if backing up non-primary user's wallpaper
78    // http://b/22388012
79    private static final String STAGE_FILE =
80            new File(Environment.getUserSystemDirectory(UserHandle.USER_SYSTEM),
81                    "wallpaper-tmp").getAbsolutePath();
82
83    Context mContext;
84    String[] mFiles;
85    String[] mKeys;
86    double mDesiredMinWidth;
87    double mDesiredMinHeight;
88
89    /**
90     * Construct a helper for backing up / restoring the files at the given absolute locations
91     * within the file system.
92     *
93     * @param context
94     * @param files
95     */
96    public WallpaperBackupHelper(Context context, String[] files, String[] keys) {
97        super(context);
98
99        mContext = context;
100        mFiles = files;
101        mKeys = keys;
102
103        final WindowManager wm =
104                (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
105        final WallpaperManager wpm =
106                (WallpaperManager) context.getSystemService(Context.WALLPAPER_SERVICE);
107        final Display d = wm.getDefaultDisplay();
108        final Point size = new Point();
109        d.getSize(size);
110        mDesiredMinWidth = Math.min(size.x, size.y);
111        mDesiredMinHeight = (double) wpm.getDesiredMinimumHeight();
112        if (mDesiredMinHeight <= 0) {
113            mDesiredMinHeight = size.y;
114        }
115
116        if (DEBUG) {
117            Slog.d(TAG, "dmW=" + mDesiredMinWidth + " dmH=" + mDesiredMinHeight);
118        }
119    }
120
121    /**
122     * Based on oldState, determine which of the files from the application's data directory
123     * need to be backed up, write them to the data stream, and fill in newState with the
124     * state as it exists now.
125     */
126    @Override
127    public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
128            ParcelFileDescriptor newState) {
129        performBackup_checked(oldState, data, newState, mFiles, mKeys);
130    }
131
132    /**
133     * Restore one absolute file entity from the restore stream.  If we're restoring the
134     * magic wallpaper file, take specific action to determine whether it is suitable for
135     * the current device.
136     */
137    @Override
138    public void restoreEntity(BackupDataInputStream data) {
139        final String key = data.getKey();
140        if (isKeyInList(key, mKeys)) {
141            if (key.equals(WALLPAPER_IMAGE_KEY)) {
142                // restore the file to the stage for inspection
143                File f = new File(STAGE_FILE);
144                if (writeFile(f, data)) {
145
146                    // Preflight the restored image's dimensions without loading it
147                    BitmapFactory.Options options = new BitmapFactory.Options();
148                    options.inJustDecodeBounds = true;
149                    BitmapFactory.decodeFile(STAGE_FILE, options);
150
151                    if (DEBUG) Slog.d(TAG, "Restoring wallpaper image w=" + options.outWidth
152                            + " h=" + options.outHeight);
153
154                    if (REJECT_OUTSIZED_RESTORE) {
155                        // We accept any wallpaper that is at least as wide as our preference
156                        // (i.e. wide enough to fill the screen), and is within a comfortable
157                        // factor of the target height, to avoid significant clipping/scaling/
158                        // letterboxing.  At this point we know that mDesiredMinWidth is the
159                        // smallest dimension, regardless of current orientation, so we can
160                        // safely require that the candidate's width and height both exceed
161                        // that hard minimum.
162                        final double heightRatio = mDesiredMinHeight / options.outHeight;
163                        if (options.outWidth < mDesiredMinWidth
164                                || options.outHeight < mDesiredMinWidth
165                                || heightRatio >= MAX_HEIGHT_RATIO
166                                || heightRatio <= MIN_HEIGHT_RATIO) {
167                            // Not wide enough for the screen, or too short/tall to be a good fit
168                            // for the height of the screen, broken image file, or the system's
169                            // desires for wallpaper size are in a bad state.  Probably one of the
170                            // first two.
171                            Slog.i(TAG, "Restored image dimensions (w="
172                                    + options.outWidth + ", h=" + options.outHeight
173                                    + ") too far off target (tw="
174                                    + mDesiredMinWidth + ", th=" + mDesiredMinHeight
175                                    + "); falling back to default wallpaper.");
176                            f.delete();
177                            return;
178                        }
179                    }
180
181                    // We passed the acceptable-dimensions test (if any), so we're going to
182                    // use the restored image.  That comes last, when we are done restoring
183                    // both the pixels and the metadata.
184                }
185            } else if (key.equals(WALLPAPER_INFO_KEY)) {
186                // XML file containing wallpaper info
187                File f = new File(WALLPAPER_INFO);
188                writeFile(f, data);
189            }
190        }
191    }
192
193    /**
194     * Hook for the agent to call this helper upon completion of the restore.  We do this
195     * upon completion so that we know both the imagery and the wallpaper info have
196     * been emplaced without requiring either or relying on ordering.
197     */
198    public void onRestoreFinished() {
199        final File f = new File(STAGE_FILE);
200        if (f.exists()) {
201            // TODO: spin a service to copy the restored image to sd/usb storage,
202            // since it does not exist anywhere other than the private wallpaper
203            // file.
204            Slog.d(TAG, "Applying restored wallpaper image.");
205            f.renameTo(new File(WALLPAPER_ORIG_IMAGE));
206        }
207    }
208}
209