Debian Codegraph @

core/java/android/service/wallpaper/WallpaperService.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2009 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
17 package android.service.wallpaper;
18
19 import static android.app.WallpaperManager.COMMAND_FREEZE;
20 import static android.app.WallpaperManager.COMMAND_UNFREEZE;
21 import static android.app.WallpaperManager.SetWallpaperFlags;
22 import static android.graphics.Matrix.MSCALE_X;
23 import static android.graphics.Matrix.MSCALE_Y;
24 import static android.graphics.Matrix.MSKEW_X;
25 import static android.graphics.Matrix.MSKEW_Y;
26 import static android.view.SurfaceControl.METADATA_WINDOW_TYPE;
27 import static android.view.View.SYSTEM_UI_FLAG_VISIBLE;
28 import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
29
30 import android.animation.AnimationHandler;
31 import android.animation.Animator;
32 import android.animation.AnimatorListenerAdapter;
33 import android.animation.ValueAnimator;
34 import android.annotation.FloatRange;
35 import android.annotation.NonNull;
36 import android.annotation.Nullable;
37 import android.annotation.SdkConstant;
38 import android.annotation.SdkConstant.SdkConstantType;
39 import android.annotation.SystemApi;
40 import android.app.Service;
41 import android.app.WallpaperColors;
42 import android.app.WallpaperInfo;
43 import android.app.WallpaperManager;
44 import android.compat.annotation.UnsupportedAppUsage;
45 import android.content.Context;
46 import android.content.Intent;
47 import android.content.res.Configuration;
48 import android.content.res.TypedArray;
49 import android.graphics.BLASTBufferQueue;
50 import android.graphics.Bitmap;
51 import android.graphics.Canvas;
52 import android.graphics.Matrix;
53 import android.graphics.PixelFormat;
54 import android.graphics.Point;
55 import android.graphics.Rect;
56 import android.graphics.RectF;
57 import android.graphics.drawable.Drawable;
58 import android.hardware.HardwareBuffer;
59 import android.hardware.display.DisplayManager;
60 import android.hardware.display.DisplayManager.DisplayListener;
61 import android.os.Build;
62 import android.os.Bundle;
63 import android.os.Handler;
64 import android.os.IBinder;
65 import android.os.Looper;
66 import android.os.Message;
67 import android.os.Process;
68 import android.os.RemoteException;
69 import android.os.SystemClock;
70 import android.os.SystemProperties;
71 import android.os.Trace;
72 import android.util.ArraySet;
73 import android.util.Log;
74 import android.util.MergedConfiguration;
75 import android.view.Display;
76 import android.view.DisplayCutout;
77 import android.view.Gravity;
78 import android.view.IWindowSession;
79 import android.view.InputChannel;
80 import android.view.InputDevice;
81 import android.view.InputEvent;
82 import android.view.InputEventReceiver;
83 import android.view.InsetsSourceControl;
84 import android.view.InsetsState;
85 import android.view.InsetsVisibilities;
86 import android.view.MotionEvent;
87 import android.view.PixelCopy;
88 import android.view.Surface;
89 import android.view.SurfaceControl;
90 import android.view.SurfaceHolder;
91 import android.view.View;
92 import android.view.ViewGroup;
93 import android.view.WindowInsets;
94 import android.view.WindowLayout;
95 import android.view.WindowManager;
96 import android.view.WindowManagerGlobal;
97 import android.window.ClientWindowFrames;
98
99 import com.android.internal.annotations.VisibleForTesting;
100 import com.android.internal.os.HandlerCaller;
101 import com.android.internal.view.BaseIWindow;
102 import com.android.internal.view.BaseSurfaceHolder;
103
104 import java.io.FileDescriptor;
105 import java.io.PrintWriter;
106 import java.util.ArrayList;
107 import java.util.Arrays;
108 import java.util.List;
109 import java.util.Objects;
110 import java.util.concurrent.TimeUnit;
111 import java.util.concurrent.atomic.AtomicBoolean;
112 import java.util.function.Supplier;
113
114 /**
115 * A wallpaper service is responsible for showing a live wallpaper behind
116 * applications that would like to sit on top of it. This service object
117 * itself does very little -- its only purpose is to generate instances of
118 * {@link Engine} as needed. Implementing a wallpaper thus
119 * involves subclassing from this, subclassing an Engine implementation,
120 * and implementing {@link #onCreateEngine()} to return a new instance of
121 * your engine.
122 */
123 public abstract class WallpaperService extends Service {
124 /**
125 * The {@link Intent} that must be declared as handled by the service.
126 * To be supported, the service must also require the
127 * {@link android.Manifest.permission#BIND_WALLPAPER} permission so
128 * that other applications can not abuse it.
129 */
130 @SdkConstant(SdkConstantType.SERVICE_ACTION)
131 public static final String SERVICE_INTERFACE =
132 "android.service.wallpaper.WallpaperService";
133
134 /**
135 * Name under which a WallpaperService component publishes information
136 * about itself. This meta-data must reference an XML resource containing
137 * a <code>&lt;{@link android.R.styleable#Wallpaper wallpaper}&gt;</code>
138 * tag.
139 */
140 public static final String SERVICE_META_DATA = "android.service.wallpaper";
141
142 static final String TAG = "WallpaperService";
143 static final boolean DEBUG = false;
144 static final float MIN_PAGE_ALLOWED_MARGIN = .05f;
145 private static final int MIN_BITMAP_SCREENSHOT_WIDTH = 64;
146 private static final long DEFAULT_UPDATE_SCREENSHOT_DURATION = 60 * 1000; //Once per minute
147 private static final @NonNull RectF LOCAL_COLOR_BOUNDS =
148 new RectF(0, 0, 1, 1);
149
150 private static final int DO_ATTACH = 10;
151 private static final int DO_DETACH = 20;
152 private static final int DO_SET_DESIRED_SIZE = 30;
153 private static final int DO_SET_DISPLAY_PADDING = 40;
154 private static final int DO_IN_AMBIENT_MODE = 50;
155
156 private static final int MSG_UPDATE_SURFACE = 10000;
157 private static final int MSG_VISIBILITY_CHANGED = 10010;
158 private static final int MSG_WALLPAPER_OFFSETS = 10020;
159 private static final int MSG_WALLPAPER_COMMAND = 10025;
160 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
161 private static final int MSG_WINDOW_RESIZED = 10030;
162 private static final int MSG_WINDOW_MOVED = 10035;
163 private static final int MSG_TOUCH_EVENT = 10040;
164 private static final int MSG_REQUEST_WALLPAPER_COLORS = 10050;
165 private static final int MSG_ZOOM = 10100;
166 private static final int MSG_RESIZE_PREVIEW = 10110;
167 private static final int MSG_REPORT_SHOWN = 10150;
168 private static final int MSG_UPDATE_DIMMING = 10200;
169 private static final List<Float> PROHIBITED_STEPS = Arrays.asList(0f, Float.POSITIVE_INFINITY,
170 Float.NEGATIVE_INFINITY);
171
172 private static final int NOTIFY_COLORS_RATE_LIMIT_MS = 1000;
173
174 private static final boolean ENABLE_WALLPAPER_DIMMING =
175 SystemProperties.getBoolean("persist.debug.enable_wallpaper_dimming", true);
176
177 private static final long DIMMING_ANIMATION_DURATION_MS = 300L;
178
179 private final ArrayList<Engine> mActiveEngines
180 = new ArrayList<Engine>();
181
182 static final class WallpaperCommand {
183 String action;
184 int x;
185 int y;
186 int z;
187 Bundle extras;
188 boolean sync;
189 }
190
191 /**
192 * The actual implementation of a wallpaper. A wallpaper service may
193 * have multiple instances running (for example as a real wallpaper
194 * and as a preview), each of which is represented by its own Engine
195 * instance. You must implement {@link WallpaperService#onCreateEngine()}
196 * to return your concrete Engine implementation.
197 */
198 public class Engine {
199 IWallpaperEngineWrapper mIWallpaperEngine;
200 final ArraySet<RectF> mLocalColorAreas = new ArraySet<>(4);
201 final ArraySet<RectF> mLocalColorsToAdd = new ArraySet<>(4);
202
203 // 2D matrix [x][y] to represent a page of a portion of a window
204 EngineWindowPage[] mWindowPages = new EngineWindowPage[0];
205 Bitmap mLastScreenshot;
206 int mLastWindowPage = -1;
207 private boolean mResetWindowPages;
208
209 // Copies from mIWallpaperEngine.
210 HandlerCaller mCaller;
211 IWallpaperConnection mConnection;
212 IBinder mWindowToken;
213
214 boolean mInitializing = true;
215 boolean mVisible;
216 boolean mReportedVisible;
217 boolean mDestroyed;
218 // Set to true after receiving WallpaperManager#COMMAND_FREEZE. It's reset back to false
219 // after receiving WallpaperManager#COMMAND_UNFREEZE. COMMAND_FREEZE is fully applied once
220 // mScreenshotSurfaceControl isn't null. When this happens, then Engine is notified through
221 // doVisibilityChanged that main wallpaper surface is no longer visible and the wallpaper
222 // host receives onVisibilityChanged(false) callback.
223 private boolean mFrozenRequested = false;
224
225 // Current window state.
226 boolean mCreated;
227 boolean mSurfaceCreated;
228 boolean mIsCreating;
229 boolean mDrawingAllowed;
230 boolean mOffsetsChanged;
231 boolean mFixedSizeAllowed;
232 boolean mShouldDim;
233 // Whether the wallpaper should be dimmed by default (when no additional dimming is applied)
234 // based on its color hints
235 boolean mShouldDimByDefault;
236 int mWidth;
237 int mHeight;
238 int mFormat;
239 int mType;
240 int mCurWidth;
241 int mCurHeight;
242 float mZoom = 0f;
243 int mWindowFlags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
244 int mWindowPrivateFlags = WindowManager.LayoutParams.PRIVATE_FLAG_WANTS_OFFSET_NOTIFICATIONS
245 | WindowManager.LayoutParams.PRIVATE_FLAG_USE_BLAST;
246 int mCurWindowFlags = mWindowFlags;
247 int mCurWindowPrivateFlags = mWindowPrivateFlags;
248 Rect mPreviewSurfacePosition;
249 final ClientWindowFrames mWinFrames = new ClientWindowFrames();
250 final Rect mDispatchedContentInsets = new Rect();
251 final Rect mDispatchedStableInsets = new Rect();
252 DisplayCutout mDispatchedDisplayCutout = DisplayCutout.NO_CUTOUT;
253 final InsetsState mInsetsState = new InsetsState();
254 final InsetsVisibilities mRequestedVisibilities = new InsetsVisibilities();
255 final InsetsSourceControl[] mTempControls = new InsetsSourceControl[0];
256 final MergedConfiguration mMergedConfiguration = new MergedConfiguration();
257 final Bundle mSyncSeqIdBundle = new Bundle();
258 private final Point mSurfaceSize = new Point();
259 private final Point mLastSurfaceSize = new Point();
260 private final Matrix mTmpMatrix = new Matrix();
261 private final float[] mTmpValues = new float[9];
262
263 final WindowManager.LayoutParams mLayout
264 = new WindowManager.LayoutParams();
265 IWindowSession mSession;
266
267 final Object mLock = new Object();
268 boolean mOffsetMessageEnqueued;
269 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
270 float mPendingXOffset;
271 float mPendingYOffset;
272 float mPendingXOffsetStep;
273 float mPendingYOffsetStep;
274 boolean mPendingSync;
275 MotionEvent mPendingMove;
276 boolean mIsInAmbientMode;
277
278 // Needed for throttling onComputeColors.
279 private long mLastColorInvalidation;
280 private final Runnable mNotifyColorsChanged = this::notifyColorsChanged;
281 private final Supplier<Long> mClockFunction;
282 private final Handler mHandler;
283
284 private Display mDisplay;
285 private Context mDisplayContext;
286 private int mDisplayState;
287 private @Surface.Rotation int mDisplayInstallOrientation;
288 private float mWallpaperDimAmount = 0.05f;
289 private float mPreviousWallpaperDimAmount = mWallpaperDimAmount;
290 private float mDefaultDimAmount = mWallpaperDimAmount;
291
292 SurfaceControl mSurfaceControl = new SurfaceControl();
293 SurfaceControl mBbqSurfaceControl;
294 BLASTBufferQueue mBlastBufferQueue;
295 private SurfaceControl mScreenshotSurfaceControl;
296 private Point mScreenshotSize = new Point();
297
298 final BaseSurfaceHolder mSurfaceHolder = new BaseSurfaceHolder() {
299 {
300 mRequestedFormat = PixelFormat.RGBX_8888;
301 }
302
303 @Override
304 public boolean onAllowLockCanvas() {
305 return mDrawingAllowed;
306 }
307
308 @Override
309 public void onRelayoutContainer() {
310 Message msg = mCaller.obtainMessage(MSG_UPDATE_SURFACE);
311 mCaller.sendMessage(msg);
312 }
313
314 @Override
315 public void onUpdateSurface() {
316 Message msg = mCaller.obtainMessage(MSG_UPDATE_SURFACE);
317 mCaller.sendMessage(msg);
318 }
319
320 public boolean isCreating() {
321 return mIsCreating;
322 }
323
324 @Override
325 public void setFixedSize(int width, int height) {
326 if (!mFixedSizeAllowed && !mIWallpaperEngine.mIsPreview) {
327 // Regular apps can't do this. It can only work for
328 // certain designs of window animations, so you can't
329 // rely on it.
330 throw new UnsupportedOperationException(
331 "Wallpapers currently only support sizing from layout");
332 }
333 super.setFixedSize(width, height);
334 }
335
336 public void setKeepScreenOn(boolean screenOn) {
337 throw new UnsupportedOperationException(
338 "Wallpapers do not support keep screen on");
339 }
340
341 private void prepareToDraw() {
342 if (mDisplayState == Display.STATE_DOZE
343 || mDisplayState == Display.STATE_DOZE_SUSPEND) {
344 try {
345 mSession.pokeDrawLock(mWindow);
346 } catch (RemoteException e) {
347 // System server died, can be ignored.
348 }
349 }
350 }
351
352 @Override
353 public Canvas lockCanvas() {
354 prepareToDraw();
355 return super.lockCanvas();
356 }
357
358 @Override
359 public Canvas lockCanvas(Rect dirty) {
360 prepareToDraw();
361 return super.lockCanvas(dirty);
362 }
363
364 @Override
365 public Canvas lockHardwareCanvas() {
366 prepareToDraw();
367 return super.lockHardwareCanvas();
368 }
369 };
370
371 final class WallpaperInputEventReceiver extends InputEventReceiver {
372 public WallpaperInputEventReceiver(InputChannel inputChannel, Looper looper) {
373 super(inputChannel, looper);
374 }
375
376 @Override
377 public void onInputEvent(InputEvent event) {
378 boolean handled = false;
379 try {
380 if (event instanceof MotionEvent
381 && (event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
382 MotionEvent dup = MotionEvent.obtainNoHistory((MotionEvent)event);
383 dispatchPointer(dup);
384 handled = true;
385 }
386 } finally {
387 finishInputEvent(event, handled);
388 }
389 }
390 }
391 WallpaperInputEventReceiver mInputEventReceiver;
392
393 final BaseIWindow mWindow = new BaseIWindow() {
394 @Override
395 public void resized(ClientWindowFrames frames, boolean reportDraw,
396 MergedConfiguration mergedConfiguration, InsetsState insetsState,
397 boolean forceLayout, boolean alwaysConsumeSystemBars, int displayId,
398 int syncSeqId, int resizeMode) {
399 Message msg = mCaller.obtainMessageIO(MSG_WINDOW_RESIZED,
400 reportDraw ? 1 : 0,
401 mergedConfiguration);
402 mCaller.sendMessage(msg);
403 }
404
405 @Override
406 public void moved(int newX, int newY) {
407 Message msg = mCaller.obtainMessageII(MSG_WINDOW_MOVED, newX, newY);
408 mCaller.sendMessage(msg);
409 }
410
411 @Override
412 public void dispatchAppVisibility(boolean visible) {
413 // We don't do this in preview mode; we'll let the preview
414 // activity tell us when to run.
415 if (!mIWallpaperEngine.mIsPreview) {
416 Message msg = mCaller.obtainMessageI(MSG_VISIBILITY_CHANGED,
417 visible ? 1 : 0);
418 mCaller.sendMessage(msg);
419 }
420 }
421
422 @Override
423 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
424 float zoom, boolean sync) {
425 synchronized (mLock) {
426 if (DEBUG) Log.v(TAG, "Dispatch wallpaper offsets: " + x + ", " + y);
427 mPendingXOffset = x;
428 mPendingYOffset = y;
429 mPendingXOffsetStep = xStep;
430 mPendingYOffsetStep = yStep;
431 if (sync) {
432 mPendingSync = true;
433 }
434 if (!mOffsetMessageEnqueued) {
435 mOffsetMessageEnqueued = true;
436 Message msg = mCaller.obtainMessage(MSG_WALLPAPER_OFFSETS);
437 mCaller.sendMessage(msg);
438 }
439 Message msg = mCaller.obtainMessageI(MSG_ZOOM, Float.floatToIntBits(zoom));
440 mCaller.sendMessage(msg);
441 }
442 }
443
444 @Override
445 public void dispatchWallpaperCommand(String action, int x, int y,
446 int z, Bundle extras, boolean sync) {
447 synchronized (mLock) {
448 if (DEBUG) Log.v(TAG, "Dispatch wallpaper command: " + x + ", " + y);
449 WallpaperCommand cmd = new WallpaperCommand();
450 cmd.action = action;
451 cmd.x = x;
452 cmd.y = y;
453 cmd.z = z;
454 cmd.extras = extras;
455 cmd.sync = sync;
456 Message msg = mCaller.obtainMessage(MSG_WALLPAPER_COMMAND);
457 msg.obj = cmd;
458 mCaller.sendMessage(msg);
459 }
460 }
461 };
462
463 /**
464 * Default constructor
465 */
466 public Engine() {
467 this(SystemClock::elapsedRealtime, Handler.getMain());
468 }
469
470 /**
471 * Constructor used for test purposes.
472 *
473 * @param clockFunction Supplies current times in millis.
474 * @param handler Used for posting/deferring asynchronous calls.
475 * @hide
476 */
477 @VisibleForTesting
478 public Engine(Supplier<Long> clockFunction, Handler handler) {
479 mClockFunction = clockFunction;
480 mHandler = handler;
481 }
482
483 /**
484 * Provides access to the surface in which this wallpaper is drawn.
485 */
486 public SurfaceHolder getSurfaceHolder() {
487 return mSurfaceHolder;
488 }
489
490 /**
491 * Convenience for {@link WallpaperManager#getDesiredMinimumWidth()
492 * WallpaperManager.getDesiredMinimumWidth()}, returning the width
493 * that the system would like this wallpaper to run in.
494 */
495 public int getDesiredMinimumWidth() {
496 return mIWallpaperEngine.mReqWidth;
497 }
498
499 /**
500 * Convenience for {@link WallpaperManager#getDesiredMinimumHeight()
501 * WallpaperManager.getDesiredMinimumHeight()}, returning the height
502 * that the system would like this wallpaper to run in.
503 */
504 public int getDesiredMinimumHeight() {
505 return mIWallpaperEngine.mReqHeight;
506 }
507
508 /**
509 * Return whether the wallpaper is currently visible to the user,
510 * this is the last value supplied to
511 * {@link #onVisibilityChanged(boolean)}.
512 */
513 public boolean isVisible() {
514 return mReportedVisible;
515 }
516
517 /**
518 * Return whether the wallpaper is capable of extracting local colors in a rectangle area,
519 * Must implement without calling super:
520 * {@link #addLocalColorsAreas(List)}
521 * {@link #removeLocalColorsAreas(List)}
522 * When local colors change, call {@link #notifyLocalColorsChanged(List, List)}
523 * See {@link com.android.systemui.wallpapers.ImageWallpaper} for an example
524 * @hide
525 */
526 public boolean supportsLocalColorExtraction() {
527 return false;
528 }
529
530 /**
531 * Returns true if this engine is running in preview mode -- that is,
532 * it is being shown to the user before they select it as the actual
533 * wallpaper.
534 */
535 public boolean isPreview() {
536 return mIWallpaperEngine.mIsPreview;
537 }
538
539 /**
540 * Returns true if this engine is running in ambient mode -- that is,
541 * it is being shown in low power mode, on always on display.
542 * @hide
543 */
544 @SystemApi
545 public boolean isInAmbientMode() {
546 return mIsInAmbientMode;
547 }
548
549 /**
550 * This will be called when the wallpaper is first started. If true is returned, the system
551 * will zoom in the wallpaper by default and zoom it out as the user interacts,
552 * to create depth. Otherwise, zoom will have to be handled manually
553 * in {@link #onZoomChanged(float)}.
554 *
555 * @hide
556 */
557 public boolean shouldZoomOutWallpaper() {
558 return false;
559 }
560
561 /**
562 * This will be called in the end of {@link #updateSurface(boolean, boolean, boolean)}.
563 * If true is returned, the engine will not report shown until rendering finished is
564 * reported. Otherwise, the engine will report shown immediately right after redraw phase
565 * in {@link #updateSurface(boolean, boolean, boolean)}.
566 *
567 * @hide
568 */
569 public boolean shouldWaitForEngineShown() {
570 return false;
571 }
572
573 /**
574 * Reports the rendering is finished, stops waiting, then invokes
575 * {@link IWallpaperEngineWrapper#reportShown()}.
576 *
577 * @hide
578 */
579 public void reportEngineShown(boolean waitForEngineShown) {
580 if (mIWallpaperEngine.mShownReported) return;
581 Trace.beginSection("WPMS.reportEngineShown-" + waitForEngineShown);
582 Log.d(TAG, "reportEngineShown: shouldWait=" + waitForEngineShown);
583 if (!waitForEngineShown) {
584 Message message = mCaller.obtainMessage(MSG_REPORT_SHOWN);
585 mCaller.removeMessages(MSG_REPORT_SHOWN);
586 mCaller.sendMessage(message);
587 } else {
588 // if we are already waiting, no need to reset the timeout.
589 if (!mCaller.hasMessages(MSG_REPORT_SHOWN)) {
590 Message message = mCaller.obtainMessage(MSG_REPORT_SHOWN);
591 mCaller.sendMessageDelayed(message, TimeUnit.SECONDS.toMillis(5));
592 }
593 }
594 Trace.endSection();
595 }
596
597 /**
598 * Control whether this wallpaper will receive raw touch events
599 * from the window manager as the user interacts with the window
600 * that is currently displaying the wallpaper. By default they
601 * are turned off. If enabled, the events will be received in
602 * {@link #onTouchEvent(MotionEvent)}.
603 */
604 public void setTouchEventsEnabled(boolean enabled) {
605 mWindowFlags = enabled
606 ? (mWindowFlags&~WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE)
607 : (mWindowFlags|WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
608 if (mCreated) {
609 updateSurface(false, false, false);
610 }
611 }
612
613 /**
614 * Control whether this wallpaper will receive notifications when the wallpaper
615 * has been scrolled. By default, wallpapers will receive notifications, although
616 * the default static image wallpapers do not. It is a performance optimization to
617 * set this to false.
618 *
619 * @param enabled whether the wallpaper wants to receive offset notifications
620 */
621 public void setOffsetNotificationsEnabled(boolean enabled) {
622 mWindowPrivateFlags = enabled
623 ? (mWindowPrivateFlags |
624 WindowManager.LayoutParams.PRIVATE_FLAG_WANTS_OFFSET_NOTIFICATIONS)
625 : (mWindowPrivateFlags &
626 ~WindowManager.LayoutParams.PRIVATE_FLAG_WANTS_OFFSET_NOTIFICATIONS);
627 if (mCreated) {
628 updateSurface(false, false, false);
629 }
630 }
631
632 /** @hide */
633 public void setShowForAllUsers(boolean show) {
634 mWindowPrivateFlags = show
635 ? (mWindowPrivateFlags
636 | WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS)
637 : (mWindowPrivateFlags
638 & ~WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS);
639 if (mCreated) {
640 updateSurface(false, false, false);
641 }
642 }
643
644 /** {@hide} */
645 @UnsupportedAppUsage
646 public void setFixedSizeAllowed(boolean allowed) {
647 mFixedSizeAllowed = allowed;
648 }
649
650 /**
651 * Returns the current scale of the surface
652 * @hide
653 */
654 @VisibleForTesting
655 public float getZoom() {
656 return mZoom;
657 }
658
659 /**
660 * Called once to initialize the engine. After returning, the
661 * engine's surface will be created by the framework.
662 */
663 public void onCreate(SurfaceHolder surfaceHolder) {
664 }
665
666 /**
667 * Called right before the engine is going away. After this the
668 * surface will be destroyed and this Engine object is no longer
669 * valid.
670 */
671 public void onDestroy() {
672 }
673
674 /**
675 * Called to inform you of the wallpaper becoming visible or
676 * hidden. <em>It is very important that a wallpaper only use
677 * CPU while it is visible.</em>.
678 */
679 public void onVisibilityChanged(boolean visible) {
680 }
681
682 /**
683 * Called with the current insets that are in effect for the wallpaper.
684 * This gives you the part of the overall wallpaper surface that will
685 * generally be visible to the user (ignoring position offsets applied to it).
686 *
687 * @param insets Insets to apply.
688 */
689 public void onApplyWindowInsets(WindowInsets insets) {
690 }
691
692 /**
693 * Called as the user performs touch-screen interaction with the
694 * window that is currently showing this wallpaper. Note that the
695 * events you receive here are driven by the actual application the
696 * user is interacting with, so if it is slow you will get fewer
697 * move events.
698 */
699 public void onTouchEvent(MotionEvent event) {
700 }
701
702 /**
703 * Called to inform you of the wallpaper's offsets changing
704 * within its contain, corresponding to the container's
705 * call to {@link WallpaperManager#setWallpaperOffsets(IBinder, float, float)
706 * WallpaperManager.setWallpaperOffsets()}.
707 */
708 public void onOffsetsChanged(float xOffset, float yOffset,
709 float xOffsetStep, float yOffsetStep,
710 int xPixelOffset, int yPixelOffset) {
711 }
712
713 /**
714 * Process a command that was sent to the wallpaper with
715 * {@link WallpaperManager#sendWallpaperCommand}.
716 * The default implementation does nothing, and always returns null
717 * as the result.
718 *
719 * @param action The name of the command to perform. This tells you
720 * what to do and how to interpret the rest of the arguments.
721 * @param x Generic integer parameter.
722 * @param y Generic integer parameter.
723 * @param z Generic integer parameter.
724 * @param extras Any additional parameters.
725 * @param resultRequested If true, the caller is requesting that
726 * a result, appropriate for the command, be returned back.
727 * @return If returning a result, create a Bundle and place the
728 * result data in to it. Otherwise return null.
729 */
730 public Bundle onCommand(String action, int x, int y, int z,
731 Bundle extras, boolean resultRequested) {
732 return null;
733 }
734
735 /**
736 * Called when the device enters or exits ambient mode.
737 *
738 * @param inAmbientMode {@code true} if in ambient mode.
739 * @param animationDuration How long the transition animation to change the ambient state
740 * should run, in milliseconds. If 0 is passed as the argument
741 * here, the state should be switched immediately.
742 *
743 * @see #isInAmbientMode()
744 * @see WallpaperInfo#supportsAmbientMode()
745 * @hide
746 */
747 @SystemApi
748 public void onAmbientModeChanged(boolean inAmbientMode, long animationDuration) {
749 }
750
751 /**
752 * Called when an application has changed the desired virtual size of
753 * the wallpaper.
754 */
755 public void onDesiredSizeChanged(int desiredWidth, int desiredHeight) {
756 }
757
758 /**
759 * Convenience for {@link SurfaceHolder.Callback#surfaceChanged
760 * SurfaceHolder.Callback.surfaceChanged()}.
761 */
762 public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
763 }
764
765 /**
766 * Convenience for {@link SurfaceHolder.Callback2#surfaceRedrawNeeded
767 * SurfaceHolder.Callback.surfaceRedrawNeeded()}.
768 */
769 public void onSurfaceRedrawNeeded(SurfaceHolder holder) {
770 }
771
772 /**
773 * Convenience for {@link SurfaceHolder.Callback#surfaceCreated
774 * SurfaceHolder.Callback.surfaceCreated()}.
775 */
776 public void onSurfaceCreated(SurfaceHolder holder) {
777 }
778
779 /**
780 * Convenience for {@link SurfaceHolder.Callback#surfaceDestroyed
781 * SurfaceHolder.Callback.surfaceDestroyed()}.
782 */
783 public void onSurfaceDestroyed(SurfaceHolder holder) {
784 }
785
786 /**
787 * Called when the zoom level of the wallpaper changed.
788 * This method will be called with the initial zoom level when the surface is created.
789 *
790 * @param zoom the zoom level, between 0 indicating fully zoomed in and 1 indicating fully
791 * zoomed out.
792 */
793 public void onZoomChanged(@FloatRange(from = 0f, to = 1f) float zoom) {
794 }
795
796 /**
797 * Notifies the engine that wallpaper colors changed significantly.
798 * This will trigger a {@link #onComputeColors()} call.
799 */
800 public void notifyColorsChanged() {
801 final long now = mClockFunction.get();
802 if (now - mLastColorInvalidation < NOTIFY_COLORS_RATE_LIMIT_MS) {
803 Log.w(TAG, "This call has been deferred. You should only call "
804 + "notifyColorsChanged() once every "
805 + (NOTIFY_COLORS_RATE_LIMIT_MS / 1000f) + " seconds.");
806 if (!mHandler.hasCallbacks(mNotifyColorsChanged)) {
807 mHandler.postDelayed(mNotifyColorsChanged, NOTIFY_COLORS_RATE_LIMIT_MS);
808 }
809 return;
810 }
811 mLastColorInvalidation = now;
812 mHandler.removeCallbacks(mNotifyColorsChanged);
813
814 try {
815 final WallpaperColors newColors = onComputeColors();
816 if (mConnection != null) {
817 mConnection.onWallpaperColorsChanged(newColors, mDisplay.getDisplayId());
818 } else {
819 Log.w(TAG, "Can't notify system because wallpaper connection "
820 + "was not established.");
821 }
822 mResetWindowPages = true;
823 processLocalColors(mPendingXOffset, mPendingXOffsetStep);
824 } catch (RemoteException e) {
825 Log.w(TAG, "Can't notify system because wallpaper connection was lost.", e);
826 }
827 }
828
829 /**
830 * Called by the system when it needs to know what colors the wallpaper is using.
831 * You might return null if no color information is available at the moment.
832 * In that case you might want to call {@link #notifyColorsChanged()} when
833 * color information becomes available.
834 * <p>
835 * The simplest way of creating a {@link android.app.WallpaperColors} object is by using
836 * {@link android.app.WallpaperColors#fromBitmap(Bitmap)} or
837 * {@link android.app.WallpaperColors#fromDrawable(Drawable)}, but you can also specify
838 * your main colors by constructing a {@link android.app.WallpaperColors} object manually.
839 *
840 * @return Wallpaper colors.
841 */
842 public @Nullable WallpaperColors onComputeColors() {
843 return null;
844 }
845
846 /**
847 * Send the changed local color areas for the connection
848 * @param regions
849 * @param colors
850 * @hide
851 */
852 public void notifyLocalColorsChanged(@NonNull List<RectF> regions,
853 @NonNull List<WallpaperColors> colors)
854 throws RuntimeException {
855 for (int i = 0; i < regions.size() && i < colors.size(); i++) {
856 WallpaperColors color = colors.get(i);
857 RectF area = regions.get(i);
858 if (color == null || area == null) {
859 if (DEBUG) {
860 Log.e(TAG, "notifyLocalColorsChanged null values. color: "
861 + color + " area " + area);
862 }
863 continue;
864 }
865 try {
866 mConnection.onLocalWallpaperColorsChanged(
867 area,
868 color,
869 mDisplayContext.getDisplayId()
870 );
871 } catch (RemoteException e) {
872 throw new RuntimeException(e);
873 }
874 }
875 WallpaperColors primaryColors = mIWallpaperEngine.mWallpaperManager
876 .getWallpaperColors(WallpaperManager.FLAG_SYSTEM);
877 setPrimaryWallpaperColors(primaryColors);
878 }
879
880 private void setPrimaryWallpaperColors(WallpaperColors colors) {
881 if (colors == null) {
882 return;
883 }
884 int colorHints = colors.getColorHints();
885 mShouldDimByDefault = ((colorHints & WallpaperColors.HINT_SUPPORTS_DARK_TEXT) == 0
886 && (colorHints & WallpaperColors.HINT_SUPPORTS_DARK_THEME) == 0);
887
888 // If default dimming value changes and no additional dimming is applied
889 if (mShouldDimByDefault != mShouldDim && mWallpaperDimAmount == 0f) {
890 mShouldDim = mShouldDimByDefault;
891 updateSurfaceDimming();
892 }
893 }
894
895 /**
896 * Update the dim amount of the wallpaper by updating the surface.
897 *
898 * @param dimAmount Float amount between [0.0, 1.0] to dim the wallpaper.
899 */
900 private void updateWallpaperDimming(float dimAmount) {
901 if (dimAmount == mWallpaperDimAmount) {
902 return;
903 }
904
905 // Custom dim amount cannot be less than the default dim amount.
906 mWallpaperDimAmount = Math.max(mDefaultDimAmount, dimAmount);
907 // If dim amount is 0f (additional dimming is removed), then the wallpaper should dim
908 // based on its default wallpaper color hints.
909 mShouldDim = dimAmount != 0f || mShouldDimByDefault;
910 updateSurfaceDimming();
911 }
912
913 private void updateSurfaceDimming() {
914 if (!ENABLE_WALLPAPER_DIMMING || mBbqSurfaceControl == null) {
915 return;
916 }
917
918 SurfaceControl.Transaction surfaceControlTransaction = new SurfaceControl.Transaction();
919 // TODO: apply the dimming to preview as well once surface transparency works in
920 // preview mode.
921 if ((!isPreview() && mShouldDim)
922 || mPreviousWallpaperDimAmount != mWallpaperDimAmount) {
923 Log.v(TAG, "Setting wallpaper dimming: " + mWallpaperDimAmount);
924
925 // Animate dimming to gradually change the wallpaper alpha from the previous
926 // dim amount to the new amount only if the dim amount changed.
927 ValueAnimator animator = ValueAnimator.ofFloat(
928 mPreviousWallpaperDimAmount, mWallpaperDimAmount);
929 animator.setDuration(DIMMING_ANIMATION_DURATION_MS);
930 animator.addUpdateListener((ValueAnimator va) -> {
931 final float dimValue = (float) va.getAnimatedValue();
932 if (mBbqSurfaceControl != null) {
933 surfaceControlTransaction
934 .setAlpha(mBbqSurfaceControl, 1 - dimValue).apply();
935 }
936 });
937 animator.addListener(new AnimatorListenerAdapter() {
938 @Override
939 public void onAnimationEnd(Animator animation) {
940 updateSurface(false, false, true);
941 }
942 });
943 animator.start();
944 } else {
945 Log.v(TAG, "Setting wallpaper dimming: " + 0);
946 surfaceControlTransaction.setAlpha(mBbqSurfaceControl, 1.0f).apply();
947 updateSurface(false, false, true);
948 }
949
950 mPreviousWallpaperDimAmount = mWallpaperDimAmount;
951 }
952
953 /**
954 * Sets internal engine state. Only for testing.
955 * @param created {@code true} or {@code false}.
956 * @hide
957 */
958 @VisibleForTesting
959 public void setCreated(boolean created) {
960 mCreated = created;
961 }
962
963 protected void dump(String prefix, FileDescriptor fd, PrintWriter out, String[] args) {
964 out.print(prefix); out.print("mInitializing="); out.print(mInitializing);
965 out.print(" mDestroyed="); out.println(mDestroyed);
966 out.print(prefix); out.print("mVisible="); out.print(mVisible);
967 out.print(" mReportedVisible="); out.println(mReportedVisible);
968 out.print(prefix); out.print("mDisplay="); out.println(mDisplay);
969 out.print(prefix); out.print("mCreated="); out.print(mCreated);
970 out.print(" mSurfaceCreated="); out.print(mSurfaceCreated);
971 out.print(" mIsCreating="); out.print(mIsCreating);
972 out.print(" mDrawingAllowed="); out.println(mDrawingAllowed);
973 out.print(prefix); out.print("mWidth="); out.print(mWidth);
974 out.print(" mCurWidth="); out.print(mCurWidth);
975 out.print(" mHeight="); out.print(mHeight);
976 out.print(" mCurHeight="); out.println(mCurHeight);
977 out.print(prefix); out.print("mType="); out.print(mType);
978 out.print(" mWindowFlags="); out.print(mWindowFlags);
979 out.print(" mCurWindowFlags="); out.println(mCurWindowFlags);
980 out.print(prefix); out.print("mWindowPrivateFlags="); out.print(mWindowPrivateFlags);
981 out.print(" mCurWindowPrivateFlags="); out.println(mCurWindowPrivateFlags);
982 out.print(prefix); out.println("mWinFrames="); out.println(mWinFrames);
983 out.print(prefix); out.print("mConfiguration=");
984 out.println(mMergedConfiguration.getMergedConfiguration());
985 out.print(prefix); out.print("mLayout="); out.println(mLayout);
986 out.print(prefix); out.print("mZoom="); out.println(mZoom);
987 out.print(prefix); out.print("mPreviewSurfacePosition=");
988 out.println(mPreviewSurfacePosition);
989 synchronized (mLock) {
990 out.print(prefix); out.print("mPendingXOffset="); out.print(mPendingXOffset);
991 out.print(" mPendingXOffset="); out.println(mPendingXOffset);
992 out.print(prefix); out.print("mPendingXOffsetStep=");
993 out.print(mPendingXOffsetStep);
994 out.print(" mPendingXOffsetStep="); out.println(mPendingXOffsetStep);
995 out.print(prefix); out.print("mOffsetMessageEnqueued=");
996 out.print(mOffsetMessageEnqueued);
997 out.print(" mPendingSync="); out.println(mPendingSync);
998 if (mPendingMove != null) {
999 out.print(prefix); out.print("mPendingMove="); out.println(mPendingMove);
1000 }
1001 }
1002 }
1003
1004 /**
1005 * Set the wallpaper zoom to the given value. This value will be ignored when in ambient
1006 * mode (and zoom will be reset to 0).
1007 * @hide
1008 * @param zoom between 0 and 1 (inclusive) indicating fully zoomed in to fully zoomed out
1009 * respectively.
1010 */
1011 @VisibleForTesting
1012 public void setZoom(float zoom) {
1013 if (DEBUG) {
1014 Log.v(TAG, "set zoom received: " + zoom);
1015 }
1016 boolean updated = false;
1017 synchronized (mLock) {
1018 if (DEBUG) {
1019 Log.v(TAG, "mZoom: " + mZoom + " updated: " + zoom);
1020 }
1021 if (mIsInAmbientMode) {
1022 mZoom = 0;
1023 }
1024 if (Float.compare(zoom, mZoom) != 0) {
1025 mZoom = zoom;
1026 updated = true;
1027 }
1028 }
1029 if (DEBUG) Log.v(TAG, "setZoom updated? " + updated);
1030 if (updated && !mDestroyed) {
1031 onZoomChanged(mZoom);
1032 }
1033 }
1034
1035 private void dispatchPointer(MotionEvent event) {
1036 if (event.isTouchEvent()) {
1037 synchronized (mLock) {
1038 if (event.getAction() == MotionEvent.ACTION_MOVE) {
1039 mPendingMove = event;
1040 } else {
1041 mPendingMove = null;
1042 }
1043 }
1044 Message msg = mCaller.obtainMessageO(MSG_TOUCH_EVENT, event);
1045 mCaller.sendMessage(msg);
1046 } else {
1047 event.recycle();
1048 }
1049 }
1050
1051 private void updateConfiguration(MergedConfiguration mergedConfiguration) {
1052 mMergedConfiguration.setTo(mergedConfiguration);
1053 }
1054
1055 void updateSurface(boolean forceRelayout, boolean forceReport, boolean redrawNeeded) {
1056 if (mDestroyed) {
1057 Log.w(TAG, "Ignoring updateSurface due to destroyed");
1058 return;
1059 }
1060
1061 boolean fixedSize = false;
1062 int myWidth = mSurfaceHolder.getRequestedWidth();
1063 if (myWidth <= 0) myWidth = ViewGroup.LayoutParams.MATCH_PARENT;
1064 else fixedSize = true;
1065 int myHeight = mSurfaceHolder.getRequestedHeight();
1066 if (myHeight <= 0) myHeight = ViewGroup.LayoutParams.MATCH_PARENT;
1067 else fixedSize = true;
1068
1069 final boolean creating = !mCreated;
1070 final boolean surfaceCreating = !mSurfaceCreated;
1071 final boolean formatChanged = mFormat != mSurfaceHolder.getRequestedFormat();
1072 boolean sizeChanged = mWidth != myWidth || mHeight != myHeight;
1073 boolean insetsChanged = !mCreated;
1074 final boolean typeChanged = mType != mSurfaceHolder.getRequestedType();
1075 final boolean flagsChanged = mCurWindowFlags != mWindowFlags ||
1076 mCurWindowPrivateFlags != mWindowPrivateFlags;
1077 if (forceRelayout || creating || surfaceCreating || formatChanged || sizeChanged
1078 || typeChanged || flagsChanged || redrawNeeded
1079 || !mIWallpaperEngine.mShownReported) {
1080
1081 if (DEBUG) Log.v(TAG, "Changes: creating=" + creating
1082 + " format=" + formatChanged + " size=" + sizeChanged);
1083
1084 try {
1085 mWidth = myWidth;
1086 mHeight = myHeight;
1087 mFormat = mSurfaceHolder.getRequestedFormat();
1088 mType = mSurfaceHolder.getRequestedType();
1089
1090 mLayout.x = 0;
1091 mLayout.y = 0;
1092
1093 mLayout.format = mFormat;
1094
1095 mCurWindowFlags = mWindowFlags;
1096 mLayout.flags = mWindowFlags
1097 | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
1098 | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
1099 | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
1100 | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
1101
1102 final Configuration config = mMergedConfiguration.getMergedConfiguration();
1103 final Rect maxBounds = config.windowConfiguration.getMaxBounds();
1104 if (myWidth == ViewGroup.LayoutParams.MATCH_PARENT
1105 && myHeight == ViewGroup.LayoutParams.MATCH_PARENT) {
1106 mLayout.width = myWidth;
1107 mLayout.height = myHeight;
1108 mLayout.flags &= ~WindowManager.LayoutParams.FLAG_SCALED;
1109 } else {
1110 final float layoutScale = Math.max(
1111 maxBounds.width() / (float) myWidth,
1112 maxBounds.height() / (float) myHeight);
1113 mLayout.width = (int) (myWidth * layoutScale + .5f);
1114 mLayout.height = (int) (myHeight * layoutScale + .5f);
1115 mLayout.flags |= WindowManager.LayoutParams.FLAG_SCALED;
1116 }
1117
1118 mCurWindowPrivateFlags = mWindowPrivateFlags;
1119 mLayout.privateFlags = mWindowPrivateFlags;
1120
1121 mLayout.memoryType = mType;
1122 mLayout.token = mWindowToken;
1123
1124 if (!mCreated) {
1125 // Retrieve watch round info
1126 TypedArray windowStyle = obtainStyledAttributes(
1127 com.android.internal.R.styleable.Window);
1128 windowStyle.recycle();
1129
1130 // Add window
1131 mLayout.type = mIWallpaperEngine.mWindowType;
1132 mLayout.gravity = Gravity.START|Gravity.TOP;
1133 mLayout.setFitInsetsTypes(0 /* types */);
1134 mLayout.setTitle(WallpaperService.this.getClass().getName());
1135 mLayout.windowAnimations =
1136 com.android.internal.R.style.Animation_Wallpaper;
1137 InputChannel inputChannel = new InputChannel();
1138
1139 if (mSession.addToDisplay(mWindow, mLayout, View.VISIBLE,
1140 mDisplay.getDisplayId(), mRequestedVisibilities, inputChannel,
1141 mInsetsState, mTempControls, new Rect(), new float[1]) < 0) {
1142 Log.w(TAG, "Failed to add window while updating wallpaper surface.");
1143 return;
1144 }
1145 mSession.setShouldZoomOutWallpaper(mWindow, shouldZoomOutWallpaper());
1146 mCreated = true;
1147
1148 mInputEventReceiver = new WallpaperInputEventReceiver(
1149 inputChannel, Looper.myLooper());
1150 }
1151
1152 mSurfaceHolder.mSurfaceLock.lock();
1153 mDrawingAllowed = true;
1154
1155 if (!fixedSize) {
1156 mLayout.surfaceInsets.set(mIWallpaperEngine.mDisplayPadding);
1157 } else {
1158 mLayout.surfaceInsets.set(0, 0, 0, 0);
1159 }
1160 final int relayoutResult = mSession.relayout(mWindow, mLayout, mWidth, mHeight,
1161 View.VISIBLE, 0, 0, 0, mWinFrames, mMergedConfiguration,
1162 mSurfaceControl, mInsetsState, mTempControls, mSyncSeqIdBundle);
1163
1164 final int transformHint = SurfaceControl.rotationToBufferTransform(
1165 (mDisplayInstallOrientation + mDisplay.getRotation()) % 4);
1166 mSurfaceControl.setTransformHint(transformHint);
1167 WindowLayout.computeSurfaceSize(mLayout, maxBounds, mWidth, mHeight,
1168 mWinFrames.frame, false /* dragResizing */, mSurfaceSize);
1169
1170 if (mSurfaceControl.isValid()) {
1171 if (mBbqSurfaceControl == null) {
1172 mBbqSurfaceControl = new SurfaceControl.Builder()
1173 .setName("Wallpaper BBQ wrapper")
1174 .setHidden(false)
1175 // TODO(b/192291754)
1176 .setMetadata(METADATA_WINDOW_TYPE, TYPE_WALLPAPER)
1177 .setBLASTLayer()
1178 .setParent(mSurfaceControl)
1179 .setCallsite("Wallpaper#relayout")
1180 .build();
1181 }
1182 // Propagate transform hint from WM, so we can use the right hint for the
1183 // first frame.
1184 mBbqSurfaceControl.setTransformHint(transformHint);
1185 Surface blastSurface = getOrCreateBLASTSurface(mSurfaceSize.x,
1186 mSurfaceSize.y, mFormat);
1187 // If blastSurface == null that means it hasn't changed since the last
1188 // time we called. In this situation, avoid calling transferFrom as we
1189 // would then inc the generation ID and cause EGL resources to be recreated.
1190 if (blastSurface != null) {
1191 mSurfaceHolder.mSurface.transferFrom(blastSurface);
1192 }
1193 }
1194 if (!mLastSurfaceSize.equals(mSurfaceSize)) {
1195 mLastSurfaceSize.set(mSurfaceSize.x, mSurfaceSize.y);
1196 }
1197
1198 if (DEBUG) Log.v(TAG, "New surface: " + mSurfaceHolder.mSurface
1199 + ", frame=" + mWinFrames);
1200
1201 int w = mWinFrames.frame.width();
1202 int h = mWinFrames.frame.height();
1203
1204 final DisplayCutout rawCutout = mInsetsState.getDisplayCutout();
1205 final Rect visibleFrame = new Rect(mWinFrames.frame);
1206 visibleFrame.intersect(mInsetsState.getDisplayFrame());
1207 WindowInsets windowInsets = mInsetsState.calculateInsets(visibleFrame,
1208 null /* ignoringVisibilityState */, config.isScreenRound(),
1209 false /* alwaysConsumeSystemBars */, mLayout.softInputMode,
1210 mLayout.flags, SYSTEM_UI_FLAG_VISIBLE, mLayout.type,
1211 config.windowConfiguration.getWindowingMode(), null /* typeSideMap */);
1212
1213 if (!fixedSize) {
1214 final Rect padding = mIWallpaperEngine.mDisplayPadding;
1215 w += padding.left + padding.right;
1216 h += padding.top + padding.bottom;
1217 windowInsets = windowInsets.insetUnchecked(
1218 -padding.left, -padding.top, -padding.right, -padding.bottom);
1219 } else {
1220 w = myWidth;
1221 h = myHeight;
1222 }
1223
1224 if (mCurWidth != w) {
1225 sizeChanged = true;
1226 mCurWidth = w;
1227 }
1228 if (mCurHeight != h) {
1229 sizeChanged = true;
1230 mCurHeight = h;
1231 }
1232
1233 if (DEBUG) {
1234 Log.v(TAG, "Wallpaper size has changed: (" + mCurWidth + ", " + mCurHeight);
1235 }
1236
1237 final Rect contentInsets = windowInsets.getSystemWindowInsets().toRect();
1238 final Rect stableInsets = windowInsets.getStableInsets().toRect();
1239 final DisplayCutout displayCutout = windowInsets.getDisplayCutout() != null
1240 ? windowInsets.getDisplayCutout() : rawCutout;
1241 insetsChanged |= !mDispatchedContentInsets.equals(contentInsets);
1242 insetsChanged |= !mDispatchedStableInsets.equals(stableInsets);
1243 insetsChanged |= !mDispatchedDisplayCutout.equals(displayCutout);
1244
1245 mSurfaceHolder.setSurfaceFrameSize(w, h);
1246 mSurfaceHolder.mSurfaceLock.unlock();
1247
1248 if (!mSurfaceHolder.mSurface.isValid()) {
1249 reportSurfaceDestroyed();
1250 if (DEBUG) Log.v(TAG, "Layout: Surface destroyed");
1251 return;
1252 }
1253
1254 boolean didSurface = false;
1255
1256 try {
1257 mSurfaceHolder.ungetCallbacks();
1258
1259 if (surfaceCreating) {
1260 mIsCreating = true;
1261 didSurface = true;
1262 if (DEBUG) Log.v(TAG, "onSurfaceCreated("
1263 + mSurfaceHolder + "): " + this);
1264 Trace.beginSection("WPMS.Engine.onSurfaceCreated");
1265 onSurfaceCreated(mSurfaceHolder);
1266 Trace.endSection();
1267 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1268 if (callbacks != null) {
1269 for (SurfaceHolder.Callback c : callbacks) {
1270 c.surfaceCreated(mSurfaceHolder);
1271 }
1272 }
1273 }
1274
1275 redrawNeeded |= creating || (relayoutResult
1276 & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0;
1277
1278 if (forceReport || creating || surfaceCreating
1279 || formatChanged || sizeChanged) {
1280 if (DEBUG) {
1281 RuntimeException e = new RuntimeException();
1282 e.fillInStackTrace();
1283 Log.w(TAG, "forceReport=" + forceReport + " creating=" + creating
1284 + " formatChanged=" + formatChanged
1285 + " sizeChanged=" + sizeChanged, e);
1286 }
1287 if (DEBUG) Log.v(TAG, "onSurfaceChanged("
1288 + mSurfaceHolder + ", " + mFormat
1289 + ", " + mCurWidth + ", " + mCurHeight
1290 + "): " + this);
1291 didSurface = true;
1292 Trace.beginSection("WPMS.Engine.onSurfaceChanged");
1293 onSurfaceChanged(mSurfaceHolder, mFormat,
1294 mCurWidth, mCurHeight);
1295 Trace.endSection();
1296 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1297 if (callbacks != null) {
1298 for (SurfaceHolder.Callback c : callbacks) {
1299 c.surfaceChanged(mSurfaceHolder, mFormat,
1300 mCurWidth, mCurHeight);
1301 }
1302 }
1303 }
1304
1305 if (insetsChanged) {
1306 mDispatchedContentInsets.set(contentInsets);
1307 mDispatchedStableInsets.set(stableInsets);
1308 mDispatchedDisplayCutout = displayCutout;
1309 if (DEBUG) {
1310 Log.v(TAG, "dispatching insets=" + windowInsets);
1311 }
1312 Trace.beginSection("WPMS.Engine.onApplyWindowInsets");
1313 onApplyWindowInsets(windowInsets);
1314 Trace.endSection();
1315 }
1316
1317 if (redrawNeeded) {
1318 Trace.beginSection("WPMS.Engine.onSurfaceRedrawNeeded");
1319 onSurfaceRedrawNeeded(mSurfaceHolder);
1320 Trace.endSection();
1321 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1322 if (callbacks != null) {
1323 for (SurfaceHolder.Callback c : callbacks) {
1324 if (c instanceof SurfaceHolder.Callback2) {
1325 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1326 mSurfaceHolder);
1327 }
1328 }
1329 }
1330 }
1331
1332 if (didSurface && !mReportedVisible) {
1333 // This wallpaper is currently invisible, but its
1334 // surface has changed. At this point let's tell it
1335 // again that it is invisible in case the report about
1336 // the surface caused it to start running. We really
1337 // don't want wallpapers running when not visible.
1338 if (mIsCreating) {
1339 // Some wallpapers will ignore this call if they
1340 // had previously been told they were invisble,
1341 // so if we are creating a new surface then toggle
1342 // the state to get them to notice.
1343 if (DEBUG) Log.v(TAG, "onVisibilityChanged(true) at surface: "
1344 + this);
1345 Trace.beginSection("WPMS.Engine.onVisibilityChanged-true");
1346 onVisibilityChanged(true);
1347 Trace.endSection();
1348 }
1349 if (DEBUG) Log.v(TAG, "onVisibilityChanged(false) at surface: "
1350 + this);
1351 Trace.beginSection("WPMS.Engine.onVisibilityChanged-false");
1352 onVisibilityChanged(false);
1353 Trace.endSection();
1354 }
1355 } finally {
1356 mIsCreating = false;
1357 mSurfaceCreated = true;
1358 if (redrawNeeded) {
1359 resetWindowPages();
1360 mSession.finishDrawing(mWindow, null /* postDrawTransaction */,
1361 Integer.MAX_VALUE);
1362 processLocalColors(mPendingXOffset, mPendingXOffsetStep);
1363 }
1364 reposition();
1365 reportEngineShown(shouldWaitForEngineShown());
1366 }
1367 } catch (RemoteException ex) {
1368 }
1369 if (DEBUG) Log.v(
1370 TAG, "Layout: x=" + mLayout.x + " y=" + mLayout.y +
1371 " w=" + mLayout.width + " h=" + mLayout.height);
1372 }
1373 }
1374
1375 private void resizePreview(Rect position) {
1376 if (position != null) {
1377 mSurfaceHolder.setFixedSize(position.width(), position.height());
1378 }
1379 }
1380
1381 private void reposition() {
1382 if (mPreviewSurfacePosition == null) {
1383 return;
1384 }
1385 if (DEBUG) {
1386 Log.i(TAG, "reposition: rect: " + mPreviewSurfacePosition);
1387 }
1388
1389 mTmpMatrix.setTranslate(mPreviewSurfacePosition.left, mPreviewSurfacePosition.top);
1390 mTmpMatrix.postScale(((float) mPreviewSurfacePosition.width()) / mCurWidth,
1391 ((float) mPreviewSurfacePosition.height()) / mCurHeight);
1392 mTmpMatrix.getValues(mTmpValues);
1393 SurfaceControl.Transaction t = new SurfaceControl.Transaction();
1394 t.setPosition(mSurfaceControl, mPreviewSurfacePosition.left,
1395 mPreviewSurfacePosition.top);
1396 t.setMatrix(mSurfaceControl, mTmpValues[MSCALE_X], mTmpValues[MSKEW_Y],
1397 mTmpValues[MSKEW_X], mTmpValues[MSCALE_Y]);
1398 t.apply();
1399 }
1400
1401 void attach(IWallpaperEngineWrapper wrapper) {
1402 if (DEBUG) Log.v(TAG, "attach: " + this + " wrapper=" + wrapper);
1403 if (mDestroyed) {
1404 return;
1405 }
1406
1407 mIWallpaperEngine = wrapper;
1408 mCaller = wrapper.mCaller;
1409 mConnection = wrapper.mConnection;
1410 mWindowToken = wrapper.mWindowToken;
1411 mSurfaceHolder.setSizeFromLayout();
1412 mInitializing = true;
1413 mSession = WindowManagerGlobal.getWindowSession();
1414
1415 mWindow.setSession(mSession);
1416
1417 mLayout.packageName = getPackageName();
1418 mIWallpaperEngine.mDisplayManager.registerDisplayListener(mDisplayListener,
1419 mCaller.getHandler());
1420 mDisplay = mIWallpaperEngine.mDisplay;
1421 // Use window context of TYPE_WALLPAPER so client can access UI resources correctly.
1422 mDisplayContext = createDisplayContext(mDisplay)
1423 .createWindowContext(TYPE_WALLPAPER, null /* options */);
1424 mDefaultDimAmount = mDisplayContext.getResources().getFloat(
1425 com.android.internal.R.dimen.config_wallpaperDimAmount);
1426 mWallpaperDimAmount = mDefaultDimAmount;
1427 mPreviousWallpaperDimAmount = mWallpaperDimAmount;
1428 mDisplayState = mDisplay.getState();
1429 mDisplayInstallOrientation = mDisplay.getInstallOrientation();
1430
1431 if (DEBUG) Log.v(TAG, "onCreate(): " + this);
1432 Trace.beginSection("WPMS.Engine.onCreate");
1433 onCreate(mSurfaceHolder);
1434 Trace.endSection();
1435
1436 mInitializing = false;
1437
1438 mReportedVisible = false;
1439 Trace.beginSection("WPMS.Engine.updateSurface");
1440 updateSurface(false, false, false);
1441 Trace.endSection();
1442 }
1443
1444 /**
1445 * The {@link Context} with resources that match the current display the wallpaper is on.
1446 * For multiple display environment, multiple engines can be created to render on each
1447 * display, but these displays may have different densities. Use this context to get the
1448 * corresponding resources for currently display, avoiding the context of the service.
1449 * <p>
1450 * The display context will never be {@code null} after
1451 * {@link Engine#onCreate(SurfaceHolder)} has been called.
1452 *
1453 * @return A {@link Context} for current display.
1454 */
1455 @Nullable
1456 public Context getDisplayContext() {
1457 return mDisplayContext;
1458 }
1459
1460 /**
1461 * Executes life cycle event and updates internal ambient mode state based on
1462 * message sent from handler.
1463 *
1464 * @param inAmbientMode {@code true} if in ambient mode.
1465 * @param animationDuration For how long the transition will last, in ms.
1466 * @hide
1467 */
1468 @VisibleForTesting
1469 public void doAmbientModeChanged(boolean inAmbientMode, long animationDuration) {
1470 if (!mDestroyed) {
1471 if (DEBUG) {
1472 Log.v(TAG, "onAmbientModeChanged(" + inAmbientMode + ", "
1473 + animationDuration + "): " + this);
1474 }
1475 mIsInAmbientMode = inAmbientMode;
1476 if (mCreated) {
1477 onAmbientModeChanged(inAmbientMode, animationDuration);
1478 }
1479 }
1480 }
1481
1482 void doDesiredSizeChanged(int desiredWidth, int desiredHeight) {
1483 if (!mDestroyed) {
1484 if (DEBUG) Log.v(TAG, "onDesiredSizeChanged("
1485 + desiredWidth + "," + desiredHeight + "): " + this);
1486 mIWallpaperEngine.mReqWidth = desiredWidth;
1487 mIWallpaperEngine.mReqHeight = desiredHeight;
1488 onDesiredSizeChanged(desiredWidth, desiredHeight);
1489 doOffsetsChanged(true);
1490 }
1491 }
1492
1493 void doDisplayPaddingChanged(Rect padding) {
1494 if (!mDestroyed) {
1495 if (DEBUG) Log.v(TAG, "onDisplayPaddingChanged(" + padding + "): " + this);
1496 if (!mIWallpaperEngine.mDisplayPadding.equals(padding)) {
1497 mIWallpaperEngine.mDisplayPadding.set(padding);
1498 updateSurface(true, false, false);
1499 }
1500 }
1501 }
1502
1503 void doVisibilityChanged(boolean visible) {
1504 if (!mDestroyed) {
1505 mVisible = visible;
1506 reportVisibility();
1507 if (mReportedVisible) processLocalColors(mPendingXOffset, mPendingXOffsetStep);
1508 } else {
1509 AnimationHandler.requestAnimatorsEnabled(visible, this);
1510 }
1511 }
1512
1513 void reportVisibility() {
1514 if (mScreenshotSurfaceControl != null && mVisible) {
1515 if (DEBUG) Log.v(TAG, "Frozen so don't report visibility change");
1516 return;
1517 }
1518 if (!mDestroyed) {
1519 mDisplayState = mDisplay == null ? Display.STATE_UNKNOWN : mDisplay.getState();
1520 boolean visible = mVisible && mDisplayState != Display.STATE_OFF;
1521 if (mReportedVisible != visible) {
1522 mReportedVisible = visible;
1523 if (DEBUG) Log.v(TAG, "onVisibilityChanged(" + visible
1524 + "): " + this);
1525 if (visible) {
1526 // If becoming visible, in preview mode the surface
1527 // may have been destroyed so now we need to make
1528 // sure it is re-created.
1529 doOffsetsChanged(false);
1530 // It will check mSurfaceCreated so no need to force relayout.
1531 updateSurface(false /* forceRelayout */, false /* forceReport */,
1532 false /* redrawNeeded */);
1533 }
1534 onVisibilityChanged(visible);
1535 if (mReportedVisible && mFrozenRequested) {
1536 if (DEBUG) Log.v(TAG, "Freezing wallpaper after visibility update");
1537 freeze();
1538 }
1539 AnimationHandler.requestAnimatorsEnabled(visible, this);
1540 }
1541 }
1542 }
1543
1544 void doOffsetsChanged(boolean always) {
1545 if (mDestroyed) {
1546 return;
1547 }
1548
1549 if (!always && !mOffsetsChanged) {
1550 return;
1551 }
1552
1553 float xOffset;
1554 float yOffset;
1555 float xOffsetStep;
1556 float yOffsetStep;
1557 boolean sync;
1558 synchronized (mLock) {
1559 xOffset = mPendingXOffset;
1560 yOffset = mPendingYOffset;
1561 xOffsetStep = mPendingXOffsetStep;
1562 yOffsetStep = mPendingYOffsetStep;
1563 sync = mPendingSync;
1564 mPendingSync = false;
1565 mOffsetMessageEnqueued = false;
1566 }
1567
1568 if (mSurfaceCreated) {
1569 if (mReportedVisible) {
1570 if (DEBUG) Log.v(TAG, "Offsets change in " + this
1571 + ": " + xOffset + "," + yOffset);
1572 final int availw = mIWallpaperEngine.mReqWidth-mCurWidth;
1573 final int xPixels = availw > 0 ? -(int)(availw*xOffset+.5f) : 0;
1574 final int availh = mIWallpaperEngine.mReqHeight-mCurHeight;
1575 final int yPixels = availh > 0 ? -(int)(availh*yOffset+.5f) : 0;
1576 onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixels, yPixels);
1577 } else {
1578 mOffsetsChanged = true;
1579 }
1580 }
1581
1582 if (sync) {
1583 try {
1584 if (DEBUG) Log.v(TAG, "Reporting offsets change complete");
1585 mSession.wallpaperOffsetsComplete(mWindow.asBinder());
1586 } catch (RemoteException e) {
1587 }
1588 }
1589
1590 // setup local color extraction data
1591 processLocalColors(xOffset, xOffsetStep);
1592 }
1593
1594 private void processLocalColors(float xOffset, float xOffsetStep) {
1595 // implemented by the wallpaper
1596 if (supportsLocalColorExtraction()) return;
1597 if (DEBUG) {
1598 Log.d(TAG, "processLocalColors " + xOffset + " of step "
1599 + xOffsetStep);
1600 }
1601 //below is the default implementation
1602 if (xOffset % xOffsetStep > MIN_PAGE_ALLOWED_MARGIN
1603 || !mSurfaceHolder.getSurface().isValid()) return;
1604 int xCurrentPage;
1605 int xPages;
1606 if (!validStep(xOffsetStep)) {
1607 if (DEBUG) {
1608 Log.w(TAG, "invalid offset step " + xOffsetStep);
1609 }
1610 xOffset = 0;
1611 xOffsetStep = 1;
1612 xCurrentPage = 0;
1613 xPages = 1;
1614 } else {
1615 xPages = Math.round(1 / xOffsetStep) + 1;
1616 xOffsetStep = (float) 1 / (float) xPages;
1617 float shrink = (float) (xPages - 1) / (float) xPages;
1618 xOffset *= shrink;
1619 xCurrentPage = Math.round(xOffset / xOffsetStep);
1620 }
1621 if (DEBUG) {
1622 Log.d(TAG, "xPages " + xPages + " xPage " + xCurrentPage);
1623 Log.d(TAG, "xOffsetStep " + xOffsetStep + " xOffset " + xOffset);
1624 }
1625
1626 float finalXOffsetStep = xOffsetStep;
1627 float finalXOffset = xOffset;
1628 mHandler.post(() -> {
1629 Trace.beginSection("WallpaperService#processLocalColors");
1630 resetWindowPages();
1631 int xPage = xCurrentPage;
1632 EngineWindowPage current;
1633 if (mWindowPages.length == 0 || (mWindowPages.length != xPages)) {
1634 mWindowPages = new EngineWindowPage[xPages];
1635 initWindowPages(mWindowPages, finalXOffsetStep);
1636 }
1637 if (mLocalColorsToAdd.size() != 0) {
1638 for (RectF colorArea : mLocalColorsToAdd) {
1639 if (!isValid(colorArea)) continue;
1640 mLocalColorAreas.add(colorArea);
1641 int colorPage = getRectFPage(colorArea, finalXOffsetStep);
1642 EngineWindowPage currentPage = mWindowPages[colorPage];
1643 currentPage.setLastUpdateTime(0);
1644 currentPage.removeColor(colorArea);
1645 }
1646 mLocalColorsToAdd.clear();
1647 }
1648 if (xPage >= mWindowPages.length) {
1649 if (DEBUG) {
1650 Log.e(TAG, "error xPage >= mWindowPages.length page: " + xPage);
1651 Log.e(TAG, "error on page " + xPage + " out of " + xPages);
1652 Log.e(TAG,
1653 "error on xOffsetStep " + finalXOffsetStep
1654 + " xOffset " + finalXOffset);
1655 }
1656 xPage = mWindowPages.length - 1;
1657 }
1658 current = mWindowPages[xPage];
1659 updatePage(current, xPage, xPages, finalXOffsetStep);
1660 Trace.endSection();
1661 });
1662 }
1663
1664 private void initWindowPages(EngineWindowPage[] windowPages, float step) {
1665 for (int i = 0; i < windowPages.length; i++) {
1666 windowPages[i] = new EngineWindowPage();
1667 }
1668 mLocalColorAreas.addAll(mLocalColorsToAdd);
1669 mLocalColorsToAdd.clear();
1670 for (RectF area: mLocalColorAreas) {
1671 if (!isValid(area)) {
1672 mLocalColorAreas.remove(area);
1673 continue;
1674 }
1675 int pageNum = getRectFPage(area, step);
1676 windowPages[pageNum].addArea(area);
1677 }
1678 }
1679
1680 void updatePage(EngineWindowPage currentPage, int pageIndx, int numPages,
1681 float xOffsetStep) {
1682 // in case the clock is zero, we start with negative time
1683 long current = SystemClock.elapsedRealtime() - DEFAULT_UPDATE_SCREENSHOT_DURATION;
1684 long lapsed = current - currentPage.getLastUpdateTime();
1685 // Always update the page when the last update time is <= 0
1686 // This is important especially when the device first boots
1687 if (lapsed < DEFAULT_UPDATE_SCREENSHOT_DURATION) {
1688 return;
1689 }
1690 Surface surface = mSurfaceHolder.getSurface();
1691 if (!surface.isValid()) return;
1692 boolean widthIsLarger = mSurfaceSize.x > mSurfaceSize.y;
1693 int smaller = widthIsLarger ? mSurfaceSize.x
1694 : mSurfaceSize.y;
1695 float ratio = (float) MIN_BITMAP_SCREENSHOT_WIDTH / (float) smaller;
1696 int width = (int) (ratio * mSurfaceSize.x);
1697 int height = (int) (ratio * mSurfaceSize.y);
1698 if (width <= 0 || height <= 0) {
1699 Log.e(TAG, "wrong width and height values of bitmap " + width + " " + height);
1700 return;
1701 }
1702 Bitmap screenShot = Bitmap.createBitmap(width, height,
1703 Bitmap.Config.ARGB_8888);
1704 final Bitmap finalScreenShot = screenShot;
1705 Trace.beginSection("WallpaperService#pixelCopy");
1706 PixelCopy.request(surface, screenShot, (res) -> {
1707 Trace.endSection();
1708 if (DEBUG) Log.d(TAG, "result of pixel copy is " + res);
1709 if (res != PixelCopy.SUCCESS) {
1710 Bitmap lastBitmap = currentPage.getBitmap();
1711 // assign the last bitmap taken for now
1712 currentPage.setBitmap(mLastScreenshot);
1713 Bitmap lastScreenshot = mLastScreenshot;
1714 if (lastScreenshot != null && !lastScreenshot.isRecycled()
1715 && !Objects.equals(lastBitmap, lastScreenshot)) {
1716 updatePageColors(currentPage, pageIndx, numPages, xOffsetStep);
1717 }
1718 } else {
1719 mLastScreenshot = finalScreenShot;
1720 // going to hold this lock for a while
1721 currentPage.setBitmap(finalScreenShot);
1722 currentPage.setLastUpdateTime(current);
1723 updatePageColors(currentPage, pageIndx, numPages, xOffsetStep);
1724 }
1725 }, mHandler);
1726
1727 }
1728 // locked by the passed page
1729 private void updatePageColors(EngineWindowPage page, int pageIndx, int numPages,
1730 float xOffsetStep) {
1731 if (page.getBitmap() == null) return;
1732 Trace.beginSection("WallpaperService#updatePageColors");
1733 if (DEBUG) {
1734 Log.d(TAG, "updatePageColorsLocked for page " + pageIndx + " with areas "
1735 + page.getAreas().size() + " and bitmap size of "
1736 + page.getBitmap().getWidth() + " x " + page.getBitmap().getHeight());
1737 }
1738 for (RectF area: page.getAreas()) {
1739 if (area == null) continue;
1740 RectF subArea = generateSubRect(area, pageIndx, numPages);
1741 Bitmap b = page.getBitmap();
1742 int x = Math.round(b.getWidth() * subArea.left);
1743 int y = Math.round(b.getHeight() * subArea.top);
1744 int width = Math.round(b.getWidth() * subArea.width());
1745 int height = Math.round(b.getHeight() * subArea.height());
1746 Bitmap target;
1747 try {
1748 target = Bitmap.createBitmap(page.getBitmap(), x, y, width, height);
1749 } catch (Exception e) {
1750 Log.e(TAG, "Error creating page local color bitmap", e);
1751 continue;
1752 }
1753 WallpaperColors color = WallpaperColors.fromBitmap(target, mWallpaperDimAmount);
1754 target.recycle();
1755 WallpaperColors currentColor = page.getColors(area);
1756
1757 if (DEBUG) {
1758 Log.d(TAG, "getting local bitmap area x " + x + " y " + y
1759 + " width " + width + " height " + height + " for sub area " + subArea
1760 + " and with page " + pageIndx + " of " + numPages);
1761
1762 }
1763 if (currentColor == null || !color.equals(currentColor)) {
1764 page.addWallpaperColors(area, color);
1765 if (DEBUG) {
1766 Log.d(TAG, "onLocalWallpaperColorsChanged"
1767 + " local color callback for area" + area + " for page " + pageIndx
1768 + " of " + numPages);
1769 }
1770 try {
1771 mConnection.onLocalWallpaperColorsChanged(area, color,
1772 mDisplayContext.getDisplayId());
1773 } catch (RemoteException e) {
1774 Log.e(TAG, "Error calling Connection.onLocalWallpaperColorsChanged", e);
1775 }
1776 }
1777 }
1778 Trace.endSection();
1779 }
1780
1781 private RectF generateSubRect(RectF in, int pageInx, int numPages) {
1782 float minLeft = (float) (pageInx) / (float) (numPages);
1783 float maxRight = (float) (pageInx + 1) / (float) (numPages);
1784 float left = in.left;
1785 float right = in.right;
1786
1787 // bound rect
1788 if (left < minLeft) left = minLeft;
1789 if (right > maxRight) right = maxRight;
1790
1791 // scale up the sub area then trim
1792 left = (left * (float) numPages) % 1f;
1793 right = (right * (float) numPages) % 1f;
1794 if (right == 0f) {
1795 right = 1f;
1796 }
1797
1798 return new RectF(left, in.top, right, in.bottom);
1799 }
1800
1801 private void resetWindowPages() {
1802 if (supportsLocalColorExtraction()) return;
1803 if (!mResetWindowPages) return;
1804 mResetWindowPages = false;
1805 mLastWindowPage = -1;
1806 for (int i = 0; i < mWindowPages.length; i++) {
1807 mWindowPages[i].setLastUpdateTime(0L);
1808 }
1809 }
1810
1811 private int getRectFPage(RectF area, float step) {
1812 if (!isValid(area)) return 0;
1813 if (!validStep(step)) return 0;
1814 int pages = Math.round(1 / step);
1815 int page = Math.round(area.centerX() * pages);
1816 if (page == pages) return pages - 1;
1817 if (page == mWindowPages.length) page = mWindowPages.length - 1;
1818 return page;
1819 }
1820
1821 /**
1822 * Add local colors areas of interest
1823 * @param regions list of areas
1824 * @hide
1825 */
1826 public void addLocalColorsAreas(@NonNull List<RectF> regions) {
1827 if (supportsLocalColorExtraction()) return;
1828 if (DEBUG) {
1829 Log.d(TAG, "addLocalColorsAreas adding local color areas " + regions);
1830 }
1831 mHandler.post(() -> {
1832 mLocalColorsToAdd.addAll(regions);
1833 processLocalColors(mPendingXOffset, mPendingYOffset);
1834 });
1835
1836
1837 }
1838
1839 /**
1840 * Remove local colors areas of interest if they exist
1841 * @param regions list of areas
1842 * @hide
1843 */
1844 public void removeLocalColorsAreas(@NonNull List<RectF> regions) {
1845 if (supportsLocalColorExtraction()) return;
1846 mHandler.post(() -> {
1847 float step = mPendingXOffsetStep;
1848 mLocalColorsToAdd.removeAll(regions);
1849 mLocalColorAreas.removeAll(regions);
1850 if (!validStep(step)) {
1851 return;
1852 }
1853 for (int i = 0; i < mWindowPages.length; i++) {
1854 for (int j = 0; j < regions.size(); j++) {
1855 mWindowPages[i].removeArea(regions.get(j));
1856 }
1857 }
1858 });
1859 }
1860
1861 // fix the rect to be included within the bounds of the bitmap
1862 private Rect fixRect(Bitmap b, Rect r) {
1863 r.left = r.left >= r.right || r.left >= b.getWidth() || r.left > 0
1864 ? 0
1865 : r.left;
1866 r.right = r.left >= r.right || r.right > b.getWidth()
1867 ? b.getWidth()
1868 : r.right;
1869 return r;
1870 }
1871
1872 private boolean validStep(float step) {
1873 return !PROHIBITED_STEPS.contains(step) && step > 0. && step <= 1.;
1874 }
1875
1876 void doCommand(WallpaperCommand cmd) {
1877 Bundle result;
1878 if (!mDestroyed) {
1879 if (COMMAND_FREEZE.equals(cmd.action) || COMMAND_UNFREEZE.equals(cmd.action)) {
1880 updateFrozenState(/* frozenRequested= */ !COMMAND_UNFREEZE.equals(cmd.action));
1881 }
1882 result = onCommand(cmd.action, cmd.x, cmd.y, cmd.z,
1883 cmd.extras, cmd.sync);
1884 } else {
1885 result = null;
1886 }
1887 if (cmd.sync) {
1888 try {
1889 if (DEBUG) Log.v(TAG, "Reporting command complete");
1890 mSession.wallpaperCommandComplete(mWindow.asBinder(), result);
1891 } catch (RemoteException e) {
1892 }
1893 }
1894 }
1895
1896 private void updateFrozenState(boolean frozenRequested) {
1897 if (mIWallpaperEngine.mWallpaperManager.getWallpaperInfo() == null
1898 // Procees the unfreeze command in case the wallaper became static while
1899 // being paused.
1900 && frozenRequested) {
1901 if (DEBUG) Log.v(TAG, "Ignoring the freeze command for static wallpapers");
1902 return;
1903 }
1904 mFrozenRequested = frozenRequested;
1905 boolean isFrozen = mScreenshotSurfaceControl != null;
1906 if (mFrozenRequested == isFrozen) {
1907 return;
1908 }
1909 if (mFrozenRequested) {
1910 freeze();
1911 } else {
1912 unfreeze();
1913 }
1914 }
1915
1916 private void freeze() {
1917 if (!mReportedVisible || mDestroyed) {
1918 // Screenshot can't be taken until visibility is reported to the wallpaper host.
1919 return;
1920 }
1921 if (!showScreenshotOfWallpaper()) {
1922 return;
1923 }
1924 // Prevent a wallpaper host from rendering wallpaper behind a screeshot.
1925 doVisibilityChanged(false);
1926 // Remember that visibility is requested since it's not guaranteed that
1927 // mWindow#dispatchAppVisibility will be called when letterboxed application with
1928 // wallpaper background transitions to the Home screen.
1929 mVisible = true;
1930 }
1931
1932 private void unfreeze() {
1933 cleanUpScreenshotSurfaceControl();
1934 if (mVisible) {
1935 doVisibilityChanged(true);
1936 }
1937 }
1938
1939 private void cleanUpScreenshotSurfaceControl() {
1940 // TODO(b/194399558): Add crossfade transition.
1941 if (mScreenshotSurfaceControl != null) {
1942 new SurfaceControl.Transaction()
1943 .remove(mScreenshotSurfaceControl)
1944 .show(mBbqSurfaceControl)
1945 .apply();
1946 mScreenshotSurfaceControl = null;
1947 }
1948 }
1949
1950 void scaleAndCropScreenshot() {
1951 if (mScreenshotSurfaceControl == null) {
1952 return;
1953 }
1954 if (mScreenshotSize.x <= 0 || mScreenshotSize.y <= 0) {
1955 Log.w(TAG, "Unexpected screenshot size: " + mScreenshotSize);
1956 return;
1957 }
1958 // Don't scale down and using the same scaling factor for both dimensions to
1959 // avoid stretching wallpaper image.
1960 float scaleFactor = Math.max(1, Math.max(
1961 ((float) mSurfaceSize.x) / mScreenshotSize.x,
1962 ((float) mSurfaceSize.y) / mScreenshotSize.y));
1963 int diffX = ((int) (mScreenshotSize.x * scaleFactor)) - mSurfaceSize.x;
1964 int diffY = ((int) (mScreenshotSize.y * scaleFactor)) - mSurfaceSize.y;
1965 if (DEBUG) {
1966 Log.v(TAG, "Adjusting screenshot: scaleFactor=" + scaleFactor
1967 + " diffX=" + diffX + " diffY=" + diffY + " mSurfaceSize=" + mSurfaceSize
1968 + " mScreenshotSize=" + mScreenshotSize);
1969 }
1970 new SurfaceControl.Transaction()
1971 .setMatrix(
1972 mScreenshotSurfaceControl,
1973 /* dsdx= */ scaleFactor, /* dtdx= */ 0,
1974 /* dtdy= */ 0, /* dsdy= */ scaleFactor)
1975 .setWindowCrop(
1976 mScreenshotSurfaceControl,
1977 new Rect(
1978 /* left= */ diffX / 2,
1979 /* top= */ diffY / 2,
1980 /* right= */ diffX / 2 + mScreenshotSize.x,
1981 /* bottom= */ diffY / 2 + mScreenshotSize.y))
1982 .setPosition(mScreenshotSurfaceControl, -diffX / 2, -diffY / 2)
1983 .apply();
1984 }
1985
1986 private boolean showScreenshotOfWallpaper() {
1987 if (mDestroyed || mSurfaceControl == null || !mSurfaceControl.isValid()) {
1988 if (DEBUG) Log.v(TAG, "Failed to screenshot wallpaper: surface isn't valid");
1989 return false;
1990 }
1991
1992 final Rect bounds = new Rect(0, 0, mSurfaceSize.x, mSurfaceSize.y);
1993 if (bounds.isEmpty()) {
1994 Log.w(TAG, "Failed to screenshot wallpaper: surface bounds are empty");
1995 return false;
1996 }
1997
1998 if (mScreenshotSurfaceControl != null) {
1999 Log.e(TAG, "Screenshot is unexpectedly not null");
2000 // Destroying previous screenshot since it can have different size.
2001 cleanUpScreenshotSurfaceControl();
2002 }
2003
2004 SurfaceControl.ScreenshotHardwareBuffer screenshotBuffer =
2005 SurfaceControl.captureLayers(
2006 new SurfaceControl.LayerCaptureArgs.Builder(mSurfaceControl)
2007 // Needed because SurfaceFlinger#validateScreenshotPermissions
2008 // uses this parameter to check whether a caller only attempts
2009 // to screenshot itself when call doesn't come from the system.
2010 .setUid(Process.myUid())
2011 .setChildrenOnly(false)
2012 .setSourceCrop(bounds)
2013 .build());
2014
2015 if (screenshotBuffer == null) {
2016 Log.w(TAG, "Failed to screenshot wallpaper: screenshotBuffer is null");
2017 return false;
2018 }
2019
2020 final HardwareBuffer hardwareBuffer = screenshotBuffer.getHardwareBuffer();
2021
2022 SurfaceControl.Transaction t = new SurfaceControl.Transaction();
2023
2024 // TODO(b/194399558): Add crossfade transition.
2025 mScreenshotSurfaceControl = new SurfaceControl.Builder()
2026 .setName("Wallpaper snapshot for engine " + this)
2027 .setFormat(hardwareBuffer.getFormat())
2028 .setParent(mSurfaceControl)
2029 .setSecure(screenshotBuffer.containsSecureLayers())
2030 .setCallsite("WallpaperService.Engine.showScreenshotOfWallpaper")
2031 .setBLASTLayer()
2032 .build();
2033
2034 mScreenshotSize.set(mSurfaceSize.x, mSurfaceSize.y);
2035
2036 t.setBuffer(mScreenshotSurfaceControl, hardwareBuffer);
2037 t.setColorSpace(mScreenshotSurfaceControl, screenshotBuffer.getColorSpace());
2038 // Place on top everything else.
2039 t.setLayer(mScreenshotSurfaceControl, Integer.MAX_VALUE);
2040 t.show(mScreenshotSurfaceControl);
2041 t.hide(mBbqSurfaceControl);
2042 t.apply();
2043
2044 return true;
2045 }
2046
2047 void reportSurfaceDestroyed() {
2048 if (mSurfaceCreated) {
2049 mSurfaceCreated = false;
2050 mSurfaceHolder.ungetCallbacks();
2051 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
2052 if (callbacks != null) {
2053 for (SurfaceHolder.Callback c : callbacks) {
2054 c.surfaceDestroyed(mSurfaceHolder);
2055 }
2056 }
2057 if (DEBUG) Log.v(TAG, "onSurfaceDestroyed("
2058 + mSurfaceHolder + "): " + this);
2059 onSurfaceDestroyed(mSurfaceHolder);
2060 }
2061 }
2062
2063 void detach() {
2064 if (mDestroyed) {
2065 return;
2066 }
2067
2068 AnimationHandler.removeRequestor(this);
2069
2070 mDestroyed = true;
2071
2072 if (mIWallpaperEngine.mDisplayManager != null) {
2073 mIWallpaperEngine.mDisplayManager.unregisterDisplayListener(mDisplayListener);
2074 }
2075
2076 if (mVisible) {
2077 mVisible = false;
2078 if (DEBUG) Log.v(TAG, "onVisibilityChanged(false): " + this);
2079 onVisibilityChanged(false);
2080 }
2081
2082 reportSurfaceDestroyed();
2083
2084 if (DEBUG) Log.v(TAG, "onDestroy(): " + this);
2085 onDestroy();
2086
2087 if (mCreated) {
2088 try {
2089 if (DEBUG) Log.v(TAG, "Removing window and destroying surface "
2090 + mSurfaceHolder.getSurface() + " of: " + this);
2091
2092 if (mInputEventReceiver != null) {
2093 mInputEventReceiver.dispose();
2094 mInputEventReceiver = null;
2095 }
2096
2097 mSession.remove(mWindow);
2098 } catch (RemoteException e) {
2099 }
2100 mSurfaceHolder.mSurface.release();
2101 if (mBlastBufferQueue != null) {
2102 mBlastBufferQueue.destroy();
2103 mBlastBufferQueue = null;
2104 }
2105 if (mBbqSurfaceControl != null) {
2106 new SurfaceControl.Transaction().remove(mBbqSurfaceControl).apply();
2107 mBbqSurfaceControl = null;
2108 }
2109 mCreated = false;
2110 }
2111 }
2112
2113 private final DisplayListener mDisplayListener = new DisplayListener() {
2114 @Override
2115 public void onDisplayChanged(int displayId) {
2116 if (mDisplay.getDisplayId() == displayId) {
2117 reportVisibility();
2118 }
2119 }
2120
2121 @Override
2122 public void onDisplayRemoved(int displayId) {
2123 }
2124
2125 @Override
2126 public void onDisplayAdded(int displayId) {
2127 }
2128 };
2129
2130 private Surface getOrCreateBLASTSurface(int width, int height, int format) {
2131 Surface ret = null;
2132 if (mBlastBufferQueue == null) {
2133 mBlastBufferQueue = new BLASTBufferQueue("Wallpaper", mBbqSurfaceControl,
2134 width, height, format);
2135 // We only return the Surface the first time, as otherwise
2136 // it hasn't changed and there is no need to update.
2137 ret = mBlastBufferQueue.createSurface();
2138 } else {
2139 mBlastBufferQueue.update(mBbqSurfaceControl, width, height, format);
2140 }
2141
2142 return ret;
2143 }
2144 }
2145
2146 private boolean isValid(RectF area) {
2147 if (area == null) return false;
2148 boolean valid = area.bottom > area.top && area.left < area.right
2149 && LOCAL_COLOR_BOUNDS.contains(area);
2150 return valid;
2151 }
2152
2153 private boolean inRectFRange(float number) {
2154 return number >= 0f && number <= 1f;
2155 }
2156
2157 class IWallpaperEngineWrapper extends IWallpaperEngine.Stub
2158 implements HandlerCaller.Callback {
2159 private final HandlerCaller mCaller;
2160
2161 final IWallpaperConnection mConnection;
2162 final IBinder mWindowToken;
2163 final int mWindowType;
2164 final boolean mIsPreview;
2165 boolean mShownReported;
2166 int mReqWidth;
2167 int mReqHeight;
2168 final Rect mDisplayPadding = new Rect();
2169 final int mDisplayId;
2170 final DisplayManager mDisplayManager;
2171 final Display mDisplay;
2172 final WallpaperManager mWallpaperManager;
2173 private final AtomicBoolean mDetached = new AtomicBoolean();
2174
2175 Engine mEngine;
2176
2177 IWallpaperEngineWrapper(WallpaperService context,
2178 IWallpaperConnection conn, IBinder windowToken,
2179 int windowType, boolean isPreview, int reqWidth, int reqHeight, Rect padding,
2180 int displayId) {
2181 mWallpaperManager = getSystemService(WallpaperManager.class);
2182 mCaller = new HandlerCaller(context, context.getMainLooper(), this, true);
2183 mConnection = conn;
2184 mWindowToken = windowToken;
2185 mWindowType = windowType;
2186 mIsPreview = isPreview;
2187 mReqWidth = reqWidth;
2188 mReqHeight = reqHeight;
2189 mDisplayPadding.set(padding);
2190 mDisplayId = displayId;
2191
2192 // Create a display context before onCreateEngine.
2193 mDisplayManager = getSystemService(DisplayManager.class);
2194 mDisplay = mDisplayManager.getDisplay(mDisplayId);
2195
2196 if (mDisplay == null) {
2197 // Ignore this engine.
2198 throw new IllegalArgumentException("Cannot find display with id" + mDisplayId);
2199 }
2200 Message msg = mCaller.obtainMessage(DO_ATTACH);
2201 mCaller.sendMessage(msg);
2202 }
2203
2204 public void setDesiredSize(int width, int height) {
2205 Message msg = mCaller.obtainMessageII(DO_SET_DESIRED_SIZE, width, height);
2206 mCaller.sendMessage(msg);
2207 }
2208
2209 public void setDisplayPadding(Rect padding) {
2210 Message msg = mCaller.obtainMessageO(DO_SET_DISPLAY_PADDING, padding);
2211 mCaller.sendMessage(msg);
2212 }
2213
2214 public void setVisibility(boolean visible) {
2215 Message msg = mCaller.obtainMessageI(MSG_VISIBILITY_CHANGED,
2216 visible ? 1 : 0);
2217 mCaller.sendMessage(msg);
2218 }
2219
2220 @Override
2221 public void setInAmbientMode(boolean inAmbientDisplay, long animationDuration)
2222 throws RemoteException {
2223 Message msg = mCaller.obtainMessageIO(DO_IN_AMBIENT_MODE, inAmbientDisplay ? 1 : 0,
2224 animationDuration);
2225 mCaller.sendMessage(msg);
2226 }
2227
2228 public void dispatchPointer(MotionEvent event) {
2229 if (mEngine != null) {
2230 mEngine.dispatchPointer(event);
2231 } else {
2232 event.recycle();
2233 }
2234 }
2235
2236 public void dispatchWallpaperCommand(String action, int x, int y,
2237 int z, Bundle extras) {
2238 if (mEngine != null) {
2239 mEngine.mWindow.dispatchWallpaperCommand(action, x, y, z, extras, false);
2240 }
2241 }
2242
2243 public void setZoomOut(float scale) {
2244 Message msg = mCaller.obtainMessageI(MSG_ZOOM, Float.floatToIntBits(scale));
2245 mCaller.sendMessage(msg);
2246 }
2247
2248 public void reportShown() {
2249 if (!mShownReported) {
2250 mShownReported = true;
2251 Trace.beginSection("WPMS.mConnection.engineShown");
2252 try {
2253 mConnection.engineShown(this);
2254 Log.d(TAG, "Wallpaper has updated the surface:"
2255 + mWallpaperManager.getWallpaperInfo());
2256 } catch (RemoteException e) {
2257 Log.w(TAG, "Wallpaper host disappeared", e);
2258 }
2259 Trace.endSection();
2260 }
2261 }
2262
2263 public void requestWallpaperColors() {
2264 Message msg = mCaller.obtainMessage(MSG_REQUEST_WALLPAPER_COLORS);
2265 mCaller.sendMessage(msg);
2266 }
2267
2268 public void addLocalColorsAreas(List<RectF> regions) {
2269 mEngine.addLocalColorsAreas(regions);
2270 }
2271
2272 public void removeLocalColorsAreas(List<RectF> regions) {
2273 mEngine.removeLocalColorsAreas(regions);
2274 }
2275
2276 public void destroy() {
2277 Message msg = mCaller.obtainMessage(DO_DETACH);
2278 mCaller.sendMessage(msg);
2279 }
2280
2281 public void detach() {
2282 mDetached.set(true);
2283 }
2284
2285 public void applyDimming(float dimAmount) throws RemoteException {
2286 Message msg = mCaller.obtainMessageI(MSG_UPDATE_DIMMING,
2287 Float.floatToIntBits(dimAmount));
2288 mCaller.sendMessage(msg);
2289 }
2290
2291 public void resizePreview(Rect position) {
2292 Message msg = mCaller.obtainMessageO(MSG_RESIZE_PREVIEW, position);
2293 mCaller.sendMessage(msg);
2294 }
2295
2296 @Nullable
2297 public SurfaceControl mirrorSurfaceControl() {
2298 return mEngine == null ? null : SurfaceControl.mirrorSurface(mEngine.mSurfaceControl);
2299 }
2300
2301 private void doAttachEngine() {
2302 Trace.beginSection("WPMS.onCreateEngine");
2303 Engine engine = onCreateEngine();
2304 Trace.endSection();
2305 mEngine = engine;
2306 Trace.beginSection("WPMS.mConnection.attachEngine-" + mDisplayId);
2307 try {
2308 mConnection.attachEngine(this, mDisplayId);
2309 } catch (RemoteException e) {
2310 engine.detach();
2311 Log.w(TAG, "Wallpaper host disappeared", e);
2312 return;
2313 } finally {
2314 Trace.endSection();
2315 }
2316 mActiveEngines.add(engine);
2317 Trace.beginSection("WPMS.engine.attach");
2318 engine.attach(this);
2319 Trace.endSection();
2320 }
2321
2322 private void doDetachEngine() {
2323 mActiveEngines.remove(mEngine);
2324 mEngine.detach();
2325 // Some wallpapers will not trigger the rendering threads of the remaining engines even
2326 // if they are visible, so we need to toggle the state to get their attention.
2327 if (!mDetached.get()) {
2328 for (Engine eng : mActiveEngines) {
2329 if (eng.mVisible) {
2330 eng.doVisibilityChanged(false);
2331 eng.doVisibilityChanged(true);
2332 }
2333 }
2334 }
2335 }
2336
2337 @Override
2338 public void executeMessage(Message message) {
2339 if (mDetached.get()) {
2340 if (mActiveEngines.contains(mEngine)) {
2341 doDetachEngine();
2342 }
2343 return;
2344 }
2345 switch (message.what) {
2346 case DO_ATTACH: {
2347 Trace.beginSection("WPMS.DO_ATTACH");
2348 doAttachEngine();
2349 Trace.endSection();
2350 return;
2351 }
2352 case DO_DETACH: {
2353 Trace.beginSection("WPMS.DO_DETACH");
2354 doDetachEngine();
2355 Trace.endSection();
2356 return;
2357 }
2358 case DO_SET_DESIRED_SIZE: {
2359 mEngine.doDesiredSizeChanged(message.arg1, message.arg2);
2360 return;
2361 }
2362 case DO_SET_DISPLAY_PADDING: {
2363 mEngine.doDisplayPaddingChanged((Rect) message.obj);
2364 return;
2365 }
2366 case DO_IN_AMBIENT_MODE: {
2367 mEngine.doAmbientModeChanged(message.arg1 != 0, (Long) message.obj);
2368 return;
2369 }
2370 case MSG_UPDATE_SURFACE:
2371 mEngine.updateSurface(true, false, false);
2372 break;
2373 case MSG_ZOOM:
2374 mEngine.setZoom(Float.intBitsToFloat(message.arg1));
2375 break;
2376 case MSG_UPDATE_DIMMING:
2377 mEngine.updateWallpaperDimming(Float.intBitsToFloat(message.arg1));
2378 break;
2379 case MSG_RESIZE_PREVIEW:
2380 mEngine.resizePreview((Rect) message.obj);
2381 break;
2382 case MSG_VISIBILITY_CHANGED:
2383 if (DEBUG) Log.v(TAG, "Visibility change in " + mEngine
2384 + ": " + message.arg1);
2385 mEngine.doVisibilityChanged(message.arg1 != 0);
2386 break;
2387 case MSG_WALLPAPER_OFFSETS: {
2388 mEngine.doOffsetsChanged(true);
2389 } break;
2390 case MSG_WALLPAPER_COMMAND: {
2391 WallpaperCommand cmd = (WallpaperCommand)message.obj;
2392 mEngine.doCommand(cmd);
2393 } break;
2394 case MSG_WINDOW_RESIZED: {
2395 final boolean reportDraw = message.arg1 != 0;
2396 mEngine.updateConfiguration(((MergedConfiguration) message.obj));
2397 mEngine.updateSurface(true, false, reportDraw);
2398 mEngine.doOffsetsChanged(true);
2399 mEngine.scaleAndCropScreenshot();
2400 } break;
2401 case MSG_WINDOW_MOVED: {
2402 // Do nothing. What does it mean for a Wallpaper to move?
2403 } break;
2404 case MSG_TOUCH_EVENT: {
2405 boolean skip = false;
2406 MotionEvent ev = (MotionEvent)message.obj;
2407 if (ev.getAction() == MotionEvent.ACTION_MOVE) {
2408 synchronized (mEngine.mLock) {
2409 if (mEngine.mPendingMove == ev) {
2410 mEngine.mPendingMove = null;
2411 } else {
2412 // this is not the motion event we are looking for....
2413 skip = true;
2414 }
2415 }
2416 }
2417 if (!skip) {
2418 if (DEBUG) Log.v(TAG, "Delivering touch event: " + ev);
2419 mEngine.onTouchEvent(ev);
2420 }
2421 ev.recycle();
2422 } break;
2423 case MSG_REQUEST_WALLPAPER_COLORS: {
2424 if (mConnection == null) {
2425 break;
2426 }
2427 try {
2428 WallpaperColors colors = mEngine.onComputeColors();
2429 mEngine.setPrimaryWallpaperColors(colors);
2430 mConnection.onWallpaperColorsChanged(colors, mDisplayId);
2431 } catch (RemoteException e) {
2432 // Connection went away, nothing to do in here.
2433 }
2434 } break;
2435 case MSG_REPORT_SHOWN: {
2436 Trace.beginSection("WPMS.MSG_REPORT_SHOWN");
2437 reportShown();
2438 Trace.endSection();
2439 } break;
2440 default :
2441 Log.w(TAG, "Unknown message type " + message.what);
2442 }
2443 }
2444 }
2445
2446 /**
2447 * Implements the internal {@link IWallpaperService} interface to convert
2448 * incoming calls to it back to calls on an {@link WallpaperService}.
2449 */
2450 class IWallpaperServiceWrapper extends IWallpaperService.Stub {
2451 private final WallpaperService mTarget;
2452 private IWallpaperEngineWrapper mEngineWrapper;
2453
2454 public IWallpaperServiceWrapper(WallpaperService context) {
2455 mTarget = context;
2456 }
2457
2458 @Override
2459 public void attach(IWallpaperConnection conn, IBinder windowToken,
2460 int windowType, boolean isPreview, int reqWidth, int reqHeight, Rect padding,
2461 int displayId, @SetWallpaperFlags int which) {
2462 Trace.beginSection("WPMS.ServiceWrapper.attach");
2463 mEngineWrapper = new IWallpaperEngineWrapper(mTarget, conn, windowToken,
2464 windowType, isPreview, reqWidth, reqHeight, padding, displayId);
2465 Trace.endSection();
2466 }
2467
2468 @Override
2469 public void detach() {
2470 mEngineWrapper.detach();
2471 }
2472 }
2473
2474 @Override
2475 public void onCreate() {
2476 Trace.beginSection("WPMS.onCreate");
2477 super.onCreate();
2478 Trace.endSection();
2479 }
2480
2481 @Override
2482 public void onDestroy() {
2483 Trace.beginSection("WPMS.onDestroy");
2484 super.onDestroy();
2485 for (int i=0; i<mActiveEngines.size(); i++) {
2486 mActiveEngines.get(i).detach();
2487 }
2488 mActiveEngines.clear();
2489 Trace.endSection();
2490 }
2491
2492 /**
2493 * Implement to return the implementation of the internal accessibility
2494 * service interface. Subclasses should not override.
2495 */
2496 @Override
2497 public final IBinder onBind(Intent intent) {
2498 return new IWallpaperServiceWrapper(this);
2499 }
2500
2501 /**
2502 * Must be implemented to return a new instance of the wallpaper's engine.
2503 * Note that multiple instances may be active at the same time, such as
2504 * when the wallpaper is currently set as the active wallpaper and the user
2505 * is in the wallpaper picker viewing a preview of it as well.
2506 */
2507 public abstract Engine onCreateEngine();
2508
2509 @Override
2510 protected void dump(FileDescriptor fd, PrintWriter out, String[] args) {
2511 out.print("State of wallpaper "); out.print(this); out.println(":");
2512 for (int i=0; i<mActiveEngines.size(); i++) {
2513 Engine engine = mActiveEngines.get(i);
2514 out.print(" Engine "); out.print(engine); out.println(":");
2515 engine.dump(" ", fd, out, args);
2516 }
2517 }
2518 }