WallpaperManagerService.java revision c28e3a93ff01a809bcfa5bb78e3358f926a09879
1/*
2 * Copyright (C) 2008 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 com.android.server.wallpaper;
18
19import static android.app.WallpaperManager.FLAG_LOCK;
20import static android.app.WallpaperManager.FLAG_SYSTEM;
21import static android.os.ParcelFileDescriptor.MODE_CREATE;
22import static android.os.ParcelFileDescriptor.MODE_READ_ONLY;
23import static android.os.ParcelFileDescriptor.MODE_READ_WRITE;
24import static android.os.ParcelFileDescriptor.MODE_TRUNCATE;
25
26import android.app.ActivityManager;
27import android.app.ActivityManagerNative;
28import android.app.AppGlobals;
29import android.app.AppOpsManager;
30import android.app.IUserSwitchObserver;
31import android.app.IWallpaperManager;
32import android.app.IWallpaperManagerCallback;
33import android.app.PendingIntent;
34import android.app.WallpaperInfo;
35import android.app.WallpaperManager;
36import android.app.admin.DevicePolicyManager;
37import android.app.backup.BackupManager;
38import android.app.backup.WallpaperBackupHelper;
39import android.content.BroadcastReceiver;
40import android.content.ComponentName;
41import android.content.Context;
42import android.content.Intent;
43import android.content.IntentFilter;
44import android.content.ServiceConnection;
45import android.content.pm.IPackageManager;
46import android.content.pm.PackageManager;
47import android.content.pm.PackageManager.NameNotFoundException;
48import android.content.pm.ResolveInfo;
49import android.content.pm.ServiceInfo;
50import android.content.pm.UserInfo;
51import android.content.res.Resources;
52import android.graphics.Bitmap;
53import android.graphics.BitmapFactory;
54import android.graphics.BitmapRegionDecoder;
55import android.graphics.Point;
56import android.graphics.Rect;
57import android.os.Binder;
58import android.os.Bundle;
59import android.os.Environment;
60import android.os.FileObserver;
61import android.os.FileUtils;
62import android.os.IBinder;
63import android.os.IRemoteCallback;
64import android.os.ParcelFileDescriptor;
65import android.os.RemoteCallbackList;
66import android.os.RemoteException;
67import android.os.SELinux;
68import android.os.ServiceManager;
69import android.os.SystemClock;
70import android.os.UserHandle;
71import android.os.UserManager;
72import android.service.wallpaper.IWallpaperConnection;
73import android.service.wallpaper.IWallpaperEngine;
74import android.service.wallpaper.IWallpaperService;
75import android.service.wallpaper.WallpaperService;
76import android.util.EventLog;
77import android.util.Slog;
78import android.util.SparseArray;
79import android.util.Xml;
80import android.view.Display;
81import android.view.IWindowManager;
82import android.view.WindowManager;
83
84import com.android.internal.R;
85import com.android.internal.content.PackageMonitor;
86import com.android.internal.util.FastXmlSerializer;
87import com.android.internal.util.JournaledFile;
88import com.android.server.EventLogTags;
89import com.android.server.SystemService;
90
91import libcore.io.IoUtils;
92
93import org.xmlpull.v1.XmlPullParser;
94import org.xmlpull.v1.XmlPullParserException;
95import org.xmlpull.v1.XmlSerializer;
96
97import java.io.BufferedOutputStream;
98import java.io.File;
99import java.io.FileDescriptor;
100import java.io.FileInputStream;
101import java.io.FileNotFoundException;
102import java.io.FileOutputStream;
103import java.io.IOException;
104import java.io.InputStream;
105import java.io.PrintWriter;
106import java.nio.charset.StandardCharsets;
107import java.util.Arrays;
108import java.util.List;
109
110public class WallpaperManagerService extends IWallpaperManager.Stub {
111    static final String TAG = "WallpaperManagerService";
112    static final boolean DEBUG = false;
113
114    public static class Lifecycle extends SystemService {
115        private WallpaperManagerService mService;
116
117        public Lifecycle(Context context) {
118            super(context);
119        }
120
121        @Override
122        public void onStart() {
123            mService = new WallpaperManagerService(getContext());
124            publishBinderService(Context.WALLPAPER_SERVICE, mService);
125        }
126
127        @Override
128        public void onBootPhase(int phase) {
129            if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
130                mService.systemReady();
131            } else if (phase == SystemService.PHASE_THIRD_PARTY_APPS_CAN_START) {
132                mService.switchUser(UserHandle.USER_SYSTEM, null);
133            }
134        }
135
136        @Override
137        public void onUnlockUser(int userHandle) {
138            mService.onUnlockUser(userHandle);
139        }
140    }
141
142    final Object mLock = new Object();
143
144    /**
145     * Minimum time between crashes of a wallpaper service for us to consider
146     * restarting it vs. just reverting to the static wallpaper.
147     */
148    static final long MIN_WALLPAPER_CRASH_TIME = 10000;
149    static final int MAX_WALLPAPER_COMPONENT_LOG_LENGTH = 128;
150    static final String WALLPAPER = "wallpaper_orig";
151    static final String WALLPAPER_CROP = "wallpaper";
152    static final String WALLPAPER_LOCK_ORIG = "wallpaper_lock_orig";
153    static final String WALLPAPER_LOCK_CROP = "wallpaper_lock";
154    static final String WALLPAPER_INFO = "wallpaper_info.xml";
155
156    // All the various per-user state files we need to be aware of
157    static final String[] sPerUserFiles = new String[] {
158        WALLPAPER, WALLPAPER_CROP,
159        WALLPAPER_LOCK_ORIG, WALLPAPER_LOCK_CROP,
160        WALLPAPER_INFO
161    };
162
163    /**
164     * Observes the wallpaper for changes and notifies all IWallpaperServiceCallbacks
165     * that the wallpaper has changed. The CREATE is triggered when there is no
166     * wallpaper set and is created for the first time. The CLOSE_WRITE is triggered
167     * everytime the wallpaper is changed.
168     */
169    private class WallpaperObserver extends FileObserver {
170
171        final int mUserId;
172        final WallpaperData mWallpaper;
173        final File mWallpaperDir;
174        final File mWallpaperFile;
175        final File mWallpaperLockFile;
176        final File mWallpaperInfoFile;
177
178        public WallpaperObserver(WallpaperData wallpaper) {
179            super(getWallpaperDir(wallpaper.userId).getAbsolutePath(),
180                    CLOSE_WRITE | MOVED_TO | DELETE | DELETE_SELF);
181            mUserId = wallpaper.userId;
182            mWallpaperDir = getWallpaperDir(wallpaper.userId);
183            mWallpaper = wallpaper;
184            mWallpaperFile = new File(mWallpaperDir, WALLPAPER);
185            mWallpaperLockFile = new File(mWallpaperDir, WALLPAPER_LOCK_ORIG);
186            mWallpaperInfoFile = new File(mWallpaperDir, WALLPAPER_INFO);
187        }
188
189        private WallpaperData dataForEvent(boolean sysChanged, boolean lockChanged) {
190            WallpaperData wallpaper = null;
191            synchronized (mLock) {
192                if (lockChanged) {
193                    wallpaper = mLockWallpaperMap.get(mUserId);
194                }
195                if (wallpaper == null) {
196                    // no lock-specific wallpaper exists, or sys case, handled together
197                    wallpaper = mWallpaperMap.get(mUserId);
198                }
199            }
200            return (wallpaper != null) ? wallpaper : mWallpaper;
201        }
202
203        @Override
204        public void onEvent(int event, String path) {
205            if (path == null) {
206                return;
207            }
208            final boolean written = (event == CLOSE_WRITE || event == MOVED_TO);
209            final File changedFile = new File(mWallpaperDir, path);
210
211            // System and system+lock changes happen on the system wallpaper input file;
212            // lock-only changes happen on the dedicated lock wallpaper input file
213            final boolean sysWallpaperChanged = (mWallpaperFile.equals(changedFile));
214            final boolean lockWallpaperChanged = (mWallpaperLockFile.equals(changedFile));
215            WallpaperData wallpaper = dataForEvent(sysWallpaperChanged, lockWallpaperChanged);
216
217            if (DEBUG) {
218                Slog.v(TAG, "Wallpaper file change: evt=" + event
219                        + " path=" + path
220                        + " sys=" + sysWallpaperChanged
221                        + " lock=" + lockWallpaperChanged
222                        + " imagePending=" + wallpaper.imageWallpaperPending
223                        + " whichPending=0x" + Integer.toHexString(wallpaper.whichPending)
224                        + " written=" + written);
225            }
226            synchronized (mLock) {
227                if (sysWallpaperChanged || mWallpaperInfoFile.equals(changedFile)) {
228                    // changing the wallpaper means we'll need to back up the new one
229                    long origId = Binder.clearCallingIdentity();
230                    BackupManager bm = new BackupManager(mContext);
231                    bm.dataChanged();
232                    Binder.restoreCallingIdentity(origId);
233                }
234                if (sysWallpaperChanged || lockWallpaperChanged) {
235                    notifyCallbacksLocked(wallpaper);
236                    if (wallpaper.wallpaperComponent == null
237                            || event != CLOSE_WRITE // includes the MOVED_TO case
238                            || wallpaper.imageWallpaperPending) {
239                        if (written) {
240                            // The image source has finished writing the source image,
241                            // so we now produce the crop rect (in the background), and
242                            // only publish the new displayable (sub)image as a result
243                            // of that work.
244                            if (DEBUG) {
245                                Slog.v(TAG, "Wallpaper written; generating crop");
246                            }
247                            generateCrop(wallpaper);
248                            if (DEBUG) {
249                                Slog.v(TAG, "Crop done; invoking completion callback");
250                            }
251                            wallpaper.imageWallpaperPending = false;
252                            if (wallpaper.setComplete != null) {
253                                try {
254                                    wallpaper.setComplete.onWallpaperChanged();
255                                } catch (RemoteException e) {
256                                    // if this fails we don't really care; the setting app may just
257                                    // have crashed and that sort of thing is a fact of life.
258                                }
259                            }
260                            if (sysWallpaperChanged) {
261                                // If this was the system wallpaper, rebind...
262                                bindWallpaperComponentLocked(mImageWallpaper, true,
263                                        false, wallpaper, null);
264                            }
265                            if (lockWallpaperChanged
266                                    || (wallpaper.whichPending & FLAG_LOCK) != 0) {
267                                if (DEBUG) {
268                                    Slog.i(TAG, "Lock-relevant wallpaper changed");
269                                }
270                                // either a lock-only wallpaper commit or a system+lock event.
271                                // if it's system-plus-lock we need to wipe the lock bookkeeping;
272                                // we're falling back to displaying the system wallpaper there.
273                                if (!lockWallpaperChanged) {
274                                    mLockWallpaperMap.remove(wallpaper.userId);
275                                }
276                                // and in any case, tell keyguard about it
277                                final IWallpaperManagerCallback cb = mKeyguardListener;
278                                if (cb != null) {
279                                    try {
280                                        cb.onWallpaperChanged();
281                                    } catch (RemoteException e) {
282                                        // Oh well it went away; no big deal
283                                    }
284                                }
285                            }
286                            saveSettingsLocked(wallpaper.userId);
287                        }
288                    }
289                }
290            }
291        }
292    }
293
294    /**
295     * Once a new wallpaper has been written via setWallpaper(...), it needs to be cropped
296     * for display.
297     */
298    private void generateCrop(WallpaperData wallpaper) {
299        boolean success = false;
300
301        Rect cropHint = new Rect(wallpaper.cropHint);
302
303        if (DEBUG) {
304            Slog.v(TAG, "Generating crop for new wallpaper(s): 0x"
305                    + Integer.toHexString(wallpaper.whichPending)
306                    + " to " + wallpaper.cropFile.getName()
307                    + " crop=(" + cropHint.width() + 'x' + cropHint.height()
308                    + ") dim=(" + wallpaper.width + 'x' + wallpaper.height + ')');
309        }
310
311        // Analyse the source; needed in multiple cases
312        BitmapFactory.Options options = new BitmapFactory.Options();
313        options.inJustDecodeBounds = true;
314        BitmapFactory.decodeFile(wallpaper.wallpaperFile.getAbsolutePath(), options);
315        if (options.outWidth <= 0 || options.outHeight <= 0) {
316            Slog.e(TAG, "Invalid wallpaper data");
317            success = false;
318        } else {
319            boolean needCrop = false;
320            boolean needScale = false;
321
322            // Empty crop means use the full image
323            if (cropHint.isEmpty()) {
324                cropHint.left = cropHint.top = 0;
325                cropHint.right = options.outWidth;
326                cropHint.bottom = options.outHeight;
327            } else {
328                // force the crop rect to lie within the measured bounds
329                cropHint.offset(
330                        (cropHint.right > options.outWidth ? options.outWidth - cropHint.right : 0),
331                        (cropHint.bottom > options.outHeight ? options.outHeight - cropHint.bottom : 0));
332
333                // Don't bother cropping if what we're left with is identity
334                needCrop = (options.outHeight >= cropHint.height()
335                        && options.outWidth >= cropHint.width());
336            }
337
338            // scale if the crop height winds up not matching the recommended metrics
339            needScale = (wallpaper.height != cropHint.height());
340
341            if (DEBUG) {
342                Slog.v(TAG, "crop: w=" + cropHint.width() + " h=" + cropHint.height());
343                Slog.v(TAG, "dims: w=" + wallpaper.width + " h=" + wallpaper.height);
344                Slog.v(TAG, "meas: w=" + options.outWidth + " h=" + options.outHeight);
345                Slog.v(TAG, "crop?=" + needCrop + " scale?=" + needScale);
346            }
347
348            if (!needCrop && !needScale) {
349                // Simple case:  the nominal crop fits what we want, so we take
350                // the whole thing and just copy the image file directly.
351                if (DEBUG) {
352                    Slog.v(TAG, "Null crop of new wallpaper; copying");
353                }
354                success = FileUtils.copyFile(wallpaper.wallpaperFile, wallpaper.cropFile);
355                if (!success) {
356                    wallpaper.cropFile.delete();
357                    // TODO: fall back to default wallpaper in this case
358                }
359            } else {
360                // Fancy case: crop and scale.  First, we decode and scale down if appropriate.
361                FileOutputStream f = null;
362                BufferedOutputStream bos = null;
363                try {
364                    BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(
365                            wallpaper.wallpaperFile.getAbsolutePath(), false);
366
367                    // This actually downsamples only by powers of two, but that's okay; we do
368                    // a proper scaling blit later.  This is to minimize transient RAM use.
369                    // We calculate the largest power-of-two under the actual ratio rather than
370                    // just let the decode take care of it because we also want to remap where the
371                    // cropHint rectangle lies in the decoded [super]rect.
372                    final BitmapFactory.Options scaler;
373                    final int actualScale = cropHint.height() / wallpaper.height;
374                    int scale = 1;
375                    while (2*scale < actualScale) {
376                        scale *= 2;
377                    }
378                    if (scale > 1) {
379                        scaler = new BitmapFactory.Options();
380                        scaler.inSampleSize = scale;
381                        if (DEBUG) {
382                            Slog.v(TAG, "Downsampling cropped rect with scale " + scale);
383                        }
384                    } else {
385                        scaler = null;
386                    }
387                    Bitmap cropped = decoder.decodeRegion(cropHint, scaler);
388                    decoder.recycle();
389
390                    if (cropped == null) {
391                        Slog.e(TAG, "Could not decode new wallpaper");
392                    } else {
393                        // We've got the extracted crop; now we want to scale it properly to
394                        // the desired rectangle.  That's a height-biased operation: make it
395                        // fit the hinted height, and accept whatever width we end up with.
396                        cropHint.offsetTo(0, 0);
397                        cropHint.right /= scale;    // adjust by downsampling factor
398                        cropHint.bottom /= scale;
399                        final float heightR = ((float)wallpaper.height) / ((float)cropHint.height());
400                        if (DEBUG) {
401                            Slog.v(TAG, "scale " + heightR + ", extracting " + cropHint);
402                        }
403                        final int destWidth = (int)(cropHint.width() * heightR);
404                        final Bitmap finalCrop = Bitmap.createScaledBitmap(cropped,
405                                destWidth, wallpaper.height, true);
406                        if (DEBUG) {
407                            Slog.v(TAG, "Final extract:");
408                            Slog.v(TAG, "  dims: w=" + wallpaper.width
409                                    + " h=" + wallpaper.height);
410                            Slog.v(TAG, "   out: w=" + finalCrop.getWidth()
411                                    + " h=" + finalCrop.getHeight());
412                        }
413
414                        f = new FileOutputStream(wallpaper.cropFile);
415                        bos = new BufferedOutputStream(f, 32*1024);
416                        finalCrop.compress(Bitmap.CompressFormat.PNG, 90, bos);
417                        bos.flush();  // don't rely on the implicit flush-at-close when noting success
418                        success = true;
419                    }
420                } catch (Exception e) {
421                    if (DEBUG) {
422                        Slog.e(TAG, "Error decoding crop", e);
423                    }
424                } finally {
425                    IoUtils.closeQuietly(bos);
426                    IoUtils.closeQuietly(f);
427                }
428            }
429        }
430
431        if (!success) {
432            Slog.e(TAG, "Unable to apply new wallpaper");
433            wallpaper.cropFile.delete();
434        }
435
436        if (wallpaper.cropFile.exists()) {
437            boolean didRestorecon = SELinux.restorecon(wallpaper.cropFile.getAbsoluteFile());
438            if (DEBUG) {
439                Slog.v(TAG, "restorecon() of crop file returned " + didRestorecon);
440            }
441        }
442    }
443
444    final Context mContext;
445    final IWindowManager mIWindowManager;
446    final IPackageManager mIPackageManager;
447    final MyPackageMonitor mMonitor;
448    final AppOpsManager mAppOpsManager;
449    WallpaperData mLastWallpaper;
450    IWallpaperManagerCallback mKeyguardListener;
451    boolean mWaitingForUnlock;
452
453    /**
454     * ID of the current wallpaper, changed every time anything sets a wallpaper.
455     * This is used for external detection of wallpaper update activity.
456     */
457    int mWallpaperId;
458
459    /**
460     * Name of the component used to display bitmap wallpapers from either the gallery or
461     * built-in wallpapers.
462     */
463    final ComponentName mImageWallpaper;
464
465    final SparseArray<WallpaperData> mWallpaperMap = new SparseArray<WallpaperData>();
466    final SparseArray<WallpaperData> mLockWallpaperMap = new SparseArray<WallpaperData>();
467
468    int mCurrentUserId;
469
470    static class WallpaperData {
471
472        int userId;
473
474        final File wallpaperFile;   // source image
475        final File cropFile;        // eventual destination
476
477        /**
478         * True while the client is writing a new wallpaper
479         */
480        boolean imageWallpaperPending;
481
482        /**
483         * Which new wallpapers are being written; mirrors the 'which'
484         * selector bit field to setWallpaper().
485         */
486        int whichPending;
487
488        /**
489         * Callback once the set + crop is finished
490         */
491        IWallpaperManagerCallback setComplete;
492
493        /**
494         * Resource name if using a picture from the wallpaper gallery
495         */
496        String name = "";
497
498        /**
499         * The component name of the currently set live wallpaper.
500         */
501        ComponentName wallpaperComponent;
502
503        /**
504         * The component name of the wallpaper that should be set next.
505         */
506        ComponentName nextWallpaperComponent;
507
508        /**
509         * The ID of this wallpaper
510         */
511        int wallpaperId;
512
513        WallpaperConnection connection;
514        long lastDiedTime;
515        boolean wallpaperUpdating;
516        WallpaperObserver wallpaperObserver;
517
518        /**
519         * List of callbacks registered they should each be notified when the wallpaper is changed.
520         */
521        private RemoteCallbackList<IWallpaperManagerCallback> callbacks
522                = new RemoteCallbackList<IWallpaperManagerCallback>();
523
524        int width = -1;
525        int height = -1;
526
527        /**
528         * The crop hint supplied for displaying a subset of the source image
529         */
530        final Rect cropHint = new Rect(0, 0, 0, 0);
531
532        final Rect padding = new Rect(0, 0, 0, 0);
533
534        WallpaperData(int userId, String inputFileName, String cropFileName) {
535            this.userId = userId;
536            final File wallpaperDir = getWallpaperDir(userId);
537            wallpaperFile = new File(wallpaperDir, inputFileName);
538            cropFile = new File(wallpaperDir, cropFileName);
539        }
540
541        // Called during initialization of a given user's wallpaper bookkeeping
542        boolean cropExists() {
543            return cropFile.exists();
544        }
545    }
546
547    int makeWallpaperIdLocked() {
548        do {
549            ++mWallpaperId;
550        } while (mWallpaperId == 0);
551        return mWallpaperId;
552    }
553
554    class WallpaperConnection extends IWallpaperConnection.Stub
555            implements ServiceConnection {
556        final WallpaperInfo mInfo;
557        final Binder mToken = new Binder();
558        IWallpaperService mService;
559        IWallpaperEngine mEngine;
560        WallpaperData mWallpaper;
561        IRemoteCallback mReply;
562
563        boolean mDimensionsChanged = false;
564        boolean mPaddingChanged = false;
565
566        public WallpaperConnection(WallpaperInfo info, WallpaperData wallpaper) {
567            mInfo = info;
568            mWallpaper = wallpaper;
569        }
570
571        @Override
572        public void onServiceConnected(ComponentName name, IBinder service) {
573            synchronized (mLock) {
574                if (mWallpaper.connection == this) {
575                    mService = IWallpaperService.Stub.asInterface(service);
576                    attachServiceLocked(this, mWallpaper);
577                    // XXX should probably do saveSettingsLocked() later
578                    // when we have an engine, but I'm not sure about
579                    // locking there and anyway we always need to be able to
580                    // recover if there is something wrong.
581                    saveSettingsLocked(mWallpaper.userId);
582                }
583            }
584        }
585
586        @Override
587        public void onServiceDisconnected(ComponentName name) {
588            synchronized (mLock) {
589                mService = null;
590                mEngine = null;
591                if (mWallpaper.connection == this) {
592                    Slog.w(TAG, "Wallpaper service gone: " + mWallpaper.wallpaperComponent);
593                    if (!mWallpaper.wallpaperUpdating
594                            && mWallpaper.userId == mCurrentUserId) {
595                        // There is a race condition which causes
596                        // {@link #mWallpaper.wallpaperUpdating} to be false even if it is
597                        // currently updating since the broadcast notifying us is async.
598                        // This race is overcome by the general rule that we only reset the
599                        // wallpaper if its service was shut down twice
600                        // during {@link #MIN_WALLPAPER_CRASH_TIME} millis.
601                        if (mWallpaper.lastDiedTime != 0
602                                && mWallpaper.lastDiedTime + MIN_WALLPAPER_CRASH_TIME
603                                    > SystemClock.uptimeMillis()) {
604                            Slog.w(TAG, "Reverting to built-in wallpaper!");
605                            clearWallpaperLocked(true, FLAG_SYSTEM, mWallpaper.userId, null);
606                        } else {
607                            mWallpaper.lastDiedTime = SystemClock.uptimeMillis();
608                        }
609                        final String flattened = name.flattenToString();
610                        EventLog.writeEvent(EventLogTags.WP_WALLPAPER_CRASHED,
611                                flattened.substring(0, Math.min(flattened.length(),
612                                        MAX_WALLPAPER_COMPONENT_LOG_LENGTH)));
613                    }
614                }
615            }
616        }
617
618        @Override
619        public void attachEngine(IWallpaperEngine engine) {
620            synchronized (mLock) {
621                mEngine = engine;
622                if (mDimensionsChanged) {
623                    try {
624                        mEngine.setDesiredSize(mWallpaper.width, mWallpaper.height);
625                    } catch (RemoteException e) {
626                        Slog.w(TAG, "Failed to set wallpaper dimensions", e);
627                    }
628                    mDimensionsChanged = false;
629                }
630                if (mPaddingChanged) {
631                    try {
632                        mEngine.setDisplayPadding(mWallpaper.padding);
633                    } catch (RemoteException e) {
634                        Slog.w(TAG, "Failed to set wallpaper padding", e);
635                    }
636                    mPaddingChanged = false;
637                }
638            }
639        }
640
641        @Override
642        public void engineShown(IWallpaperEngine engine) {
643            synchronized (mLock) {
644                if (mReply != null) {
645                    long ident = Binder.clearCallingIdentity();
646                    try {
647                        mReply.sendResult(null);
648                    } catch (RemoteException e) {
649                        Binder.restoreCallingIdentity(ident);
650                    }
651                    mReply = null;
652                }
653            }
654        }
655
656        @Override
657        public ParcelFileDescriptor setWallpaper(String name) {
658            synchronized (mLock) {
659                if (mWallpaper.connection == this) {
660                    return updateWallpaperBitmapLocked(name, mWallpaper, null);
661                }
662                return null;
663            }
664        }
665    }
666
667    class MyPackageMonitor extends PackageMonitor {
668        @Override
669        public void onPackageUpdateFinished(String packageName, int uid) {
670            synchronized (mLock) {
671                if (mCurrentUserId != getChangingUserId()) {
672                    return;
673                }
674                WallpaperData wallpaper = mWallpaperMap.get(mCurrentUserId);
675                if (wallpaper != null) {
676                    if (wallpaper.wallpaperComponent != null
677                            && wallpaper.wallpaperComponent.getPackageName().equals(packageName)) {
678                        wallpaper.wallpaperUpdating = false;
679                        ComponentName comp = wallpaper.wallpaperComponent;
680                        clearWallpaperComponentLocked(wallpaper);
681                        if (!bindWallpaperComponentLocked(comp, false, false,
682                                wallpaper, null)) {
683                            Slog.w(TAG, "Wallpaper no longer available; reverting to default");
684                            clearWallpaperLocked(false, FLAG_SYSTEM, wallpaper.userId, null);
685                        }
686                    }
687                }
688            }
689        }
690
691        @Override
692        public void onPackageModified(String packageName) {
693            synchronized (mLock) {
694                if (mCurrentUserId != getChangingUserId()) {
695                    return;
696                }
697                WallpaperData wallpaper = mWallpaperMap.get(mCurrentUserId);
698                if (wallpaper != null) {
699                    if (wallpaper.wallpaperComponent == null
700                            || !wallpaper.wallpaperComponent.getPackageName().equals(packageName)) {
701                        return;
702                    }
703                    doPackagesChangedLocked(true, wallpaper);
704                }
705            }
706        }
707
708        @Override
709        public void onPackageUpdateStarted(String packageName, int uid) {
710            synchronized (mLock) {
711                if (mCurrentUserId != getChangingUserId()) {
712                    return;
713                }
714                WallpaperData wallpaper = mWallpaperMap.get(mCurrentUserId);
715                if (wallpaper != null) {
716                    if (wallpaper.wallpaperComponent != null
717                            && wallpaper.wallpaperComponent.getPackageName().equals(packageName)) {
718                        wallpaper.wallpaperUpdating = true;
719                    }
720                }
721            }
722        }
723
724        @Override
725        public boolean onHandleForceStop(Intent intent, String[] packages, int uid, boolean doit) {
726            synchronized (mLock) {
727                boolean changed = false;
728                if (mCurrentUserId != getChangingUserId()) {
729                    return false;
730                }
731                WallpaperData wallpaper = mWallpaperMap.get(mCurrentUserId);
732                if (wallpaper != null) {
733                    boolean res = doPackagesChangedLocked(doit, wallpaper);
734                    changed |= res;
735                }
736                return changed;
737            }
738        }
739
740        @Override
741        public void onSomePackagesChanged() {
742            synchronized (mLock) {
743                if (mCurrentUserId != getChangingUserId()) {
744                    return;
745                }
746                WallpaperData wallpaper = mWallpaperMap.get(mCurrentUserId);
747                if (wallpaper != null) {
748                    doPackagesChangedLocked(true, wallpaper);
749                }
750            }
751        }
752
753        boolean doPackagesChangedLocked(boolean doit, WallpaperData wallpaper) {
754            boolean changed = false;
755            if (wallpaper.wallpaperComponent != null) {
756                int change = isPackageDisappearing(wallpaper.wallpaperComponent
757                        .getPackageName());
758                if (change == PACKAGE_PERMANENT_CHANGE
759                        || change == PACKAGE_TEMPORARY_CHANGE) {
760                    changed = true;
761                    if (doit) {
762                        Slog.w(TAG, "Wallpaper uninstalled, removing: "
763                                + wallpaper.wallpaperComponent);
764                        clearWallpaperLocked(false, FLAG_SYSTEM, wallpaper.userId, null);
765                    }
766                }
767            }
768            if (wallpaper.nextWallpaperComponent != null) {
769                int change = isPackageDisappearing(wallpaper.nextWallpaperComponent
770                        .getPackageName());
771                if (change == PACKAGE_PERMANENT_CHANGE
772                        || change == PACKAGE_TEMPORARY_CHANGE) {
773                    wallpaper.nextWallpaperComponent = null;
774                }
775            }
776            if (wallpaper.wallpaperComponent != null
777                    && isPackageModified(wallpaper.wallpaperComponent.getPackageName())) {
778                try {
779                    mContext.getPackageManager().getServiceInfo(wallpaper.wallpaperComponent,
780                            PackageManager.MATCH_DIRECT_BOOT_AWARE
781                                    | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
782                } catch (NameNotFoundException e) {
783                    Slog.w(TAG, "Wallpaper component gone, removing: "
784                            + wallpaper.wallpaperComponent);
785                    clearWallpaperLocked(false, FLAG_SYSTEM, wallpaper.userId, null);
786                }
787            }
788            if (wallpaper.nextWallpaperComponent != null
789                    && isPackageModified(wallpaper.nextWallpaperComponent.getPackageName())) {
790                try {
791                    mContext.getPackageManager().getServiceInfo(wallpaper.nextWallpaperComponent,
792                            PackageManager.MATCH_DIRECT_BOOT_AWARE
793                                    | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
794                } catch (NameNotFoundException e) {
795                    wallpaper.nextWallpaperComponent = null;
796                }
797            }
798            return changed;
799        }
800    }
801
802    public WallpaperManagerService(Context context) {
803        if (DEBUG) Slog.v(TAG, "WallpaperService startup");
804        mContext = context;
805        mImageWallpaper = ComponentName.unflattenFromString(
806                context.getResources().getString(R.string.image_wallpaper_component));
807        mIWindowManager = IWindowManager.Stub.asInterface(
808                ServiceManager.getService(Context.WINDOW_SERVICE));
809        mIPackageManager = AppGlobals.getPackageManager();
810        mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
811        mMonitor = new MyPackageMonitor();
812        mMonitor.register(context, null, UserHandle.ALL, true);
813        getWallpaperDir(UserHandle.USER_SYSTEM).mkdirs();
814        loadSettingsLocked(UserHandle.USER_SYSTEM);
815    }
816
817    private static File getWallpaperDir(int userId) {
818        return Environment.getUserSystemDirectory(userId);
819    }
820
821    @Override
822    protected void finalize() throws Throwable {
823        super.finalize();
824        for (int i = 0; i < mWallpaperMap.size(); i++) {
825            WallpaperData wallpaper = mWallpaperMap.valueAt(i);
826            wallpaper.wallpaperObserver.stopWatching();
827        }
828    }
829
830    void systemReady() {
831        if (DEBUG) Slog.v(TAG, "systemReady");
832        WallpaperData wallpaper = mWallpaperMap.get(UserHandle.USER_SYSTEM);
833        // If we think we're going to be using the system image wallpaper imagery, make
834        // sure we have something to render
835        if (mImageWallpaper.equals(wallpaper.nextWallpaperComponent)) {
836            // No crop file? Make sure we've finished the processing sequence if necessary
837            if (!wallpaper.cropExists()) {
838                if (DEBUG) {
839                    Slog.i(TAG, "No crop; regenerating from source");
840                }
841                generateCrop(wallpaper);
842            }
843            // Still nothing?  Fall back to default.
844            if (!wallpaper.cropExists()) {
845                if (DEBUG) {
846                    Slog.i(TAG, "Unable to regenerate crop; resetting");
847                }
848                clearWallpaperLocked(false, FLAG_SYSTEM, UserHandle.USER_SYSTEM, null);
849            }
850        } else {
851            if (DEBUG) {
852                Slog.i(TAG, "Nondefault wallpaper component; gracefully ignoring");
853            }
854        }
855
856        IntentFilter userFilter = new IntentFilter();
857        userFilter.addAction(Intent.ACTION_USER_REMOVED);
858        userFilter.addAction(Intent.ACTION_USER_STOPPING);
859        mContext.registerReceiver(new BroadcastReceiver() {
860            @Override
861            public void onReceive(Context context, Intent intent) {
862                final String action = intent.getAction();
863                if (Intent.ACTION_USER_REMOVED.equals(action)) {
864                    onRemoveUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
865                            UserHandle.USER_NULL));
866                }
867                // TODO: Race condition causing problems when cleaning up on stopping a user.
868                // Comment this out for now.
869                // else if (Intent.ACTION_USER_STOPPING.equals(action)) {
870                //     onStoppingUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
871                //             UserHandle.USER_NULL));
872                // }
873            }
874        }, userFilter);
875
876        try {
877            ActivityManagerNative.getDefault().registerUserSwitchObserver(
878                    new IUserSwitchObserver.Stub() {
879                        @Override
880                        public void onUserSwitching(int newUserId, IRemoteCallback reply) {
881                            switchUser(newUserId, reply);
882                        }
883
884                        @Override
885                        public void onUserSwitchComplete(int newUserId) throws RemoteException {
886                        }
887
888                        @Override
889                        public void onForegroundProfileSwitch(int newProfileId) {
890                            // Ignore.
891                        }
892                    });
893        } catch (RemoteException e) {
894            // TODO Auto-generated catch block
895            e.printStackTrace();
896        }
897    }
898
899    /** Called by SystemBackupAgent */
900    public String getName() {
901        // Verify caller is the system
902        if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
903            throw new RuntimeException("getName() can only be called from the system process");
904        }
905        synchronized (mLock) {
906            return mWallpaperMap.get(0).name;
907        }
908    }
909
910    void stopObserver(WallpaperData wallpaper) {
911        if (wallpaper != null) {
912            if (wallpaper.wallpaperObserver != null) {
913                wallpaper.wallpaperObserver.stopWatching();
914                wallpaper.wallpaperObserver = null;
915            }
916        }
917    }
918
919    void stopObserversLocked(int userId) {
920        stopObserver(mWallpaperMap.get(userId));
921        stopObserver(mLockWallpaperMap.get(userId));
922        mWallpaperMap.remove(userId);
923        mLockWallpaperMap.remove(userId);
924    }
925
926    void onUnlockUser(int userId) {
927        synchronized (mLock) {
928            if (mCurrentUserId == userId && mWaitingForUnlock) {
929                switchUser(userId, null);
930            }
931        }
932    }
933
934    void onRemoveUser(int userId) {
935        if (userId < 1) return;
936
937        final File wallpaperDir = getWallpaperDir(userId);
938        synchronized (mLock) {
939            stopObserversLocked(userId);
940            for (String filename : sPerUserFiles) {
941                new File(wallpaperDir, filename).delete();
942            }
943        }
944    }
945
946    void switchUser(int userId, IRemoteCallback reply) {
947        synchronized (mLock) {
948            mCurrentUserId = userId;
949            WallpaperData wallpaper = getWallpaperSafeLocked(userId, FLAG_SYSTEM);
950            // Not started watching yet, in case wallpaper data was loaded for other reasons.
951            if (wallpaper.wallpaperObserver == null) {
952                wallpaper.wallpaperObserver = new WallpaperObserver(wallpaper);
953                wallpaper.wallpaperObserver.startWatching();
954            }
955            switchWallpaper(wallpaper, reply);
956        }
957    }
958
959    void switchWallpaper(WallpaperData wallpaper, IRemoteCallback reply) {
960        synchronized (mLock) {
961            mWaitingForUnlock = false;
962            final ComponentName cname = wallpaper.wallpaperComponent != null ?
963                    wallpaper.wallpaperComponent : wallpaper.nextWallpaperComponent;
964            if (!bindWallpaperComponentLocked(cname, true, false, wallpaper, reply)) {
965                // We failed to bind the desired wallpaper, but that might
966                // happen if the wallpaper isn't direct-boot aware
967                ServiceInfo si = null;
968                try {
969                    si = mIPackageManager.getServiceInfo(cname,
970                            PackageManager.MATCH_DIRECT_BOOT_UNAWARE, wallpaper.userId);
971                } catch (RemoteException ignored) {
972                }
973
974                if (si == null) {
975                    Slog.w(TAG, "Failure starting previous wallpaper; clearing");
976                    clearWallpaperLocked(false, FLAG_SYSTEM, wallpaper.userId, reply);
977                } else {
978                    Slog.w(TAG, "Wallpaper isn't direct boot aware; using fallback until unlocked");
979                    // We might end up persisting the current wallpaper data
980                    // while locked, so pretend like the component was actually
981                    // bound into place
982                    wallpaper.wallpaperComponent = wallpaper.nextWallpaperComponent;
983                    final WallpaperData fallback = new WallpaperData(wallpaper.userId,
984                            WALLPAPER_LOCK_ORIG, WALLPAPER_LOCK_CROP);
985                    ensureSaneWallpaperData(fallback);
986                    bindWallpaperComponentLocked(mImageWallpaper, true, false, fallback, reply);
987                    mWaitingForUnlock = true;
988                }
989            }
990        }
991    }
992
993    @Override
994    public void clearWallpaper(String callingPackage, int which, int userId) {
995        if (DEBUG) Slog.v(TAG, "clearWallpaper");
996        checkPermission(android.Manifest.permission.SET_WALLPAPER);
997        if (!isWallpaperSupported(callingPackage) || !isWallpaperSettingAllowed(callingPackage)) {
998            return;
999        }
1000        userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1001                Binder.getCallingUid(), userId, false, true, "clearWallpaper", null);
1002
1003        synchronized (mLock) {
1004            clearWallpaperLocked(false, which, userId, null);
1005        }
1006    }
1007
1008    void clearWallpaperLocked(boolean defaultFailed, int which, int userId, IRemoteCallback reply) {
1009        if (which != FLAG_SYSTEM && which != FLAG_LOCK) {
1010            throw new IllegalArgumentException("Must specify exactly one kind of wallpaper to read");
1011        }
1012
1013        WallpaperData wallpaper = null;
1014        if (which == FLAG_LOCK) {
1015            wallpaper = mLockWallpaperMap.get(userId);
1016            if (wallpaper == null) {
1017                // It's already gone; we're done.
1018                if (DEBUG) {
1019                    Slog.i(TAG, "Lock wallpaper already cleared");
1020                }
1021                return;
1022            }
1023        } else {
1024            wallpaper = mWallpaperMap.get(userId);
1025            if (wallpaper == null) {
1026                // Might need to bring it in the first time to establish our rewrite
1027                loadSettingsLocked(userId);
1028                wallpaper = mWallpaperMap.get(userId);
1029            }
1030        }
1031        if (wallpaper == null) {
1032            return;
1033        }
1034
1035        final long ident = Binder.clearCallingIdentity();
1036        try {
1037            if (wallpaper.wallpaperFile.exists()) {
1038                wallpaper.wallpaperFile.delete();
1039                wallpaper.cropFile.delete();
1040                if (which == FLAG_LOCK) {
1041                    mLockWallpaperMap.remove(userId);
1042                    final IWallpaperManagerCallback cb = mKeyguardListener;
1043                    if (cb != null) {
1044                        if (DEBUG) {
1045                            Slog.i(TAG, "Notifying keyguard of lock wallpaper clear");
1046                        }
1047                        try {
1048                            cb.onWallpaperChanged();
1049                        } catch (RemoteException e) {
1050                            // Oh well it went away; no big deal
1051                        }
1052                    }
1053                    saveSettingsLocked(userId);
1054                    return;
1055                }
1056            }
1057
1058            RuntimeException e = null;
1059            try {
1060                wallpaper.imageWallpaperPending = false;
1061                if (userId != mCurrentUserId) return;
1062                if (bindWallpaperComponentLocked(defaultFailed
1063                        ? mImageWallpaper
1064                                : null, true, false, wallpaper, reply)) {
1065                    return;
1066                }
1067            } catch (IllegalArgumentException e1) {
1068                e = e1;
1069            }
1070
1071            // This can happen if the default wallpaper component doesn't
1072            // exist.  This should be a system configuration problem, but
1073            // let's not let it crash the system and just live with no
1074            // wallpaper.
1075            Slog.e(TAG, "Default wallpaper component not found!", e);
1076            clearWallpaperComponentLocked(wallpaper);
1077            if (reply != null) {
1078                try {
1079                    reply.sendResult(null);
1080                } catch (RemoteException e1) {
1081                }
1082            }
1083        } finally {
1084            Binder.restoreCallingIdentity(ident);
1085        }
1086    }
1087
1088    public boolean hasNamedWallpaper(String name) {
1089        synchronized (mLock) {
1090            List<UserInfo> users;
1091            long ident = Binder.clearCallingIdentity();
1092            try {
1093                users = ((UserManager) mContext.getSystemService(Context.USER_SERVICE)).getUsers();
1094            } finally {
1095                Binder.restoreCallingIdentity(ident);
1096            }
1097            for (UserInfo user: users) {
1098                // ignore managed profiles
1099                if (user.isManagedProfile()) {
1100                    continue;
1101                }
1102                WallpaperData wd = mWallpaperMap.get(user.id);
1103                if (wd == null) {
1104                    // User hasn't started yet, so load her settings to peek at the wallpaper
1105                    loadSettingsLocked(user.id);
1106                    wd = mWallpaperMap.get(user.id);
1107                }
1108                if (wd != null && name.equals(wd.name)) {
1109                    return true;
1110                }
1111            }
1112        }
1113        return false;
1114    }
1115
1116    private Point getDefaultDisplaySize() {
1117        Point p = new Point();
1118        WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
1119        Display d = wm.getDefaultDisplay();
1120        d.getRealSize(p);
1121        return p;
1122    }
1123
1124    public void setDimensionHints(int width, int height, String callingPackage)
1125            throws RemoteException {
1126        checkPermission(android.Manifest.permission.SET_WALLPAPER_HINTS);
1127        if (!isWallpaperSupported(callingPackage)) {
1128            return;
1129        }
1130        synchronized (mLock) {
1131            int userId = UserHandle.getCallingUserId();
1132            WallpaperData wallpaper = getWallpaperSafeLocked(userId, FLAG_SYSTEM);
1133            if (width <= 0 || height <= 0) {
1134                throw new IllegalArgumentException("width and height must be > 0");
1135            }
1136            // Make sure it is at least as large as the display.
1137            Point displaySize = getDefaultDisplaySize();
1138            width = Math.max(width, displaySize.x);
1139            height = Math.max(height, displaySize.y);
1140
1141            if (width != wallpaper.width || height != wallpaper.height) {
1142                wallpaper.width = width;
1143                wallpaper.height = height;
1144                saveSettingsLocked(userId);
1145                if (mCurrentUserId != userId) return; // Don't change the properties now
1146                if (wallpaper.connection != null) {
1147                    if (wallpaper.connection.mEngine != null) {
1148                        try {
1149                            wallpaper.connection.mEngine.setDesiredSize(
1150                                    width, height);
1151                        } catch (RemoteException e) {
1152                        }
1153                        notifyCallbacksLocked(wallpaper);
1154                    } else if (wallpaper.connection.mService != null) {
1155                        // We've attached to the service but the engine hasn't attached back to us
1156                        // yet. This means it will be created with the previous dimensions, so we
1157                        // need to update it to the new dimensions once it attaches.
1158                        wallpaper.connection.mDimensionsChanged = true;
1159                    }
1160                }
1161            }
1162        }
1163    }
1164
1165    public int getWidthHint() throws RemoteException {
1166        synchronized (mLock) {
1167            WallpaperData wallpaper = mWallpaperMap.get(UserHandle.getCallingUserId());
1168            if (wallpaper != null) {
1169                return wallpaper.width;
1170            } else {
1171                return 0;
1172            }
1173        }
1174    }
1175
1176    public int getHeightHint() throws RemoteException {
1177        synchronized (mLock) {
1178            WallpaperData wallpaper = mWallpaperMap.get(UserHandle.getCallingUserId());
1179            if (wallpaper != null) {
1180                return wallpaper.height;
1181            } else {
1182                return 0;
1183            }
1184        }
1185    }
1186
1187    public void setDisplayPadding(Rect padding, String callingPackage) {
1188        checkPermission(android.Manifest.permission.SET_WALLPAPER_HINTS);
1189        if (!isWallpaperSupported(callingPackage)) {
1190            return;
1191        }
1192        synchronized (mLock) {
1193            int userId = UserHandle.getCallingUserId();
1194            WallpaperData wallpaper = getWallpaperSafeLocked(userId, FLAG_SYSTEM);
1195            if (padding.left < 0 || padding.top < 0 || padding.right < 0 || padding.bottom < 0) {
1196                throw new IllegalArgumentException("padding must be positive: " + padding);
1197            }
1198
1199            if (!padding.equals(wallpaper.padding)) {
1200                wallpaper.padding.set(padding);
1201                saveSettingsLocked(userId);
1202                if (mCurrentUserId != userId) return; // Don't change the properties now
1203                if (wallpaper.connection != null) {
1204                    if (wallpaper.connection.mEngine != null) {
1205                        try {
1206                            wallpaper.connection.mEngine.setDisplayPadding(padding);
1207                        } catch (RemoteException e) {
1208                        }
1209                        notifyCallbacksLocked(wallpaper);
1210                    } else if (wallpaper.connection.mService != null) {
1211                        // We've attached to the service but the engine hasn't attached back to us
1212                        // yet. This means it will be created with the previous dimensions, so we
1213                        // need to update it to the new dimensions once it attaches.
1214                        wallpaper.connection.mPaddingChanged = true;
1215                    }
1216                }
1217            }
1218        }
1219    }
1220
1221    @Override
1222    public ParcelFileDescriptor getWallpaper(IWallpaperManagerCallback cb, final int which,
1223            Bundle outParams, int wallpaperUserId) {
1224        wallpaperUserId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1225                Binder.getCallingUid(), wallpaperUserId, false, true, "getWallpaper", null);
1226
1227        if (which != FLAG_SYSTEM && which != FLAG_LOCK) {
1228            throw new IllegalArgumentException("Must specify exactly one kind of wallpaper to read");
1229        }
1230
1231        synchronized (mLock) {
1232            final SparseArray<WallpaperData> whichSet =
1233                    (which == FLAG_LOCK) ? mLockWallpaperMap : mWallpaperMap;
1234            WallpaperData wallpaper = whichSet.get(wallpaperUserId);
1235            if (wallpaper == null) {
1236                // common case, this is the first lookup post-boot of the system or
1237                // unified lock, so we bring up the saved state lazily now and recheck.
1238                loadSettingsLocked(wallpaperUserId);
1239                wallpaper = whichSet.get(wallpaperUserId);
1240                if (wallpaper == null) {
1241                    return null;
1242                }
1243            }
1244            try {
1245                if (outParams != null) {
1246                    outParams.putInt("width", wallpaper.width);
1247                    outParams.putInt("height", wallpaper.height);
1248                }
1249                if (cb != null) {
1250                    wallpaper.callbacks.register(cb);
1251                }
1252                if (!wallpaper.cropFile.exists()) {
1253                    return null;
1254                }
1255                return ParcelFileDescriptor.open(wallpaper.cropFile, MODE_READ_ONLY);
1256            } catch (FileNotFoundException e) {
1257                /* Shouldn't happen as we check to see if the file exists */
1258                Slog.w(TAG, "Error getting wallpaper", e);
1259            }
1260            return null;
1261        }
1262    }
1263
1264    @Override
1265    public WallpaperInfo getWallpaperInfo() {
1266        int userId = UserHandle.getCallingUserId();
1267        synchronized (mLock) {
1268            WallpaperData wallpaper = mWallpaperMap.get(userId);
1269            if (wallpaper != null && wallpaper.connection != null) {
1270                return wallpaper.connection.mInfo;
1271            }
1272            return null;
1273        }
1274    }
1275
1276    @Override
1277    public int getWallpaperIdForUser(int which, int userId) {
1278        userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1279                Binder.getCallingUid(), userId, false, true, "getWallpaperIdForUser", null);
1280
1281        if (which != FLAG_SYSTEM && which != FLAG_LOCK) {
1282            throw new IllegalArgumentException("Must specify exactly one kind of wallpaper");
1283        }
1284
1285        final SparseArray<WallpaperData> map =
1286                (which == FLAG_LOCK) ? mLockWallpaperMap : mWallpaperMap;
1287        synchronized (mLock) {
1288            WallpaperData wallpaper = map.get(userId);
1289            if (wallpaper != null) {
1290                return wallpaper.wallpaperId;
1291            }
1292        }
1293        return -1;
1294    }
1295
1296    @Override
1297    public boolean setLockWallpaperCallback(IWallpaperManagerCallback cb) {
1298        checkPermission(android.Manifest.permission.INTERNAL_SYSTEM_WINDOW);
1299        synchronized (mLock) {
1300            mKeyguardListener = cb;
1301        }
1302        return true;
1303    }
1304
1305    @Override
1306    public ParcelFileDescriptor setWallpaper(String name, String callingPackage,
1307            Rect cropHint, Bundle extras, int which, IWallpaperManagerCallback completion) {
1308        checkPermission(android.Manifest.permission.SET_WALLPAPER);
1309
1310        if ((which & (FLAG_LOCK|FLAG_SYSTEM)) == 0) {
1311            Slog.e(TAG, "Must specify a valid wallpaper category to set");
1312            return null;
1313        }
1314
1315        if (!isWallpaperSupported(callingPackage) || !isWallpaperSettingAllowed(callingPackage)) {
1316            return null;
1317        }
1318
1319        // "null" means the no-op crop, preserving the full input image
1320        if (cropHint == null) {
1321            cropHint = new Rect(0, 0, 0, 0);
1322        } else {
1323            if (cropHint.isEmpty()
1324                    || cropHint.left < 0
1325                    || cropHint.top < 0) {
1326                return null;
1327            }
1328        }
1329
1330        final int userId = UserHandle.getCallingUserId();
1331
1332        synchronized (mLock) {
1333            if (DEBUG) Slog.v(TAG, "setWallpaper which=0x" + Integer.toHexString(which));
1334            WallpaperData wallpaper;
1335
1336            wallpaper = getWallpaperSafeLocked(userId, which);
1337            final long ident = Binder.clearCallingIdentity();
1338            try {
1339                ParcelFileDescriptor pfd = updateWallpaperBitmapLocked(name, wallpaper, extras);
1340                if (pfd != null) {
1341                    wallpaper.imageWallpaperPending = true;
1342                    wallpaper.whichPending = which;
1343                    wallpaper.setComplete = completion;
1344                    wallpaper.cropHint.set(cropHint);
1345                }
1346                return pfd;
1347            } finally {
1348                Binder.restoreCallingIdentity(ident);
1349            }
1350        }
1351    }
1352
1353    ParcelFileDescriptor updateWallpaperBitmapLocked(String name, WallpaperData wallpaper,
1354            Bundle extras) {
1355        if (name == null) name = "";
1356        try {
1357            File dir = getWallpaperDir(wallpaper.userId);
1358            if (!dir.exists()) {
1359                dir.mkdir();
1360                FileUtils.setPermissions(
1361                        dir.getPath(),
1362                        FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1363                        -1, -1);
1364            }
1365            ParcelFileDescriptor fd = ParcelFileDescriptor.open(wallpaper.wallpaperFile,
1366                    MODE_CREATE|MODE_READ_WRITE|MODE_TRUNCATE);
1367            if (!SELinux.restorecon(wallpaper.wallpaperFile)) {
1368                return null;
1369            }
1370            wallpaper.name = name;
1371            wallpaper.wallpaperId = makeWallpaperIdLocked();
1372            if (extras != null) {
1373                extras.putInt(WallpaperManager.EXTRA_NEW_WALLPAPER_ID, wallpaper.wallpaperId);
1374            }
1375            if (DEBUG) {
1376                Slog.v(TAG, "updateWallpaperBitmapLocked() : id=" + wallpaper.wallpaperId
1377                        + " name=" + name + " file=" + wallpaper.wallpaperFile.getName());
1378            }
1379            return fd;
1380        } catch (FileNotFoundException e) {
1381            Slog.w(TAG, "Error setting wallpaper", e);
1382        }
1383        return null;
1384    }
1385
1386    @Override
1387    public void setWallpaperComponentChecked(ComponentName name, String callingPackage) {
1388        if (isWallpaperSupported(callingPackage) && isWallpaperSettingAllowed(callingPackage)) {
1389            setWallpaperComponent(name);
1390        }
1391    }
1392
1393    // ToDo: Remove this version of the function
1394    @Override
1395    public void setWallpaperComponent(ComponentName name) {
1396        checkPermission(android.Manifest.permission.SET_WALLPAPER_COMPONENT);
1397        synchronized (mLock) {
1398            if (DEBUG) Slog.v(TAG, "setWallpaperComponent name=" + name);
1399            int userId = UserHandle.getCallingUserId();
1400            WallpaperData wallpaper = mWallpaperMap.get(userId);
1401            if (wallpaper == null) {
1402                throw new IllegalStateException("Wallpaper not yet initialized for user " + userId);
1403            }
1404            final long ident = Binder.clearCallingIdentity();
1405            try {
1406                wallpaper.imageWallpaperPending = false;
1407                if (bindWallpaperComponentLocked(name, false, true, wallpaper, null)) {
1408                    wallpaper.wallpaperId = makeWallpaperIdLocked();
1409                    notifyCallbacksLocked(wallpaper);
1410                }
1411            } finally {
1412                Binder.restoreCallingIdentity(ident);
1413            }
1414        }
1415    }
1416
1417    boolean bindWallpaperComponentLocked(ComponentName componentName, boolean force,
1418            boolean fromUser, WallpaperData wallpaper, IRemoteCallback reply) {
1419        if (DEBUG) Slog.v(TAG, "bindWallpaperComponentLocked: componentName=" + componentName);
1420        // Has the component changed?
1421        if (!force) {
1422            if (wallpaper.connection != null) {
1423                if (wallpaper.wallpaperComponent == null) {
1424                    if (componentName == null) {
1425                        if (DEBUG) Slog.v(TAG, "bindWallpaperComponentLocked: still using default");
1426                        // Still using default wallpaper.
1427                        return true;
1428                    }
1429                } else if (wallpaper.wallpaperComponent.equals(componentName)) {
1430                    // Changing to same wallpaper.
1431                    if (DEBUG) Slog.v(TAG, "same wallpaper");
1432                    return true;
1433                }
1434            }
1435        }
1436
1437        try {
1438            if (componentName == null) {
1439                componentName = WallpaperManager.getDefaultWallpaperComponent(mContext);
1440                if (componentName == null) {
1441                    // Fall back to static image wallpaper
1442                    componentName = mImageWallpaper;
1443                    //clearWallpaperComponentLocked();
1444                    //return;
1445                    if (DEBUG) Slog.v(TAG, "Using image wallpaper");
1446                }
1447            }
1448            int serviceUserId = wallpaper.userId;
1449            ServiceInfo si = mIPackageManager.getServiceInfo(componentName,
1450                    PackageManager.GET_META_DATA | PackageManager.GET_PERMISSIONS, serviceUserId);
1451            if (si == null) {
1452                // The wallpaper component we're trying to use doesn't exist
1453                Slog.w(TAG, "Attempted wallpaper " + componentName + " is unavailable");
1454                return false;
1455            }
1456            if (!android.Manifest.permission.BIND_WALLPAPER.equals(si.permission)) {
1457                String msg = "Selected service does not require "
1458                        + android.Manifest.permission.BIND_WALLPAPER
1459                        + ": " + componentName;
1460                if (fromUser) {
1461                    throw new SecurityException(msg);
1462                }
1463                Slog.w(TAG, msg);
1464                return false;
1465            }
1466
1467            WallpaperInfo wi = null;
1468
1469            Intent intent = new Intent(WallpaperService.SERVICE_INTERFACE);
1470            if (componentName != null && !componentName.equals(mImageWallpaper)) {
1471                // Make sure the selected service is actually a wallpaper service.
1472                List<ResolveInfo> ris =
1473                        mIPackageManager.queryIntentServices(intent,
1474                                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
1475                                PackageManager.GET_META_DATA, serviceUserId).getList();
1476                for (int i=0; i<ris.size(); i++) {
1477                    ServiceInfo rsi = ris.get(i).serviceInfo;
1478                    if (rsi.name.equals(si.name) &&
1479                            rsi.packageName.equals(si.packageName)) {
1480                        try {
1481                            wi = new WallpaperInfo(mContext, ris.get(i));
1482                        } catch (XmlPullParserException e) {
1483                            if (fromUser) {
1484                                throw new IllegalArgumentException(e);
1485                            }
1486                            Slog.w(TAG, e);
1487                            return false;
1488                        } catch (IOException e) {
1489                            if (fromUser) {
1490                                throw new IllegalArgumentException(e);
1491                            }
1492                            Slog.w(TAG, e);
1493                            return false;
1494                        }
1495                        break;
1496                    }
1497                }
1498                if (wi == null) {
1499                    String msg = "Selected service is not a wallpaper: "
1500                            + componentName;
1501                    if (fromUser) {
1502                        throw new SecurityException(msg);
1503                    }
1504                    Slog.w(TAG, msg);
1505                    return false;
1506                }
1507            }
1508
1509            // Bind the service!
1510            if (DEBUG) Slog.v(TAG, "Binding to:" + componentName);
1511            WallpaperConnection newConn = new WallpaperConnection(wi, wallpaper);
1512            intent.setComponent(componentName);
1513            intent.putExtra(Intent.EXTRA_CLIENT_LABEL,
1514                    com.android.internal.R.string.wallpaper_binding_label);
1515            intent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivityAsUser(
1516                    mContext, 0,
1517                    Intent.createChooser(new Intent(Intent.ACTION_SET_WALLPAPER),
1518                            mContext.getText(com.android.internal.R.string.chooser_wallpaper)),
1519                    0, null, new UserHandle(serviceUserId)));
1520            if (!mContext.bindServiceAsUser(intent, newConn,
1521                    Context.BIND_AUTO_CREATE | Context.BIND_SHOWING_UI
1522                            | Context.BIND_FOREGROUND_SERVICE_WHILE_AWAKE,
1523                    new UserHandle(serviceUserId))) {
1524                String msg = "Unable to bind service: "
1525                        + componentName;
1526                if (fromUser) {
1527                    throw new IllegalArgumentException(msg);
1528                }
1529                Slog.w(TAG, msg);
1530                return false;
1531            }
1532            if (wallpaper.userId == mCurrentUserId && mLastWallpaper != null) {
1533                detachWallpaperLocked(mLastWallpaper);
1534            }
1535            wallpaper.wallpaperComponent = componentName;
1536            wallpaper.connection = newConn;
1537            newConn.mReply = reply;
1538            try {
1539                if (wallpaper.userId == mCurrentUserId) {
1540                    if (DEBUG)
1541                        Slog.v(TAG, "Adding window token: " + newConn.mToken);
1542                    mIWindowManager.addWindowToken(newConn.mToken,
1543                            WindowManager.LayoutParams.TYPE_WALLPAPER);
1544                    mLastWallpaper = wallpaper;
1545                }
1546            } catch (RemoteException e) {
1547            }
1548        } catch (RemoteException e) {
1549            String msg = "Remote exception for " + componentName + "\n" + e;
1550            if (fromUser) {
1551                throw new IllegalArgumentException(msg);
1552            }
1553            Slog.w(TAG, msg);
1554            return false;
1555        }
1556        return true;
1557    }
1558
1559    void detachWallpaperLocked(WallpaperData wallpaper) {
1560        if (wallpaper.connection != null) {
1561            if (wallpaper.connection.mReply != null) {
1562                try {
1563                    wallpaper.connection.mReply.sendResult(null);
1564                } catch (RemoteException e) {
1565                }
1566                wallpaper.connection.mReply = null;
1567            }
1568            if (wallpaper.connection.mEngine != null) {
1569                try {
1570                    wallpaper.connection.mEngine.destroy();
1571                } catch (RemoteException e) {
1572                }
1573            }
1574            mContext.unbindService(wallpaper.connection);
1575            try {
1576                if (DEBUG)
1577                    Slog.v(TAG, "Removing window token: " + wallpaper.connection.mToken);
1578                mIWindowManager.removeWindowToken(wallpaper.connection.mToken);
1579            } catch (RemoteException e) {
1580            }
1581            wallpaper.connection.mService = null;
1582            wallpaper.connection.mEngine = null;
1583            wallpaper.connection = null;
1584        }
1585    }
1586
1587    void clearWallpaperComponentLocked(WallpaperData wallpaper) {
1588        wallpaper.wallpaperComponent = null;
1589        detachWallpaperLocked(wallpaper);
1590    }
1591
1592    void attachServiceLocked(WallpaperConnection conn, WallpaperData wallpaper) {
1593        try {
1594            conn.mService.attach(conn, conn.mToken,
1595                    WindowManager.LayoutParams.TYPE_WALLPAPER, false,
1596                    wallpaper.width, wallpaper.height, wallpaper.padding);
1597        } catch (RemoteException e) {
1598            Slog.w(TAG, "Failed attaching wallpaper; clearing", e);
1599            if (!wallpaper.wallpaperUpdating) {
1600                bindWallpaperComponentLocked(null, false, false, wallpaper, null);
1601            }
1602        }
1603    }
1604
1605    private void notifyCallbacksLocked(WallpaperData wallpaper) {
1606        final int n = wallpaper.callbacks.beginBroadcast();
1607        for (int i = 0; i < n; i++) {
1608            try {
1609                wallpaper.callbacks.getBroadcastItem(i).onWallpaperChanged();
1610            } catch (RemoteException e) {
1611
1612                // The RemoteCallbackList will take care of removing
1613                // the dead object for us.
1614            }
1615        }
1616        wallpaper.callbacks.finishBroadcast();
1617        final Intent intent = new Intent(Intent.ACTION_WALLPAPER_CHANGED);
1618        mContext.sendBroadcastAsUser(intent, new UserHandle(mCurrentUserId));
1619    }
1620
1621    private void checkPermission(String permission) {
1622        if (PackageManager.PERMISSION_GRANTED!= mContext.checkCallingOrSelfPermission(permission)) {
1623            throw new SecurityException("Access denied to process: " + Binder.getCallingPid()
1624                    + ", must have permission " + permission);
1625        }
1626    }
1627
1628    /**
1629     * Certain user types do not support wallpapers (e.g. managed profiles). The check is
1630     * implemented through through the OP_WRITE_WALLPAPER AppOp.
1631     */
1632    public boolean isWallpaperSupported(String callingPackage) {
1633        return mAppOpsManager.checkOpNoThrow(AppOpsManager.OP_WRITE_WALLPAPER, Binder.getCallingUid(),
1634                callingPackage) == AppOpsManager.MODE_ALLOWED;
1635    }
1636
1637    @Override
1638    public boolean isWallpaperSettingAllowed(String callingPackage) {
1639        final PackageManager pm = mContext.getPackageManager();
1640        String[] uidPackages = pm.getPackagesForUid(Binder.getCallingUid());
1641        boolean uidMatchPackage = Arrays.asList(uidPackages).contains(callingPackage);
1642        if (!uidMatchPackage) {
1643            return false;   // callingPackage was faked.
1644        }
1645
1646        final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
1647        if (dpm.isDeviceOwnerApp(callingPackage) || dpm.isProfileOwnerApp(callingPackage)) {
1648            return true;
1649        }
1650        final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1651        return !um.hasUserRestriction(UserManager.DISALLOW_SET_WALLPAPER);
1652    }
1653
1654    private static JournaledFile makeJournaledFile(int userId) {
1655        final String base = new File(getWallpaperDir(userId), WALLPAPER_INFO).getAbsolutePath();
1656        return new JournaledFile(new File(base), new File(base + ".tmp"));
1657    }
1658
1659    private void saveSettingsLocked(int userId) {
1660        JournaledFile journal = makeJournaledFile(userId);
1661        FileOutputStream fstream = null;
1662        BufferedOutputStream stream = null;
1663        try {
1664            XmlSerializer out = new FastXmlSerializer();
1665            fstream = new FileOutputStream(journal.chooseForWrite(), false);
1666            stream = new BufferedOutputStream(fstream);
1667            out.setOutput(stream, StandardCharsets.UTF_8.name());
1668            out.startDocument(null, true);
1669
1670            WallpaperData wallpaper;
1671
1672            wallpaper = mWallpaperMap.get(userId);
1673            if (wallpaper != null) {
1674                writeWallpaperAttributes(out, "wp", wallpaper);
1675            }
1676            wallpaper = mLockWallpaperMap.get(userId);
1677            if (wallpaper != null) {
1678                writeWallpaperAttributes(out, "kwp", wallpaper);
1679            }
1680
1681            out.endDocument();
1682
1683            stream.flush(); // also flushes fstream
1684            FileUtils.sync(fstream);
1685            stream.close(); // also closes fstream
1686            journal.commit();
1687        } catch (IOException e) {
1688            IoUtils.closeQuietly(stream);
1689            journal.rollback();
1690        }
1691    }
1692
1693    private void writeWallpaperAttributes(XmlSerializer out, String tag, WallpaperData wallpaper)
1694            throws IllegalArgumentException, IllegalStateException, IOException {
1695        out.startTag(null, tag);
1696        out.attribute(null, "id", Integer.toString(wallpaper.wallpaperId));
1697        out.attribute(null, "width", Integer.toString(wallpaper.width));
1698        out.attribute(null, "height", Integer.toString(wallpaper.height));
1699
1700        out.attribute(null, "cropLeft", Integer.toString(wallpaper.cropHint.left));
1701        out.attribute(null, "cropTop", Integer.toString(wallpaper.cropHint.top));
1702        out.attribute(null, "cropRight", Integer.toString(wallpaper.cropHint.right));
1703        out.attribute(null, "cropBottom", Integer.toString(wallpaper.cropHint.bottom));
1704
1705        if (wallpaper.padding.left != 0) {
1706            out.attribute(null, "paddingLeft", Integer.toString(wallpaper.padding.left));
1707        }
1708        if (wallpaper.padding.top != 0) {
1709            out.attribute(null, "paddingTop", Integer.toString(wallpaper.padding.top));
1710        }
1711        if (wallpaper.padding.right != 0) {
1712            out.attribute(null, "paddingRight", Integer.toString(wallpaper.padding.right));
1713        }
1714        if (wallpaper.padding.bottom != 0) {
1715            out.attribute(null, "paddingBottom", Integer.toString(wallpaper.padding.bottom));
1716        }
1717
1718        out.attribute(null, "name", wallpaper.name);
1719        if (wallpaper.wallpaperComponent != null
1720                && !wallpaper.wallpaperComponent.equals(mImageWallpaper)) {
1721            out.attribute(null, "component",
1722                    wallpaper.wallpaperComponent.flattenToShortString());
1723        }
1724        out.endTag(null, tag);
1725    }
1726
1727    private void migrateFromOld() {
1728        File oldWallpaper = new File(WallpaperBackupHelper.WALLPAPER_IMAGE_KEY);
1729        File oldInfo = new File(WallpaperBackupHelper.WALLPAPER_INFO_KEY);
1730        if (oldWallpaper.exists()) {
1731            File newWallpaper = new File(getWallpaperDir(0), WALLPAPER);
1732            oldWallpaper.renameTo(newWallpaper);
1733        }
1734        if (oldInfo.exists()) {
1735            File newInfo = new File(getWallpaperDir(0), WALLPAPER_INFO);
1736            oldInfo.renameTo(newInfo);
1737        }
1738    }
1739
1740    private int getAttributeInt(XmlPullParser parser, String name, int defValue) {
1741        String value = parser.getAttributeValue(null, name);
1742        if (value == null) {
1743            return defValue;
1744        }
1745        return Integer.parseInt(value);
1746    }
1747
1748    /**
1749     * Sometimes it is expected the wallpaper map may not have a user's data.  E.g. This could
1750     * happen during user switch.  The async user switch observer may not have received
1751     * the event yet.  We use this safe method when we don't care about this ordering and just
1752     * want to update the data.  The data is going to be applied when the user switch observer
1753     * is eventually executed.
1754     */
1755    private WallpaperData getWallpaperSafeLocked(int userId, int which) {
1756        // We're setting either just system (work with the system wallpaper),
1757        // both (also work with the system wallpaper), or just the lock
1758        // wallpaper (update against the existing lock wallpaper if any).
1759        // Combined or just-system operations use the 'system' WallpaperData
1760        // for this use; lock-only operations use the dedicated one.
1761        final SparseArray<WallpaperData> whichSet =
1762                (which == FLAG_LOCK) ? mLockWallpaperMap : mWallpaperMap;
1763        WallpaperData wallpaper = whichSet.get(userId);
1764        if (wallpaper == null) {
1765            // common case, this is the first lookup post-boot of the system or
1766            // unified lock, so we bring up the saved state lazily now and recheck.
1767            loadSettingsLocked(userId);
1768            wallpaper = whichSet.get(userId);
1769            // if it's still null here, this is a lock-only operation and there is not
1770            // yet a lock-only wallpaper set for this user, so we need to establish
1771            // it now.
1772            if (wallpaper == null) {
1773                if (which == FLAG_LOCK) {
1774                    wallpaper = new WallpaperData(userId,
1775                            WALLPAPER_LOCK_ORIG, WALLPAPER_LOCK_CROP);
1776                    mLockWallpaperMap.put(userId, wallpaper);
1777                    ensureSaneWallpaperData(wallpaper);
1778                } else {
1779                    // sanity fallback: we're in bad shape, but establishing a known
1780                    // valid system+lock WallpaperData will keep us from dying.
1781                    Slog.wtf(TAG, "Didn't find wallpaper in non-lock case!");
1782                    wallpaper = new WallpaperData(userId, WALLPAPER, WALLPAPER_CROP);
1783                    mWallpaperMap.put(userId, wallpaper);
1784                    ensureSaneWallpaperData(wallpaper);
1785                }
1786            }
1787        }
1788        return wallpaper;
1789    }
1790
1791    private void loadSettingsLocked(int userId) {
1792        if (DEBUG) Slog.v(TAG, "loadSettingsLocked");
1793
1794        JournaledFile journal = makeJournaledFile(userId);
1795        FileInputStream stream = null;
1796        File file = journal.chooseForRead();
1797        if (!file.exists()) {
1798            // This should only happen one time, when upgrading from a legacy system
1799            migrateFromOld();
1800        }
1801        WallpaperData wallpaper = mWallpaperMap.get(userId);
1802        if (wallpaper == null) {
1803            wallpaper = new WallpaperData(userId, WALLPAPER, WALLPAPER_CROP);
1804            mWallpaperMap.put(userId, wallpaper);
1805            if (!wallpaper.cropExists()) {
1806                generateCrop(wallpaper);
1807            }
1808        }
1809        boolean success = false;
1810        try {
1811            stream = new FileInputStream(file);
1812            XmlPullParser parser = Xml.newPullParser();
1813            parser.setInput(stream, StandardCharsets.UTF_8.name());
1814
1815            int type;
1816            do {
1817                type = parser.next();
1818                if (type == XmlPullParser.START_TAG) {
1819                    String tag = parser.getName();
1820                    if ("wp".equals(tag)) {
1821                        // Common to system + lock wallpapers
1822                        parseWallpaperAttributes(parser, wallpaper);
1823
1824                        // A system wallpaper might also be a live wallpaper
1825                        String comp = parser.getAttributeValue(null, "component");
1826                        wallpaper.nextWallpaperComponent = comp != null
1827                                ? ComponentName.unflattenFromString(comp)
1828                                : null;
1829                        if (wallpaper.nextWallpaperComponent == null
1830                                || "android".equals(wallpaper.nextWallpaperComponent
1831                                        .getPackageName())) {
1832                            wallpaper.nextWallpaperComponent = mImageWallpaper;
1833                        }
1834
1835                        if (DEBUG) {
1836                            Slog.v(TAG, "mWidth:" + wallpaper.width);
1837                            Slog.v(TAG, "mHeight:" + wallpaper.height);
1838                            Slog.v(TAG, "cropRect:" + wallpaper.cropHint);
1839                            Slog.v(TAG, "mName:" + wallpaper.name);
1840                            Slog.v(TAG, "mNextWallpaperComponent:"
1841                                    + wallpaper.nextWallpaperComponent);
1842                        }
1843                    } else if ("kwp".equals(tag)) {
1844                        // keyguard-specific wallpaper for this user
1845                        WallpaperData lockWallpaper = mLockWallpaperMap.get(userId);
1846                        if (lockWallpaper == null) {
1847                            lockWallpaper = new WallpaperData(userId,
1848                                    WALLPAPER_LOCK_ORIG, WALLPAPER_LOCK_CROP);
1849                            mLockWallpaperMap.put(userId, lockWallpaper);
1850                        }
1851                        parseWallpaperAttributes(parser, lockWallpaper);
1852                    }
1853                }
1854            } while (type != XmlPullParser.END_DOCUMENT);
1855            success = true;
1856        } catch (FileNotFoundException e) {
1857            Slog.w(TAG, "no current wallpaper -- first boot?");
1858        } catch (NullPointerException e) {
1859            Slog.w(TAG, "failed parsing " + file + " " + e);
1860        } catch (NumberFormatException e) {
1861            Slog.w(TAG, "failed parsing " + file + " " + e);
1862        } catch (XmlPullParserException e) {
1863            Slog.w(TAG, "failed parsing " + file + " " + e);
1864        } catch (IOException e) {
1865            Slog.w(TAG, "failed parsing " + file + " " + e);
1866        } catch (IndexOutOfBoundsException e) {
1867            Slog.w(TAG, "failed parsing " + file + " " + e);
1868        }
1869        IoUtils.closeQuietly(stream);
1870
1871        if (!success) {
1872            wallpaper.width = -1;
1873            wallpaper.height = -1;
1874            wallpaper.cropHint.set(0, 0, 0, 0);
1875            wallpaper.padding.set(0, 0, 0, 0);
1876            wallpaper.name = "";
1877
1878            mLockWallpaperMap.remove(userId);
1879        } else {
1880            if (wallpaper.wallpaperId <= 0) {
1881                wallpaper.wallpaperId = makeWallpaperIdLocked();
1882                if (DEBUG) {
1883                    Slog.w(TAG, "Didn't set wallpaper id in loadSettingsLocked(" + userId
1884                            + "); now " + wallpaper.wallpaperId);
1885                }
1886            }
1887        }
1888
1889        ensureSaneWallpaperData(wallpaper);
1890        WallpaperData lockWallpaper = mLockWallpaperMap.get(userId);
1891        if (lockWallpaper != null) {
1892            ensureSaneWallpaperData(lockWallpaper);
1893        }
1894    }
1895
1896    private void ensureSaneWallpaperData(WallpaperData wallpaper) {
1897        // We always want to have some reasonable width hint.
1898        int baseSize = getMaximumSizeDimension();
1899        if (wallpaper.width < baseSize) {
1900            wallpaper.width = baseSize;
1901        }
1902        if (wallpaper.height < baseSize) {
1903            wallpaper.height = baseSize;
1904        }
1905        // and crop, if not previously specified
1906        if (wallpaper.cropHint.width() <= 0
1907                || wallpaper.cropHint.height() <= 0) {
1908            wallpaper.cropHint.set(0, 0, wallpaper.width, wallpaper.height);
1909        }
1910    }
1911
1912    private void parseWallpaperAttributes(XmlPullParser parser, WallpaperData wallpaper) {
1913        final String idString = parser.getAttributeValue(null, "id");
1914        if (idString != null) {
1915            final int id = wallpaper.wallpaperId = Integer.parseInt(idString);
1916            if (id > mWallpaperId) {
1917                mWallpaperId = id;
1918            }
1919        } else {
1920            wallpaper.wallpaperId = makeWallpaperIdLocked();
1921        }
1922
1923        wallpaper.width = Integer.parseInt(parser.getAttributeValue(null, "width"));
1924        wallpaper.height = Integer.parseInt(parser
1925                .getAttributeValue(null, "height"));
1926        wallpaper.cropHint.left = getAttributeInt(parser, "cropLeft", 0);
1927        wallpaper.cropHint.top = getAttributeInt(parser, "cropTop", 0);
1928        wallpaper.cropHint.right = getAttributeInt(parser, "cropRight", 0);
1929        wallpaper.cropHint.bottom = getAttributeInt(parser, "cropBottom", 0);
1930        wallpaper.padding.left = getAttributeInt(parser, "paddingLeft", 0);
1931        wallpaper.padding.top = getAttributeInt(parser, "paddingTop", 0);
1932        wallpaper.padding.right = getAttributeInt(parser, "paddingRight", 0);
1933        wallpaper.padding.bottom = getAttributeInt(parser, "paddingBottom", 0);
1934        wallpaper.name = parser.getAttributeValue(null, "name");
1935    }
1936
1937    private int getMaximumSizeDimension() {
1938        WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
1939        Display d = wm.getDefaultDisplay();
1940        return d.getMaximumSizeDimension();
1941    }
1942
1943    // Called by SystemBackupAgent after files are restored to disk.
1944    public void settingsRestored() {
1945        // Verify caller is the system
1946        if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
1947            throw new RuntimeException("settingsRestored() can only be called from the system process");
1948        }
1949        // TODO: If necessary, make it work for secondary users as well. This currently assumes
1950        // restores only to the primary user
1951        if (DEBUG) Slog.v(TAG, "settingsRestored");
1952        WallpaperData wallpaper = null;
1953        boolean success = false;
1954        synchronized (mLock) {
1955            loadSettingsLocked(UserHandle.USER_SYSTEM);
1956            wallpaper = mWallpaperMap.get(UserHandle.USER_SYSTEM);
1957            wallpaper.wallpaperId = makeWallpaperIdLocked();    // always bump id at restore
1958            if (wallpaper.nextWallpaperComponent != null
1959                    && !wallpaper.nextWallpaperComponent.equals(mImageWallpaper)) {
1960                if (!bindWallpaperComponentLocked(wallpaper.nextWallpaperComponent, false, false,
1961                        wallpaper, null)) {
1962                    // No such live wallpaper or other failure; fall back to the default
1963                    // live wallpaper (since the profile being restored indicated that the
1964                    // user had selected a live rather than static one).
1965                    bindWallpaperComponentLocked(null, false, false, wallpaper, null);
1966                }
1967                success = true;
1968            } else {
1969                // If there's a wallpaper name, we use that.  If that can't be loaded, then we
1970                // use the default.
1971                if ("".equals(wallpaper.name)) {
1972                    if (DEBUG) Slog.v(TAG, "settingsRestored: name is empty");
1973                    success = true;
1974                } else {
1975                    if (DEBUG) Slog.v(TAG, "settingsRestored: attempting to restore named resource");
1976                    success = restoreNamedResourceLocked(wallpaper);
1977                }
1978                if (DEBUG) Slog.v(TAG, "settingsRestored: success=" + success
1979                        + " id=" + wallpaper.wallpaperId);
1980                if (success) {
1981                    generateCrop(wallpaper);    // based on the new image + metadata
1982                    bindWallpaperComponentLocked(wallpaper.nextWallpaperComponent, true, false,
1983                            wallpaper, null);
1984                }
1985            }
1986        }
1987
1988        if (!success) {
1989            Slog.e(TAG, "Failed to restore wallpaper: '" + wallpaper.name + "'");
1990            wallpaper.name = "";
1991            getWallpaperDir(UserHandle.USER_SYSTEM).delete();
1992        }
1993
1994        synchronized (mLock) {
1995            saveSettingsLocked(UserHandle.USER_SYSTEM);
1996        }
1997    }
1998
1999    // Restore the named resource bitmap to both source + crop files
2000    boolean restoreNamedResourceLocked(WallpaperData wallpaper) {
2001        if (wallpaper.name.length() > 4 && "res:".equals(wallpaper.name.substring(0, 4))) {
2002            String resName = wallpaper.name.substring(4);
2003
2004            String pkg = null;
2005            int colon = resName.indexOf(':');
2006            if (colon > 0) {
2007                pkg = resName.substring(0, colon);
2008            }
2009
2010            String ident = null;
2011            int slash = resName.lastIndexOf('/');
2012            if (slash > 0) {
2013                ident = resName.substring(slash+1);
2014            }
2015
2016            String type = null;
2017            if (colon > 0 && slash > 0 && (slash-colon) > 1) {
2018                type = resName.substring(colon+1, slash);
2019            }
2020
2021            if (pkg != null && ident != null && type != null) {
2022                int resId = -1;
2023                InputStream res = null;
2024                FileOutputStream fos = null;
2025                FileOutputStream cos = null;
2026                try {
2027                    Context c = mContext.createPackageContext(pkg, Context.CONTEXT_RESTRICTED);
2028                    Resources r = c.getResources();
2029                    resId = r.getIdentifier(resName, null, null);
2030                    if (resId == 0) {
2031                        Slog.e(TAG, "couldn't resolve identifier pkg=" + pkg + " type=" + type
2032                                + " ident=" + ident);
2033                        return false;
2034                    }
2035
2036                    res = r.openRawResource(resId);
2037                    if (wallpaper.wallpaperFile.exists()) {
2038                        wallpaper.wallpaperFile.delete();
2039                        wallpaper.cropFile.delete();
2040                    }
2041                    fos = new FileOutputStream(wallpaper.wallpaperFile);
2042                    cos = new FileOutputStream(wallpaper.cropFile);
2043
2044                    byte[] buffer = new byte[32768];
2045                    int amt;
2046                    while ((amt=res.read(buffer)) > 0) {
2047                        fos.write(buffer, 0, amt);
2048                        cos.write(buffer, 0, amt);
2049                    }
2050                    // mWallpaperObserver will notice the close and send the change broadcast
2051
2052                    Slog.v(TAG, "Restored wallpaper: " + resName);
2053                    return true;
2054                } catch (NameNotFoundException e) {
2055                    Slog.e(TAG, "Package name " + pkg + " not found");
2056                } catch (Resources.NotFoundException e) {
2057                    Slog.e(TAG, "Resource not found: " + resId);
2058                } catch (IOException e) {
2059                    Slog.e(TAG, "IOException while restoring wallpaper ", e);
2060                } finally {
2061                    IoUtils.closeQuietly(res);
2062                    if (fos != null) {
2063                        FileUtils.sync(fos);
2064                    }
2065                    if (cos != null) {
2066                        FileUtils.sync(cos);
2067                    }
2068                    IoUtils.closeQuietly(fos);
2069                    IoUtils.closeQuietly(cos);
2070                }
2071            }
2072        }
2073        return false;
2074    }
2075
2076    @Override
2077    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2078        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2079                != PackageManager.PERMISSION_GRANTED) {
2080
2081            pw.println("Permission Denial: can't dump wallpaper service from from pid="
2082                    + Binder.getCallingPid()
2083                    + ", uid=" + Binder.getCallingUid());
2084            return;
2085        }
2086
2087        synchronized (mLock) {
2088            pw.println("System wallpaper state:");
2089            for (int i = 0; i < mWallpaperMap.size(); i++) {
2090                WallpaperData wallpaper = mWallpaperMap.valueAt(i);
2091                pw.print(" User "); pw.print(wallpaper.userId);
2092                    pw.print(": id="); pw.println(wallpaper.wallpaperId);
2093                pw.print("  mWidth=");
2094                    pw.print(wallpaper.width);
2095                    pw.print(" mHeight=");
2096                    pw.println(wallpaper.height);
2097                pw.print("  mCropHint="); pw.println(wallpaper.cropHint);
2098                pw.print("  mPadding="); pw.println(wallpaper.padding);
2099                pw.print("  mName=");  pw.println(wallpaper.name);
2100                pw.print("  mWallpaperComponent="); pw.println(wallpaper.wallpaperComponent);
2101                if (wallpaper.connection != null) {
2102                    WallpaperConnection conn = wallpaper.connection;
2103                    pw.print("  Wallpaper connection ");
2104                    pw.print(conn);
2105                    pw.println(":");
2106                    if (conn.mInfo != null) {
2107                        pw.print("    mInfo.component=");
2108                        pw.println(conn.mInfo.getComponent());
2109                    }
2110                    pw.print("    mToken=");
2111                    pw.println(conn.mToken);
2112                    pw.print("    mService=");
2113                    pw.println(conn.mService);
2114                    pw.print("    mEngine=");
2115                    pw.println(conn.mEngine);
2116                    pw.print("    mLastDiedTime=");
2117                    pw.println(wallpaper.lastDiedTime - SystemClock.uptimeMillis());
2118                }
2119            }
2120            pw.println("Lock wallpaper state:");
2121            for (int i = 0; i < mLockWallpaperMap.size(); i++) {
2122                WallpaperData wallpaper = mLockWallpaperMap.valueAt(i);
2123                pw.print(" User "); pw.print(wallpaper.userId);
2124                    pw.print(": id="); pw.println(wallpaper.wallpaperId);
2125                pw.print("  mWidth="); pw.print(wallpaper.width);
2126                    pw.print(" mHeight="); pw.println(wallpaper.height);
2127                pw.print("  mCropHint="); pw.println(wallpaper.cropHint);
2128                pw.print("  mPadding="); pw.println(wallpaper.padding);
2129                pw.print("  mName=");  pw.println(wallpaper.name);
2130            }
2131
2132        }
2133    }
2134}
2135