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