blob: 5d88c0d78eb7346fac4fec29c2007a7d5ef24a31 [file] [log] [blame]
Jon Miranda16ea1b12017-12-12 14:52:48 -08001/*
2 * Copyright (C) 2017 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 */
16package com.android.wallpaper.module;
17
18import android.annotation.SuppressLint;
19import android.app.Activity;
20import android.app.WallpaperManager;
21import android.content.Context;
Santiago Etchebeheree95b6d92020-06-08 14:19:46 -070022import android.content.res.Resources;
Jon Miranda16ea1b12017-12-12 14:52:48 -080023import android.graphics.Bitmap;
24import android.graphics.Bitmap.CompressFormat;
25import android.graphics.BitmapFactory;
26import android.graphics.Point;
Santiago Etchebeheree95b6d92020-06-08 14:19:46 -070027import android.graphics.PointF;
Jon Miranda16ea1b12017-12-12 14:52:48 -080028import android.graphics.Rect;
29import android.graphics.drawable.BitmapDrawable;
30import android.os.AsyncTask;
31import android.os.ParcelFileDescriptor;
Jon Miranda16ea1b12017-12-12 14:52:48 -080032import android.util.Log;
33import android.view.Display;
34import android.view.WindowManager;
35
Samuel Fufa03bc6ac2019-09-19 12:01:50 -070036import androidx.annotation.Nullable;
37
Jon Miranda16ea1b12017-12-12 14:52:48 -080038import com.android.wallpaper.asset.Asset;
39import com.android.wallpaper.asset.Asset.BitmapReceiver;
40import com.android.wallpaper.asset.Asset.DimensionsReceiver;
41import com.android.wallpaper.asset.BitmapUtils;
42import com.android.wallpaper.asset.StreamableAsset;
43import com.android.wallpaper.asset.StreamableAsset.StreamReceiver;
44import com.android.wallpaper.compat.BuildCompat;
45import com.android.wallpaper.compat.WallpaperManagerCompat;
46import com.android.wallpaper.model.WallpaperInfo;
47import com.android.wallpaper.module.BitmapCropper.Callback;
Jon Miranda16ea1b12017-12-12 14:52:48 -080048import com.android.wallpaper.util.BitmapTransformer;
Jon Miranda16ea1b12017-12-12 14:52:48 -080049import com.android.wallpaper.util.ScreenSizeCalculator;
Santiago Etchebeheree95b6d92020-06-08 14:19:46 -070050import com.android.wallpaper.util.WallpaperCropUtils;
Jon Miranda16ea1b12017-12-12 14:52:48 -080051
52import java.io.ByteArrayInputStream;
53import java.io.ByteArrayOutputStream;
Jon Miranda16ea1b12017-12-12 14:52:48 -080054import java.io.FileInputStream;
Jon Miranda16ea1b12017-12-12 14:52:48 -080055import java.io.IOException;
56import java.io.InputStream;
57import java.util.List;
58
59/**
60 * Concrete implementation of WallpaperPersister which actually sets wallpapers to the system via
61 * the WallpaperManager.
62 */
63public class DefaultWallpaperPersister implements WallpaperPersister {
64
65 private static final int DEFAULT_COMPRESS_QUALITY = 100;
66 private static final String TAG = "WallpaperPersister";
67
68 private final Context mAppContext; // The application's context.
Santiago Etchebehere5a7f1dd2018-04-03 15:01:29 -070069 // Context that accesses files in device protected storage
Jon Miranda16ea1b12017-12-12 14:52:48 -080070 private final WallpaperManager mWallpaperManager;
71 private final WallpaperManagerCompat mWallpaperManagerCompat;
72 private final WallpaperPreferences mWallpaperPreferences;
Jon Miranda16ea1b12017-12-12 14:52:48 -080073 private final WallpaperChangedNotifier mWallpaperChangedNotifier;
74
75 private WallpaperInfo mWallpaperInfoInPreview;
76
77 @SuppressLint("ServiceCast")
78 public DefaultWallpaperPersister(Context context) {
79 mAppContext = context.getApplicationContext();
80 // Retrieve WallpaperManager using Context#getSystemService instead of
81 // WallpaperManager#getInstance so it can be mocked out in test.
82 Injector injector = InjectorProvider.getInjector();
83 mWallpaperManager = (WallpaperManager) context.getSystemService(Context.WALLPAPER_SERVICE);
84 mWallpaperManagerCompat = injector.getWallpaperManagerCompat(context);
85 mWallpaperPreferences = injector.getPreferences(context);
Jon Miranda16ea1b12017-12-12 14:52:48 -080086 mWallpaperChangedNotifier = WallpaperChangedNotifier.getInstance();
87 }
88
89 @Override
90 public void setIndividualWallpaper(final WallpaperInfo wallpaper, Asset asset,
Samuel Fufa03bc6ac2019-09-19 12:01:50 -070091 @Nullable Rect cropRect, float scale, @Destination final int destination,
92 final SetWallpaperCallback callback) {
Jon Miranda16ea1b12017-12-12 14:52:48 -080093 // Set wallpaper without downscaling directly from an input stream if there's no crop rect
94 // specified by the caller and the asset is streamable.
95 if (cropRect == null && asset instanceof StreamableAsset) {
96 ((StreamableAsset) asset).fetchInputStream(new StreamReceiver() {
97 @Override
98 public void onInputStreamOpened(@Nullable InputStream inputStream) {
99 if (inputStream == null) {
100 callback.onError(null /* throwable */);
101 return;
102 }
103 setIndividualWallpaper(wallpaper, inputStream, destination, callback);
104 }
105 });
106 return;
107 }
108
109 // If no crop rect is specified but the wallpaper asset is not streamable, then fall back to
110 // using the device's display size.
111 if (cropRect == null) {
112 Display display = ((WindowManager) mAppContext.getSystemService(Context.WINDOW_SERVICE))
113 .getDefaultDisplay();
114 Point screenSize = ScreenSizeCalculator.getInstance().getScreenSize(display);
115 asset.decodeBitmap(screenSize.x, screenSize.y, new BitmapReceiver() {
116 @Override
117 public void onBitmapDecoded(@Nullable Bitmap bitmap) {
118 if (bitmap == null) {
119 callback.onError(null /* throwable */);
120 return;
121 }
122 setIndividualWallpaper(wallpaper, bitmap, destination, callback);
123 }
124 });
125 return;
126 }
127
128 BitmapCropper bitmapCropper = InjectorProvider.getInjector().getBitmapCropper();
129 bitmapCropper.cropAndScaleBitmap(asset, scale, cropRect, new Callback() {
130 @Override
131 public void onBitmapCropped(Bitmap croppedBitmap) {
132 setIndividualWallpaper(wallpaper, croppedBitmap, destination, callback);
133 }
134
135 @Override
136 public void onError(@Nullable Throwable e) {
137 callback.onError(e);
138 }
139 });
140 }
141
142 @Override
143 public void setIndividualWallpaperWithPosition(Activity activity, WallpaperInfo wallpaper,
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700144 @WallpaperPosition int wallpaperPosition, SetWallpaperCallback callback) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800145 Display display = ((WindowManager) mAppContext.getSystemService(Context.WINDOW_SERVICE))
146 .getDefaultDisplay();
147 Point screenSize = ScreenSizeCalculator.getInstance().getScreenSize(display);
148
149 Asset asset = wallpaper.getAsset(activity);
150 asset.decodeRawDimensions(activity, new DimensionsReceiver() {
151 @Override
152 public void onDimensionsDecoded(@Nullable Point dimensions) {
153 if (dimensions == null) {
154 callback.onError(null);
155 return;
156 }
157
158 switch (wallpaperPosition) {
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700159 // Crop out screen-sized center portion of the source image if it's larger
160 // than the screen
161 // in both dimensions. Otherwise, decode the entire bitmap and fill the space
162 // around it to fill a new screen-sized bitmap with plain black pixels.
Jon Miranda16ea1b12017-12-12 14:52:48 -0800163 case WALLPAPER_POSITION_CENTER:
164 setIndividualWallpaperWithCenterPosition(
165 wallpaper, asset, dimensions, screenSize, callback);
166 break;
167
168 // Crop out a screen-size portion of the source image and set the bitmap region.
169 case WALLPAPER_POSITION_CENTER_CROP:
170 setIndividualWallpaperWithCenterCropPosition(
171 wallpaper, asset, dimensions, screenSize, callback);
172 break;
173
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700174 // Decode full bitmap sized for screen and stretch it to fill the screen
175 // dimensions.
Jon Miranda16ea1b12017-12-12 14:52:48 -0800176 case WALLPAPER_POSITION_STRETCH:
177 asset.decodeBitmap(screenSize.x, screenSize.y, new BitmapReceiver() {
178 @Override
179 public void onBitmapDecoded(@Nullable Bitmap bitmap) {
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700180 setIndividualWallpaperStretch(wallpaper, bitmap,
181 screenSize /* stretchSize */,
Jon Miranda16ea1b12017-12-12 14:52:48 -0800182 WallpaperPersister.DEST_BOTH, callback);
183 }
184 });
185 break;
186
187 default:
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700188 Log.e(TAG, "Unsupported wallpaper position option specified: "
189 + wallpaperPosition);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800190 callback.onError(null);
191 }
192 }
193 });
194 }
195
196 /**
197 * Sets an individual wallpaper to both home + lock static wallpaper destinations with a center
198 * wallpaper position.
199 *
200 * @param wallpaper The wallpaper model object representing the wallpaper to be set.
201 * @param asset The wallpaper asset that should be used to set a wallpaper.
202 * @param dimensions Raw dimensions of the wallpaper asset.
203 * @param screenSize Dimensions of the device screen.
204 * @param callback Callback used to notify original caller of wallpaper set operation result.
205 */
206 private void setIndividualWallpaperWithCenterPosition(WallpaperInfo wallpaper, Asset asset,
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700207 Point dimensions, Point screenSize, SetWallpaperCallback callback) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800208 if (dimensions.x >= screenSize.x && dimensions.y >= screenSize.y) {
209 Rect cropRect = new Rect(
210 (dimensions.x - screenSize.x) / 2,
211 (dimensions.y - screenSize.y) / 2,
212 dimensions.x - ((dimensions.x - screenSize.x) / 2),
213 dimensions.y - ((dimensions.y - screenSize.y) / 2));
214 asset.decodeBitmapRegion(cropRect, screenSize.x, screenSize.y, new BitmapReceiver() {
215 @Override
216 public void onBitmapDecoded(@Nullable Bitmap bitmap) {
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700217 setIndividualWallpaper(wallpaper, bitmap, WallpaperPersister.DEST_BOTH,
218 callback);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800219 }
220 });
221 } else {
222 // Decode the full bitmap and pass with the screen size as a fill rect.
223 asset.decodeBitmap(dimensions.x, dimensions.y, new BitmapReceiver() {
224 @Override
225 public void onBitmapDecoded(@Nullable Bitmap bitmap) {
226 if (bitmap == null) {
227 callback.onError(null);
228 return;
229 }
230
231 setIndividualWallpaperFill(wallpaper, bitmap, screenSize /* fillSize */,
232 WallpaperPersister.DEST_BOTH, callback);
233 }
234 });
235 }
236 }
237
238 /**
239 * Sets an individual wallpaper to both home + lock static wallpaper destinations with a center
240 * cropped wallpaper position.
241 *
242 * @param wallpaper The wallpaper model object representing the wallpaper to be set.
243 * @param asset The wallpaper asset that should be used to set a wallpaper.
244 * @param dimensions Raw dimensions of the wallpaper asset.
245 * @param screenSize Dimensions of the device screen.
246 * @param callback Callback used to notify original caller of wallpaper set operation result.
247 */
248 private void setIndividualWallpaperWithCenterCropPosition(WallpaperInfo wallpaper, Asset asset,
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700249 Point dimensions, Point screenSize, SetWallpaperCallback callback) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800250 float scale = Math.max((float) screenSize.x / dimensions.x,
251 (float) screenSize.y / dimensions.y);
252
253 int scaledImageWidth = (int) (dimensions.x * scale);
254 int scaledImageHeight = (int) (dimensions.y * scale);
255
256 // Crop rect is in post-scale units.
257 Rect cropRect = new Rect(
258 (scaledImageWidth - screenSize.x) / 2,
259 (scaledImageHeight - screenSize.y) / 2,
260 scaledImageWidth - ((scaledImageWidth - screenSize.x) / 2),
261 scaledImageHeight - (((scaledImageHeight - screenSize.y) / 2)));
262
263 setIndividualWallpaper(
264 wallpaper, asset, cropRect, scale, WallpaperPersister.DEST_BOTH, callback);
265 }
266
267 /**
268 * Sets a static individual wallpaper to the system via the WallpaperManager.
269 *
270 * @param wallpaper Wallpaper model object.
271 * @param croppedBitmap Bitmap representing the individual wallpaper image.
272 * @param destination The destination - where to set the wallpaper to.
273 * @param callback Called once the wallpaper was set or if an error occurred.
274 */
275 private void setIndividualWallpaper(WallpaperInfo wallpaper, Bitmap croppedBitmap,
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700276 @Destination int destination, SetWallpaperCallback callback) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800277 SetWallpaperTask setWallpaperTask =
278 new SetWallpaperTask(wallpaper, croppedBitmap, destination, callback);
279 setWallpaperTask.execute();
280 }
281
282 /**
283 * Sets a static individual wallpaper to the system via the WallpaperManager with a fill option.
284 *
285 * @param wallpaper Wallpaper model object.
286 * @param croppedBitmap Bitmap representing the individual wallpaper image.
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700287 * @param fillSize Specifies the final bitmap size that should be set to WallpaperManager.
288 * This final bitmap will show the visible area of the provided bitmap
289 * after applying a mask with black background the source bitmap and
290 * centering. There may be black borders around the original bitmap if
291 * it's smaller than the fillSize in one or both dimensions.
Jon Miranda16ea1b12017-12-12 14:52:48 -0800292 * @param destination The destination - where to set the wallpaper to.
293 * @param callback Called once the wallpaper was set or if an error occurred.
294 */
295 private void setIndividualWallpaperFill(WallpaperInfo wallpaper, Bitmap croppedBitmap,
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700296 Point fillSize, @Destination int destination, SetWallpaperCallback callback) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800297 SetWallpaperTask setWallpaperTask =
298 new SetWallpaperTask(wallpaper, croppedBitmap, destination, callback);
299 setWallpaperTask.setFillSize(fillSize);
300 setWallpaperTask.execute();
301 }
302
303 /**
304 * Sets a static individual wallpaper to the system via the WallpaperManager with a stretch
305 * option.
306 *
307 * @param wallpaper Wallpaper model object.
308 * @param croppedBitmap Bitmap representing the individual wallpaper image.
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700309 * @param stretchSize Specifies the final size to which the bitmap should be stretched
310 * prior
Jon Miranda16ea1b12017-12-12 14:52:48 -0800311 * to being set to the device.
312 * @param destination The destination - where to set the wallpaper to.
313 * @param callback Called once the wallpaper was set or if an error occurred.
314 */
315 private void setIndividualWallpaperStretch(WallpaperInfo wallpaper, Bitmap croppedBitmap,
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700316 Point stretchSize, @Destination int destination, SetWallpaperCallback callback) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800317 SetWallpaperTask setWallpaperTask =
318 new SetWallpaperTask(wallpaper, croppedBitmap, destination, callback);
319 setWallpaperTask.setStretchSize(stretchSize);
320 setWallpaperTask.execute();
321 }
322
323 /**
324 * Sets a static individual wallpaper stream to the system via the WallpaperManager.
325 *
326 * @param wallpaper Wallpaper model object.
327 * @param inputStream JPEG or PNG stream of wallpaper image's bytes.
328 * @param destination The destination - where to set the wallpaper to.
329 * @param callback Called once the wallpaper was set or if an error occurred.
330 */
331 private void setIndividualWallpaper(WallpaperInfo wallpaper, InputStream inputStream,
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700332 @Destination int destination, SetWallpaperCallback callback) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800333 SetWallpaperTask setWallpaperTask =
334 new SetWallpaperTask(wallpaper, inputStream, destination, callback);
335 setWallpaperTask.execute();
336 }
337
338 @Override
339 public boolean setWallpaperInRotation(Bitmap wallpaperBitmap, List<String> attributions,
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700340 int actionLabelRes, int actionIconRes, String actionUrl, String collectionId) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800341
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700342 return setWallpaperInRotationStatic(wallpaperBitmap, attributions, actionUrl,
343 actionLabelRes, actionIconRes, collectionId);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800344 }
345
346 @Override
347 public int setWallpaperBitmapInNextRotation(Bitmap wallpaperBitmap) {
Santiago Etchebeheree95b6d92020-06-08 14:19:46 -0700348 return cropAndSetWallpaperBitmapInRotationStatic(wallpaperBitmap);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800349 }
350
351 @Override
352 public boolean finalizeWallpaperForNextRotation(List<String> attributions, String actionUrl,
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700353 int actionLabelRes, int actionIconRes, String collectionId, int wallpaperId) {
Santiago Etchebehered1bd5092018-04-18 16:03:30 -0700354 return finalizeWallpaperForRotatingComponent(attributions, actionUrl, actionLabelRes,
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700355 actionIconRes, collectionId, wallpaperId);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800356 }
357
358 /**
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700359 * Sets wallpaper image and attributions when a static wallpaper is responsible for presenting
360 * the
Jon Miranda16ea1b12017-12-12 14:52:48 -0800361 * current "daily wallpaper".
362 */
363 private boolean setWallpaperInRotationStatic(Bitmap wallpaperBitmap, List<String> attributions,
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700364 String actionUrl, int actionLabelRes, int actionIconRes, String collectionId) {
Santiago Etchebeheree95b6d92020-06-08 14:19:46 -0700365 final int wallpaperId = cropAndSetWallpaperBitmapInRotationStatic(wallpaperBitmap);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800366
367 if (wallpaperId == 0) {
368 return false;
369 }
370
Santiago Etchebehered1bd5092018-04-18 16:03:30 -0700371 return finalizeWallpaperForRotatingComponent(attributions, actionUrl, actionLabelRes,
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700372 actionIconRes, collectionId, wallpaperId);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800373 }
374
375 /**
376 * Finalizes wallpaper metadata by persisting them to SharedPreferences and finalizes the
377 * wallpaper image for live rotating components by copying the "preview" image to the "final"
378 * image file location.
379 *
380 * @return Whether the operation was successful.
381 */
382 private boolean finalizeWallpaperForRotatingComponent(List<String> attributions,
Santiago Etchebehered1bd5092018-04-18 16:03:30 -0700383 String actionUrl,
384 int actionLabelRes,
385 int actionIconRes,
386 String collectionId,
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700387 int wallpaperId) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800388 mWallpaperPreferences.clearHomeWallpaperMetadata();
389
390 boolean isLockWallpaperSet = isSeparateLockScreenWallpaperSet();
391
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700392 // Persist wallpaper IDs if the rotating wallpaper component
393 mWallpaperPreferences.setHomeWallpaperManagerId(wallpaperId);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800394
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700395 // Only copy over wallpaper ID to lock wallpaper if no explicit lock wallpaper is set
396 // (so metadata isn't lost if a user explicitly sets a home-only wallpaper).
397 if (!isLockWallpaperSet) {
398 mWallpaperPreferences.setLockWallpaperId(wallpaperId);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800399 }
400
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700401
Jon Miranda16ea1b12017-12-12 14:52:48 -0800402 mWallpaperPreferences.setHomeWallpaperAttributions(attributions);
403 mWallpaperPreferences.setHomeWallpaperActionUrl(actionUrl);
Santiago Etchebehered1bd5092018-04-18 16:03:30 -0700404 mWallpaperPreferences.setHomeWallpaperActionLabelRes(actionLabelRes);
405 mWallpaperPreferences.setHomeWallpaperActionIconRes(actionIconRes);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800406 // Only set base image URL for static Backdrop images, not for rotation.
407 mWallpaperPreferences.setHomeWallpaperBaseImageUrl(null);
408 mWallpaperPreferences.setHomeWallpaperCollectionId(collectionId);
409
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700410 // Set metadata to lock screen also when the rotating wallpaper so if user sets a home
411 // screen-only wallpaper later, these attributions will still be available.
412 if (!isLockWallpaperSet) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800413 mWallpaperPreferences.setLockWallpaperAttributions(attributions);
414 mWallpaperPreferences.setLockWallpaperActionUrl(actionUrl);
Santiago Etchebehered1bd5092018-04-18 16:03:30 -0700415 mWallpaperPreferences.setLockWallpaperActionLabelRes(actionLabelRes);
416 mWallpaperPreferences.setLockWallpaperActionIconRes(actionIconRes);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800417 mWallpaperPreferences.setLockWallpaperCollectionId(collectionId);
418 }
419
420 return true;
421 }
422
423 /**
Jon Miranda16ea1b12017-12-12 14:52:48 -0800424 * Sets a wallpaper in rotation as a static wallpaper to the {@link WallpaperManager} with the
425 * option allowBackup=false to save user data.
426 *
427 * @return wallpaper ID for the wallpaper bitmap.
428 */
Santiago Etchebeheree95b6d92020-06-08 14:19:46 -0700429 private int cropAndSetWallpaperBitmapInRotationStatic(Bitmap wallpaperBitmap) {
430 // Calculate crop and scale of the wallpaper to match the default one used in preview
431 Point wallpaperSize = new Point(wallpaperBitmap.getWidth(), wallpaperBitmap.getHeight());
432 WindowManager windowManager =
433 (WindowManager) mAppContext.getSystemService(Context.WINDOW_SERVICE);
434 Resources resources = mAppContext.getResources();
435 Point defaultCropSurfaceSize = WallpaperCropUtils.getDefaultCropSurfaceSize(
436 resources, windowManager.getDefaultDisplay());
437 Point screenSize = ScreenSizeCalculator.getInstance().getScreenSize(
438 windowManager.getDefaultDisplay());
439
440 // Determine minimum zoom to fit maximum visible area of wallpaper on crop surface.
441 float minWallpaperZoom =
442 WallpaperCropUtils.calculateMinZoom(wallpaperSize, screenSize);
443
444 PointF centerPosition = WallpaperCropUtils.calculateDefaultCenter(mAppContext,
445 wallpaperSize, WallpaperCropUtils.calculateVisibleRect(wallpaperSize, screenSize));
446
447 Point scaledCenter = new Point((int) (minWallpaperZoom * centerPosition.x),
448 (int) (minWallpaperZoom * centerPosition.y));
449
450 int offsetX = Math.max(0, -(screenSize.x / 2 - scaledCenter.x));
451 int offsetY = Math.max(0, -(screenSize.y / 2 - scaledCenter.y));
452
453 Rect cropRect = WallpaperCropUtils.calculateCropRect(mAppContext, minWallpaperZoom,
454 wallpaperSize, defaultCropSurfaceSize, screenSize, offsetX, offsetY);
455
456 Rect scaledCropRect = new Rect(
457 Math.round((float) cropRect.left / minWallpaperZoom),
458 Math.round((float) cropRect.top / minWallpaperZoom),
459 Math.round((float) cropRect.right / minWallpaperZoom),
460 Math.round((float) cropRect.bottom / minWallpaperZoom));
461
462 // Scale and crop the bitmap
463 wallpaperBitmap = Bitmap.createBitmap(wallpaperBitmap,
464 scaledCropRect.left,
465 scaledCropRect.top,
466 scaledCropRect.width(),
467 scaledCropRect.height());
468
Jon Miranda16ea1b12017-12-12 14:52:48 -0800469 // Set wallpaper to home-only instead of both home and lock if there's a distinct lock-only
470 // static wallpaper set so we don't override the lock wallpaper.
471 boolean isLockWallpaperSet = isSeparateLockScreenWallpaperSet();
472
473 int whichWallpaper = (isLockWallpaperSet)
474 ? WallpaperManagerCompat.FLAG_SYSTEM
475 : WallpaperManagerCompat.FLAG_SYSTEM | WallpaperManagerCompat.FLAG_LOCK;
476
477 return setBitmapToWallpaperManagerCompat(wallpaperBitmap, false /* allowBackup */,
478 whichWallpaper);
479 }
480
481 /**
Jon Miranda16ea1b12017-12-12 14:52:48 -0800482 * Sets a wallpaper bitmap to the {@link WallpaperManagerCompat}.
483 *
484 * @return an integer wallpaper ID. This is an actual wallpaper ID on N and later versions of
485 * Android, otherwise on pre-N versions of Android will return a positive integer when the
486 * operation was successful and zero if the operation encountered an error.
487 */
488 private int setBitmapToWallpaperManagerCompat(Bitmap wallpaperBitmap, boolean allowBackup,
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700489 int whichWallpaper) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800490 ByteArrayOutputStream tmpOut = new ByteArrayOutputStream();
491 if (wallpaperBitmap.compress(CompressFormat.JPEG, DEFAULT_COMPRESS_QUALITY, tmpOut)) {
492 try {
493 byte[] outByteArray = tmpOut.toByteArray();
494 return mWallpaperManagerCompat.setStream(
495 new ByteArrayInputStream(outByteArray),
496 null /* visibleCropHint */,
497 allowBackup,
498 whichWallpaper);
499 } catch (IOException e) {
500 Log.e(TAG, "unable to write stream to wallpaper manager");
501 return 0;
502 }
503 } else {
504 Log.e(TAG, "unable to compress wallpaper");
505 try {
506 return mWallpaperManagerCompat.setBitmap(
507 wallpaperBitmap,
508 null /* visibleCropHint */,
509 allowBackup,
510 whichWallpaper);
511 } catch (IOException e) {
512 Log.e(TAG, "unable to set wallpaper");
513 return 0;
514 }
515 }
516 }
517
518 private int setStreamToWallpaperManagerCompat(InputStream inputStream, boolean allowBackup,
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700519 int whichWallpaper) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800520 try {
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700521 return mWallpaperManagerCompat.setStream(inputStream, null, allowBackup,
522 whichWallpaper);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800523 } catch (IOException e) {
524 return 0;
525 }
526 }
527
528 @Override
529 public void setWallpaperInfoInPreview(WallpaperInfo wallpaper) {
530 mWallpaperInfoInPreview = wallpaper;
531 }
532
533 @Override
534 public void onLiveWallpaperSet() {
535 android.app.WallpaperInfo currentWallpaperComponent = mWallpaperManager.getWallpaperInfo();
chihhangchuang210c9602020-06-02 12:38:14 +0800536 android.app.WallpaperInfo previewedWallpaperComponent = mWallpaperInfoInPreview != null
537 ? mWallpaperInfoInPreview.getWallpaperComponent() : null;
Jon Miranda16ea1b12017-12-12 14:52:48 -0800538
539 // If there is no live wallpaper set on the WallpaperManager or it doesn't match the
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700540 // WallpaperInfo which was last previewed, then do nothing and nullify last previewed
541 // wallpaper.
Jon Miranda16ea1b12017-12-12 14:52:48 -0800542 if (currentWallpaperComponent == null || previewedWallpaperComponent == null
543 || !currentWallpaperComponent.getPackageName()
544 .equals(previewedWallpaperComponent.getPackageName())) {
545 mWallpaperInfoInPreview = null;
546 return;
547 }
548
549 setLiveWallpaperMetadata();
550 }
551
552 /**
553 * Returns whether a separate lock-screen (static) wallpaper is set to the WallpaperManager.
554 */
555 private boolean isSeparateLockScreenWallpaperSet() {
556 ParcelFileDescriptor lockWallpaperFile =
557 mWallpaperManagerCompat.getWallpaperFile(WallpaperManagerCompat.FLAG_LOCK);
558
559 boolean isLockWallpaperSet = false;
560
561 if (lockWallpaperFile != null) {
562 isLockWallpaperSet = true;
563
564 try {
565 lockWallpaperFile.close();
566 } catch (IOException e) {
567 Log.e(TAG, "Unable to close PFD for lock wallpaper", e);
568 }
569 }
570
571 return isLockWallpaperSet;
572 }
573
574 /**
575 * Sets the live wallpaper's metadata on SharedPreferences.
576 */
577 private void setLiveWallpaperMetadata() {
578 android.app.WallpaperInfo previewedWallpaperComponent =
579 mWallpaperInfoInPreview.getWallpaperComponent();
580
581 mWallpaperPreferences.clearHomeWallpaperMetadata();
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700582 // NOTE: We explicitly do not also clear the lock wallpaper metadata. Since the user may
583 // have set the live wallpaper on the home screen only, we leave the lock wallpaper metadata
584 // intact. If the user has set the live wallpaper for both home and lock screens, then the
Jon Miranda16ea1b12017-12-12 14:52:48 -0800585 // WallpaperRefresher will pick up on that and update the preferences later.
586 mWallpaperPreferences
587 .setHomeWallpaperAttributions(mWallpaperInfoInPreview.getAttributions(mAppContext));
588 mWallpaperPreferences.setHomeWallpaperPackageName(
589 previewedWallpaperComponent.getPackageName());
Kunhung Li3e50fd22020-05-12 20:46:18 +0800590 mWallpaperPreferences.setHomeWallpaperServiceName(
591 previewedWallpaperComponent.getServiceName());
Jon Miranda16ea1b12017-12-12 14:52:48 -0800592 mWallpaperPreferences.setHomeWallpaperCollectionId(
593 mWallpaperInfoInPreview.getCollectionId(mAppContext));
594 mWallpaperPreferences.setWallpaperPresentationMode(
595 WallpaperPreferences.PRESENTATION_MODE_STATIC);
596 mWallpaperPreferences.clearDailyRotations();
597 }
598
Jon Miranda16ea1b12017-12-12 14:52:48 -0800599 private class SetWallpaperTask extends AsyncTask<Void, Void, Boolean> {
600
601 private final WallpaperInfo mWallpaper;
602 @Destination
603 private final int mDestination;
604 private final WallpaperPersister.SetWallpaperCallback mCallback;
605
606 private Bitmap mBitmap;
607 private InputStream mInputStream;
608
609 /**
610 * Optional parameters for applying a post-decoding fill or stretch transformation.
611 */
612 @Nullable
613 private Point mFillSize;
614 @Nullable
615 private Point mStretchSize;
616
617 SetWallpaperTask(WallpaperInfo wallpaper, Bitmap bitmap, @Destination int destination,
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700618 WallpaperPersister.SetWallpaperCallback callback) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800619 super();
620 mWallpaper = wallpaper;
621 mBitmap = bitmap;
622 mDestination = destination;
623 mCallback = callback;
624 }
625
626 /**
627 * Constructor for SetWallpaperTask which takes an InputStream instead of a bitmap. The task
628 * will close the InputStream once it is done with it.
629 */
630 SetWallpaperTask(WallpaperInfo wallpaper, InputStream stream,
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700631 @Destination int destination, WallpaperPersister.SetWallpaperCallback callback) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800632 mWallpaper = wallpaper;
633 mInputStream = stream;
634 mDestination = destination;
635 mCallback = callback;
636 }
637
638 void setFillSize(Point fillSize) {
639 if (mStretchSize != null) {
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700640 throw new IllegalArgumentException(
641 "Can't pass a fill size option if a stretch size is "
642 + "already set.");
Jon Miranda16ea1b12017-12-12 14:52:48 -0800643 }
644 mFillSize = fillSize;
645 }
646
647 void setStretchSize(Point stretchSize) {
648 if (mFillSize != null) {
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700649 throw new IllegalArgumentException(
650 "Can't pass a stretch size option if a fill size is "
651 + "already set.");
Jon Miranda16ea1b12017-12-12 14:52:48 -0800652 }
653 mStretchSize = stretchSize;
654 }
655
656 @Override
657 protected Boolean doInBackground(Void... unused) {
658 int whichWallpaper;
659 if (mDestination == DEST_HOME_SCREEN) {
660 whichWallpaper = WallpaperManagerCompat.FLAG_SYSTEM;
661 } else if (mDestination == DEST_LOCK_SCREEN) {
662 whichWallpaper = WallpaperManagerCompat.FLAG_LOCK;
663 } else { // DEST_BOTH
664 whichWallpaper = WallpaperManagerCompat.FLAG_SYSTEM
665 | WallpaperManagerCompat.FLAG_LOCK;
666 }
667
Jon Miranda16ea1b12017-12-12 14:52:48 -0800668
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700669 boolean wasLockWallpaperSet = LockWallpaperStatusChecker.isLockWallpaperSet(
670 mAppContext);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800671
672 boolean allowBackup = mWallpaper.getBackupPermission() == WallpaperInfo.BACKUP_ALLOWED;
673 final int wallpaperId;
674 if (mBitmap != null) {
675 // Apply fill or stretch transformations on mBitmap if necessary.
676 if (mFillSize != null) {
677 mBitmap = BitmapTransformer.applyFillTransformation(mBitmap, mFillSize);
678 }
679 if (mStretchSize != null) {
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700680 mBitmap = Bitmap.createScaledBitmap(mBitmap, mStretchSize.x, mStretchSize.y,
681 true);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800682 }
683
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700684 wallpaperId = setBitmapToWallpaperManagerCompat(mBitmap, allowBackup,
685 whichWallpaper);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800686 } else if (mInputStream != null) {
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700687 wallpaperId = setStreamToWallpaperManagerCompat(mInputStream, allowBackup,
688 whichWallpaper);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800689 } else {
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700690 Log.e(TAG,
691 "Both the wallpaper bitmap and input stream are null so we're unable to "
692 + "set any "
693 + "kind of wallpaper here.");
Jon Miranda16ea1b12017-12-12 14:52:48 -0800694 wallpaperId = 0;
695 }
696
697 if (wallpaperId > 0) {
698 if (mDestination == DEST_HOME_SCREEN
699 && mWallpaperPreferences.getWallpaperPresentationMode()
700 == WallpaperPreferences.PRESENTATION_MODE_ROTATING
701 && !wasLockWallpaperSet
702 && BuildCompat.isAtLeastN()) {
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700703 copyRotatingWallpaperToLock();
Jon Miranda16ea1b12017-12-12 14:52:48 -0800704 }
705 setImageWallpaperMetadata(mDestination, wallpaperId);
706 return true;
707 } else {
708 return false;
709 }
710 }
711
712 @Override
713 protected void onPostExecute(Boolean isSuccess) {
714 if (mInputStream != null) {
715 try {
716 mInputStream.close();
717 } catch (IOException e) {
718 Log.e(TAG, "Failed to close input stream " + e);
719 mCallback.onError(e /* throwable */);
720 return;
721 }
722 }
723
724 if (isSuccess) {
“Chuckffd832c2020-03-22 02:15:58 +0800725 mCallback.onSuccess(mWallpaper);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800726 mWallpaperChangedNotifier.notifyWallpaperChanged();
727 } else {
728 mCallback.onError(null /* throwable */);
729 }
730 }
731
732 /**
733 * Copies home wallpaper metadata to lock, and if rotation was enabled with a live wallpaper
734 * previously, then copies over the rotating wallpaper image to the WallpaperManager also.
735 * <p>
736 * Used to accommodate the case where a user had gone from a home+lock daily rotation to
737 * selecting a static wallpaper on home-only. The image and metadata that was previously
738 * rotating is now copied to the lock screen.
Jon Miranda16ea1b12017-12-12 14:52:48 -0800739 */
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700740 private void copyRotatingWallpaperToLock() {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800741
742 mWallpaperPreferences.setLockWallpaperAttributions(
743 mWallpaperPreferences.getHomeWallpaperAttributions());
744 mWallpaperPreferences.setLockWallpaperActionUrl(
745 mWallpaperPreferences.getHomeWallpaperActionUrl());
Santiago Etchebehered1bd5092018-04-18 16:03:30 -0700746 mWallpaperPreferences.setLockWallpaperActionLabelRes(
747 mWallpaperPreferences.getHomeWallpaperActionLabelRes());
748 mWallpaperPreferences.setLockWallpaperActionIconRes(
749 mWallpaperPreferences.getHomeWallpaperActionIconRes());
Jon Miranda16ea1b12017-12-12 14:52:48 -0800750 mWallpaperPreferences.setLockWallpaperCollectionId(
751 mWallpaperPreferences.getHomeWallpaperCollectionId());
752
753 // Set the lock wallpaper ID to what Android set it to, following its having
754 // copied the system wallpaper over to the lock screen when we changed from
755 // "both" to distinct system and lock screen wallpapers.
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700756 mWallpaperPreferences.setLockWallpaperId(
757 mWallpaperManagerCompat.getWallpaperId(WallpaperManagerCompat.FLAG_LOCK));
758
Jon Miranda16ea1b12017-12-12 14:52:48 -0800759 }
760
761 /**
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700762 * Sets the image wallpaper's metadata on SharedPreferences. This method is called after the
763 * set wallpaper operation is successful.
Jon Miranda16ea1b12017-12-12 14:52:48 -0800764 *
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700765 * @param destination Which destination of wallpaper the metadata corresponds to (home
766 * screen, lock screen, or both).
767 * @param wallpaperId The ID of the static wallpaper returned by WallpaperManager, which
768 * on N and later versions of Android uniquely identifies a wallpaper
769 * image.
Jon Miranda16ea1b12017-12-12 14:52:48 -0800770 */
771 private void setImageWallpaperMetadata(@Destination int destination, int wallpaperId) {
772 if (destination == DEST_HOME_SCREEN || destination == DEST_BOTH) {
773 mWallpaperPreferences.clearHomeWallpaperMetadata();
774 setImageWallpaperHomeMetadata(wallpaperId);
775
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700776 // Reset presentation mode to STATIC if an individual wallpaper is set to the
777 // home screen
Jon Miranda16ea1b12017-12-12 14:52:48 -0800778 // because rotation always affects at least the home screen.
779 mWallpaperPreferences.setWallpaperPresentationMode(
780 WallpaperPreferences.PRESENTATION_MODE_STATIC);
781 }
782
783 if (destination == DEST_LOCK_SCREEN || destination == DEST_BOTH) {
784 mWallpaperPreferences.clearLockWallpaperMetadata();
785 setImageWallpaperLockMetadata(wallpaperId);
786 }
787
788 mWallpaperPreferences.clearDailyRotations();
789 }
790
791 private void setImageWallpaperHomeMetadata(int homeWallpaperId) {
792 if (BuildCompat.isAtLeastN()) {
793 mWallpaperPreferences.setHomeWallpaperManagerId(homeWallpaperId);
794 }
795
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700796 // Compute bitmap hash code after setting the wallpaper because JPEG compression has
797 // likely changed many pixels' color values. Forget the previously loaded wallpaper
798 // bitmap so that WallpaperManager doesn't return the old wallpaper drawable. Do this
799 // on N+ devices in addition to saving the wallpaper ID for the purpose of backup &
800 // restore.
Jon Miranda16ea1b12017-12-12 14:52:48 -0800801 mWallpaperManager.forgetLoadedWallpaper();
802 mBitmap = ((BitmapDrawable) mWallpaperManagerCompat.getDrawable()).getBitmap();
803 long bitmapHash = BitmapUtils.generateHashCode(mBitmap);
804
805 mWallpaperPreferences.setHomeWallpaperHashCode(bitmapHash);
806
Santiago Etchebehered1bd5092018-04-18 16:03:30 -0700807 mWallpaperPreferences.setHomeWallpaperAttributions(
808 mWallpaper.getAttributions(mAppContext));
Jon Miranda16ea1b12017-12-12 14:52:48 -0800809 mWallpaperPreferences.setHomeWallpaperBaseImageUrl(mWallpaper.getBaseImageUrl());
810 mWallpaperPreferences.setHomeWallpaperActionUrl(mWallpaper.getActionUrl(mAppContext));
Santiago Etchebeheree0810d02018-05-10 17:39:40 -0700811 mWallpaperPreferences.setHomeWallpaperActionLabelRes(
812 mWallpaper.getActionLabelRes(mAppContext));
813 mWallpaperPreferences.setHomeWallpaperActionIconRes(
814 mWallpaper.getActionIconRes(mAppContext));
Santiago Etchebehered1bd5092018-04-18 16:03:30 -0700815 mWallpaperPreferences.setHomeWallpaperCollectionId(
816 mWallpaper.getCollectionId(mAppContext));
Jon Miranda16ea1b12017-12-12 14:52:48 -0800817 mWallpaperPreferences.setHomeWallpaperRemoteId(mWallpaper.getWallpaperId());
818 }
819
820 private void setImageWallpaperLockMetadata(int lockWallpaperId) {
821 mWallpaperPreferences.setLockWallpaperId(lockWallpaperId);
Santiago Etchebehered1bd5092018-04-18 16:03:30 -0700822 mWallpaperPreferences.setLockWallpaperAttributions(
823 mWallpaper.getAttributions(mAppContext));
Jon Miranda16ea1b12017-12-12 14:52:48 -0800824 mWallpaperPreferences.setLockWallpaperActionUrl(mWallpaper.getActionUrl(mAppContext));
Santiago Etchebehere1ab75482018-06-15 15:05:25 -0700825 mWallpaperPreferences.setLockWallpaperActionLabelRes(
Santiago Etchebeheree0810d02018-05-10 17:39:40 -0700826 mWallpaper.getActionLabelRes(mAppContext));
Santiago Etchebehere1ab75482018-06-15 15:05:25 -0700827 mWallpaperPreferences.setLockWallpaperActionIconRes(
Santiago Etchebeheree0810d02018-05-10 17:39:40 -0700828 mWallpaper.getActionIconRes(mAppContext));
Santiago Etchebehered1bd5092018-04-18 16:03:30 -0700829 mWallpaperPreferences.setLockWallpaperCollectionId(
830 mWallpaper.getCollectionId(mAppContext));
“Chuck2c8626f2020-03-22 03:47:59 +0800831 mWallpaperPreferences.setLockWallpaperRemoteId(mWallpaper.getWallpaperId());
Jon Miranda16ea1b12017-12-12 14:52:48 -0800832
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700833 // Save the lock wallpaper image's hash code as well for the sake of backup & restore
834 // because WallpaperManager-generated IDs are specific to a physical device and
835 // cannot be used to identify a wallpaper image on another device after restore is
836 // complete.
Jon Miranda16ea1b12017-12-12 14:52:48 -0800837 saveLockWallpaperHashCode();
838 }
839
840 private void saveLockWallpaperHashCode() {
841 Bitmap lockBitmap = null;
842
843 ParcelFileDescriptor parcelFd = mWallpaperManagerCompat.getWallpaperFile(
844 WallpaperManagerCompat.FLAG_LOCK);
845
846 if (parcelFd == null) {
847 return;
848 }
849
850 InputStream fileStream = null;
851 try {
852 fileStream = new FileInputStream(parcelFd.getFileDescriptor());
853 lockBitmap = BitmapFactory.decodeStream(fileStream);
854 parcelFd.close();
855 } catch (IOException e) {
856 Log.e(TAG, "IO exception when closing the file descriptor.");
857 } finally {
858 if (fileStream != null) {
859 try {
860 fileStream.close();
861 } catch (IOException e) {
Samuel Fufa03bc6ac2019-09-19 12:01:50 -0700862 Log.e(TAG,
863 "IO exception when closing the input stream for the lock screen "
864 + "WP.");
Jon Miranda16ea1b12017-12-12 14:52:48 -0800865 }
866 }
867 }
868
869 if (lockBitmap != null) {
870 long bitmapHash = BitmapUtils.generateHashCode(lockBitmap);
871 mWallpaperPreferences.setLockWallpaperHashCode(bitmapHash);
872 }
873 }
874 }
875}