WallpaperManagerService.java revision ecd827ac0d7a62ea81b8123120be1fe6424c2338
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.os.ParcelFileDescriptor.*;
20
21import android.app.ActivityManagerNative;
22import android.app.AppGlobals;
23import android.app.IUserSwitchObserver;
24import android.app.IWallpaperManager;
25import android.app.IWallpaperManagerCallback;
26import android.app.PendingIntent;
27import android.app.WallpaperInfo;
28import android.app.WallpaperManager;
29import android.app.backup.BackupManager;
30import android.app.backup.WallpaperBackupHelper;
31import android.content.BroadcastReceiver;
32import android.content.ComponentName;
33import android.content.Context;
34import android.content.Intent;
35import android.content.IntentFilter;
36import android.content.ServiceConnection;
37import android.content.pm.IPackageManager;
38import android.content.pm.PackageManager;
39import android.content.pm.ResolveInfo;
40import android.content.pm.ServiceInfo;
41import android.content.pm.PackageManager.NameNotFoundException;
42import android.content.pm.UserInfo;
43import android.content.res.Resources;
44import android.graphics.Point;
45import android.os.Binder;
46import android.os.Bundle;
47import android.os.Environment;
48import android.os.FileUtils;
49import android.os.IBinder;
50import android.os.IRemoteCallback;
51import android.os.RemoteException;
52import android.os.FileObserver;
53import android.os.ParcelFileDescriptor;
54import android.os.RemoteCallbackList;
55import android.os.SELinux;
56import android.os.ServiceManager;
57import android.os.SystemClock;
58import android.os.UserHandle;
59import android.os.UserManager;
60import android.service.wallpaper.IWallpaperConnection;
61import android.service.wallpaper.IWallpaperEngine;
62import android.service.wallpaper.IWallpaperService;
63import android.service.wallpaper.WallpaperService;
64import android.util.Slog;
65import android.util.SparseArray;
66import android.util.Xml;
67import android.view.Display;
68import android.view.IWindowManager;
69import android.view.WindowManager;
70
71import java.io.FileDescriptor;
72import java.io.IOException;
73import java.io.InputStream;
74import java.io.File;
75import java.io.FileNotFoundException;
76import java.io.FileInputStream;
77import java.io.FileOutputStream;
78import java.io.PrintWriter;
79import java.util.List;
80
81import org.xmlpull.v1.XmlPullParser;
82import org.xmlpull.v1.XmlPullParserException;
83import org.xmlpull.v1.XmlSerializer;
84
85import com.android.internal.content.PackageMonitor;
86import com.android.internal.util.FastXmlSerializer;
87import com.android.internal.util.JournaledFile;
88import com.android.internal.R;
89
90public class WallpaperManagerService extends IWallpaperManager.Stub {
91    static final String TAG = "WallpaperManagerService";
92    static final boolean DEBUG = false;
93
94    final Object mLock = new Object[0];
95
96    /**
97     * Minimum time between crashes of a wallpaper service for us to consider
98     * restarting it vs. just reverting to the static wallpaper.
99     */
100    static final long MIN_WALLPAPER_CRASH_TIME = 10000;
101    static final String WALLPAPER = "wallpaper";
102    static final String WALLPAPER_INFO = "wallpaper_info.xml";
103
104    /**
105     * Observes the wallpaper for changes and notifies all IWallpaperServiceCallbacks
106     * that the wallpaper has changed. The CREATE is triggered when there is no
107     * wallpaper set and is created for the first time. The CLOSE_WRITE is triggered
108     * everytime the wallpaper is changed.
109     */
110    private class WallpaperObserver extends FileObserver {
111
112        final WallpaperData mWallpaper;
113        final File mWallpaperDir;
114        final File mWallpaperFile;
115
116        public WallpaperObserver(WallpaperData wallpaper) {
117            super(getWallpaperDir(wallpaper.userId).getAbsolutePath(),
118                    CLOSE_WRITE | DELETE | DELETE_SELF);
119            mWallpaperDir = getWallpaperDir(wallpaper.userId);
120            mWallpaper = wallpaper;
121            mWallpaperFile = new File(mWallpaperDir, WALLPAPER);
122        }
123
124        @Override
125        public void onEvent(int event, String path) {
126            if (path == null) {
127                return;
128            }
129            synchronized (mLock) {
130                // changing the wallpaper means we'll need to back up the new one
131                long origId = Binder.clearCallingIdentity();
132                BackupManager bm = new BackupManager(mContext);
133                bm.dataChanged();
134                Binder.restoreCallingIdentity(origId);
135
136                File changedFile = new File(mWallpaperDir, path);
137                if (mWallpaperFile.equals(changedFile)) {
138                    notifyCallbacksLocked(mWallpaper);
139                    if (mWallpaper.wallpaperComponent == null || event != CLOSE_WRITE
140                            || mWallpaper.imageWallpaperPending) {
141                        if (event == CLOSE_WRITE) {
142                            mWallpaper.imageWallpaperPending = false;
143                        }
144                        bindWallpaperComponentLocked(mImageWallpaper, true,
145                                false, mWallpaper, null);
146                        saveSettingsLocked(mWallpaper);
147                    }
148                }
149            }
150        }
151    }
152
153    final Context mContext;
154    final IWindowManager mIWindowManager;
155    final IPackageManager mIPackageManager;
156    final MyPackageMonitor mMonitor;
157    WallpaperData mLastWallpaper;
158
159    /**
160     * Name of the component used to display bitmap wallpapers from either the gallery or
161     * built-in wallpapers.
162     */
163    final ComponentName mImageWallpaper;
164
165    SparseArray<WallpaperData> mWallpaperMap = new SparseArray<WallpaperData>();
166
167    int mCurrentUserId;
168
169    static class WallpaperData {
170
171        int userId;
172
173        File wallpaperFile;
174
175        /**
176         * Client is currently writing a new image wallpaper.
177         */
178        boolean imageWallpaperPending;
179
180        /**
181         * Resource name if using a picture from the wallpaper gallery
182         */
183        String name = "";
184
185        /**
186         * The component name of the currently set live wallpaper.
187         */
188        ComponentName wallpaperComponent;
189
190        /**
191         * The component name of the wallpaper that should be set next.
192         */
193        ComponentName nextWallpaperComponent;
194
195        WallpaperConnection connection;
196        long lastDiedTime;
197        boolean wallpaperUpdating;
198        WallpaperObserver wallpaperObserver;
199
200        /**
201         * List of callbacks registered they should each be notified when the wallpaper is changed.
202         */
203        private RemoteCallbackList<IWallpaperManagerCallback> callbacks
204                = new RemoteCallbackList<IWallpaperManagerCallback>();
205
206        int width = -1;
207        int height = -1;
208
209        WallpaperData(int userId) {
210            this.userId = userId;
211            wallpaperFile = new File(getWallpaperDir(userId), WALLPAPER);
212        }
213    }
214
215    class WallpaperConnection extends IWallpaperConnection.Stub
216            implements ServiceConnection {
217        final WallpaperInfo mInfo;
218        final Binder mToken = new Binder();
219        IWallpaperService mService;
220        IWallpaperEngine mEngine;
221        WallpaperData mWallpaper;
222        IRemoteCallback mReply;
223
224        boolean mDimensionsChanged = false;
225
226        public WallpaperConnection(WallpaperInfo info, WallpaperData wallpaper) {
227            mInfo = info;
228            mWallpaper = wallpaper;
229        }
230
231        @Override
232        public void onServiceConnected(ComponentName name, IBinder service) {
233            synchronized (mLock) {
234                if (mWallpaper.connection == this) {
235                    mService = IWallpaperService.Stub.asInterface(service);
236                    attachServiceLocked(this, mWallpaper);
237                    // XXX should probably do saveSettingsLocked() later
238                    // when we have an engine, but I'm not sure about
239                    // locking there and anyway we always need to be able to
240                    // recover if there is something wrong.
241                    saveSettingsLocked(mWallpaper);
242                }
243            }
244        }
245
246        @Override
247        public void onServiceDisconnected(ComponentName name) {
248            synchronized (mLock) {
249                mService = null;
250                mEngine = null;
251                if (mWallpaper.connection == this) {
252                    Slog.w(TAG, "Wallpaper service gone: " + mWallpaper.wallpaperComponent);
253                    if (!mWallpaper.wallpaperUpdating
254                            && mWallpaper.userId == mCurrentUserId) {
255                        // There is a race condition which causes
256                        // {@link #mWallpaper.wallpaperUpdating} to be false even if it is
257                        // currently updating since the broadcast notifying us is async.
258                        // This race is overcome by the general rule that we only reset the
259                        // wallpaper if its service was shut down twice
260                        // during {@link #MIN_WALLPAPER_CRASH_TIME} millis.
261                        if (mWallpaper.lastDiedTime != 0
262                                && mWallpaper.lastDiedTime + MIN_WALLPAPER_CRASH_TIME
263                                    > SystemClock.uptimeMillis()) {
264                            Slog.w(TAG, "Reverting to built-in wallpaper!");
265                            clearWallpaperLocked(true, mWallpaper.userId, null);
266                        } else {
267                            mWallpaper.lastDiedTime = SystemClock.uptimeMillis();
268                        }
269                    }
270                }
271            }
272        }
273
274        @Override
275        public void attachEngine(IWallpaperEngine engine) {
276            synchronized (mLock) {
277                mEngine = engine;
278                if (mDimensionsChanged) {
279                    try {
280                        mEngine.setDesiredSize(mWallpaper.width, mWallpaper.height);
281                    } catch (RemoteException e) {
282                        Slog.w(TAG, "Failed to set wallpaper dimensions", e);
283                    }
284                    mDimensionsChanged = false;
285                }
286            }
287        }
288
289        @Override
290        public void engineShown(IWallpaperEngine engine) {
291            synchronized (mLock) {
292                if (mReply != null) {
293                    long ident = Binder.clearCallingIdentity();
294                    try {
295                        mReply.sendResult(null);
296                    } catch (RemoteException e) {
297                        Binder.restoreCallingIdentity(ident);
298                    }
299                    mReply = null;
300                }
301            }
302        }
303
304        @Override
305        public ParcelFileDescriptor setWallpaper(String name) {
306            synchronized (mLock) {
307                if (mWallpaper.connection == this) {
308                    return updateWallpaperBitmapLocked(name, mWallpaper);
309                }
310                return null;
311            }
312        }
313    }
314
315    class MyPackageMonitor extends PackageMonitor {
316        @Override
317        public void onPackageUpdateFinished(String packageName, int uid) {
318            synchronized (mLock) {
319                if (mCurrentUserId != getChangingUserId()) {
320                    return;
321                }
322                WallpaperData wallpaper = mWallpaperMap.get(mCurrentUserId);
323                if (wallpaper != null) {
324                    if (wallpaper.wallpaperComponent != null
325                            && wallpaper.wallpaperComponent.getPackageName().equals(packageName)) {
326                        wallpaper.wallpaperUpdating = false;
327                        ComponentName comp = wallpaper.wallpaperComponent;
328                        clearWallpaperComponentLocked(wallpaper);
329                        if (!bindWallpaperComponentLocked(comp, false, false,
330                                wallpaper, null)) {
331                            Slog.w(TAG, "Wallpaper no longer available; reverting to default");
332                            clearWallpaperLocked(false, wallpaper.userId, null);
333                        }
334                    }
335                }
336            }
337        }
338
339        @Override
340        public void onPackageModified(String packageName) {
341            synchronized (mLock) {
342                if (mCurrentUserId != getChangingUserId()) {
343                    return;
344                }
345                WallpaperData wallpaper = mWallpaperMap.get(mCurrentUserId);
346                if (wallpaper != null) {
347                    if (wallpaper.wallpaperComponent == null
348                            || !wallpaper.wallpaperComponent.getPackageName().equals(packageName)) {
349                        return;
350                    }
351                    doPackagesChangedLocked(true, wallpaper);
352                }
353            }
354        }
355
356        @Override
357        public void onPackageUpdateStarted(String packageName, int uid) {
358            synchronized (mLock) {
359                if (mCurrentUserId != getChangingUserId()) {
360                    return;
361                }
362                WallpaperData wallpaper = mWallpaperMap.get(mCurrentUserId);
363                if (wallpaper != null) {
364                    if (wallpaper.wallpaperComponent != null
365                            && wallpaper.wallpaperComponent.getPackageName().equals(packageName)) {
366                        wallpaper.wallpaperUpdating = true;
367                    }
368                }
369            }
370        }
371
372        @Override
373        public boolean onHandleForceStop(Intent intent, String[] packages, int uid, boolean doit) {
374            synchronized (mLock) {
375                boolean changed = false;
376                if (mCurrentUserId != getChangingUserId()) {
377                    return false;
378                }
379                WallpaperData wallpaper = mWallpaperMap.get(mCurrentUserId);
380                if (wallpaper != null) {
381                    boolean res = doPackagesChangedLocked(doit, wallpaper);
382                    changed |= res;
383                }
384                return changed;
385            }
386        }
387
388        @Override
389        public void onSomePackagesChanged() {
390            synchronized (mLock) {
391                if (mCurrentUserId != getChangingUserId()) {
392                    return;
393                }
394                WallpaperData wallpaper = mWallpaperMap.get(mCurrentUserId);
395                if (wallpaper != null) {
396                    doPackagesChangedLocked(true, wallpaper);
397                }
398            }
399        }
400
401        boolean doPackagesChangedLocked(boolean doit, WallpaperData wallpaper) {
402            boolean changed = false;
403            if (wallpaper.wallpaperComponent != null) {
404                int change = isPackageDisappearing(wallpaper.wallpaperComponent
405                        .getPackageName());
406                if (change == PACKAGE_PERMANENT_CHANGE
407                        || change == PACKAGE_TEMPORARY_CHANGE) {
408                    changed = true;
409                    if (doit) {
410                        Slog.w(TAG, "Wallpaper uninstalled, removing: "
411                                + wallpaper.wallpaperComponent);
412                        clearWallpaperLocked(false, wallpaper.userId, null);
413                    }
414                }
415            }
416            if (wallpaper.nextWallpaperComponent != null) {
417                int change = isPackageDisappearing(wallpaper.nextWallpaperComponent
418                        .getPackageName());
419                if (change == PACKAGE_PERMANENT_CHANGE
420                        || change == PACKAGE_TEMPORARY_CHANGE) {
421                    wallpaper.nextWallpaperComponent = null;
422                }
423            }
424            if (wallpaper.wallpaperComponent != null
425                    && isPackageModified(wallpaper.wallpaperComponent.getPackageName())) {
426                try {
427                    mContext.getPackageManager().getServiceInfo(
428                            wallpaper.wallpaperComponent, 0);
429                } catch (NameNotFoundException e) {
430                    Slog.w(TAG, "Wallpaper component gone, removing: "
431                            + wallpaper.wallpaperComponent);
432                    clearWallpaperLocked(false, wallpaper.userId, null);
433                }
434            }
435            if (wallpaper.nextWallpaperComponent != null
436                    && isPackageModified(wallpaper.nextWallpaperComponent.getPackageName())) {
437                try {
438                    mContext.getPackageManager().getServiceInfo(
439                            wallpaper.nextWallpaperComponent, 0);
440                } catch (NameNotFoundException e) {
441                    wallpaper.nextWallpaperComponent = null;
442                }
443            }
444            return changed;
445        }
446    }
447
448    public WallpaperManagerService(Context context) {
449        if (DEBUG) Slog.v(TAG, "WallpaperService startup");
450        mContext = context;
451        mImageWallpaper = ComponentName.unflattenFromString(
452                context.getResources().getString(R.string.image_wallpaper_component));
453        mIWindowManager = IWindowManager.Stub.asInterface(
454                ServiceManager.getService(Context.WINDOW_SERVICE));
455        mIPackageManager = AppGlobals.getPackageManager();
456        mMonitor = new MyPackageMonitor();
457        mMonitor.register(context, null, UserHandle.ALL, true);
458        getWallpaperDir(UserHandle.USER_OWNER).mkdirs();
459        loadSettingsLocked(UserHandle.USER_OWNER);
460    }
461
462    private static File getWallpaperDir(int userId) {
463        return Environment.getUserSystemDirectory(userId);
464    }
465
466    @Override
467    protected void finalize() throws Throwable {
468        super.finalize();
469        for (int i = 0; i < mWallpaperMap.size(); i++) {
470            WallpaperData wallpaper = mWallpaperMap.valueAt(i);
471            wallpaper.wallpaperObserver.stopWatching();
472        }
473    }
474
475    public void systemRunning() {
476        if (DEBUG) Slog.v(TAG, "systemReady");
477        WallpaperData wallpaper = mWallpaperMap.get(UserHandle.USER_OWNER);
478        switchWallpaper(wallpaper, null);
479        wallpaper.wallpaperObserver = new WallpaperObserver(wallpaper);
480        wallpaper.wallpaperObserver.startWatching();
481
482        IntentFilter userFilter = new IntentFilter();
483        userFilter.addAction(Intent.ACTION_USER_REMOVED);
484        userFilter.addAction(Intent.ACTION_USER_STOPPING);
485        mContext.registerReceiver(new BroadcastReceiver() {
486            @Override
487            public void onReceive(Context context, Intent intent) {
488                String action = intent.getAction();
489                if (Intent.ACTION_USER_REMOVED.equals(action)) {
490                    onRemoveUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
491                            UserHandle.USER_NULL));
492                }
493                // TODO: Race condition causing problems when cleaning up on stopping a user.
494                // Comment this out for now.
495                // else if (Intent.ACTION_USER_STOPPING.equals(action)) {
496                //     onStoppingUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
497                //             UserHandle.USER_NULL));
498                // }
499            }
500        }, userFilter);
501
502        try {
503            ActivityManagerNative.getDefault().registerUserSwitchObserver(
504                    new IUserSwitchObserver.Stub() {
505                        @Override
506                        public void onUserSwitching(int newUserId, IRemoteCallback reply) {
507                            switchUser(newUserId, reply);
508                        }
509
510                        @Override
511                        public void onUserSwitchComplete(int newUserId) throws RemoteException {
512                        }
513                    });
514        } catch (RemoteException e) {
515            // TODO Auto-generated catch block
516            e.printStackTrace();
517        }
518    }
519
520    /** Called by SystemBackupAgent */
521    public String getName() {
522        // Verify caller is the system
523        if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
524            throw new RuntimeException("getName() can only be called from the system process");
525        }
526        synchronized (mLock) {
527            return mWallpaperMap.get(0).name;
528        }
529    }
530
531    void onStoppingUser(int userId) {
532        if (userId < 1) return;
533        synchronized (mLock) {
534            WallpaperData wallpaper = mWallpaperMap.get(userId);
535            if (wallpaper != null) {
536                if (wallpaper.wallpaperObserver != null) {
537                    wallpaper.wallpaperObserver.stopWatching();
538                    wallpaper.wallpaperObserver = null;
539                }
540                mWallpaperMap.remove(userId);
541            }
542        }
543    }
544
545    void onRemoveUser(int userId) {
546        if (userId < 1) return;
547        synchronized (mLock) {
548            onStoppingUser(userId);
549            File wallpaperFile = new File(getWallpaperDir(userId), WALLPAPER);
550            wallpaperFile.delete();
551            File wallpaperInfoFile = new File(getWallpaperDir(userId), WALLPAPER_INFO);
552            wallpaperInfoFile.delete();
553        }
554    }
555
556    void switchUser(int userId, IRemoteCallback reply) {
557        synchronized (mLock) {
558            mCurrentUserId = userId;
559            WallpaperData wallpaper = mWallpaperMap.get(userId);
560            if (wallpaper == null) {
561                wallpaper = new WallpaperData(userId);
562                mWallpaperMap.put(userId, wallpaper);
563                loadSettingsLocked(userId);
564            }
565            // Not started watching yet, in case wallpaper data was loaded for other reasons.
566            if (wallpaper.wallpaperObserver == null) {
567                wallpaper.wallpaperObserver = new WallpaperObserver(wallpaper);
568                wallpaper.wallpaperObserver.startWatching();
569            }
570            switchWallpaper(wallpaper, reply);
571        }
572    }
573
574    void switchWallpaper(WallpaperData wallpaper, IRemoteCallback reply) {
575        synchronized (mLock) {
576            RuntimeException e = null;
577            try {
578                ComponentName cname = wallpaper.wallpaperComponent != null ?
579                        wallpaper.wallpaperComponent : wallpaper.nextWallpaperComponent;
580                if (bindWallpaperComponentLocked(cname, true, false, wallpaper, reply)) {
581                    return;
582                }
583            } catch (RuntimeException e1) {
584                e = e1;
585            }
586            Slog.w(TAG, "Failure starting previous wallpaper", e);
587            clearWallpaperLocked(false, wallpaper.userId, reply);
588        }
589    }
590
591    public void clearWallpaper() {
592        if (DEBUG) Slog.v(TAG, "clearWallpaper");
593        synchronized (mLock) {
594            clearWallpaperLocked(false, UserHandle.getCallingUserId(), null);
595        }
596    }
597
598    void clearWallpaperLocked(boolean defaultFailed, int userId, IRemoteCallback reply) {
599        WallpaperData wallpaper = mWallpaperMap.get(userId);
600        File f = new File(getWallpaperDir(userId), WALLPAPER);
601        if (f.exists()) {
602            f.delete();
603        }
604        final long ident = Binder.clearCallingIdentity();
605        try {
606            RuntimeException e = null;
607            try {
608                wallpaper.imageWallpaperPending = false;
609                if (userId != mCurrentUserId) return;
610                if (bindWallpaperComponentLocked(defaultFailed
611                        ? mImageWallpaper
612                                : null, true, false, wallpaper, reply)) {
613                    return;
614                }
615            } catch (IllegalArgumentException e1) {
616                e = e1;
617            }
618
619            // This can happen if the default wallpaper component doesn't
620            // exist.  This should be a system configuration problem, but
621            // let's not let it crash the system and just live with no
622            // wallpaper.
623            Slog.e(TAG, "Default wallpaper component not found!", e);
624            clearWallpaperComponentLocked(wallpaper);
625            if (reply != null) {
626                try {
627                    reply.sendResult(null);
628                } catch (RemoteException e1) {
629                }
630            }
631        } finally {
632            Binder.restoreCallingIdentity(ident);
633        }
634    }
635
636    public boolean hasNamedWallpaper(String name) {
637        synchronized (mLock) {
638            List<UserInfo> users;
639            long ident = Binder.clearCallingIdentity();
640            try {
641                users = ((UserManager) mContext.getSystemService(Context.USER_SERVICE)).getUsers();
642            } finally {
643                Binder.restoreCallingIdentity(ident);
644            }
645            for (UserInfo user: users) {
646                WallpaperData wd = mWallpaperMap.get(user.id);
647                if (wd == null) {
648                    // User hasn't started yet, so load her settings to peek at the wallpaper
649                    loadSettingsLocked(user.id);
650                    wd = mWallpaperMap.get(user.id);
651                }
652                if (wd != null && name.equals(wd.name)) {
653                    return true;
654                }
655            }
656        }
657        return false;
658    }
659
660    private Point getDefaultDisplaySize() {
661        Point p = new Point();
662        WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
663        Display d = wm.getDefaultDisplay();
664        d.getRealSize(p);
665        return p;
666    }
667
668    public void setDimensionHints(int width, int height) throws RemoteException {
669        checkPermission(android.Manifest.permission.SET_WALLPAPER_HINTS);
670        synchronized (mLock) {
671            int userId = UserHandle.getCallingUserId();
672            WallpaperData wallpaper = mWallpaperMap.get(userId);
673            if (wallpaper == null) {
674                throw new IllegalStateException("Wallpaper not yet initialized for user " + userId);
675            }
676            if (width <= 0 || height <= 0) {
677                throw new IllegalArgumentException("width and height must be > 0");
678            }
679            // Make sure it is at least as large as the display.
680            Point displaySize = getDefaultDisplaySize();
681            width = Math.max(width, displaySize.x);
682            height = Math.max(height, displaySize.y);
683
684            if (width != wallpaper.width || height != wallpaper.height) {
685                wallpaper.width = width;
686                wallpaper.height = height;
687                saveSettingsLocked(wallpaper);
688                if (mCurrentUserId != userId) return; // Don't change the properties now
689                if (wallpaper.connection != null) {
690                    if (wallpaper.connection.mEngine != null) {
691                        try {
692                            wallpaper.connection.mEngine.setDesiredSize(
693                                    width, height);
694                        } catch (RemoteException e) {
695                        }
696                        notifyCallbacksLocked(wallpaper);
697                    } else if (wallpaper.connection.mService != null) {
698                        // We've attached to the service but the engine hasn't attached back to us
699                        // yet. This means it will be created with the previous dimensions, so we
700                        // need to update it to the new dimensions once it attaches.
701                        wallpaper.connection.mDimensionsChanged = true;
702                    }
703                }
704            }
705        }
706    }
707
708    public int getWidthHint() throws RemoteException {
709        synchronized (mLock) {
710            WallpaperData wallpaper = mWallpaperMap.get(UserHandle.getCallingUserId());
711            return wallpaper.width;
712        }
713    }
714
715    public int getHeightHint() throws RemoteException {
716        synchronized (mLock) {
717            WallpaperData wallpaper = mWallpaperMap.get(UserHandle.getCallingUserId());
718            return wallpaper.height;
719        }
720    }
721
722    public ParcelFileDescriptor getWallpaper(IWallpaperManagerCallback cb,
723            Bundle outParams) {
724        synchronized (mLock) {
725            // This returns the current user's wallpaper, if called by a system service. Else it
726            // returns the wallpaper for the calling user.
727            int callingUid = Binder.getCallingUid();
728            int wallpaperUserId = 0;
729            if (callingUid == android.os.Process.SYSTEM_UID) {
730                wallpaperUserId = mCurrentUserId;
731            } else {
732                wallpaperUserId = UserHandle.getUserId(callingUid);
733            }
734            WallpaperData wallpaper = mWallpaperMap.get(wallpaperUserId);
735            try {
736                if (outParams != null) {
737                    outParams.putInt("width", wallpaper.width);
738                    outParams.putInt("height", wallpaper.height);
739                }
740                wallpaper.callbacks.register(cb);
741                File f = new File(getWallpaperDir(wallpaperUserId), WALLPAPER);
742                if (!f.exists()) {
743                    return null;
744                }
745                return ParcelFileDescriptor.open(f, MODE_READ_ONLY);
746            } catch (FileNotFoundException e) {
747                /* Shouldn't happen as we check to see if the file exists */
748                Slog.w(TAG, "Error getting wallpaper", e);
749            }
750            return null;
751        }
752    }
753
754    public WallpaperInfo getWallpaperInfo() {
755        int userId = UserHandle.getCallingUserId();
756        synchronized (mLock) {
757            WallpaperData wallpaper = mWallpaperMap.get(userId);
758            if (wallpaper.connection != null) {
759                return wallpaper.connection.mInfo;
760            }
761            return null;
762        }
763    }
764
765    public ParcelFileDescriptor setWallpaper(String name) {
766        checkPermission(android.Manifest.permission.SET_WALLPAPER);
767        synchronized (mLock) {
768            if (DEBUG) Slog.v(TAG, "setWallpaper");
769            int userId = UserHandle.getCallingUserId();
770            WallpaperData wallpaper = mWallpaperMap.get(userId);
771            if (wallpaper == null) {
772                throw new IllegalStateException("Wallpaper not yet initialized for user " + userId);
773            }
774            final long ident = Binder.clearCallingIdentity();
775            try {
776                ParcelFileDescriptor pfd = updateWallpaperBitmapLocked(name, wallpaper);
777                if (pfd != null) {
778                    wallpaper.imageWallpaperPending = true;
779                }
780                return pfd;
781            } finally {
782                Binder.restoreCallingIdentity(ident);
783            }
784        }
785    }
786
787    ParcelFileDescriptor updateWallpaperBitmapLocked(String name, WallpaperData wallpaper) {
788        if (name == null) name = "";
789        try {
790            File dir = getWallpaperDir(wallpaper.userId);
791            if (!dir.exists()) {
792                dir.mkdir();
793                FileUtils.setPermissions(
794                        dir.getPath(),
795                        FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
796                        -1, -1);
797            }
798            File file = new File(dir, WALLPAPER);
799            ParcelFileDescriptor fd = ParcelFileDescriptor.open(file,
800                    MODE_CREATE|MODE_READ_WRITE);
801            if (!SELinux.restorecon(file)) {
802                return null;
803            }
804            wallpaper.name = name;
805            return fd;
806        } catch (FileNotFoundException e) {
807            Slog.w(TAG, "Error setting wallpaper", e);
808        }
809        return null;
810    }
811
812    public void setWallpaperComponent(ComponentName name) {
813        checkPermission(android.Manifest.permission.SET_WALLPAPER_COMPONENT);
814        synchronized (mLock) {
815            if (DEBUG) Slog.v(TAG, "setWallpaperComponent name=" + name);
816            int userId = UserHandle.getCallingUserId();
817            WallpaperData wallpaper = mWallpaperMap.get(userId);
818            if (wallpaper == null) {
819                throw new IllegalStateException("Wallpaper not yet initialized for user " + userId);
820            }
821            final long ident = Binder.clearCallingIdentity();
822            try {
823                wallpaper.imageWallpaperPending = false;
824                bindWallpaperComponentLocked(name, false, true, wallpaper, null);
825            } finally {
826                Binder.restoreCallingIdentity(ident);
827            }
828        }
829    }
830
831    boolean bindWallpaperComponentLocked(ComponentName componentName, boolean force,
832            boolean fromUser, WallpaperData wallpaper, IRemoteCallback reply) {
833        if (DEBUG) Slog.v(TAG, "bindWallpaperComponentLocked: componentName=" + componentName);
834        // Has the component changed?
835        if (!force) {
836            if (wallpaper.connection != null) {
837                if (wallpaper.wallpaperComponent == null) {
838                    if (componentName == null) {
839                        if (DEBUG) Slog.v(TAG, "bindWallpaperComponentLocked: still using default");
840                        // Still using default wallpaper.
841                        return true;
842                    }
843                } else if (wallpaper.wallpaperComponent.equals(componentName)) {
844                    // Changing to same wallpaper.
845                    if (DEBUG) Slog.v(TAG, "same wallpaper");
846                    return true;
847                }
848            }
849        }
850
851        try {
852            if (componentName == null) {
853                componentName = WallpaperManager.getDefaultWallpaperComponent(mContext);
854                if (componentName == null) {
855                    // Fall back to static image wallpaper
856                    componentName = mImageWallpaper;
857                    //clearWallpaperComponentLocked();
858                    //return;
859                    if (DEBUG) Slog.v(TAG, "Using image wallpaper");
860                }
861            }
862            int serviceUserId = wallpaper.userId;
863            ServiceInfo si = mIPackageManager.getServiceInfo(componentName,
864                    PackageManager.GET_META_DATA | PackageManager.GET_PERMISSIONS, serviceUserId);
865            if (si == null) {
866                // The wallpaper component we're trying to use doesn't exist
867                Slog.w(TAG, "Attempted wallpaper " + componentName + " is unavailable");
868                return false;
869            }
870            if (!android.Manifest.permission.BIND_WALLPAPER.equals(si.permission)) {
871                String msg = "Selected service does not require "
872                        + android.Manifest.permission.BIND_WALLPAPER
873                        + ": " + componentName;
874                if (fromUser) {
875                    throw new SecurityException(msg);
876                }
877                Slog.w(TAG, msg);
878                return false;
879            }
880
881            WallpaperInfo wi = null;
882
883            Intent intent = new Intent(WallpaperService.SERVICE_INTERFACE);
884            if (componentName != null && !componentName.equals(mImageWallpaper)) {
885                // Make sure the selected service is actually a wallpaper service.
886                List<ResolveInfo> ris =
887                        mIPackageManager.queryIntentServices(intent,
888                                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
889                                PackageManager.GET_META_DATA, serviceUserId);
890                for (int i=0; i<ris.size(); i++) {
891                    ServiceInfo rsi = ris.get(i).serviceInfo;
892                    if (rsi.name.equals(si.name) &&
893                            rsi.packageName.equals(si.packageName)) {
894                        try {
895                            wi = new WallpaperInfo(mContext, ris.get(i));
896                        } catch (XmlPullParserException e) {
897                            if (fromUser) {
898                                throw new IllegalArgumentException(e);
899                            }
900                            Slog.w(TAG, e);
901                            return false;
902                        } catch (IOException e) {
903                            if (fromUser) {
904                                throw new IllegalArgumentException(e);
905                            }
906                            Slog.w(TAG, e);
907                            return false;
908                        }
909                        break;
910                    }
911                }
912                if (wi == null) {
913                    String msg = "Selected service is not a wallpaper: "
914                            + componentName;
915                    if (fromUser) {
916                        throw new SecurityException(msg);
917                    }
918                    Slog.w(TAG, msg);
919                    return false;
920                }
921            }
922
923            // Bind the service!
924            if (DEBUG) Slog.v(TAG, "Binding to:" + componentName);
925            WallpaperConnection newConn = new WallpaperConnection(wi, wallpaper);
926            intent.setComponent(componentName);
927            intent.putExtra(Intent.EXTRA_CLIENT_LABEL,
928                    com.android.internal.R.string.wallpaper_binding_label);
929            intent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivityAsUser(
930                    mContext, 0,
931                    Intent.createChooser(new Intent(Intent.ACTION_SET_WALLPAPER),
932                            mContext.getText(com.android.internal.R.string.chooser_wallpaper)),
933                    0, null, new UserHandle(serviceUserId)));
934            if (!mContext.bindServiceAsUser(intent, newConn,
935                    Context.BIND_AUTO_CREATE | Context.BIND_SHOWING_UI,
936                    new UserHandle(serviceUserId))) {
937                String msg = "Unable to bind service: "
938                        + componentName;
939                if (fromUser) {
940                    throw new IllegalArgumentException(msg);
941                }
942                Slog.w(TAG, msg);
943                return false;
944            }
945            if (wallpaper.userId == mCurrentUserId && mLastWallpaper != null) {
946                detachWallpaperLocked(mLastWallpaper);
947            }
948            wallpaper.wallpaperComponent = componentName;
949            wallpaper.connection = newConn;
950            newConn.mReply = reply;
951            try {
952                if (wallpaper.userId == mCurrentUserId) {
953                    if (DEBUG)
954                        Slog.v(TAG, "Adding window token: " + newConn.mToken);
955                    mIWindowManager.addWindowToken(newConn.mToken,
956                            WindowManager.LayoutParams.TYPE_WALLPAPER);
957                    mLastWallpaper = wallpaper;
958                }
959            } catch (RemoteException e) {
960            }
961        } catch (RemoteException e) {
962            String msg = "Remote exception for " + componentName + "\n" + e;
963            if (fromUser) {
964                throw new IllegalArgumentException(msg);
965            }
966            Slog.w(TAG, msg);
967            return false;
968        }
969        return true;
970    }
971
972    void detachWallpaperLocked(WallpaperData wallpaper) {
973        if (wallpaper.connection != null) {
974            if (wallpaper.connection.mReply != null) {
975                try {
976                    wallpaper.connection.mReply.sendResult(null);
977                } catch (RemoteException e) {
978                }
979                wallpaper.connection.mReply = null;
980            }
981            if (wallpaper.connection.mEngine != null) {
982                try {
983                    wallpaper.connection.mEngine.destroy();
984                } catch (RemoteException e) {
985                }
986            }
987            mContext.unbindService(wallpaper.connection);
988            try {
989                if (DEBUG)
990                    Slog.v(TAG, "Removing window token: " + wallpaper.connection.mToken);
991                mIWindowManager.removeWindowToken(wallpaper.connection.mToken);
992            } catch (RemoteException e) {
993            }
994            wallpaper.connection.mService = null;
995            wallpaper.connection.mEngine = null;
996            wallpaper.connection = null;
997        }
998    }
999
1000    void clearWallpaperComponentLocked(WallpaperData wallpaper) {
1001        wallpaper.wallpaperComponent = null;
1002        detachWallpaperLocked(wallpaper);
1003    }
1004
1005    void attachServiceLocked(WallpaperConnection conn, WallpaperData wallpaper) {
1006        try {
1007            conn.mService.attach(conn, conn.mToken,
1008                    WindowManager.LayoutParams.TYPE_WALLPAPER, false,
1009                    wallpaper.width, wallpaper.height);
1010        } catch (RemoteException e) {
1011            Slog.w(TAG, "Failed attaching wallpaper; clearing", e);
1012            if (!wallpaper.wallpaperUpdating) {
1013                bindWallpaperComponentLocked(null, false, false, wallpaper, null);
1014            }
1015        }
1016    }
1017
1018    private void notifyCallbacksLocked(WallpaperData wallpaper) {
1019        final int n = wallpaper.callbacks.beginBroadcast();
1020        for (int i = 0; i < n; i++) {
1021            try {
1022                wallpaper.callbacks.getBroadcastItem(i).onWallpaperChanged();
1023            } catch (RemoteException e) {
1024
1025                // The RemoteCallbackList will take care of removing
1026                // the dead object for us.
1027            }
1028        }
1029        wallpaper.callbacks.finishBroadcast();
1030        final Intent intent = new Intent(Intent.ACTION_WALLPAPER_CHANGED);
1031        mContext.sendBroadcastAsUser(intent, new UserHandle(mCurrentUserId));
1032    }
1033
1034    private void checkPermission(String permission) {
1035        if (PackageManager.PERMISSION_GRANTED!= mContext.checkCallingOrSelfPermission(permission)) {
1036            throw new SecurityException("Access denied to process: " + Binder.getCallingPid()
1037                    + ", must have permission " + permission);
1038        }
1039    }
1040
1041    private static JournaledFile makeJournaledFile(int userId) {
1042        final String base = new File(getWallpaperDir(userId), WALLPAPER_INFO).getAbsolutePath();
1043        return new JournaledFile(new File(base), new File(base + ".tmp"));
1044    }
1045
1046    private void saveSettingsLocked(WallpaperData wallpaper) {
1047        JournaledFile journal = makeJournaledFile(wallpaper.userId);
1048        FileOutputStream stream = null;
1049        try {
1050            stream = new FileOutputStream(journal.chooseForWrite(), false);
1051            XmlSerializer out = new FastXmlSerializer();
1052            out.setOutput(stream, "utf-8");
1053            out.startDocument(null, true);
1054
1055            out.startTag(null, "wp");
1056            out.attribute(null, "width", Integer.toString(wallpaper.width));
1057            out.attribute(null, "height", Integer.toString(wallpaper.height));
1058            out.attribute(null, "name", wallpaper.name);
1059            if (wallpaper.wallpaperComponent != null
1060                    && !wallpaper.wallpaperComponent.equals(mImageWallpaper)) {
1061                out.attribute(null, "component",
1062                        wallpaper.wallpaperComponent.flattenToShortString());
1063            }
1064            out.endTag(null, "wp");
1065
1066            out.endDocument();
1067            stream.close();
1068            journal.commit();
1069        } catch (IOException e) {
1070            try {
1071                if (stream != null) {
1072                    stream.close();
1073                }
1074            } catch (IOException ex) {
1075                // Ignore
1076            }
1077            journal.rollback();
1078        }
1079    }
1080
1081    private void migrateFromOld() {
1082        File oldWallpaper = new File(WallpaperBackupHelper.WALLPAPER_IMAGE_KEY);
1083        File oldInfo = new File(WallpaperBackupHelper.WALLPAPER_INFO_KEY);
1084        if (oldWallpaper.exists()) {
1085            File newWallpaper = new File(getWallpaperDir(0), WALLPAPER);
1086            oldWallpaper.renameTo(newWallpaper);
1087        }
1088        if (oldInfo.exists()) {
1089            File newInfo = new File(getWallpaperDir(0), WALLPAPER_INFO);
1090            oldInfo.renameTo(newInfo);
1091        }
1092    }
1093
1094    private void loadSettingsLocked(int userId) {
1095        if (DEBUG) Slog.v(TAG, "loadSettingsLocked");
1096
1097        JournaledFile journal = makeJournaledFile(userId);
1098        FileInputStream stream = null;
1099        File file = journal.chooseForRead();
1100        if (!file.exists()) {
1101            // This should only happen one time, when upgrading from a legacy system
1102            migrateFromOld();
1103        }
1104        WallpaperData wallpaper = mWallpaperMap.get(userId);
1105        if (wallpaper == null) {
1106            wallpaper = new WallpaperData(userId);
1107            mWallpaperMap.put(userId, wallpaper);
1108        }
1109        boolean success = false;
1110        try {
1111            stream = new FileInputStream(file);
1112            XmlPullParser parser = Xml.newPullParser();
1113            parser.setInput(stream, null);
1114
1115            int type;
1116            do {
1117                type = parser.next();
1118                if (type == XmlPullParser.START_TAG) {
1119                    String tag = parser.getName();
1120                    if ("wp".equals(tag)) {
1121                        wallpaper.width = Integer.parseInt(parser.getAttributeValue(null, "width"));
1122                        wallpaper.height = Integer.parseInt(parser
1123                                .getAttributeValue(null, "height"));
1124                        wallpaper.name = parser.getAttributeValue(null, "name");
1125                        String comp = parser.getAttributeValue(null, "component");
1126                        wallpaper.nextWallpaperComponent = comp != null
1127                                ? ComponentName.unflattenFromString(comp)
1128                                : null;
1129                        if (wallpaper.nextWallpaperComponent == null
1130                                || "android".equals(wallpaper.nextWallpaperComponent
1131                                        .getPackageName())) {
1132                            wallpaper.nextWallpaperComponent = mImageWallpaper;
1133                        }
1134
1135                        if (DEBUG) {
1136                            Slog.v(TAG, "mWidth:" + wallpaper.width);
1137                            Slog.v(TAG, "mHeight:" + wallpaper.height);
1138                            Slog.v(TAG, "mName:" + wallpaper.name);
1139                            Slog.v(TAG, "mNextWallpaperComponent:"
1140                                    + wallpaper.nextWallpaperComponent);
1141                        }
1142                    }
1143                }
1144            } while (type != XmlPullParser.END_DOCUMENT);
1145            success = true;
1146        } catch (FileNotFoundException e) {
1147            Slog.w(TAG, "no current wallpaper -- first boot?");
1148        } catch (NullPointerException e) {
1149            Slog.w(TAG, "failed parsing " + file + " " + e);
1150        } catch (NumberFormatException e) {
1151            Slog.w(TAG, "failed parsing " + file + " " + e);
1152        } catch (XmlPullParserException e) {
1153            Slog.w(TAG, "failed parsing " + file + " " + e);
1154        } catch (IOException e) {
1155            Slog.w(TAG, "failed parsing " + file + " " + e);
1156        } catch (IndexOutOfBoundsException e) {
1157            Slog.w(TAG, "failed parsing " + file + " " + e);
1158        }
1159        try {
1160            if (stream != null) {
1161                stream.close();
1162            }
1163        } catch (IOException e) {
1164            // Ignore
1165        }
1166
1167        if (!success) {
1168            wallpaper.width = -1;
1169            wallpaper.height = -1;
1170            wallpaper.name = "";
1171        }
1172
1173        // We always want to have some reasonable width hint.
1174        int baseSize = getMaximumSizeDimension();
1175        if (wallpaper.width < baseSize) {
1176            wallpaper.width = baseSize;
1177        }
1178        if (wallpaper.height < baseSize) {
1179            wallpaper.height = baseSize;
1180        }
1181    }
1182
1183    private int getMaximumSizeDimension() {
1184        WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
1185        Display d = wm.getDefaultDisplay();
1186        return d.getMaximumSizeDimension();
1187    }
1188
1189    // Called by SystemBackupAgent after files are restored to disk.
1190    public void settingsRestored() {
1191        // Verify caller is the system
1192        if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
1193            throw new RuntimeException("settingsRestored() can only be called from the system process");
1194        }
1195        // TODO: If necessary, make it work for secondary users as well. This currently assumes
1196        // restores only to the primary user
1197        if (DEBUG) Slog.v(TAG, "settingsRestored");
1198        WallpaperData wallpaper = null;
1199        boolean success = false;
1200        synchronized (mLock) {
1201            loadSettingsLocked(0);
1202            wallpaper = mWallpaperMap.get(0);
1203            if (wallpaper.nextWallpaperComponent != null
1204                    && !wallpaper.nextWallpaperComponent.equals(mImageWallpaper)) {
1205                if (!bindWallpaperComponentLocked(wallpaper.nextWallpaperComponent, false, false,
1206                        wallpaper, null)) {
1207                    // No such live wallpaper or other failure; fall back to the default
1208                    // live wallpaper (since the profile being restored indicated that the
1209                    // user had selected a live rather than static one).
1210                    bindWallpaperComponentLocked(null, false, false, wallpaper, null);
1211                }
1212                success = true;
1213            } else {
1214                // If there's a wallpaper name, we use that.  If that can't be loaded, then we
1215                // use the default.
1216                if ("".equals(wallpaper.name)) {
1217                    if (DEBUG) Slog.v(TAG, "settingsRestored: name is empty");
1218                    success = true;
1219                } else {
1220                    if (DEBUG) Slog.v(TAG, "settingsRestored: attempting to restore named resource");
1221                    success = restoreNamedResourceLocked(wallpaper);
1222                }
1223                if (DEBUG) Slog.v(TAG, "settingsRestored: success=" + success);
1224                if (success) {
1225                    bindWallpaperComponentLocked(wallpaper.nextWallpaperComponent, false, false,
1226                            wallpaper, null);
1227                }
1228            }
1229        }
1230
1231        if (!success) {
1232            Slog.e(TAG, "Failed to restore wallpaper: '" + wallpaper.name + "'");
1233            wallpaper.name = "";
1234            getWallpaperDir(0).delete();
1235        }
1236
1237        synchronized (mLock) {
1238            saveSettingsLocked(wallpaper);
1239        }
1240    }
1241
1242    boolean restoreNamedResourceLocked(WallpaperData wallpaper) {
1243        if (wallpaper.name.length() > 4 && "res:".equals(wallpaper.name.substring(0, 4))) {
1244            String resName = wallpaper.name.substring(4);
1245
1246            String pkg = null;
1247            int colon = resName.indexOf(':');
1248            if (colon > 0) {
1249                pkg = resName.substring(0, colon);
1250            }
1251
1252            String ident = null;
1253            int slash = resName.lastIndexOf('/');
1254            if (slash > 0) {
1255                ident = resName.substring(slash+1);
1256            }
1257
1258            String type = null;
1259            if (colon > 0 && slash > 0 && (slash-colon) > 1) {
1260                type = resName.substring(colon+1, slash);
1261            }
1262
1263            if (pkg != null && ident != null && type != null) {
1264                int resId = -1;
1265                InputStream res = null;
1266                FileOutputStream fos = null;
1267                try {
1268                    Context c = mContext.createPackageContext(pkg, Context.CONTEXT_RESTRICTED);
1269                    Resources r = c.getResources();
1270                    resId = r.getIdentifier(resName, null, null);
1271                    if (resId == 0) {
1272                        Slog.e(TAG, "couldn't resolve identifier pkg=" + pkg + " type=" + type
1273                                + " ident=" + ident);
1274                        return false;
1275                    }
1276
1277                    res = r.openRawResource(resId);
1278                    if (wallpaper.wallpaperFile.exists()) {
1279                        wallpaper.wallpaperFile.delete();
1280                    }
1281                    fos = new FileOutputStream(wallpaper.wallpaperFile);
1282
1283                    byte[] buffer = new byte[32768];
1284                    int amt;
1285                    while ((amt=res.read(buffer)) > 0) {
1286                        fos.write(buffer, 0, amt);
1287                    }
1288                    // mWallpaperObserver will notice the close and send the change broadcast
1289
1290                    Slog.v(TAG, "Restored wallpaper: " + resName);
1291                    return true;
1292                } catch (NameNotFoundException e) {
1293                    Slog.e(TAG, "Package name " + pkg + " not found");
1294                } catch (Resources.NotFoundException e) {
1295                    Slog.e(TAG, "Resource not found: " + resId);
1296                } catch (IOException e) {
1297                    Slog.e(TAG, "IOException while restoring wallpaper ", e);
1298                } finally {
1299                    if (res != null) {
1300                        try {
1301                            res.close();
1302                        } catch (IOException ex) {}
1303                    }
1304                    if (fos != null) {
1305                        FileUtils.sync(fos);
1306                        try {
1307                            fos.close();
1308                        } catch (IOException ex) {}
1309                    }
1310                }
1311            }
1312        }
1313        return false;
1314    }
1315
1316    @Override
1317    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1318        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1319                != PackageManager.PERMISSION_GRANTED) {
1320
1321            pw.println("Permission Denial: can't dump wallpaper service from from pid="
1322                    + Binder.getCallingPid()
1323                    + ", uid=" + Binder.getCallingUid());
1324            return;
1325        }
1326
1327        synchronized (mLock) {
1328            pw.println("Current Wallpaper Service state:");
1329            for (int i = 0; i < mWallpaperMap.size(); i++) {
1330                WallpaperData wallpaper = mWallpaperMap.valueAt(i);
1331                pw.println(" User " + wallpaper.userId + ":");
1332                pw.print("  mWidth=");
1333                pw.print(wallpaper.width);
1334                pw.print(" mHeight=");
1335                pw.println(wallpaper.height);
1336                pw.print("  mName=");
1337                pw.println(wallpaper.name);
1338                pw.print("  mWallpaperComponent=");
1339                pw.println(wallpaper.wallpaperComponent);
1340                if (wallpaper.connection != null) {
1341                    WallpaperConnection conn = wallpaper.connection;
1342                    pw.print("  Wallpaper connection ");
1343                    pw.print(conn);
1344                    pw.println(":");
1345                    if (conn.mInfo != null) {
1346                        pw.print("    mInfo.component=");
1347                        pw.println(conn.mInfo.getComponent());
1348                    }
1349                    pw.print("    mToken=");
1350                    pw.println(conn.mToken);
1351                    pw.print("    mService=");
1352                    pw.println(conn.mService);
1353                    pw.print("    mEngine=");
1354                    pw.println(conn.mEngine);
1355                    pw.print("    mLastDiedTime=");
1356                    pw.println(wallpaper.lastDiedTime - SystemClock.uptimeMillis());
1357                }
1358            }
1359        }
1360    }
1361}
1362