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