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