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