1 /*
2  * Copyright (C) 2013 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.view;
18 
19 import static android.graphics.Matrix.MSCALE_X;
20 import static android.graphics.Matrix.MSCALE_Y;
21 import static android.graphics.Matrix.MSKEW_X;
22 import static android.graphics.Matrix.MSKEW_Y;
23 import static android.graphics.Matrix.MTRANS_X;
24 import static android.graphics.Matrix.MTRANS_Y;
25 import static android.view.Display.INVALID_DISPLAY;
26 import static android.view.SurfaceControlProto.HASH_CODE;
27 import static android.view.SurfaceControlProto.LAYER_ID;
28 import static android.view.SurfaceControlProto.NAME;
29 
30 import android.Manifest;
31 import android.annotation.CallbackExecutor;
32 import android.annotation.FloatRange;
33 import android.annotation.IntDef;
34 import android.annotation.IntRange;
35 import android.annotation.NonNull;
36 import android.annotation.Nullable;
37 import android.annotation.RequiresPermission;
38 import android.annotation.Size;
39 import android.annotation.TestApi;
40 import android.compat.annotation.UnsupportedAppUsage;
41 import android.content.Context;
42 import android.graphics.ColorSpace;
43 import android.graphics.GraphicBuffer;
44 import android.graphics.Matrix;
45 import android.graphics.PixelFormat;
46 import android.graphics.Point;
47 import android.graphics.Rect;
48 import android.graphics.Region;
49 import android.gui.DropInputMode;
50 import android.gui.StalledTransactionInfo;
51 import android.hardware.DataSpace;
52 import android.hardware.HardwareBuffer;
53 import android.hardware.OverlayProperties;
54 import android.hardware.SyncFence;
55 import android.hardware.display.DeviceProductInfo;
56 import android.hardware.display.DisplayManager;
57 import android.hardware.display.DisplayManagerGlobal;
58 import android.hardware.display.DisplayedContentSample;
59 import android.hardware.display.DisplayedContentSamplingAttributes;
60 import android.hardware.display.IDisplayManager;
61 import android.hardware.display.IVirtualDisplayCallback;
62 import android.hardware.display.VirtualDisplay;
63 import android.hardware.graphics.common.DisplayDecorationSupport;
64 import android.opengl.EGLDisplay;
65 import android.opengl.EGLSync;
66 import android.os.Build;
67 import android.os.IBinder;
68 import android.os.Looper;
69 import android.os.Parcel;
70 import android.os.Parcelable;
71 import android.os.RemoteException;
72 import android.os.ServiceManager;
73 import android.util.ArrayMap;
74 import android.util.Log;
75 import android.util.Slog;
76 import android.util.SparseIntArray;
77 import android.util.proto.ProtoOutputStream;
78 import android.view.Surface.OutOfResourcesException;
79 
80 import com.android.internal.annotations.GuardedBy;
81 import com.android.internal.util.Preconditions;
82 import com.android.internal.util.VirtualRefBasePtr;
83 
84 import dalvik.system.CloseGuard;
85 
86 import libcore.util.NativeAllocationRegistry;
87 
88 import java.io.Closeable;
89 import java.lang.annotation.Retention;
90 import java.lang.annotation.RetentionPolicy;
91 import java.lang.ref.WeakReference;
92 import java.nio.ByteBuffer;
93 import java.nio.ByteOrder;
94 import java.util.ArrayList;
95 import java.util.Arrays;
96 import java.util.Objects;
97 import java.util.concurrent.Executor;
98 import java.util.function.Consumer;
99 
100 /**
101  * Handle to an on-screen Surface managed by the system compositor. The SurfaceControl is
102  * a combination of a buffer source, and metadata about how to display the buffers.
103  * By constructing a {@link Surface} from this SurfaceControl you can submit buffers to be
104  * composited. Using {@link SurfaceControl.Transaction} you can manipulate various
105  * properties of how the buffer will be displayed on-screen. SurfaceControl's are
106  * arranged into a scene-graph like hierarchy, and as such any SurfaceControl may have
107  * a parent. Geometric properties like transform, crop, and Z-ordering will be inherited
108  * from the parent, as if the child were content in the parents buffer stream.
109  */
110 public final class SurfaceControl implements Parcelable {
111     private static final String TAG = "SurfaceControl";
112 
nativeCreate(SurfaceSession session, String name, int w, int h, int format, int flags, long parentObject, Parcel metadata)113     private static native long nativeCreate(SurfaceSession session, String name,
114             int w, int h, int format, int flags, long parentObject, Parcel metadata)
115             throws OutOfResourcesException;
nativeReadFromParcel(Parcel in)116     private static native long nativeReadFromParcel(Parcel in);
nativeCopyFromSurfaceControl(long nativeObject)117     private static native long nativeCopyFromSurfaceControl(long nativeObject);
nativeWriteToParcel(long nativeObject, Parcel out)118     private static native void nativeWriteToParcel(long nativeObject, Parcel out);
nativeGetNativeSurfaceControlFinalizer()119     private static native long nativeGetNativeSurfaceControlFinalizer();
nativeDisconnect(long nativeObject)120     private static native void nativeDisconnect(long nativeObject);
nativeUpdateDefaultBufferSize(long nativeObject, int width, int height)121     private static native void nativeUpdateDefaultBufferSize(long nativeObject, int width, int height);
122 
nativeMirrorSurface(long mirrorOfObject)123     private static native long nativeMirrorSurface(long mirrorOfObject);
nativeCreateTransaction()124     private static native long nativeCreateTransaction();
nativeGetNativeTransactionFinalizer()125     private static native long nativeGetNativeTransactionFinalizer();
nativeApplyTransaction(long transactionObj, boolean sync)126     private static native void nativeApplyTransaction(long transactionObj, boolean sync);
nativeMergeTransaction(long transactionObj, long otherTransactionObj)127     private static native void nativeMergeTransaction(long transactionObj,
128             long otherTransactionObj);
nativeClearTransaction(long transactionObj)129     private static native void nativeClearTransaction(long transactionObj);
nativeSetAnimationTransaction(long transactionObj)130     private static native void nativeSetAnimationTransaction(long transactionObj);
nativeSetEarlyWakeupStart(long transactionObj)131     private static native void nativeSetEarlyWakeupStart(long transactionObj);
nativeSetEarlyWakeupEnd(long transactionObj)132     private static native void nativeSetEarlyWakeupEnd(long transactionObj);
nativeGetTransactionId(long transactionObj)133     private static native long nativeGetTransactionId(long transactionObj);
134 
nativeSetLayer(long transactionObj, long nativeObject, int zorder)135     private static native void nativeSetLayer(long transactionObj, long nativeObject, int zorder);
nativeSetRelativeLayer(long transactionObj, long nativeObject, long relativeToObject, int zorder)136     private static native void nativeSetRelativeLayer(long transactionObj, long nativeObject,
137             long relativeToObject, int zorder);
nativeSetPosition(long transactionObj, long nativeObject, float x, float y)138     private static native void nativeSetPosition(long transactionObj, long nativeObject,
139             float x, float y);
nativeSetScale(long transactionObj, long nativeObject, float x, float y)140     private static native void nativeSetScale(long transactionObj, long nativeObject,
141             float x, float y);
nativeSetTransparentRegionHint(long transactionObj, long nativeObject, Region region)142     private static native void nativeSetTransparentRegionHint(long transactionObj,
143             long nativeObject, Region region);
nativeSetAlpha(long transactionObj, long nativeObject, float alpha)144     private static native void nativeSetAlpha(long transactionObj, long nativeObject, float alpha);
nativeSetMatrix(long transactionObj, long nativeObject, float dsdx, float dtdx, float dtdy, float dsdy)145     private static native void nativeSetMatrix(long transactionObj, long nativeObject,
146             float dsdx, float dtdx,
147             float dtdy, float dsdy);
nativeSetColorTransform(long transactionObj, long nativeObject, float[] matrix, float[] translation)148     private static native void nativeSetColorTransform(long transactionObj, long nativeObject,
149             float[] matrix, float[] translation);
nativeSetColorSpaceAgnostic(long transactionObj, long nativeObject, boolean agnostic)150     private static native void nativeSetColorSpaceAgnostic(long transactionObj, long nativeObject,
151             boolean agnostic);
nativeSetGeometry(long transactionObj, long nativeObject, Rect sourceCrop, Rect dest, long orientation)152     private static native void nativeSetGeometry(long transactionObj, long nativeObject,
153             Rect sourceCrop, Rect dest, long orientation);
nativeSetColor(long transactionObj, long nativeObject, float[] color)154     private static native void nativeSetColor(long transactionObj, long nativeObject, float[] color);
nativeSetFlags(long transactionObj, long nativeObject, int flags, int mask)155     private static native void nativeSetFlags(long transactionObj, long nativeObject,
156             int flags, int mask);
nativeSetFrameRateSelectionPriority(long transactionObj, long nativeObject, int priority)157     private static native void nativeSetFrameRateSelectionPriority(long transactionObj,
158             long nativeObject, int priority);
nativeSetWindowCrop(long transactionObj, long nativeObject, int l, int t, int r, int b)159     private static native void nativeSetWindowCrop(long transactionObj, long nativeObject,
160             int l, int t, int r, int b);
nativeSetCornerRadius(long transactionObj, long nativeObject, float cornerRadius)161     private static native void nativeSetCornerRadius(long transactionObj, long nativeObject,
162             float cornerRadius);
nativeSetBackgroundBlurRadius(long transactionObj, long nativeObject, int blurRadius)163     private static native void nativeSetBackgroundBlurRadius(long transactionObj, long nativeObject,
164             int blurRadius);
nativeSetLayerStack(long transactionObj, long nativeObject, int layerStack)165     private static native void nativeSetLayerStack(long transactionObj, long nativeObject,
166             int layerStack);
nativeSetBlurRegions(long transactionObj, long nativeObj, float[][] regions, int length)167     private static native void nativeSetBlurRegions(long transactionObj, long nativeObj,
168             float[][] regions, int length);
nativeSetStretchEffect(long transactionObj, long nativeObj, float width, float height, float vecX, float vecY, float maxStretchAmountX, float maxStretchAmountY, float childRelativeLeft, float childRelativeTop, float childRelativeRight, float childRelativeBottom)169     private static native void nativeSetStretchEffect(long transactionObj, long nativeObj,
170             float width, float height, float vecX, float vecY,
171             float maxStretchAmountX, float maxStretchAmountY, float childRelativeLeft,
172             float childRelativeTop, float childRelativeRight, float childRelativeBottom);
nativeSetTrustedOverlay(long transactionObj, long nativeObject, boolean isTrustedOverlay)173     private static native void nativeSetTrustedOverlay(long transactionObj, long nativeObject,
174             boolean isTrustedOverlay);
nativeSetDropInputMode( long transactionObj, long nativeObject, int flags)175     private static native void nativeSetDropInputMode(
176             long transactionObj, long nativeObject, int flags);
nativeSurfaceFlushJankData(long nativeSurfaceObject)177     private static native void nativeSurfaceFlushJankData(long nativeSurfaceObject);
nativeClearContentFrameStats(long nativeObject)178     private static native boolean nativeClearContentFrameStats(long nativeObject);
nativeGetContentFrameStats(long nativeObject, WindowContentFrameStats outStats)179     private static native boolean nativeGetContentFrameStats(long nativeObject, WindowContentFrameStats outStats);
nativeClearAnimationFrameStats()180     private static native boolean nativeClearAnimationFrameStats();
nativeGetAnimationFrameStats(WindowAnimationFrameStats outStats)181     private static native boolean nativeGetAnimationFrameStats(WindowAnimationFrameStats outStats);
182 
nativeSetDisplaySurface(long transactionObj, IBinder displayToken, long nativeSurfaceObject)183     private static native void nativeSetDisplaySurface(long transactionObj,
184             IBinder displayToken, long nativeSurfaceObject);
nativeSetDisplayLayerStack(long transactionObj, IBinder displayToken, int layerStack)185     private static native void nativeSetDisplayLayerStack(long transactionObj,
186             IBinder displayToken, int layerStack);
nativeSetDisplayFlags(long transactionObj, IBinder displayToken, int flags)187     private static native void nativeSetDisplayFlags(long transactionObj,
188             IBinder displayToken, int flags);
nativeSetDisplayProjection(long transactionObj, IBinder displayToken, int orientation, int l, int t, int r, int b, int L, int T, int R, int B)189     private static native void nativeSetDisplayProjection(long transactionObj,
190             IBinder displayToken, int orientation,
191             int l, int t, int r, int b,
192             int L, int T, int R, int B);
nativeSetDisplaySize(long transactionObj, IBinder displayToken, int width, int height)193     private static native void nativeSetDisplaySize(long transactionObj, IBinder displayToken,
194             int width, int height);
nativeGetStaticDisplayInfo(long displayId)195     private static native StaticDisplayInfo nativeGetStaticDisplayInfo(long displayId);
nativeGetDynamicDisplayInfo(long displayId)196     private static native DynamicDisplayInfo nativeGetDynamicDisplayInfo(long displayId);
197     private static native DisplayedContentSamplingAttributes
nativeGetDisplayedContentSamplingAttributes(IBinder displayToken)198             nativeGetDisplayedContentSamplingAttributes(IBinder displayToken);
nativeSetDisplayedContentSamplingEnabled(IBinder displayToken, boolean enable, int componentMask, int maxFrames)199     private static native boolean nativeSetDisplayedContentSamplingEnabled(IBinder displayToken,
200             boolean enable, int componentMask, int maxFrames);
nativeGetDisplayedContentSample( IBinder displayToken, long numFrames, long timestamp)201     private static native DisplayedContentSample nativeGetDisplayedContentSample(
202             IBinder displayToken, long numFrames, long timestamp);
nativeSetDesiredDisplayModeSpecs(IBinder displayToken, DesiredDisplayModeSpecs desiredDisplayModeSpecs)203     private static native boolean nativeSetDesiredDisplayModeSpecs(IBinder displayToken,
204             DesiredDisplayModeSpecs desiredDisplayModeSpecs);
205     private static native DesiredDisplayModeSpecs
nativeGetDesiredDisplayModeSpecs(IBinder displayToken)206             nativeGetDesiredDisplayModeSpecs(IBinder displayToken);
nativeGetDisplayNativePrimaries( IBinder displayToken)207     private static native DisplayPrimaries nativeGetDisplayNativePrimaries(
208             IBinder displayToken);
nativeGetCompositionDataspaces()209     private static native int[] nativeGetCompositionDataspaces();
nativeGetOverlaySupport()210     private static native OverlayProperties nativeGetOverlaySupport();
nativeSetActiveColorMode(IBinder displayToken, int colorMode)211     private static native boolean nativeSetActiveColorMode(IBinder displayToken,
212             int colorMode);
nativeGetBootDisplayModeSupport()213     private static native boolean nativeGetBootDisplayModeSupport();
nativeSetBootDisplayMode(IBinder displayToken, int displayMode)214     private static native void nativeSetBootDisplayMode(IBinder displayToken, int displayMode);
nativeClearBootDisplayMode(IBinder displayToken)215     private static native void nativeClearBootDisplayMode(IBinder displayToken);
nativeSetAutoLowLatencyMode(IBinder displayToken, boolean on)216     private static native void nativeSetAutoLowLatencyMode(IBinder displayToken, boolean on);
nativeSetGameContentType(IBinder displayToken, boolean on)217     private static native void nativeSetGameContentType(IBinder displayToken, boolean on);
nativeSetDisplayPowerMode( IBinder displayToken, int mode)218     private static native void nativeSetDisplayPowerMode(
219             IBinder displayToken, int mode);
nativeReparent(long transactionObj, long nativeObject, long newParentNativeObject)220     private static native void nativeReparent(long transactionObj, long nativeObject,
221             long newParentNativeObject);
nativeSetBuffer(long transactionObj, long nativeObject, HardwareBuffer buffer, long fencePtr, Consumer<SyncFence> releaseCallback)222     private static native void nativeSetBuffer(long transactionObj, long nativeObject,
223             HardwareBuffer buffer, long fencePtr, Consumer<SyncFence> releaseCallback);
nativeUnsetBuffer(long transactionObj, long nativeObject)224     private static native void nativeUnsetBuffer(long transactionObj, long nativeObject);
nativeSetBufferTransform(long transactionObj, long nativeObject, int transform)225     private static native void nativeSetBufferTransform(long transactionObj, long nativeObject,
226             int transform);
nativeSetDataSpace(long transactionObj, long nativeObject, @DataSpace.NamedDataSpace int dataSpace)227     private static native void nativeSetDataSpace(long transactionObj, long nativeObject,
228             @DataSpace.NamedDataSpace int dataSpace);
nativeSetExtendedRangeBrightness(long transactionObj, long nativeObject, float currentBufferRatio, float desiredRatio)229     private static native void nativeSetExtendedRangeBrightness(long transactionObj,
230             long nativeObject, float currentBufferRatio, float desiredRatio);
231 
nativeSetCachingHint(long transactionObj, long nativeObject, int cachingHint)232     private static native void nativeSetCachingHint(long transactionObj,
233             long nativeObject, int cachingHint);
nativeSetDamageRegion(long transactionObj, long nativeObject, Region region)234     private static native void nativeSetDamageRegion(long transactionObj, long nativeObject,
235             Region region);
nativeSetDimmingEnabled(long transactionObj, long nativeObject, boolean dimmingEnabled)236     private static native void nativeSetDimmingEnabled(long transactionObj, long nativeObject,
237             boolean dimmingEnabled);
238 
nativeSetInputWindowInfo(long transactionObj, long nativeObject, InputWindowHandle handle)239     private static native void nativeSetInputWindowInfo(long transactionObj, long nativeObject,
240             InputWindowHandle handle);
241 
nativeGetProtectedContentSupport()242     private static native boolean nativeGetProtectedContentSupport();
nativeSetMetadata(long transactionObj, long nativeObject, int key, Parcel data)243     private static native void nativeSetMetadata(long transactionObj, long nativeObject, int key,
244             Parcel data);
nativeAddWindowInfosReportedListener(long transactionObj, Runnable listener)245     private static native void nativeAddWindowInfosReportedListener(long transactionObj,
246             Runnable listener);
nativeGetDisplayBrightnessSupport(IBinder displayToken)247     private static native boolean nativeGetDisplayBrightnessSupport(IBinder displayToken);
nativeSetDisplayBrightness(IBinder displayToken, float sdrBrightness, float sdrBrightnessNits, float displayBrightness, float displayBrightnessNits)248     private static native boolean nativeSetDisplayBrightness(IBinder displayToken,
249             float sdrBrightness, float sdrBrightnessNits, float displayBrightness,
250             float displayBrightnessNits);
nativeReadTransactionFromParcel(Parcel in)251     private static native long nativeReadTransactionFromParcel(Parcel in);
nativeWriteTransactionToParcel(long nativeObject, Parcel out)252     private static native void nativeWriteTransactionToParcel(long nativeObject, Parcel out);
nativeSetShadowRadius(long transactionObj, long nativeObject, float shadowRadius)253     private static native void nativeSetShadowRadius(long transactionObj, long nativeObject,
254             float shadowRadius);
nativeSetGlobalShadowSettings(@ize4) float[] ambientColor, @Size(4) float[] spotColor, float lightPosY, float lightPosZ, float lightRadius)255     private static native void nativeSetGlobalShadowSettings(@Size(4) float[] ambientColor,
256             @Size(4) float[] spotColor, float lightPosY, float lightPosZ, float lightRadius);
nativeGetDisplayDecorationSupport( IBinder displayToken)257     private static native DisplayDecorationSupport nativeGetDisplayDecorationSupport(
258             IBinder displayToken);
259 
nativeSetFrameRate(long transactionObj, long nativeObject, float frameRate, int compatibility, int changeFrameRateStrategy)260     private static native void nativeSetFrameRate(long transactionObj, long nativeObject,
261             float frameRate, int compatibility, int changeFrameRateStrategy);
nativeSetDefaultFrameRateCompatibility(long transactionObj, long nativeObject, int compatibility)262     private static native void nativeSetDefaultFrameRateCompatibility(long transactionObj,
263             long nativeObject, int compatibility);
nativeGetHandle(long nativeObject)264     private static native long nativeGetHandle(long nativeObject);
265 
nativeSetFixedTransformHint(long transactionObj, long nativeObject, int transformHint)266     private static native void nativeSetFixedTransformHint(long transactionObj, long nativeObject,
267             int transformHint);
nativeRemoveCurrentInputFocus(long nativeObject, int displayId)268     private static native void nativeRemoveCurrentInputFocus(long nativeObject, int displayId);
nativeSetFocusedWindow(long transactionObj, IBinder toToken, String windowName, int displayId)269     private static native void nativeSetFocusedWindow(long transactionObj, IBinder toToken,
270             String windowName, int displayId);
nativeSetFrameTimelineVsync(long transactionObj, long frameTimelineVsyncId)271     private static native void nativeSetFrameTimelineVsync(long transactionObj,
272             long frameTimelineVsyncId);
nativeAddJankDataListener(long nativeListener, long nativeSurfaceControl)273     private static native void nativeAddJankDataListener(long nativeListener,
274             long nativeSurfaceControl);
nativeRemoveJankDataListener(long nativeListener)275     private static native void nativeRemoveJankDataListener(long nativeListener);
nativeCreateJankDataListenerWrapper(OnJankDataListener listener)276     private static native long nativeCreateJankDataListenerWrapper(OnJankDataListener listener);
nativeGetGPUContextPriority()277     private static native int nativeGetGPUContextPriority();
nativeSetTransformHint(long nativeObject, @SurfaceControl.BufferTransform int transformHint)278     private static native void nativeSetTransformHint(long nativeObject,
279             @SurfaceControl.BufferTransform int transformHint);
nativeGetTransformHint(long nativeObject)280     private static native int nativeGetTransformHint(long nativeObject);
nativeGetLayerId(long nativeObject)281     private static native int nativeGetLayerId(long nativeObject);
nativeAddTransactionCommittedListener(long nativeObject, TransactionCommittedListener listener)282     private static native void nativeAddTransactionCommittedListener(long nativeObject,
283             TransactionCommittedListener listener);
nativeSanitize(long transactionObject, int pid, int uid)284     private static native void nativeSanitize(long transactionObject, int pid, int uid);
nativeSetDestinationFrame(long transactionObj, long nativeObject, int l, int t, int r, int b)285     private static native void nativeSetDestinationFrame(long transactionObj, long nativeObject,
286             int l, int t, int r, int b);
nativeSetDefaultApplyToken(IBinder token)287     private static native void nativeSetDefaultApplyToken(IBinder token);
nativeGetDefaultApplyToken()288     private static native IBinder nativeGetDefaultApplyToken();
nativeBootFinished()289     private static native boolean nativeBootFinished();
nativeCreateTpc(TrustedPresentationCallback callback)290     private static native long nativeCreateTpc(TrustedPresentationCallback callback);
getNativeTrustedPresentationCallbackFinalizer()291     private static native long getNativeTrustedPresentationCallbackFinalizer();
nativeSetTrustedPresentationCallback(long transactionObj, long nativeObject, long nativeTpc, TrustedPresentationThresholds thresholds)292     private static native void nativeSetTrustedPresentationCallback(long transactionObj,
293             long nativeObject, long nativeTpc, TrustedPresentationThresholds thresholds);
nativeClearTrustedPresentationCallback(long transactionObj, long nativeObject)294     private static native void nativeClearTrustedPresentationCallback(long transactionObj,
295             long nativeObject);
nativeGetStalledTransactionInfo(int pid)296     private static native StalledTransactionInfo nativeGetStalledTransactionInfo(int pid);
297 
298     /**
299      * Transforms that can be applied to buffers as they are displayed to a window.
300      *
301      * Supported transforms are any combination of horizontal mirror, vertical mirror, and
302      * clock-wise 90 degree rotation, in that order. Rotations of 180 and 270 degrees are made up
303      * of those basic transforms.
304      * Mirrors {@code ANativeWindowTransform} definitions.
305      * @hide
306      */
307     @Retention(RetentionPolicy.SOURCE)
308     @IntDef(prefix = {"BUFFER_TRANSFORM_"},
309             value = {BUFFER_TRANSFORM_IDENTITY, BUFFER_TRANSFORM_MIRROR_HORIZONTAL,
310                     BUFFER_TRANSFORM_MIRROR_VERTICAL, BUFFER_TRANSFORM_ROTATE_90,
311                     BUFFER_TRANSFORM_ROTATE_180, BUFFER_TRANSFORM_ROTATE_270,
312                     BUFFER_TRANSFORM_MIRROR_HORIZONTAL | BUFFER_TRANSFORM_ROTATE_90,
313                     BUFFER_TRANSFORM_MIRROR_VERTICAL | BUFFER_TRANSFORM_ROTATE_90})
314     public @interface BufferTransform {
315     }
316 
317     /**
318      * Identity transform.
319      *
320      * These transforms that can be applied to buffers as they are displayed to a window.
321      * @see HardwareBuffer
322      *
323      * Supported transforms are any combination of horizontal mirror, vertical mirror, and
324      * clock-wise 90 degree rotation, in that order. Rotations of 180 and 270 degrees are
325      * made up of those basic transforms.
326      */
327     public static final int BUFFER_TRANSFORM_IDENTITY = 0x00;
328     /**
329      * Mirror horizontally. Can be combined with {@link #BUFFER_TRANSFORM_MIRROR_VERTICAL}
330      * and {@link #BUFFER_TRANSFORM_ROTATE_90}.
331      */
332     public static final int BUFFER_TRANSFORM_MIRROR_HORIZONTAL = 0x01;
333     /**
334      * Mirror vertically. Can be combined with {@link #BUFFER_TRANSFORM_MIRROR_HORIZONTAL}
335      * and {@link #BUFFER_TRANSFORM_ROTATE_90}.
336      */
337     public static final int BUFFER_TRANSFORM_MIRROR_VERTICAL = 0x02;
338     /**
339      * Rotate 90 degrees clock-wise. Can be combined with {@link
340      * #BUFFER_TRANSFORM_MIRROR_HORIZONTAL} and {@link #BUFFER_TRANSFORM_MIRROR_VERTICAL}.
341      */
342     public static final int BUFFER_TRANSFORM_ROTATE_90 = 0x04;
343     /**
344      * Rotate 180 degrees clock-wise. Cannot be combined with other transforms.
345      */
346     public static final int BUFFER_TRANSFORM_ROTATE_180 =
347             BUFFER_TRANSFORM_MIRROR_HORIZONTAL | BUFFER_TRANSFORM_MIRROR_VERTICAL;
348     /**
349      * Rotate 270 degrees clock-wise. Cannot be combined with other transforms.
350      */
351     public static final int BUFFER_TRANSFORM_ROTATE_270 =
352             BUFFER_TRANSFORM_ROTATE_180 | BUFFER_TRANSFORM_ROTATE_90;
353 
354     /**
355      * @hide
356      */
rotationToBufferTransform(@urface.Rotation int rotation)357     public static @BufferTransform int rotationToBufferTransform(@Surface.Rotation int rotation) {
358         switch (rotation) {
359             case Surface.ROTATION_0: return BUFFER_TRANSFORM_IDENTITY;
360             case Surface.ROTATION_90: return BUFFER_TRANSFORM_ROTATE_90;
361             case Surface.ROTATION_180: return BUFFER_TRANSFORM_ROTATE_180;
362             case Surface.ROTATION_270: return BUFFER_TRANSFORM_ROTATE_270;
363         }
364         Log.e(TAG, "Trying to convert unknown rotation=" + rotation);
365         return BUFFER_TRANSFORM_IDENTITY;
366     }
367 
368     @Nullable
369     @GuardedBy("mLock")
370     private ArrayList<OnReparentListener> mReparentListeners;
371 
372     /**
373      * Listener to observe surface reparenting.
374      *
375      * @hide
376      */
377     public interface OnReparentListener {
378 
379         /**
380          * Callback for reparenting surfaces.
381          *
382          * Important: You should only interact with the provided surface control
383          * only if you have a contract with its owner to avoid them closing it
384          * under you or vise versa.
385          *
386          * @param transaction The transaction that would commit reparenting.
387          * @param parent The future parent surface.
388          */
onReparent(@onNull Transaction transaction, @Nullable SurfaceControl parent)389         void onReparent(@NonNull Transaction transaction, @Nullable SurfaceControl parent);
390     }
391 
392     /**
393      * Jank information to be fed back via {@link OnJankDataListener}.
394      * @hide
395      */
396     public static class JankData {
397 
398         /** @hide */
399         @IntDef(flag = true, value = {JANK_NONE,
400                 DISPLAY_HAL,
401                 JANK_SURFACEFLINGER_DEADLINE_MISSED,
402                 JANK_SURFACEFLINGER_GPU_DEADLINE_MISSED,
403                 JANK_APP_DEADLINE_MISSED,
404                 PREDICTION_ERROR,
405                 SURFACE_FLINGER_SCHEDULING})
406         @Retention(RetentionPolicy.SOURCE)
407         public @interface JankType {}
408 
409         // Needs to be kept in sync with frameworks/native/libs/gui/include/gui/JankInfo.h
410 
411         // No Jank
412         public static final int JANK_NONE = 0x0;
413 
414         // Jank not related to SurfaceFlinger or the App
415         public static final int DISPLAY_HAL = 0x1;
416         // SF took too long on the CPU
417         public static final int JANK_SURFACEFLINGER_DEADLINE_MISSED = 0x2;
418         // SF took too long on the GPU
419         public static final int JANK_SURFACEFLINGER_GPU_DEADLINE_MISSED = 0x4;
420         // Either App or GPU took too long on the frame
421         public static final int JANK_APP_DEADLINE_MISSED = 0x8;
422         // Vsync predictions have drifted beyond the threshold from the actual HWVsync
423         public static final int PREDICTION_ERROR = 0x10;
424         // Latching a buffer early might cause an early present of the frame
425         public static final int SURFACE_FLINGER_SCHEDULING = 0x20;
426         // A buffer is said to be stuffed if it was expected to be presented on a vsync but was
427         // presented later because the previous buffer was presented in its expected vsync. This
428         // usually happens if there is an unexpectedly long frame causing the rest of the buffers
429         // to enter a stuffed state.
430         public static final int BUFFER_STUFFING = 0x40;
431         // Jank due to unknown reasons.
432         public static final int UNKNOWN = 0x80;
433 
JankData(long frameVsyncId, @JankType int jankType)434         public JankData(long frameVsyncId, @JankType int jankType) {
435             this.frameVsyncId = frameVsyncId;
436             this.jankType = jankType;
437         }
438 
439         public final long frameVsyncId;
440         public final @JankType int jankType;
441     }
442 
443     /**
444      * Listener interface to be informed about SurfaceFlinger's jank classification for a specific
445      * surface.
446      *
447      * @see JankData
448      * @see #addJankDataListener
449      * @hide
450      */
451     public static abstract class OnJankDataListener {
452         private final VirtualRefBasePtr mNativePtr;
453 
OnJankDataListener()454         public OnJankDataListener() {
455             mNativePtr = new VirtualRefBasePtr(nativeCreateJankDataListenerWrapper(this));
456         }
457 
458         /**
459          * Called when new jank classifications are available.
460          */
onJankDataAvailable(JankData[] jankStats)461         public abstract void onJankDataAvailable(JankData[] jankStats);
462     }
463 
464     private final CloseGuard mCloseGuard = CloseGuard.get();
465     private String mName;
466     private String mCallsite;
467 
468      /**
469      * Note: do not rename, this field is used by native code.
470      * @hide
471      */
472     public long mNativeObject;
473     private long mNativeHandle;
474 
475     private final Object mChoreographerLock = new Object();
476     @GuardedBy("mChoreographerLock")
477     private Choreographer mChoreographer;
478 
479     // TODO: Move width/height to native and fix locking through out.
480     private final Object mLock = new Object();
481     @GuardedBy("mLock")
482     private int mWidth;
483     @GuardedBy("mLock")
484     private int mHeight;
485 
486     private TrustedPresentationCallback mTrustedPresentationCallback;
487 
488     private WeakReference<View> mLocalOwnerView;
489 
490     // A throwable with the stack filled when this SurfaceControl is released (only if
491     // sDebugUsageAfterRelease) is enabled
492     private Throwable mReleaseStack = null;
493 
494     // Triggers the stack to be saved when any SurfaceControl in this process is released, which can
495     // be dumped as additional context
496     private static volatile boolean sDebugUsageAfterRelease = false;
497 
498     static GlobalTransactionWrapper sGlobalTransaction;
499     static long sTransactionNestCount = 0;
500 
501     private static final NativeAllocationRegistry sRegistry =
502             NativeAllocationRegistry.createMalloced(SurfaceControl.class.getClassLoader(),
503                     nativeGetNativeSurfaceControlFinalizer());
504 
505     private Runnable mFreeNativeResources;
506 
507     /**
508      * Adds a reparenting listener.
509      *
510      * @param listener The listener.
511      * @return Whether listener was added.
512      *
513      * @hide
514      */
addOnReparentListener(@onNull OnReparentListener listener)515     public boolean addOnReparentListener(@NonNull OnReparentListener listener) {
516         synchronized (mLock) {
517             if (mReparentListeners == null) {
518                 mReparentListeners = new ArrayList<>(1);
519             }
520             return mReparentListeners.add(listener);
521         }
522     }
523 
524     /**
525      * Removes a reparenting listener.
526      *
527      * @param listener The listener.
528      * @return Whether listener was removed.
529      *
530      * @hide
531      */
removeOnReparentListener(@onNull OnReparentListener listener)532     public boolean removeOnReparentListener(@NonNull OnReparentListener listener) {
533         synchronized (mLock) {
534             final boolean removed = mReparentListeners.remove(listener);
535             if (mReparentListeners.isEmpty()) {
536                 mReparentListeners = null;
537             }
538             return removed;
539         }
540     }
541 
542     /* flags used in constructor (keep in sync with ISurfaceComposerClient.h) */
543 
544     /**
545      * Surface creation flag: Surface is created hidden
546      * @hide
547      */
548     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
549     public static final int HIDDEN = 0x00000004;
550 
551     /**
552      * Surface creation flag: Skip this layer and its children when taking a screenshot. This
553      * also includes mirroring and screen recording, so the layers with flag SKIP_SCREENSHOT
554      * will not be included on non primary displays.
555      * @hide
556      */
557     public static final int SKIP_SCREENSHOT = 0x00000040;
558 
559     /**
560      * Surface creation flag: Special measures will be taken to disallow the surface's content to
561      * be copied. In particular, screenshots and secondary, non-secure displays will render black
562      * content instead of the surface content.
563      *
564      * @see com.android.server.display.DisplayControl#createDisplay(String, boolean)
565      * @hide
566      */
567     public static final int SECURE = 0x00000080;
568 
569 
570     /**
571      * Queue up BufferStateLayer buffers instead of dropping the oldest buffer when this flag is
572      * set. This blocks the client until all the buffers have been presented. If the buffers
573      * have presentation timestamps, then we may drop buffers.
574      * @hide
575      */
576     public static final int ENABLE_BACKPRESSURE = 0x00000100;
577 
578     /**
579      * Buffers from this SurfaceControl should be considered display decorations.
580      *
581      * If the hardware has optimizations for display decorations (e.g. rounded corners, camera
582      * cutouts, etc), it should use them for this layer.
583      * @hide
584      */
585     public static final int DISPLAY_DECORATION = 0x00000200;
586 
587     /**
588      * Surface creation flag: Creates a surface where color components are interpreted
589      * as "non pre-multiplied" by their alpha channel. Of course this flag is
590      * meaningless for surfaces without an alpha channel. By default
591      * surfaces are pre-multiplied, which means that each color component is
592      * already multiplied by its alpha value. In this case the blending
593      * equation used is:
594      * <p>
595      *    <code>DEST = SRC + DEST * (1-SRC_ALPHA)</code>
596      * <p>
597      * By contrast, non pre-multiplied surfaces use the following equation:
598      * <p>
599      *    <code>DEST = SRC * SRC_ALPHA * DEST * (1-SRC_ALPHA)</code>
600      * <p>
601      * pre-multiplied surfaces must always be used if transparent pixels are
602      * composited on top of each-other into the surface. A pre-multiplied
603      * surface can never lower the value of the alpha component of a given
604      * pixel.
605      * <p>
606      * In some rare situations, a non pre-multiplied surface is preferable.
607      * @hide
608      */
609     public static final int NON_PREMULTIPLIED = 0x00000100;
610 
611     /**
612      * Surface creation flag: Indicates that the surface must be considered opaque,
613      * even if its pixel format contains an alpha channel. This can be useful if an
614      * application needs full RGBA 8888 support for instance but will
615      * still draw every pixel opaque.
616      * <p>
617      * This flag is ignored if setAlpha() is used to make the surface non-opaque.
618      * Combined effects are (assuming a buffer format with an alpha channel):
619      * <ul>
620      * <li>OPAQUE + alpha(1.0) == opaque composition
621      * <li>OPAQUE + alpha(0.x) == blended composition
622      * <li>!OPAQUE + alpha(1.0) == blended composition
623      * <li>!OPAQUE + alpha(0.x) == blended composition
624      * </ul>
625      * If the underlying buffer lacks an alpha channel, the OPAQUE flag is effectively
626      * set automatically.
627      * @hide
628      */
629     public static final int OPAQUE = 0x00000400;
630 
631     /**
632      * Surface creation flag: Application requires a hardware-protected path to an
633      * external display sink. If a hardware-protected path is not available,
634      * then this surface will not be displayed on the external sink.
635      *
636      * @hide
637      */
638     public static final int PROTECTED_APP = 0x00000800;
639 
640     // 0x1000 is reserved for an independent DRM protected flag in framework
641 
642     /**
643      * Surface creation flag: Window represents a cursor glyph.
644      * @hide
645      */
646     public static final int CURSOR_WINDOW = 0x00002000;
647 
648     /**
649      * Surface creation flag: Indicates the effect layer will not have a color fill on
650      * creation.
651      *
652      * @hide
653      */
654     public static final int NO_COLOR_FILL = 0x00004000;
655 
656     /**
657      * Surface creation flag: Creates a normal surface.
658      * This is the default.
659      *
660      * @hide
661      */
662     public static final int FX_SURFACE_NORMAL   = 0x00000000;
663 
664     /**
665      * Surface creation flag: Creates a effect surface which
666      * represents a solid color and or shadows.
667      *
668      * @hide
669      */
670     public static final int FX_SURFACE_EFFECT = 0x00020000;
671 
672     /**
673      * Surface creation flag: Creates a container surface.
674      * This surface will have no buffers and will only be used
675      * as a container for other surfaces, or for its InputInfo.
676      * @hide
677      */
678     public static final int FX_SURFACE_CONTAINER = 0x00080000;
679 
680     /**
681      * @hide
682      */
683     public static final int FX_SURFACE_BLAST = 0x00040000;
684 
685     /**
686      * Mask used for FX values above.
687      *
688      * @hide
689      */
690     public static final int FX_SURFACE_MASK = 0x000F0000;
691 
692     /* flags used with setFlags() (keep in sync with ISurfaceComposer.h) */
693 
694     /**
695      * Surface flag: Hide the surface.
696      * Equivalent to calling hide().
697      * Updates the value set during Surface creation (see {@link #HIDDEN}).
698      */
699     private static final int SURFACE_HIDDEN = 0x01;
700 
701     /**
702      * Surface flag: composite without blending when possible.
703      * Updates the value set during Surface creation (see {@link #OPAQUE}).
704      */
705     private static final int SURFACE_OPAQUE = 0x02;
706 
707     /* flags used with setDisplayFlags() (keep in sync with DisplayDevice.h) */
708 
709     /**
710      * DisplayDevice flag: This display's transform is sent to inputflinger and used for input
711      * dispatch. This flag is used to disambiguate displays which share a layerstack.
712      * @hide
713      */
714     public static final int DISPLAY_RECEIVES_INPUT = 0x01;
715 
716     // Display power modes.
717     /**
718      * Display power mode off: used while blanking the screen.
719      * Use only with {@link SurfaceControl#setDisplayPowerMode}.
720      * @hide
721      */
722     public static final int POWER_MODE_OFF = 0;
723 
724     /**
725      * Display power mode doze: used while putting the screen into low power mode.
726      * Use only with {@link SurfaceControl#setDisplayPowerMode}.
727      * @hide
728      */
729     public static final int POWER_MODE_DOZE = 1;
730 
731     /**
732      * Display power mode normal: used while unblanking the screen.
733      * Use only with {@link SurfaceControl#setDisplayPowerMode}.
734      * @hide
735      */
736     public static final int POWER_MODE_NORMAL = 2;
737 
738     /**
739      * Display power mode doze: used while putting the screen into a suspended
740      * low power mode.  Use only with {@link SurfaceControl#setDisplayPowerMode}.
741      * @hide
742      */
743     public static final int POWER_MODE_DOZE_SUSPEND = 3;
744 
745     /**
746      * Display power mode on: used while putting the screen into a suspended
747      * full power mode.  Use only with {@link SurfaceControl#setDisplayPowerMode}.
748      * @hide
749      */
750     public static final int POWER_MODE_ON_SUSPEND = 4;
751 
752     /**
753      * Hint that this SurfaceControl should not participate in layer caching within SurfaceFlinger.
754      *
755      * A system layer may request that a layer does not participate in caching when there are known
756      * quality limitations when caching via the compositor's GPU path.
757      * Use only with {@link SurfaceControl.Transaction#setCachingHint}.
758      * @hide
759      */
760     public static final int CACHING_DISABLED = 0;
761 
762     /**
763      * Hint that this SurfaceControl should participate in layer caching within SurfaceFlinger.
764      *
765      * Use only with {@link SurfaceControl.Transaction#setCachingHint}.
766      * @hide
767      */
768     public static final int CACHING_ENABLED = 1;
769 
770     /** @hide */
771     @IntDef(flag = true, value = {CACHING_DISABLED, CACHING_ENABLED})
772     @Retention(RetentionPolicy.SOURCE)
773     public @interface CachingHint {}
774 
assignNativeObject(long nativeObject, String callsite)775     private void assignNativeObject(long nativeObject, String callsite) {
776         if (mNativeObject != 0) {
777             release();
778         }
779         if (nativeObject != 0) {
780             mFreeNativeResources =
781                     sRegistry.registerNativeAllocation(this, nativeObject);
782         }
783         mNativeObject = nativeObject;
784         mNativeHandle = mNativeObject != 0 ? nativeGetHandle(nativeObject) : 0;
785         if (sDebugUsageAfterRelease && mNativeObject == 0) {
786             mReleaseStack = new Throwable("Assigned invalid nativeObject");
787         } else {
788             mReleaseStack = null;
789         }
790         setUnreleasedWarningCallSite(callsite);
791         if (nativeObject != 0) {
792             // Only add valid surface controls to the registry. This is called at the end of this
793             // method since its information is dumped if the process threshold is reached.
794             addToRegistry();
795         }
796     }
797 
798     /**
799      * @hide
800      */
copyFrom(@onNull SurfaceControl other, String callsite)801     public void copyFrom(@NonNull SurfaceControl other, String callsite) {
802         mName = other.mName;
803         mWidth = other.mWidth;
804         mHeight = other.mHeight;
805         mLocalOwnerView = other.mLocalOwnerView;
806         assignNativeObject(nativeCopyFromSurfaceControl(other.mNativeObject), callsite);
807     }
808 
809     /**
810      * owner UID.
811      * @hide
812      */
813     public static final int METADATA_OWNER_UID = 1;
814 
815     /**
816      * Window type as per {@link WindowManager.LayoutParams}.
817      * @hide
818      */
819     public static final int METADATA_WINDOW_TYPE = 2;
820 
821     /**
822      * Task id to allow association between surfaces and task.
823      * @hide
824      */
825     public static final int METADATA_TASK_ID = 3;
826 
827     /**
828      * The style of mouse cursor and hotspot.
829      * @hide
830      */
831     public static final int METADATA_MOUSE_CURSOR = 4;
832 
833     /**
834      * Accessibility ID to allow association between surfaces and accessibility tree.
835      * @hide
836      */
837     public static final int METADATA_ACCESSIBILITY_ID = 5;
838 
839     /**
840      * owner PID.
841      * @hide
842      */
843     public static final int METADATA_OWNER_PID = 6;
844 
845     /**
846      * game mode for the layer - used for metrics
847      * @hide
848      */
849     public static final int METADATA_GAME_MODE = 8;
850 
851     /**
852      * Builder class for {@link SurfaceControl} objects.
853      *
854      * By default the surface will be hidden, and have "unset" bounds, meaning it can
855      * be as large as the bounds of its parent if a buffer or child so requires.
856      *
857      * It is necessary to set at least a name via {@link Builder#setName}
858      */
859     public static class Builder {
860         private SurfaceSession mSession;
861         private int mFlags = HIDDEN;
862         private int mWidth;
863         private int mHeight;
864         private int mFormat = PixelFormat.OPAQUE;
865         private String mName;
866         private WeakReference<View> mLocalOwnerView;
867         private SurfaceControl mParent;
868         private SparseIntArray mMetadata;
869         private String mCallsite = "SurfaceControl.Builder";
870 
871         /**
872          * Begin building a SurfaceControl with a given {@link SurfaceSession}.
873          *
874          * @param session The {@link SurfaceSession} with which to eventually construct the surface.
875          * @hide
876          */
Builder(SurfaceSession session)877         public Builder(SurfaceSession session) {
878             mSession = session;
879         }
880 
881         /**
882          * Begin building a SurfaceControl.
883          */
Builder()884         public Builder() {
885         }
886 
887         /**
888          * Construct a new {@link SurfaceControl} with the set parameters. The builder
889          * remains valid.
890          */
891         @NonNull
build()892         public SurfaceControl build() {
893             if (mWidth < 0 || mHeight < 0) {
894                 throw new IllegalStateException(
895                         "width and height must be positive or unset");
896             }
897             if ((mWidth > 0 || mHeight > 0) && (isEffectLayer() || isContainerLayer())) {
898                 throw new IllegalStateException(
899                         "Only buffer layers can set a valid buffer size.");
900             }
901 
902             if (mName == null) {
903                 Log.w(TAG, "Missing name for SurfaceControl", new Throwable());
904             }
905 
906             if ((mFlags & FX_SURFACE_MASK) == FX_SURFACE_NORMAL) {
907                 setBLASTLayer();
908             }
909 
910             return new SurfaceControl(
911                     mSession, mName, mWidth, mHeight, mFormat, mFlags, mParent, mMetadata,
912                     mLocalOwnerView, mCallsite);
913         }
914 
915         /**
916          * Set a debugging-name for the SurfaceControl.
917          *
918          * @param name A name to identify the Surface in debugging.
919          */
920         @NonNull
setName(@onNull String name)921         public Builder setName(@NonNull String name) {
922             mName = name;
923             return this;
924         }
925 
926         /**
927          * Set the local owner view for the surface. This view is only
928          * valid in the same process and is not transferred in an IPC.
929          *
930          * Note: This is used for cases where we want to know the view
931          * that manages the surface control while intercepting reparenting.
932          * A specific example is InlineContentView which exposes is surface
933          * control for reparenting as a way to implement clipping of several
934          * InlineContentView instances within a certain area.
935          *
936          * @param view The owner view.
937          * @return This builder.
938          *
939          * @hide
940          */
941         @NonNull
setLocalOwnerView(@onNull View view)942         public Builder setLocalOwnerView(@NonNull View view) {
943             mLocalOwnerView = new WeakReference<>(view);
944             return this;
945         }
946 
947         /**
948          * Set the initial size of the controlled surface's buffers in pixels.
949          *
950          * @param width The buffer width in pixels.
951          * @param height The buffer height in pixels.
952          */
953         @NonNull
setBufferSize(@ntRangefrom = 0) int width, @IntRange(from = 0) int height)954         public Builder setBufferSize(@IntRange(from = 0) int width,
955                 @IntRange(from = 0) int height) {
956             if (width < 0 || height < 0) {
957                 throw new IllegalArgumentException(
958                         "width and height must be positive");
959             }
960             mWidth = width;
961             mHeight = height;
962             // set this as a buffer layer since we are specifying a buffer size.
963             return setFlags(FX_SURFACE_NORMAL, FX_SURFACE_MASK);
964         }
965 
unsetBufferSize()966         private void unsetBufferSize() {
967             mWidth = 0;
968             mHeight = 0;
969         }
970 
971         /**
972          * Set the pixel format of the controlled surface's buffers, using constants from
973          * {@link android.graphics.PixelFormat}.
974          */
975         @NonNull
setFormat(@ixelFormat.Format int format)976         public Builder setFormat(@PixelFormat.Format int format) {
977             mFormat = format;
978             return this;
979         }
980 
981         /**
982          * Specify if the app requires a hardware-protected path to
983          * an external display sync. If protected content is enabled, but
984          * such a path is not available, then the controlled Surface will
985          * not be displayed.
986          *
987          * @param protectedContent Whether to require a protected sink.
988          * @hide
989          */
990         @NonNull
setProtected(boolean protectedContent)991         public Builder setProtected(boolean protectedContent) {
992             if (protectedContent) {
993                 mFlags |= PROTECTED_APP;
994             } else {
995                 mFlags &= ~PROTECTED_APP;
996             }
997             return this;
998         }
999 
1000         /**
1001          * Specify whether the Surface contains secure content. If true, the system
1002          * will prevent the surfaces content from being copied by another process. In
1003          * particular screenshots and VNC servers will be disabled. This is however
1004          * not a complete prevention of readback as {@link #setProtected}.
1005          * @hide
1006          */
1007         @NonNull
setSecure(boolean secure)1008         public Builder setSecure(boolean secure) {
1009             if (secure) {
1010                 mFlags |= SECURE;
1011             } else {
1012                 mFlags &= ~SECURE;
1013             }
1014             return this;
1015         }
1016 
1017         /**
1018          * Indicates whether the surface must be considered opaque,
1019          * even if its pixel format is set to translucent. This can be useful if an
1020          * application needs full RGBA 8888 support for instance but will
1021          * still draw every pixel opaque.
1022          * <p>
1023          * This flag only determines whether opacity will be sampled from the alpha channel.
1024          * Plane-alpha from calls to setAlpha() can still result in blended composition
1025          * regardless of the opaque setting.
1026          *
1027          * Combined effects are (assuming a buffer format with an alpha channel):
1028          * <ul>
1029          * <li>OPAQUE + alpha(1.0) == opaque composition
1030          * <li>OPAQUE + alpha(0.x) == blended composition
1031          * <li>OPAQUE + alpha(0.0) == no composition
1032          * <li>!OPAQUE + alpha(1.0) == blended composition
1033          * <li>!OPAQUE + alpha(0.x) == blended composition
1034          * <li>!OPAQUE + alpha(0.0) == no composition
1035          * </ul>
1036          * If the underlying buffer lacks an alpha channel, it is as if setOpaque(true)
1037          * were set automatically.
1038          * @param opaque Whether the Surface is OPAQUE.
1039          */
1040         @NonNull
setOpaque(boolean opaque)1041         public Builder setOpaque(boolean opaque) {
1042             if (opaque) {
1043                 mFlags |= OPAQUE;
1044             } else {
1045                 mFlags &= ~OPAQUE;
1046             }
1047             return this;
1048         }
1049 
1050         /**
1051          * Set the initial visibility for the SurfaceControl.
1052          *
1053          * @param hidden Whether the Surface is initially HIDDEN.
1054          */
1055         @NonNull
setHidden(boolean hidden)1056         public Builder setHidden(boolean hidden) {
1057             if (hidden) {
1058                 mFlags |= HIDDEN;
1059             } else {
1060                 mFlags &= ~HIDDEN;
1061             }
1062             return this;
1063         }
1064 
1065         /**
1066          * Set a parent surface for our new SurfaceControl.
1067          *
1068          * Child surfaces are constrained to the onscreen region of their parent.
1069          * Furthermore they stack relatively in Z order, and inherit the transformation
1070          * of the parent.
1071          *
1072          * @param parent The parent control.
1073          */
1074         @NonNull
setParent(@ullable SurfaceControl parent)1075         public Builder setParent(@Nullable SurfaceControl parent) {
1076             mParent = parent;
1077             return this;
1078         }
1079 
1080         /**
1081          * Sets a metadata int.
1082          *
1083          * @param key metadata key
1084          * @param data associated data
1085          * @hide
1086          */
setMetadata(int key, int data)1087         public Builder setMetadata(int key, int data) {
1088             if (mMetadata == null) {
1089                 mMetadata = new SparseIntArray();
1090             }
1091             mMetadata.put(key, data);
1092             return this;
1093         }
1094 
1095         /**
1096          * Indicate whether an 'EffectLayer' is to be constructed.
1097          *
1098          * An effect layer behaves like a container layer by default but it can support
1099          * color fill, shadows and/or blur. These layers will not have an associated buffer.
1100          * When created, this layer has no effects set and will be transparent but the caller
1101          * can render an effect by calling:
1102          *  - {@link Transaction#setColor(SurfaceControl, float[])}
1103          *  - {@link Transaction#setBackgroundBlurRadius(SurfaceControl, int)}
1104          *  - {@link Transaction#setShadowRadius(SurfaceControl, float)}
1105          *
1106          * @hide
1107          */
setEffectLayer()1108         public Builder setEffectLayer() {
1109             mFlags |= NO_COLOR_FILL;
1110             unsetBufferSize();
1111             return setFlags(FX_SURFACE_EFFECT, FX_SURFACE_MASK);
1112         }
1113 
1114         /**
1115          * A convenience function to create an effect layer with a default color fill
1116          * applied to it. Currently that color is black.
1117          *
1118          * @hide
1119          */
setColorLayer()1120         public Builder setColorLayer() {
1121             unsetBufferSize();
1122             return setFlags(FX_SURFACE_EFFECT, FX_SURFACE_MASK);
1123         }
1124 
isEffectLayer()1125         private boolean isEffectLayer() {
1126             return  (mFlags & FX_SURFACE_EFFECT) == FX_SURFACE_EFFECT;
1127         }
1128 
1129         /**
1130          * @hide
1131          */
setBLASTLayer()1132         public Builder setBLASTLayer() {
1133             return setFlags(FX_SURFACE_BLAST, FX_SURFACE_MASK);
1134         }
1135 
1136         /**
1137          * Indicates whether a 'ContainerLayer' is to be constructed.
1138          *
1139          * Container layers will not be rendered in any fashion and instead are used
1140          * as a parent of renderable layers.
1141          *
1142          * @hide
1143          */
setContainerLayer()1144         public Builder setContainerLayer() {
1145             unsetBufferSize();
1146             return setFlags(FX_SURFACE_CONTAINER, FX_SURFACE_MASK);
1147         }
1148 
isContainerLayer()1149         private boolean isContainerLayer() {
1150             return  (mFlags & FX_SURFACE_CONTAINER) == FX_SURFACE_CONTAINER;
1151         }
1152 
1153         /**
1154          * Set 'Surface creation flags' such as {@link #HIDDEN}, {@link #SECURE}.
1155          *
1156          * TODO: Finish conversion to individual builder methods?
1157          * @param flags The combined flags
1158          * @hide
1159          */
setFlags(int flags)1160         public Builder setFlags(int flags) {
1161             mFlags = flags;
1162             return this;
1163         }
1164 
1165         /**
1166          * Sets the callsite this SurfaceControl is constructed from.
1167          *
1168          * @param callsite String uniquely identifying callsite that created this object. Used for
1169          *                 leakage tracking.
1170          * @hide
1171          */
setCallsite(String callsite)1172         public Builder setCallsite(String callsite) {
1173             mCallsite = callsite;
1174             return this;
1175         }
1176 
setFlags(int flags, int mask)1177         private Builder setFlags(int flags, int mask) {
1178             mFlags = (mFlags & ~mask) | flags;
1179             return this;
1180         }
1181     }
1182 
1183     /**
1184      * Create a surface with a name.
1185      * <p>
1186      * The surface creation flags specify what kind of surface to create and
1187      * certain options such as whether the surface can be assumed to be opaque
1188      * and whether it should be initially hidden.  Surfaces should always be
1189      * created with the {@link #HIDDEN} flag set to ensure that they are not
1190      * made visible prematurely before all of the surface's properties have been
1191      * configured.
1192      * <p>
1193      * Good practice is to first create the surface with the {@link #HIDDEN} flag
1194      * specified, open a transaction, set the surface layer, layer stack, alpha,
1195      * and position, call {@link Transaction#show(SurfaceControl)} if appropriate, and close the
1196      * transaction.
1197      * <p>
1198      * Bounds of the surface is determined by its crop and its buffer size. If the
1199      * surface has no buffer or crop, the surface is boundless and only constrained
1200      * by the size of its parent bounds.
1201      *
1202      * @param session  The surface session, must not be null.
1203      * @param name     The surface name, must not be null.
1204      * @param w        The surface initial width.
1205      * @param h        The surface initial height.
1206      * @param flags    The surface creation flags.
1207      * @param metadata Initial metadata.
1208      * @param callsite String uniquely identifying callsite that created this object. Used for
1209      *                 leakage tracking.
1210      * @throws throws OutOfResourcesException If the SurfaceControl cannot be created.
1211      */
SurfaceControl(SurfaceSession session, String name, int w, int h, int format, int flags, SurfaceControl parent, SparseIntArray metadata, WeakReference<View> localOwnerView, String callsite)1212     private SurfaceControl(SurfaceSession session, String name, int w, int h, int format, int flags,
1213             SurfaceControl parent, SparseIntArray metadata, WeakReference<View> localOwnerView,
1214             String callsite)
1215                     throws OutOfResourcesException, IllegalArgumentException {
1216         if (name == null) {
1217             throw new IllegalArgumentException("name must not be null");
1218         }
1219 
1220         mName = name;
1221         mWidth = w;
1222         mHeight = h;
1223         mLocalOwnerView = localOwnerView;
1224         Parcel metaParcel = Parcel.obtain();
1225         long nativeObject = 0;
1226         try {
1227             if (metadata != null && metadata.size() > 0) {
1228                 metaParcel.writeInt(metadata.size());
1229                 for (int i = 0; i < metadata.size(); ++i) {
1230                     metaParcel.writeInt(metadata.keyAt(i));
1231                     metaParcel.writeByteArray(
1232                             ByteBuffer.allocate(4).order(ByteOrder.nativeOrder())
1233                                     .putInt(metadata.valueAt(i)).array());
1234                 }
1235                 metaParcel.setDataPosition(0);
1236             }
1237             nativeObject = nativeCreate(session, name, w, h, format, flags,
1238                     parent != null ? parent.mNativeObject : 0, metaParcel);
1239         } finally {
1240             metaParcel.recycle();
1241         }
1242         if (nativeObject == 0) {
1243             throw new OutOfResourcesException(
1244                     "Couldn't allocate SurfaceControl native object");
1245         }
1246         assignNativeObject(nativeObject, callsite);
1247     }
1248 
1249     /**
1250      * Copy constructor. Creates a new native object pointing to the same surface as {@code other}.
1251      *
1252      * @param other The object to copy the surface from.
1253      * @param callsite String uniquely identifying callsite that created this object. Used for
1254      *                 leakage tracking.
1255      * @hide
1256      */
1257     @TestApi
SurfaceControl(@onNull SurfaceControl other, @NonNull String callsite)1258     public SurfaceControl(@NonNull SurfaceControl other, @NonNull String callsite) {
1259         copyFrom(other, callsite);
1260     }
1261 
SurfaceControl(Parcel in)1262     private SurfaceControl(Parcel in) {
1263         readFromParcel(in);
1264     }
1265 
1266     /**
1267      * Note: Most callers should use {@link SurfaceControl.Builder} or one of the other constructors
1268      *       to build an instance of a SurfaceControl. This constructor is mainly used for
1269      *       unparceling and passing into an AIDL call as an out parameter.
1270      * @hide
1271      */
SurfaceControl()1272     public SurfaceControl() {
1273     }
1274 
readFromParcel(Parcel in)1275     public void readFromParcel(Parcel in) {
1276         if (in == null) {
1277             throw new IllegalArgumentException("source must not be null");
1278         }
1279 
1280         mName = in.readString8();
1281         mWidth = in.readInt();
1282         mHeight = in.readInt();
1283 
1284         long object = 0;
1285         if (in.readInt() != 0) {
1286             object = nativeReadFromParcel(in);
1287         }
1288         assignNativeObject(object, "readFromParcel");
1289     }
1290 
1291     @Override
describeContents()1292     public int describeContents() {
1293         return 0;
1294     }
1295 
1296     @Override
writeToParcel(Parcel dest, int flags)1297     public void writeToParcel(Parcel dest, int flags) {
1298         if (sDebugUsageAfterRelease) {
1299             checkNotReleased();
1300         }
1301         dest.writeString8(mName);
1302         dest.writeInt(mWidth);
1303         dest.writeInt(mHeight);
1304         if (mNativeObject == 0) {
1305             dest.writeInt(0);
1306         } else {
1307             dest.writeInt(1);
1308         }
1309         nativeWriteToParcel(mNativeObject, dest);
1310 
1311         if ((flags & Parcelable.PARCELABLE_WRITE_RETURN_VALUE) != 0) {
1312             release();
1313         }
1314     }
1315 
1316     /**
1317      * Enables additional debug logs to track usage-after-release of all SurfaceControls in this
1318      * process.
1319      * @hide
1320      */
setDebugUsageAfterRelease(boolean debug)1321     public static void setDebugUsageAfterRelease(boolean debug) {
1322         if (!Build.isDebuggable()) {
1323             return;
1324         }
1325         sDebugUsageAfterRelease = debug;
1326     }
1327 
1328     /**
1329      * Provides more information to show about the source of this SurfaceControl if it is finalized
1330      * without being released. This is primarily intended for callers to update the call site after
1331      * receiving a SurfaceControl from another process, which would otherwise get a generic default
1332      * call site.
1333      * @hide
1334      */
setUnreleasedWarningCallSite(@onNull String callsite)1335     public void setUnreleasedWarningCallSite(@NonNull String callsite) {
1336         if (!isValid()) {
1337             return;
1338         }
1339         mCloseGuard.openWithCallSite("release", callsite);
1340         mCallsite = callsite;
1341     }
1342 
1343     /**
1344      * Returns the last provided call site when this SurfaceControl was created.
1345      * @hide
1346      */
getCallsite()1347     @Nullable String getCallsite() {
1348         return mCallsite;
1349     }
1350 
1351     /**
1352      * Returns the name of this SurfaceControl, mainly for debugging purposes.
1353      * @hide
1354      */
getName()1355     @NonNull String getName() {
1356         return mName;
1357     }
1358 
1359     /**
1360      * Checks whether two {@link SurfaceControl} objects represent the same surface.
1361      *
1362      * @param other The other object to check
1363      * @return {@code true} if these two {@link SurfaceControl} objects represent the same surface.
1364      * @hide
1365      */
1366     @TestApi
isSameSurface(@onNull SurfaceControl other)1367     public boolean isSameSurface(@NonNull SurfaceControl other) {
1368         return other.mNativeHandle == mNativeHandle;
1369     }
1370 
1371     /**
1372      * When called for the first time a new instance of the {@link Choreographer} is created
1373      * with a {@link android.os.Looper} of the current thread. Every subsequent call will return
1374      * the same instance of the Choreographer.
1375      *
1376      * @see #getChoreographer(Looper) to create Choreographer with a different
1377      * looper than current thread looper.
1378      *
1379      * @hide
1380      */
1381     @TestApi
getChoreographer()1382     public @NonNull Choreographer getChoreographer() {
1383         checkNotReleased();
1384         synchronized (mChoreographerLock) {
1385             if (mChoreographer == null) {
1386                 return getChoreographer(Looper.myLooper());
1387             }
1388             return mChoreographer;
1389         }
1390     }
1391 
1392     /**
1393      * When called for the first time a new instance of the {@link Choreographer} is created with
1394      * the sourced {@link android.os.Looper}. Every subsequent call will return the same
1395      * instance of the Choreographer.
1396      *
1397      * @see #getChoreographer()
1398      *
1399      * @throws IllegalStateException when a {@link Choreographer} instance exists with a different
1400      * looper than sourced.
1401      * @param looper the choreographer is attached on this looper.
1402      *
1403      * @hide
1404      */
1405     @TestApi
getChoreographer(@onNull Looper looper)1406     public @NonNull Choreographer getChoreographer(@NonNull Looper looper) {
1407         checkNotReleased();
1408         synchronized (mChoreographerLock) {
1409             if (mChoreographer == null) {
1410                 mChoreographer = Choreographer.getInstanceForSurfaceControl(mNativeHandle, looper);
1411             } else if (!mChoreographer.isTheLooperSame(looper)) {
1412                 throw new IllegalStateException(
1413                         "Choreographer already exists with a different looper");
1414             }
1415             return mChoreographer;
1416         }
1417     }
1418 
1419     /**
1420      * Returns true if {@link Choreographer} is present otherwise false.
1421      * To check the validity use {@link #isValid} on the SurfaceControl, a valid SurfaceControl with
1422      * choreographer will have the valid Choreographer.
1423      *
1424      * @hide
1425      */
1426     @TestApi
1427     @UnsupportedAppUsage
hasChoreographer()1428     public boolean hasChoreographer() {
1429         synchronized (mChoreographerLock) {
1430             return mChoreographer != null;
1431         }
1432     }
1433 
1434     /**
1435      * Write to a protocol buffer output stream. Protocol buffer message definition is at {@link
1436      * android.view.SurfaceControlProto}.
1437      *
1438      * @param proto Stream to write the SurfaceControl object to.
1439      * @param fieldId Field Id of the SurfaceControl as defined in the parent message.
1440      * @hide
1441      */
dumpDebug(ProtoOutputStream proto, long fieldId)1442     public void dumpDebug(ProtoOutputStream proto, long fieldId) {
1443         final long token = proto.start(fieldId);
1444         proto.write(HASH_CODE, System.identityHashCode(this));
1445         proto.write(NAME, mName);
1446         proto.write(LAYER_ID, getLayerId());
1447         proto.end(token);
1448     }
1449 
1450     public static final @android.annotation.NonNull Creator<SurfaceControl> CREATOR
1451             = new Creator<SurfaceControl>() {
1452         public SurfaceControl createFromParcel(Parcel in) {
1453             return new SurfaceControl(in);
1454         }
1455 
1456         public SurfaceControl[] newArray(int size) {
1457             return new SurfaceControl[size];
1458         }
1459     };
1460 
1461     /**
1462      * @hide
1463      */
1464     @Override
finalize()1465     protected void finalize() throws Throwable {
1466         try {
1467             if (mCloseGuard != null) {
1468                 mCloseGuard.warnIfOpen();
1469             }
1470             removeFromRegistry();
1471         } finally {
1472             super.finalize();
1473         }
1474     }
1475 
1476     /**
1477      * Release the local reference to the server-side surface. The surface
1478      * may continue to exist on-screen as long as its parent continues
1479      * to exist. To explicitly remove a surface from the screen use
1480      * {@link Transaction#reparent} with a null-parent. After release,
1481      * {@link #isValid} will return false and other methods will throw
1482      * an exception.
1483      *
1484      * Always call release() when you're done with a SurfaceControl.
1485      */
release()1486     public void release() {
1487         if (mNativeObject != 0) {
1488             mFreeNativeResources.run();
1489             mNativeObject = 0;
1490             mNativeHandle = 0;
1491             if (sDebugUsageAfterRelease) {
1492                 mReleaseStack = new Throwable("Released");
1493             }
1494             mCloseGuard.close();
1495             synchronized (mChoreographerLock) {
1496                 if (mChoreographer != null) {
1497                     mChoreographer.invalidate();
1498                     mChoreographer = null;
1499                 }
1500             }
1501             removeFromRegistry();
1502         }
1503     }
1504 
1505     /**
1506      * Disconnect any client still connected to the surface.
1507      * @hide
1508      */
disconnect()1509     public void disconnect() {
1510         if (mNativeObject != 0) {
1511             nativeDisconnect(mNativeObject);
1512         }
1513     }
1514 
checkNotReleased()1515     private void checkNotReleased() {
1516         if (mNativeObject == 0) {
1517             if (mReleaseStack != null) {
1518                 throw new IllegalStateException("Invalid usage after release of " + this,
1519                         mReleaseStack);
1520             } else {
1521                 throw new NullPointerException("mNativeObject of " + this
1522                         + " is null. Have you called release() already?");
1523             }
1524         }
1525     }
1526 
1527     /**
1528      * Check whether this instance points to a valid layer with the system-compositor. For
1529      * example this may be false if construction failed, or the layer was released
1530      * ({@link #release}).
1531      *
1532      * @return Whether this SurfaceControl is valid.
1533      */
isValid()1534     public boolean isValid() {
1535         return mNativeObject != 0;
1536     }
1537 
1538     /*
1539      * set surface parameters.
1540      * needs to be inside open/closeTransaction block
1541      */
1542 
1543     /** start a transaction
1544      * @hide
1545      */
1546     @UnsupportedAppUsage
openTransaction()1547     public static void openTransaction() {
1548         synchronized (SurfaceControl.class) {
1549             if (sGlobalTransaction == null) {
1550                 sGlobalTransaction = new GlobalTransactionWrapper();
1551             }
1552             synchronized(SurfaceControl.class) {
1553                 sTransactionNestCount++;
1554             }
1555         }
1556     }
1557 
1558     /**
1559      * Merge the supplied transaction in to the deprecated "global" transaction.
1560      * This clears the supplied transaction in an identical fashion to {@link Transaction#merge}.
1561      * <p>
1562      * This is a utility for interop with legacy-code and will go away with the Global Transaction.
1563      * @hide
1564      */
1565     @Deprecated
mergeToGlobalTransaction(Transaction t)1566     public static void mergeToGlobalTransaction(Transaction t) {
1567         synchronized(SurfaceControl.class) {
1568             sGlobalTransaction.merge(t);
1569         }
1570     }
1571 
1572     /** end a transaction
1573      * @hide
1574      */
1575     @UnsupportedAppUsage
closeTransaction()1576     public static void closeTransaction() {
1577         synchronized(SurfaceControl.class) {
1578             if (sTransactionNestCount == 0) {
1579                 Log.e(TAG,
1580                         "Call to SurfaceControl.closeTransaction without matching openTransaction");
1581             } else if (--sTransactionNestCount > 0) {
1582                 return;
1583             }
1584             sGlobalTransaction.applyGlobalTransaction(false);
1585         }
1586     }
1587 
1588     /**
1589      * @hide
1590      */
clearContentFrameStats()1591     public boolean clearContentFrameStats() {
1592         checkNotReleased();
1593         return nativeClearContentFrameStats(mNativeObject);
1594     }
1595 
1596     /**
1597      * @hide
1598      */
getContentFrameStats(WindowContentFrameStats outStats)1599     public boolean getContentFrameStats(WindowContentFrameStats outStats) {
1600         checkNotReleased();
1601         return nativeGetContentFrameStats(mNativeObject, outStats);
1602     }
1603 
1604     /**
1605      * @hide
1606      */
clearAnimationFrameStats()1607     public static boolean clearAnimationFrameStats() {
1608         return nativeClearAnimationFrameStats();
1609     }
1610 
1611     /**
1612      * @hide
1613      */
getAnimationFrameStats(WindowAnimationFrameStats outStats)1614     public static boolean getAnimationFrameStats(WindowAnimationFrameStats outStats) {
1615         return nativeGetAnimationFrameStats(outStats);
1616     }
1617 
1618     /**
1619      * @hide
1620      */
getWidth()1621     public int getWidth() {
1622         synchronized (mLock) {
1623             return mWidth;
1624         }
1625     }
1626 
1627     /**
1628      * @hide
1629      */
getHeight()1630     public int getHeight() {
1631         synchronized (mLock) {
1632             return mHeight;
1633         }
1634     }
1635 
1636     /**
1637      * Gets the local view that owns this surface.
1638      *
1639      * @return The owner view.
1640      *
1641      * @hide
1642      */
getLocalOwnerView()1643     public @Nullable View getLocalOwnerView() {
1644         return (mLocalOwnerView != null) ? mLocalOwnerView.get() : null;
1645     }
1646 
1647     @Override
toString()1648     public String toString() {
1649         return "Surface(name=" + mName + ")/@0x" +
1650                 Integer.toHexString(System.identityHashCode(this));
1651     }
1652 
1653     /**
1654      * Immutable information about physical display.
1655      *
1656      * @hide
1657      */
1658     public static final class StaticDisplayInfo {
1659         public boolean isInternal;
1660         public float density;
1661         public boolean secure;
1662         public DeviceProductInfo deviceProductInfo;
1663         public @Surface.Rotation int installOrientation;
1664 
1665         @Override
toString()1666         public String toString() {
1667             return "StaticDisplayInfo{isInternal=" + isInternal
1668                     + ", density=" + density
1669                     + ", secure=" + secure
1670                     + ", deviceProductInfo=" + deviceProductInfo
1671                     + ", installOrientation=" + installOrientation + "}";
1672         }
1673 
1674         @Override
equals(@ullable Object o)1675         public boolean equals(@Nullable Object o) {
1676             if (this == o) return true;
1677             if (o == null || getClass() != o.getClass()) return false;
1678             StaticDisplayInfo that = (StaticDisplayInfo) o;
1679             return isInternal == that.isInternal
1680                     && density == that.density
1681                     && secure == that.secure
1682                     && Objects.equals(deviceProductInfo, that.deviceProductInfo)
1683                     && installOrientation == that.installOrientation;
1684         }
1685 
1686         @Override
hashCode()1687         public int hashCode() {
1688             return Objects.hash(isInternal, density, secure, deviceProductInfo, installOrientation);
1689         }
1690     }
1691 
1692     /**
1693      * Dynamic information about physical display.
1694      *
1695      * @hide
1696      */
1697     public static final class DynamicDisplayInfo {
1698         public DisplayMode[] supportedDisplayModes;
1699         public int activeDisplayModeId;
1700         public float renderFrameRate;
1701 
1702         public int[] supportedColorModes;
1703         public int activeColorMode;
1704 
1705         public Display.HdrCapabilities hdrCapabilities;
1706 
1707         public boolean autoLowLatencyModeSupported;
1708         public boolean gameContentTypeSupported;
1709 
1710         public int preferredBootDisplayMode;
1711 
1712         @Override
toString()1713         public String toString() {
1714             return "DynamicDisplayInfo{"
1715                     + "supportedDisplayModes=" + Arrays.toString(supportedDisplayModes)
1716                     + ", activeDisplayModeId=" + activeDisplayModeId
1717                     + ", renderFrameRate=" + renderFrameRate
1718                     + ", supportedColorModes=" + Arrays.toString(supportedColorModes)
1719                     + ", activeColorMode=" + activeColorMode
1720                     + ", hdrCapabilities=" + hdrCapabilities
1721                     + ", autoLowLatencyModeSupported=" + autoLowLatencyModeSupported
1722                     + ", gameContentTypeSupported" + gameContentTypeSupported
1723                     + ", preferredBootDisplayMode" + preferredBootDisplayMode + "}";
1724         }
1725 
1726         @Override
equals(@ullable Object o)1727         public boolean equals(@Nullable Object o) {
1728             if (this == o) return true;
1729             if (o == null || getClass() != o.getClass()) return false;
1730             DynamicDisplayInfo that = (DynamicDisplayInfo) o;
1731             return Arrays.equals(supportedDisplayModes, that.supportedDisplayModes)
1732                 && activeDisplayModeId == that.activeDisplayModeId
1733                 && renderFrameRate == that.renderFrameRate
1734                 && Arrays.equals(supportedColorModes, that.supportedColorModes)
1735                 && activeColorMode == that.activeColorMode
1736                 && Objects.equals(hdrCapabilities, that.hdrCapabilities)
1737                 && preferredBootDisplayMode == that.preferredBootDisplayMode;
1738         }
1739 
1740         @Override
hashCode()1741         public int hashCode() {
1742             return Objects.hash(Arrays.hashCode(supportedDisplayModes), activeDisplayModeId,
1743                     renderFrameRate, activeColorMode, hdrCapabilities);
1744         }
1745     }
1746 
1747     /**
1748      * Configuration supported by physical display.
1749      *
1750      * @hide
1751      */
1752     public static final class DisplayMode {
1753         public int id;
1754         public int width;
1755         public int height;
1756         public float xDpi;
1757         public float yDpi;
1758 
1759         public float refreshRate;
1760         public long appVsyncOffsetNanos;
1761         public long presentationDeadlineNanos;
1762         public int[] supportedHdrTypes;
1763 
1764         /**
1765          * The config group ID this config is associated to.
1766          * Configs in the same group are similar from vendor's perspective and switching between
1767          * configs within the same group can be done seamlessly in most cases.
1768          * @see: android.hardware.graphics.composer@2.4::IComposerClient::Attribute::CONFIG_GROUP
1769          */
1770         public int group;
1771 
1772         @Override
toString()1773         public String toString() {
1774             return "DisplayMode{id=" + id
1775                     + ", width=" + width
1776                     + ", height=" + height
1777                     + ", xDpi=" + xDpi
1778                     + ", yDpi=" + yDpi
1779                     + ", refreshRate=" + refreshRate
1780                     + ", appVsyncOffsetNanos=" + appVsyncOffsetNanos
1781                     + ", presentationDeadlineNanos=" + presentationDeadlineNanos
1782                     + ", supportedHdrTypes=" + Arrays.toString(supportedHdrTypes)
1783                     + ", group=" + group + "}";
1784         }
1785 
1786         @Override
equals(Object o)1787         public boolean equals(Object o) {
1788             if (this == o) return true;
1789             if (o == null || getClass() != o.getClass()) return false;
1790             DisplayMode that = (DisplayMode) o;
1791             return id == that.id
1792                     && width == that.width
1793                     && height == that.height
1794                     && Float.compare(that.xDpi, xDpi) == 0
1795                     && Float.compare(that.yDpi, yDpi) == 0
1796                     && Float.compare(that.refreshRate, refreshRate) == 0
1797                     && appVsyncOffsetNanos == that.appVsyncOffsetNanos
1798                     && presentationDeadlineNanos == that.presentationDeadlineNanos
1799                     && Arrays.equals(supportedHdrTypes, that.supportedHdrTypes)
1800                     && group == that.group;
1801         }
1802 
1803         @Override
hashCode()1804         public int hashCode() {
1805             return Objects.hash(id, width, height, xDpi, yDpi, refreshRate, appVsyncOffsetNanos,
1806                     presentationDeadlineNanos, group, Arrays.hashCode(supportedHdrTypes));
1807         }
1808     }
1809 
1810     /**
1811      * @hide
1812      */
setDisplayPowerMode(IBinder displayToken, int mode)1813     public static void setDisplayPowerMode(IBinder displayToken, int mode) {
1814         if (displayToken == null) {
1815             throw new IllegalArgumentException("displayToken must not be null");
1816         }
1817         nativeSetDisplayPowerMode(displayToken, mode);
1818     }
1819 
1820     /**
1821      * @hide
1822      */
getStaticDisplayInfo(long displayId)1823     public static StaticDisplayInfo getStaticDisplayInfo(long displayId) {
1824         return nativeGetStaticDisplayInfo(displayId);
1825     }
1826 
1827     /**
1828      * @hide
1829      */
getDynamicDisplayInfo(long displayId)1830     public static DynamicDisplayInfo getDynamicDisplayInfo(long displayId) {
1831         return nativeGetDynamicDisplayInfo(displayId);
1832     }
1833 
1834     /**
1835      * @hide
1836      */
getDisplayedContentSamplingAttributes( IBinder displayToken)1837     public static DisplayedContentSamplingAttributes getDisplayedContentSamplingAttributes(
1838             IBinder displayToken) {
1839         if (displayToken == null) {
1840             throw new IllegalArgumentException("displayToken must not be null");
1841         }
1842         return nativeGetDisplayedContentSamplingAttributes(displayToken);
1843     }
1844 
1845     /**
1846      * @hide
1847      */
setDisplayedContentSamplingEnabled( IBinder displayToken, boolean enable, int componentMask, int maxFrames)1848     public static boolean setDisplayedContentSamplingEnabled(
1849             IBinder displayToken, boolean enable, int componentMask, int maxFrames) {
1850         if (displayToken == null) {
1851             throw new IllegalArgumentException("displayToken must not be null");
1852         }
1853         final int maxColorComponents = 4;
1854         if ((componentMask >> maxColorComponents) != 0) {
1855             throw new IllegalArgumentException("invalid componentMask when enabling sampling");
1856         }
1857         return nativeSetDisplayedContentSamplingEnabled(
1858                 displayToken, enable, componentMask, maxFrames);
1859     }
1860 
1861     /**
1862      * @hide
1863      */
getDisplayedContentSample( IBinder displayToken, long maxFrames, long timestamp)1864     public static DisplayedContentSample getDisplayedContentSample(
1865             IBinder displayToken, long maxFrames, long timestamp) {
1866         if (displayToken == null) {
1867             throw new IllegalArgumentException("displayToken must not be null");
1868         }
1869         return nativeGetDisplayedContentSample(displayToken, maxFrames, timestamp);
1870     }
1871 
1872     /**
1873      * Information about the min and max refresh rate DM would like to set the display to.
1874      * @hide
1875      */
1876     public static final class RefreshRateRange implements Parcelable {
1877         public static final String TAG = "RefreshRateRange";
1878 
1879         // The tolerance within which we consider something approximately equals.
1880         public static final float FLOAT_TOLERANCE = 0.01f;
1881 
1882         /**
1883          * The lowest desired refresh rate.
1884          */
1885         public float min;
1886 
1887         /**
1888          * The highest desired refresh rate.
1889          */
1890         public float max;
1891 
RefreshRateRange()1892         public RefreshRateRange() {}
1893 
RefreshRateRange(float min, float max)1894         public RefreshRateRange(float min, float max) {
1895             if (min < 0 || max < 0 || min > max + FLOAT_TOLERANCE) {
1896                 Slog.e(TAG, "Wrong values for min and max when initializing RefreshRateRange : "
1897                         + min + " " + max);
1898                 this.min = this.max = 0;
1899                 return;
1900             }
1901             if (min > max) {
1902                 // Min and max are within epsilon of each other, but in the wrong order.
1903                 float t = min;
1904                 min = max;
1905                 max = t;
1906             }
1907             this.min = min;
1908             this.max = max;
1909         }
1910 
1911         /**
1912          * Checks whether the two objects have the same values.
1913          */
1914         @Override
equals(Object other)1915         public boolean equals(Object other) {
1916             if (other == this) {
1917                 return true;
1918             }
1919 
1920             if (!(other instanceof RefreshRateRange)) {
1921                 return false;
1922             }
1923 
1924             RefreshRateRange refreshRateRange = (RefreshRateRange) other;
1925             return (min == refreshRateRange.min && max == refreshRateRange.max);
1926         }
1927 
1928         @Override
hashCode()1929         public int hashCode() {
1930             return Objects.hash(min, max);
1931         }
1932 
1933         @Override
toString()1934         public String toString() {
1935             return "(" + min + " " + max + ")";
1936         }
1937 
1938         /**
1939          * Copies the supplied object's values to this object.
1940          */
copyFrom(RefreshRateRange other)1941         public void copyFrom(RefreshRateRange other) {
1942             this.min = other.min;
1943             this.max = other.max;
1944         }
1945 
1946         /**
1947          * Writes the RefreshRateRange to parce
1948          *
1949          * @param dest parcel to write the transaction to
1950          */
1951         @Override
writeToParcel(@onNull Parcel dest, @WriteFlags int flags)1952         public void writeToParcel(@NonNull Parcel dest, @WriteFlags int flags) {
1953             dest.writeFloat(min);
1954             dest.writeFloat(max);
1955         }
1956 
1957         @Override
describeContents()1958         public int describeContents() {
1959             return 0;
1960         }
1961 
1962         public static final @NonNull Creator<RefreshRateRange> CREATOR =
1963                 new Creator<RefreshRateRange>() {
1964                     @Override
1965                     public RefreshRateRange createFromParcel(Parcel in) {
1966                         return new RefreshRateRange(in.readFloat(), in.readFloat());
1967                     }
1968 
1969                     @Override
1970                     public RefreshRateRange[] newArray(int size) {
1971                         return new RefreshRateRange[size];
1972                     }
1973                 };
1974     }
1975 
1976     /**
1977      * Information about the ranges of refresh rates for the display physical refresh rates and the
1978      * render frame rate DM would like to set the policy to.
1979      * @hide
1980      */
1981     public static final class RefreshRateRanges {
1982         public static final String TAG = "RefreshRateRanges";
1983 
1984         /**
1985          *  The range of refresh rates that the display should run at.
1986          */
1987         public final RefreshRateRange physical;
1988 
1989         /**
1990          *  The range of refresh rates that apps should render at.
1991          */
1992         public final RefreshRateRange render;
1993 
RefreshRateRanges()1994         public RefreshRateRanges() {
1995             physical = new RefreshRateRange();
1996             render = new RefreshRateRange();
1997         }
1998 
RefreshRateRanges(RefreshRateRange physical, RefreshRateRange render)1999         public RefreshRateRanges(RefreshRateRange physical, RefreshRateRange render) {
2000             this.physical = new RefreshRateRange(physical.min, physical.max);
2001             this.render = new RefreshRateRange(render.min, render.max);
2002         }
2003 
2004         /**
2005          * Checks whether the two objects have the same values.
2006          */
2007         @Override
equals(Object other)2008         public boolean equals(Object other) {
2009             if (other == this) {
2010                 return true;
2011             }
2012 
2013             if (!(other instanceof RefreshRateRanges)) {
2014                 return false;
2015             }
2016 
2017             RefreshRateRanges rates = (RefreshRateRanges) other;
2018             return physical.equals(rates.physical) && render.equals(
2019                     rates.render);
2020         }
2021 
2022         @Override
hashCode()2023         public int hashCode() {
2024             return Objects.hash(physical, render);
2025         }
2026 
2027         @Override
toString()2028         public String toString() {
2029             return "physical: " + physical + " render:  " + render;
2030         }
2031 
2032         /**
2033          * Copies the supplied object's values to this object.
2034          */
copyFrom(RefreshRateRanges other)2035         public void copyFrom(RefreshRateRanges other) {
2036             this.physical.copyFrom(other.physical);
2037             this.render.copyFrom(other.render);
2038         }
2039     }
2040 
2041 
2042     /**
2043      * Contains information about desired display configuration.
2044      *
2045      * @hide
2046      */
2047     public static final class DesiredDisplayModeSpecs {
2048         public int defaultMode;
2049         /**
2050          * If true this will allow switching between modes in different display configuration
2051          * groups. This way the user may see visual interruptions when the display mode changes.
2052          */
2053         public boolean allowGroupSwitching;
2054 
2055         /**
2056          * The primary physical and render refresh rate ranges represent display manager's general
2057          * guidance on the display configs surface flinger will consider when switching refresh
2058          * rates and scheduling the frame rate. Unless surface flinger has a specific reason to do
2059          * otherwise, it will stay within this range.
2060          */
2061         public final RefreshRateRanges primaryRanges;
2062 
2063         /**
2064          * The app request physical and render refresh rate ranges allow surface flinger to consider
2065          * more display configs when switching refresh rates. Although surface flinger will
2066          * generally stay within the primary range, specific considerations, such as layer frame
2067          * rate settings specified via the setFrameRate() api, may cause surface flinger to go
2068          * outside the primary range. Surface flinger never goes outside the app request range.
2069          * The app request range will be greater than or equal to the primary refresh rate range,
2070          * never smaller.
2071          */
2072         public final RefreshRateRanges appRequestRanges;
2073 
DesiredDisplayModeSpecs()2074         public DesiredDisplayModeSpecs() {
2075             this.primaryRanges = new RefreshRateRanges();
2076             this.appRequestRanges = new RefreshRateRanges();
2077         }
2078 
DesiredDisplayModeSpecs(DesiredDisplayModeSpecs other)2079         public DesiredDisplayModeSpecs(DesiredDisplayModeSpecs other) {
2080             this.primaryRanges = new RefreshRateRanges();
2081             this.appRequestRanges = new RefreshRateRanges();
2082             copyFrom(other);
2083         }
2084 
DesiredDisplayModeSpecs(int defaultMode, boolean allowGroupSwitching, RefreshRateRanges primaryRanges, RefreshRateRanges appRequestRanges)2085         public DesiredDisplayModeSpecs(int defaultMode, boolean allowGroupSwitching,
2086                 RefreshRateRanges primaryRanges, RefreshRateRanges appRequestRanges) {
2087             this.defaultMode = defaultMode;
2088             this.allowGroupSwitching = allowGroupSwitching;
2089             this.primaryRanges =
2090                     new RefreshRateRanges(primaryRanges.physical, primaryRanges.render);
2091             this.appRequestRanges =
2092                     new RefreshRateRanges(appRequestRanges.physical, appRequestRanges.render);
2093         }
2094 
2095         @Override
equals(@ullable Object o)2096         public boolean equals(@Nullable Object o) {
2097             return o instanceof DesiredDisplayModeSpecs && equals((DesiredDisplayModeSpecs) o);
2098         }
2099 
2100         /**
2101          * Tests for equality.
2102          */
equals(DesiredDisplayModeSpecs other)2103         public boolean equals(DesiredDisplayModeSpecs other) {
2104             return other != null && defaultMode == other.defaultMode
2105                     && allowGroupSwitching == other.allowGroupSwitching
2106                     && primaryRanges.equals(other.primaryRanges)
2107                     && appRequestRanges.equals(other.appRequestRanges);
2108         }
2109 
2110         @Override
hashCode()2111         public int hashCode() {
2112             return 0; // don't care
2113         }
2114 
2115         /**
2116          * Copies the supplied object's values to this object.
2117          */
copyFrom(DesiredDisplayModeSpecs other)2118         public void copyFrom(DesiredDisplayModeSpecs other) {
2119             defaultMode = other.defaultMode;
2120             allowGroupSwitching = other.allowGroupSwitching;
2121             primaryRanges.copyFrom(other.primaryRanges);
2122             appRequestRanges.copyFrom(other.appRequestRanges);
2123         }
2124 
2125         @Override
toString()2126         public String toString() {
2127             return "defaultMode=" + defaultMode
2128                     + " allowGroupSwitching=" + allowGroupSwitching
2129                     + " primaryRanges=" + primaryRanges
2130                     + " appRequestRanges=" + appRequestRanges;
2131         }
2132     }
2133 
2134     /**
2135      * @hide
2136      */
setDesiredDisplayModeSpecs(IBinder displayToken, DesiredDisplayModeSpecs desiredDisplayModeSpecs)2137     public static boolean setDesiredDisplayModeSpecs(IBinder displayToken,
2138             DesiredDisplayModeSpecs desiredDisplayModeSpecs) {
2139         if (displayToken == null) {
2140             throw new IllegalArgumentException("displayToken must not be null");
2141         }
2142         if (desiredDisplayModeSpecs == null) {
2143             throw new IllegalArgumentException("desiredDisplayModeSpecs must not be null");
2144         }
2145         if (desiredDisplayModeSpecs.defaultMode < 0) {
2146             throw new IllegalArgumentException("defaultMode must be non-negative");
2147         }
2148 
2149         return nativeSetDesiredDisplayModeSpecs(displayToken, desiredDisplayModeSpecs);
2150     }
2151 
2152     /**
2153      * @hide
2154      */
getDesiredDisplayModeSpecs( IBinder displayToken)2155     public static DesiredDisplayModeSpecs getDesiredDisplayModeSpecs(
2156             IBinder displayToken) {
2157         if (displayToken == null) {
2158             throw new IllegalArgumentException("displayToken must not be null");
2159         }
2160 
2161         return nativeGetDesiredDisplayModeSpecs(displayToken);
2162     }
2163 
2164     /**
2165      * Color coordinates in CIE1931 XYZ color space
2166      *
2167      * @hide
2168      */
2169     public static final class CieXyz {
2170         /**
2171          * @hide
2172          */
2173         public float X;
2174 
2175         /**
2176          * @hide
2177          */
2178         public float Y;
2179 
2180         /**
2181          * @hide
2182          */
2183         public float Z;
2184     }
2185 
2186     /**
2187      * Contains a display's color primaries
2188      *
2189      * @hide
2190      */
2191     public static final class DisplayPrimaries {
2192         /**
2193          * @hide
2194          */
2195         public CieXyz red;
2196 
2197         /**
2198          * @hide
2199          */
2200         public CieXyz green;
2201 
2202         /**
2203          * @hide
2204          */
2205         public CieXyz blue;
2206 
2207         /**
2208          * @hide
2209          */
2210         public CieXyz white;
2211 
2212         /**
2213          * @hide
2214          */
DisplayPrimaries()2215         public DisplayPrimaries() {
2216         }
2217     }
2218 
2219     /**
2220      * @hide
2221      */
getDisplayNativePrimaries( IBinder displayToken)2222     public static DisplayPrimaries getDisplayNativePrimaries(
2223             IBinder displayToken) {
2224         if (displayToken == null) {
2225             throw new IllegalArgumentException("displayToken must not be null");
2226         }
2227 
2228         return nativeGetDisplayNativePrimaries(displayToken);
2229     }
2230 
2231     /**
2232      * @hide
2233      */
setActiveColorMode(IBinder displayToken, int colorMode)2234     public static boolean setActiveColorMode(IBinder displayToken, int colorMode) {
2235         if (displayToken == null) {
2236             throw new IllegalArgumentException("displayToken must not be null");
2237         }
2238         return nativeSetActiveColorMode(displayToken, colorMode);
2239     }
2240 
2241     /**
2242      * Returns an array of color spaces with 2 elements. The first color space is the
2243      * default color space and second one is wide color gamut color space.
2244      * @hide
2245      */
getCompositionColorSpaces()2246     public static ColorSpace[] getCompositionColorSpaces() {
2247         int[] dataspaces = nativeGetCompositionDataspaces();
2248         ColorSpace srgb = ColorSpace.get(ColorSpace.Named.SRGB);
2249         ColorSpace[] colorSpaces = { srgb, srgb };
2250         if (dataspaces.length == 2) {
2251             for (int i = 0; i < 2; ++i) {
2252                 ColorSpace cs = ColorSpace.getFromDataSpace(dataspaces[i]);
2253                 if (cs != null) {
2254                     colorSpaces[i] = cs;
2255                 }
2256             }
2257         }
2258         return colorSpaces;
2259     }
2260 
2261     /**
2262      * @return the overlay properties of the device
2263      * @hide
2264      */
getOverlaySupport()2265     public static OverlayProperties getOverlaySupport() {
2266         return nativeGetOverlaySupport();
2267     }
2268 
2269     /**
2270      * @hide
2271      */
getBootDisplayModeSupport()2272     public static boolean getBootDisplayModeSupport() {
2273         return nativeGetBootDisplayModeSupport();
2274     }
2275 
2276     /** There is no associated getter for this method.  When this is set, the display is expected
2277      * to start up in this mode next time the device reboots.
2278      * @hide
2279      */
setBootDisplayMode(IBinder displayToken, int displayModeId)2280     public static void setBootDisplayMode(IBinder displayToken, int displayModeId) {
2281         if (displayToken == null) {
2282             throw new IllegalArgumentException("displayToken must not be null");
2283         }
2284 
2285         nativeSetBootDisplayMode(displayToken, displayModeId);
2286     }
2287 
2288     /**
2289      * @hide
2290      */
clearBootDisplayMode(IBinder displayToken)2291     public static void clearBootDisplayMode(IBinder displayToken) {
2292         if (displayToken == null) {
2293             throw new IllegalArgumentException("displayToken must not be null");
2294         }
2295 
2296         nativeClearBootDisplayMode(displayToken);
2297     }
2298 
2299     /**
2300      * @hide
2301      */
setAutoLowLatencyMode(IBinder displayToken, boolean on)2302     public static void setAutoLowLatencyMode(IBinder displayToken, boolean on) {
2303         if (displayToken == null) {
2304             throw new IllegalArgumentException("displayToken must not be null");
2305         }
2306 
2307         nativeSetAutoLowLatencyMode(displayToken, on);
2308     }
2309 
2310     /**
2311      * @hide
2312      */
setGameContentType(IBinder displayToken, boolean on)2313     public static void setGameContentType(IBinder displayToken, boolean on) {
2314         if (displayToken == null) {
2315             throw new IllegalArgumentException("displayToken must not be null");
2316         }
2317 
2318         nativeSetGameContentType(displayToken, on);
2319     }
2320 
2321     /**
2322      * Because this API is now going through {@link DisplayManager}, orientation and displayRect
2323      * will automatically be computed based on configuration changes. Because of this, the params
2324      * orientation and displayRect are ignored
2325      *
2326      * @hide
2327      */
2328     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.TIRAMISU,
2329             publicAlternatives = "Use {@code VirtualDisplay#resize(int, int, int)} instead.",
2330             trackingBug = 247078497)
setDisplayProjection(IBinder displayToken, int orientation, Rect layerStackRect, Rect displayRect)2331     public static void setDisplayProjection(IBinder displayToken, int orientation,
2332             Rect layerStackRect, Rect displayRect) {
2333         DisplayManagerGlobal.getInstance().resizeVirtualDisplay(
2334                 IVirtualDisplayCallback.Stub.asInterface(displayToken), layerStackRect.width(),
2335                 layerStackRect.height(), 1);
2336     }
2337 
2338     /**
2339      * @hide
2340      */
2341     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.TIRAMISU,
2342             publicAlternatives = "Use {@code MediaProjection#createVirtualDisplay()} with flag "
2343                     + " {@code VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR} for mirroring instead.",
2344             trackingBug = 247078497)
setDisplayLayerStack(IBinder displayToken, int layerStack)2345     public static void setDisplayLayerStack(IBinder displayToken, int layerStack) {
2346         IBinder b = ServiceManager.getService(Context.DISPLAY_SERVICE);
2347         if (b == null) {
2348             throw new UnsupportedOperationException();
2349         }
2350 
2351         IDisplayManager dm = IDisplayManager.Stub.asInterface(b);
2352         try {
2353             dm.setDisplayIdToMirror(displayToken, layerStack);
2354         } catch (RemoteException e) {
2355             throw new UnsupportedOperationException(e);
2356         }
2357     }
2358 
2359     /**
2360      * @hide
2361      */
2362     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.TIRAMISU,
2363             publicAlternatives = "Use {@code VirtualDisplay#setSurface(Surface)} instead.",
2364             trackingBug = 247078497)
setDisplaySurface(IBinder displayToken, Surface surface)2365     public static void setDisplaySurface(IBinder displayToken, Surface surface) {
2366         IVirtualDisplayCallback virtualDisplayCallback =
2367                 IVirtualDisplayCallback.Stub.asInterface(displayToken);
2368         DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance();
2369         dm.setVirtualDisplaySurface(virtualDisplayCallback, surface);
2370     }
2371 
2372     /**
2373      * Secure is no longer supported because this is only called from outside system which cannot
2374      * create secure displays.
2375      * @hide
2376      */
2377     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.TIRAMISU,
2378             publicAlternatives = "Use {@code MediaProjection#createVirtualDisplay()} or "
2379                     + "{@code DisplayManager#createVirtualDisplay()} instead.",
2380             trackingBug = 247078497)
createDisplay(String name, boolean secure)2381     public static IBinder createDisplay(String name, boolean secure) {
2382         if (name == null) {
2383             throw new IllegalArgumentException("name must not be null");
2384         }
2385 
2386         // We don't have a size yet so pass in 1 for width and height since 0 is invalid
2387         VirtualDisplay vd = DisplayManager.createVirtualDisplay(name, 1 /* width */, 1 /* height */,
2388                 INVALID_DISPLAY, null /* Surface */);
2389         return vd == null ? null : vd.getToken().asBinder();
2390     }
2391 
2392     /**
2393      * @hide
2394      */
2395     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.TIRAMISU,
2396             publicAlternatives = "Use {@code VirtualDisplay#release()} instead.",
2397             trackingBug = 247078497)
destroyDisplay(IBinder displayToken)2398     public static void destroyDisplay(IBinder displayToken) {
2399         if (displayToken == null) {
2400             throw new IllegalArgumentException("displayToken must not be null");
2401         }
2402 
2403         DisplayManagerGlobal.getInstance().releaseVirtualDisplay(
2404                 IVirtualDisplayCallback.Stub.asInterface(displayToken));
2405     }
2406 
2407     /**
2408      * Returns whether protected content is supported in GPU composition.
2409      * @hide
2410      */
getProtectedContentSupport()2411     public static boolean getProtectedContentSupport() {
2412         return nativeGetProtectedContentSupport();
2413     }
2414 
2415     /**
2416      * Returns whether brightness operations are supported on a display.
2417      *
2418      * @param displayToken
2419      *      The token for the display.
2420      *
2421      * @return Whether brightness operations are supported on the display.
2422      *
2423      * @hide
2424      */
getDisplayBrightnessSupport(IBinder displayToken)2425     public static boolean getDisplayBrightnessSupport(IBinder displayToken) {
2426         return nativeGetDisplayBrightnessSupport(displayToken);
2427     }
2428 
2429     /**
2430      * Sets the brightness of a display.
2431      *
2432      * @param displayToken
2433      *      The token for the display whose brightness is set.
2434      * @param brightness
2435      *      A number between 0.0f (minimum brightness) and 1.0f (maximum brightness), or -1.0f to
2436      *      turn the backlight off.
2437      *
2438      * @return Whether the method succeeded or not.
2439      *
2440      * @throws IllegalArgumentException if:
2441      *      - displayToken is null;
2442      *      - brightness is NaN or greater than 1.0f.
2443      *
2444      * @hide
2445      */
setDisplayBrightness(IBinder displayToken, float brightness)2446     public static boolean setDisplayBrightness(IBinder displayToken, float brightness) {
2447         return setDisplayBrightness(displayToken, brightness, -1, brightness, -1);
2448     }
2449 
2450     /**
2451      * Sets the brightness of a display.
2452      *
2453      * @param displayToken
2454      *      The token for the display whose brightness is set.
2455      * @param sdrBrightness
2456      *      A number between 0.0f (minimum brightness) and 1.0f (maximum brightness), or -1.0f to
2457      *      turn the backlight off. Specifies the desired brightness of SDR content.
2458      * @param sdrBrightnessNits
2459      *      The value of sdrBrightness converted to calibrated nits. -1 if this isn't available.
2460      * @param displayBrightness
2461      *     A number between 0.0f (minimum brightness) and 1.0f (maximum brightness), or
2462      *     -1.0f to turn the backlight off. Specifies the desired brightness of the display itself,
2463      *     used directly for HDR content.
2464      * @param displayBrightnessNits
2465      *      The value of displayBrightness converted to calibrated nits. -1 if this isn't
2466      *      available.
2467      *
2468      * @return Whether the method succeeded or not.
2469      *
2470      * @throws IllegalArgumentException if:
2471      *      - displayToken is null;
2472      *      - brightness is NaN or greater than 1.0f.
2473      *
2474      * @hide
2475      */
setDisplayBrightness(IBinder displayToken, float sdrBrightness, float sdrBrightnessNits, float displayBrightness, float displayBrightnessNits)2476     public static boolean setDisplayBrightness(IBinder displayToken, float sdrBrightness,
2477             float sdrBrightnessNits, float displayBrightness, float displayBrightnessNits) {
2478         Objects.requireNonNull(displayToken);
2479         if (Float.isNaN(displayBrightness) || displayBrightness > 1.0f
2480                 || (displayBrightness < 0.0f && displayBrightness != -1.0f)) {
2481             throw new IllegalArgumentException("displayBrightness must be a number between 0.0f "
2482                     + " and 1.0f, or -1 to turn the backlight off: " + displayBrightness);
2483         }
2484         if (Float.isNaN(sdrBrightness) || sdrBrightness > 1.0f
2485                 || (sdrBrightness < 0.0f && sdrBrightness != -1.0f)) {
2486             throw new IllegalArgumentException("sdrBrightness must be a number between 0.0f "
2487                     + "and 1.0f, or -1 to turn the backlight off: " + sdrBrightness);
2488         }
2489         return nativeSetDisplayBrightness(displayToken, sdrBrightness, sdrBrightnessNits,
2490                 displayBrightness, displayBrightnessNits);
2491     }
2492 
2493     /**
2494      * Creates a mirrored hierarchy for the mirrorOf {@link SurfaceControl}
2495      *
2496      * Real Hierarchy    Mirror
2497      *                     SC (value that's returned)
2498      *                      |
2499      *      A               A'
2500      *      |               |
2501      *      B               B'
2502      *
2503      * @param mirrorOf The root of the hierarchy that should be mirrored.
2504      * @return A SurfaceControl that's the parent of the root of the mirrored hierarchy.
2505      *
2506      * @hide
2507      */
mirrorSurface(SurfaceControl mirrorOf)2508     public static SurfaceControl mirrorSurface(SurfaceControl mirrorOf) {
2509         long nativeObj = nativeMirrorSurface(mirrorOf.mNativeObject);
2510         SurfaceControl sc = new SurfaceControl();
2511         sc.mName = mirrorOf.mName + " (mirror)";
2512         sc.assignNativeObject(nativeObj, "mirrorSurface");
2513         return sc;
2514     }
2515 
validateColorArg(@ize4) float[] color)2516     private static void validateColorArg(@Size(4) float[] color) {
2517         final String msg = "Color must be specified as a float array with"
2518                 + " four values to represent r, g, b, a in range [0..1]";
2519         if (color.length != 4) {
2520             throw new IllegalArgumentException(msg);
2521         }
2522         for (float c:color) {
2523             if ((c < 0.f) || (c > 1.f)) {
2524                 throw new IllegalArgumentException(msg);
2525             }
2526         }
2527     }
2528 
2529     /**
2530      * Sets the global configuration for all the shadows drawn by SurfaceFlinger. Shadow follows
2531      * material design guidelines.
2532      *
2533      * @param ambientColor Color applied to the ambient shadow. The alpha is premultiplied. A
2534      *                     float array with four values to represent r, g, b, a in range [0..1]
2535      * @param spotColor Color applied to the spot shadow. The alpha is premultiplied. The position
2536      *                  of the spot shadow depends on the light position. A float array with
2537      *                  four values to represent r, g, b, a in range [0..1]
2538      * @param lightPosY Y axis position of the light used to cast the spot shadow in pixels.
2539      * @param lightPosZ Z axis position of the light used to cast the spot shadow in pixels. The X
2540      *                  axis position is set to the display width / 2.
2541      * @param lightRadius Radius of the light casting the shadow in pixels.
2542      *[
2543      * @hide
2544      */
setGlobalShadowSettings(@ize4) float[] ambientColor, @Size(4) float[] spotColor, float lightPosY, float lightPosZ, float lightRadius)2545     public static void setGlobalShadowSettings(@Size(4) float[] ambientColor,
2546             @Size(4) float[] spotColor, float lightPosY, float lightPosZ, float lightRadius) {
2547         validateColorArg(ambientColor);
2548         validateColorArg(spotColor);
2549         nativeSetGlobalShadowSettings(ambientColor, spotColor, lightPosY, lightPosZ, lightRadius);
2550     }
2551 
2552     /**
2553      * Returns whether/how a display supports DISPLAY_DECORATION.
2554      *
2555      * @param displayToken
2556      *      The token for the display.
2557      *
2558      * @return A class describing how the display supports DISPLAY_DECORATION or null if it does
2559      * not.
2560      *
2561      * TODO (b/218524164): Move this out of SurfaceControl.
2562      * @hide
2563      */
getDisplayDecorationSupport(IBinder displayToken)2564     public static DisplayDecorationSupport getDisplayDecorationSupport(IBinder displayToken) {
2565         return nativeGetDisplayDecorationSupport(displayToken);
2566     }
2567 
2568     /**
2569      * Adds a callback to be informed about SF's jank classification for a specific surface.
2570      * @hide
2571      */
addJankDataListener(OnJankDataListener listener, SurfaceControl surface)2572     public static void addJankDataListener(OnJankDataListener listener, SurfaceControl surface) {
2573         nativeAddJankDataListener(listener.mNativePtr.get(), surface.mNativeObject);
2574     }
2575 
2576     /**
2577      * Removes a jank callback previously added with {@link #addJankDataListener}
2578      * @hide
2579      */
removeJankDataListener(OnJankDataListener listener)2580     public static void removeJankDataListener(OnJankDataListener listener) {
2581         nativeRemoveJankDataListener(listener.mNativePtr.get());
2582     }
2583 
2584     /**
2585      * Return GPU Context priority that is set in SurfaceFlinger's Render Engine.
2586      * @hide
2587      */
getGPUContextPriority()2588     public static int getGPUContextPriority() {
2589         return nativeGetGPUContextPriority();
2590     }
2591 
2592     /**
2593      * Lets surfaceFlinger know the boot procedure is completed.
2594      * @hide
2595      */
bootFinished()2596     public static boolean bootFinished() {
2597         return nativeBootFinished();
2598     }
2599 
2600     /**
2601      * Interface to handle request to
2602      * {@link SurfaceControl.Transaction#addTransactionCommittedListener(Executor, TransactionCommittedListener)}
2603      */
2604     public interface TransactionCommittedListener {
2605         /**
2606          * Invoked when the transaction has been committed in SurfaceFlinger.
2607          */
onTransactionCommitted()2608         void onTransactionCommitted();
2609     }
2610 
2611     /**
2612      * Threshold values that are sent with
2613      * {@link Transaction#setTrustedPresentationCallback(SurfaceControl,
2614      * TrustedPresentationThresholds, Executor, Consumer)}
2615      */
2616     public static final class TrustedPresentationThresholds {
2617         private final float mMinAlpha;
2618         private final float mMinFractionRendered;
2619         private final int mStabilityRequirementMs;
2620 
2621         /**
2622          * Creates a TrustedPresentationThresholds that's used when calling
2623          * {@link Transaction#setTrustedPresentationCallback(SurfaceControl,
2624          * TrustedPresentationThresholds, Executor, Consumer)}
2625          *
2626          * @param minAlpha               The min alpha the {@link SurfaceControl} is required to
2627          *                               have to be considered inside the threshold.
2628          * @param minFractionRendered    The min fraction of the SurfaceControl that was resented
2629          *                               to the user to be considered inside the threshold.
2630          * @param stabilityRequirementMs The time in milliseconds required for the
2631          *                               {@link SurfaceControl} to be in the threshold.
2632          * @throws IllegalArgumentException If threshold values are invalid.
2633          */
TrustedPresentationThresholds( @loatRangefrom = 0f, fromInclusive = false, to = 1f) float minAlpha, @FloatRange(from = 0f, fromInclusive = false, to = 1f) float minFractionRendered, @IntRange(from = 1) int stabilityRequirementMs)2634         public TrustedPresentationThresholds(
2635                 @FloatRange(from = 0f, fromInclusive = false, to = 1f) float minAlpha,
2636                 @FloatRange(from = 0f, fromInclusive = false, to = 1f) float minFractionRendered,
2637                 @IntRange(from = 1) int stabilityRequirementMs) {
2638             mMinAlpha = minAlpha;
2639             mMinFractionRendered = minFractionRendered;
2640             mStabilityRequirementMs = stabilityRequirementMs;
2641 
2642             checkValid();
2643         }
2644 
checkValid()2645         private void checkValid() {
2646             if (mMinAlpha <= 0 || mMinFractionRendered <= 0 || mStabilityRequirementMs < 1) {
2647                 throw new IllegalArgumentException(
2648                         "TrustedPresentationThresholds values are invalid");
2649             }
2650         }
2651     }
2652 
2653     /**
2654      * Register a TrustedPresentationCallback for a particular SurfaceControl so it can be notified
2655      * when the specified Threshold has been crossed.
2656      *
2657      * @hide
2658      */
2659     public abstract static class TrustedPresentationCallback {
2660         private final long mNativeObject;
2661 
2662         private static final NativeAllocationRegistry sRegistry =
2663                 NativeAllocationRegistry.createMalloced(
2664                         TrustedPresentationCallback.class.getClassLoader(),
2665                         getNativeTrustedPresentationCallbackFinalizer());
2666 
2667         private final Runnable mFreeNativeResources;
2668 
TrustedPresentationCallback()2669         private TrustedPresentationCallback() {
2670             mNativeObject = nativeCreateTpc(this);
2671             mFreeNativeResources = sRegistry.registerNativeAllocation(this, mNativeObject);
2672         }
2673 
2674         /**
2675          * Invoked when the SurfaceControl that this TrustedPresentationCallback was registered for
2676          * enters or exits the threshold bounds.
2677          *
2678          * @param inTrustedPresentationState true when the SurfaceControl entered the
2679          *                                   presentation state, false when it has left.
2680          */
onTrustedPresentationChanged(boolean inTrustedPresentationState)2681         public abstract void onTrustedPresentationChanged(boolean inTrustedPresentationState);
2682     }
2683 
2684     /**
2685      * An atomic set of changes to a set of SurfaceControl.
2686      */
2687     public static class Transaction implements Closeable, Parcelable {
2688         /**
2689          * @hide
2690          */
2691         public static final NativeAllocationRegistry sRegistry = new NativeAllocationRegistry(
2692                 Transaction.class.getClassLoader(),
2693                 nativeGetNativeTransactionFinalizer(), 512);
2694         /**
2695          * @hide
2696          */
2697         public long mNativeObject;
2698 
2699         private final ArrayMap<SurfaceControl, Point> mResizedSurfaces = new ArrayMap<>();
2700         private final ArrayMap<SurfaceControl, SurfaceControl> mReparentedSurfaces =
2701                  new ArrayMap<>();
2702 
2703         Runnable mFreeNativeResources;
2704         private static final float[] INVALID_COLOR = {-1, -1, -1};
2705 
2706         /**
2707          * @hide
2708          */
checkPreconditions(SurfaceControl sc)2709         protected void checkPreconditions(SurfaceControl sc) {
2710             sc.checkNotReleased();
2711         }
2712 
2713         /**
2714          * Open a new transaction object. The transaction may be filed with commands to
2715          * manipulate {@link SurfaceControl} instances, and then applied atomically with
2716          * {@link #apply}. Eventually the user should invoke {@link #close}, when the object
2717          * is no longer required. Note however that re-using a transaction after a call to apply
2718          * is allowed as a convenience.
2719          */
Transaction()2720         public Transaction() {
2721             this(nativeCreateTransaction());
2722         }
2723 
Transaction(long nativeObject)2724         private Transaction(long nativeObject) {
2725             mNativeObject = nativeObject;
2726             mFreeNativeResources =
2727                     sRegistry.registerNativeAllocation(this, mNativeObject);
2728         }
2729 
Transaction(Parcel in)2730         private Transaction(Parcel in) {
2731             readFromParcel(in);
2732         }
2733 
2734         /**
2735          *
2736          * @hide
2737          */
setDefaultApplyToken(IBinder token)2738         public static void setDefaultApplyToken(IBinder token) {
2739             nativeSetDefaultApplyToken(token);
2740         }
2741 
2742         /**
2743          *
2744          * @hide
2745          */
getDefaultApplyToken()2746         public static IBinder getDefaultApplyToken() {
2747             return nativeGetDefaultApplyToken();
2748         }
2749 
2750         /**
2751          * Apply the transaction, clearing it's state, and making it usable
2752          * as a new transaction.
2753          */
apply()2754         public void apply() {
2755             apply(false);
2756         }
2757 
2758         /**
2759          * Clear the transaction object, without applying it.
2760          *
2761          * @hide
2762          */
clear()2763         public void clear() {
2764             mResizedSurfaces.clear();
2765             mReparentedSurfaces.clear();
2766             if (mNativeObject != 0) {
2767                 nativeClearTransaction(mNativeObject);
2768             }
2769         }
2770 
2771         /**
2772          * Release the native transaction object, without applying it.
2773          */
2774         @Override
close()2775         public void close() {
2776             mResizedSurfaces.clear();
2777             mReparentedSurfaces.clear();
2778             mFreeNativeResources.run();
2779             mNativeObject = 0;
2780         }
2781 
2782         /**
2783          * Jankier version of apply. Avoid use (b/28068298).
2784          * @hide
2785          */
apply(boolean sync)2786         public void apply(boolean sync) {
2787             applyResizedSurfaces();
2788             notifyReparentedSurfaces();
2789             nativeApplyTransaction(mNativeObject, sync);
2790         }
2791 
2792         /**
2793          * @hide
2794          */
applyResizedSurfaces()2795         protected void applyResizedSurfaces() {
2796             for (int i = mResizedSurfaces.size() - 1; i >= 0; i--) {
2797                 final Point size = mResizedSurfaces.valueAt(i);
2798                 final SurfaceControl surfaceControl = mResizedSurfaces.keyAt(i);
2799                 synchronized (surfaceControl.mLock) {
2800                     surfaceControl.resize(size.x, size.y);
2801                 }
2802             }
2803             mResizedSurfaces.clear();
2804         }
2805 
2806         /**
2807          * @hide
2808          */
notifyReparentedSurfaces()2809         protected void notifyReparentedSurfaces() {
2810             final int reparentCount = mReparentedSurfaces.size();
2811             for (int i = reparentCount - 1; i >= 0; i--) {
2812                 final SurfaceControl child = mReparentedSurfaces.keyAt(i);
2813                 synchronized (child.mLock) {
2814                     final int listenerCount = (child.mReparentListeners != null)
2815                             ? child.mReparentListeners.size() : 0;
2816                     for (int j = 0; j < listenerCount; j++) {
2817                         final OnReparentListener listener = child.mReparentListeners.get(j);
2818                         listener.onReparent(this, mReparentedSurfaces.valueAt(i));
2819                     }
2820                     mReparentedSurfaces.removeAt(i);
2821                 }
2822             }
2823         }
2824 
2825         /**
2826          * Toggle the visibility of a given Layer and it's sub-tree.
2827          *
2828          * @param sc The SurfaceControl for which to set the visibility
2829          * @param visible The new visibility
2830          * @return This transaction object.
2831          */
2832         @NonNull
setVisibility(@onNull SurfaceControl sc, boolean visible)2833         public Transaction setVisibility(@NonNull SurfaceControl sc, boolean visible) {
2834             checkPreconditions(sc);
2835             if (visible) {
2836                 return show(sc);
2837             } else {
2838                 return hide(sc);
2839             }
2840         }
2841 
2842         /**
2843          * This information is passed to SurfaceFlinger to decide which window should have a
2844          * priority when deciding about the refresh rate of the display. All windows have the
2845          * lowest priority by default.
2846          * @hide
2847          */
2848         @NonNull
setFrameRateSelectionPriority(@onNull SurfaceControl sc, int priority)2849         public Transaction setFrameRateSelectionPriority(@NonNull SurfaceControl sc, int priority) {
2850             checkPreconditions(sc);
2851             nativeSetFrameRateSelectionPriority(mNativeObject, sc.mNativeObject, priority);
2852             return this;
2853         }
2854 
2855         /**
2856          * Request that a given surface and it's sub-tree be shown.
2857          *
2858          * @param sc The surface to show.
2859          * @return This transaction.
2860          * @hide
2861          */
2862         @UnsupportedAppUsage
show(SurfaceControl sc)2863         public Transaction show(SurfaceControl sc) {
2864             checkPreconditions(sc);
2865             nativeSetFlags(mNativeObject, sc.mNativeObject, 0, SURFACE_HIDDEN);
2866             return this;
2867         }
2868 
2869         /**
2870          * Request that a given surface and it's sub-tree be hidden.
2871          *
2872          * @param sc The surface to hidden.
2873          * @return This transaction.
2874          * @hide
2875          */
2876         @UnsupportedAppUsage
hide(SurfaceControl sc)2877         public Transaction hide(SurfaceControl sc) {
2878             checkPreconditions(sc);
2879             nativeSetFlags(mNativeObject, sc.mNativeObject, SURFACE_HIDDEN, SURFACE_HIDDEN);
2880             return this;
2881         }
2882 
2883         /**
2884          * Sets the SurfaceControl to the specified position relative to the parent
2885          * SurfaceControl
2886          *
2887          * @param sc The SurfaceControl to change position
2888          * @param x the X position
2889          * @param y the Y position
2890          * @return this transaction
2891          */
2892         @NonNull
setPosition(@onNull SurfaceControl sc, float x, float y)2893         public Transaction setPosition(@NonNull SurfaceControl sc, float x, float y) {
2894             checkPreconditions(sc);
2895             nativeSetPosition(mNativeObject, sc.mNativeObject, x, y);
2896             return this;
2897         }
2898 
2899         /**
2900          * Sets the SurfaceControl to the specified scale with (0, 0) as the center point
2901          * of the scale.
2902          *
2903          * @param sc The SurfaceControl to change scale
2904          * @param scaleX the X scale
2905          * @param scaleY the Y scale
2906          * @return this transaction
2907          */
2908         @NonNull
setScale(@onNull SurfaceControl sc, float scaleX, float scaleY)2909         public Transaction setScale(@NonNull SurfaceControl sc, float scaleX, float scaleY) {
2910             checkPreconditions(sc);
2911             Preconditions.checkArgument(scaleX >= 0, "Negative value passed in for scaleX");
2912             Preconditions.checkArgument(scaleY >= 0, "Negative value passed in for scaleY");
2913             nativeSetScale(mNativeObject, sc.mNativeObject, scaleX, scaleY);
2914             return this;
2915         }
2916 
2917         /**
2918          * Set the default buffer size for the SurfaceControl, if there is a
2919          * {@link Surface} associated with the control, then
2920          * this will be the default size for buffers dequeued from it.
2921          * @param sc The surface to set the buffer size for.
2922          * @param w The default width
2923          * @param h The default height
2924          * @return This Transaction
2925          */
2926         @NonNull
setBufferSize(@onNull SurfaceControl sc, @IntRange(from = 0) int w, @IntRange(from = 0) int h)2927         public Transaction setBufferSize(@NonNull SurfaceControl sc,
2928                 @IntRange(from = 0) int w, @IntRange(from = 0) int h) {
2929             checkPreconditions(sc);
2930             mResizedSurfaces.put(sc, new Point(w, h));
2931             return this;
2932         }
2933 
2934         /**
2935          * Provide the graphic producer a transform hint if the layer and its children are
2936          * in an orientation different from the display's orientation. The caller is responsible
2937          * for clearing this transform hint if the layer is no longer in a fixed orientation.
2938          *
2939          * The transform hint is used to prevent allocating a buffer of different size when a
2940          * layer is rotated. The producer can choose to consume the hint and allocate the buffer
2941          * with the same size.
2942          *
2943          * @return This Transaction.
2944          * @hide
2945          */
2946         @NonNull
setFixedTransformHint(@onNull SurfaceControl sc, @Surface.Rotation int transformHint)2947         public Transaction setFixedTransformHint(@NonNull SurfaceControl sc,
2948                        @Surface.Rotation int transformHint) {
2949             checkPreconditions(sc);
2950             nativeSetFixedTransformHint(mNativeObject, sc.mNativeObject, transformHint);
2951             return this;
2952         }
2953 
2954         /**
2955          * Clearing any transform hint if set on this layer.
2956          *
2957          * @return This Transaction.
2958          * @hide
2959          */
2960         @NonNull
unsetFixedTransformHint(@onNull SurfaceControl sc)2961         public Transaction unsetFixedTransformHint(@NonNull SurfaceControl sc) {
2962             checkPreconditions(sc);
2963             nativeSetFixedTransformHint(mNativeObject, sc.mNativeObject, -1/* INVALID_ROTATION */);
2964             return this;
2965         }
2966 
2967         /**
2968          * Set the Z-order for a given SurfaceControl, relative to it's siblings.
2969          * If two siblings share the same Z order the ordering is undefined. Surfaces
2970          * with a negative Z will be placed below the parent surface.
2971          *
2972          * @param sc The SurfaceControl to set the Z order on
2973          * @param z The Z-order
2974          * @return This Transaction.
2975          */
2976         @NonNull
setLayer(@onNull SurfaceControl sc, @IntRange(from = Integer.MIN_VALUE, to = Integer.MAX_VALUE) int z)2977         public Transaction setLayer(@NonNull SurfaceControl sc,
2978                 @IntRange(from = Integer.MIN_VALUE, to = Integer.MAX_VALUE) int z) {
2979             checkPreconditions(sc);
2980             nativeSetLayer(mNativeObject, sc.mNativeObject, z);
2981             return this;
2982         }
2983 
2984         /**
2985          * @hide
2986          */
setRelativeLayer(SurfaceControl sc, SurfaceControl relativeTo, int z)2987         public Transaction setRelativeLayer(SurfaceControl sc, SurfaceControl relativeTo, int z) {
2988             checkPreconditions(sc);
2989             nativeSetRelativeLayer(mNativeObject, sc.mNativeObject, relativeTo.mNativeObject, z);
2990             return this;
2991         }
2992 
2993         /**
2994          * @hide
2995          */
setTransparentRegionHint(SurfaceControl sc, Region transparentRegion)2996         public Transaction setTransparentRegionHint(SurfaceControl sc, Region transparentRegion) {
2997             checkPreconditions(sc);
2998             nativeSetTransparentRegionHint(mNativeObject,
2999                     sc.mNativeObject, transparentRegion);
3000             return this;
3001         }
3002 
3003         /**
3004          * Set the alpha for a given surface. If the alpha is non-zero the SurfaceControl
3005          * will be blended with the Surfaces under it according to the specified ratio.
3006          *
3007          * @param sc The given SurfaceControl.
3008          * @param alpha The alpha to set.
3009          */
3010         @NonNull
setAlpha(@onNull SurfaceControl sc, @FloatRange(from = 0.0, to = 1.0) float alpha)3011         public Transaction setAlpha(@NonNull SurfaceControl sc,
3012                 @FloatRange(from = 0.0, to = 1.0) float alpha) {
3013             checkPreconditions(sc);
3014             nativeSetAlpha(mNativeObject, sc.mNativeObject, alpha);
3015             return this;
3016         }
3017 
3018         /**
3019          * @hide
3020          */
setInputWindowInfo(SurfaceControl sc, InputWindowHandle handle)3021         public Transaction setInputWindowInfo(SurfaceControl sc, InputWindowHandle handle) {
3022             checkPreconditions(sc);
3023             nativeSetInputWindowInfo(mNativeObject, sc.mNativeObject, handle);
3024             return this;
3025         }
3026 
3027         /**
3028          * Adds a callback that is called after WindowInfosListeners from the systems server are
3029          * complete. This is primarily used to ensure that InputDispatcher::setInputWindowsLocked
3030          * has been called before running the added callback.
3031          *
3032          * @hide
3033          */
addWindowInfosReportedListener(@onNull Runnable listener)3034         public Transaction addWindowInfosReportedListener(@NonNull Runnable listener) {
3035             nativeAddWindowInfosReportedListener(mNativeObject, listener);
3036             return this;
3037         }
3038 
3039         /**
3040          * Specify how the buffer associated with this Surface is mapped in to the
3041          * parent coordinate space. The source frame will be scaled to fit the destination
3042          * frame, after being rotated according to the orientation parameter.
3043          *
3044          * @param sc The SurfaceControl to specify the geometry of
3045          * @param sourceCrop The source rectangle in buffer space. Or null for the entire buffer.
3046          * @param destFrame The destination rectangle in parent space. Or null for the source frame.
3047          * @param orientation The buffer rotation
3048          * @return This transaction object.
3049          * @deprecated Use {@link #setCrop(SurfaceControl, Rect)},
3050          * {@link #setBufferTransform(SurfaceControl, int)},
3051          * {@link #setPosition(SurfaceControl, float, float)} and
3052          * {@link #setScale(SurfaceControl, float, float)} instead.
3053          */
3054         @NonNull
setGeometry(@onNull SurfaceControl sc, @Nullable Rect sourceCrop, @Nullable Rect destFrame, @Surface.Rotation int orientation)3055         public Transaction setGeometry(@NonNull SurfaceControl sc, @Nullable Rect sourceCrop,
3056                 @Nullable Rect destFrame, @Surface.Rotation int orientation) {
3057             checkPreconditions(sc);
3058             nativeSetGeometry(mNativeObject, sc.mNativeObject, sourceCrop, destFrame, orientation);
3059             return this;
3060         }
3061 
3062         /**
3063          * @hide
3064          */
3065         @UnsupportedAppUsage
setMatrix(SurfaceControl sc, float dsdx, float dtdx, float dtdy, float dsdy)3066         public Transaction setMatrix(SurfaceControl sc,
3067                 float dsdx, float dtdx, float dtdy, float dsdy) {
3068             checkPreconditions(sc);
3069             nativeSetMatrix(mNativeObject, sc.mNativeObject,
3070                     dsdx, dtdx, dtdy, dsdy);
3071             return this;
3072         }
3073 
3074         /**
3075          * Sets the transform and position of a {@link SurfaceControl} from a 3x3 transformation
3076          * matrix.
3077          *
3078          * @param sc     SurfaceControl to set matrix of
3079          * @param matrix The matrix to apply.
3080          * @param float9 An array of 9 floats to be used to extract the values from the matrix.
3081          * @hide
3082          */
3083         @UnsupportedAppUsage
setMatrix(SurfaceControl sc, Matrix matrix, float[] float9)3084         public Transaction setMatrix(SurfaceControl sc, Matrix matrix, float[] float9) {
3085             matrix.getValues(float9);
3086             setMatrix(sc, float9[MSCALE_X], float9[MSKEW_Y],
3087                     float9[MSKEW_X], float9[MSCALE_Y]);
3088             setPosition(sc, float9[MTRANS_X], float9[MTRANS_Y]);
3089             return this;
3090         }
3091 
3092         /**
3093          * Sets the color transform for the Surface.
3094          *
3095          * @param sc          SurfaceControl to set color transform of
3096          * @param matrix      A float array with 9 values represents a 3x3 transform matrix
3097          * @param translation A float array with 3 values represents a translation vector
3098          * @hide
3099          */
setColorTransform(SurfaceControl sc, @Size(9) float[] matrix, @Size(3) float[] translation)3100         public Transaction setColorTransform(SurfaceControl sc, @Size(9) float[] matrix,
3101                 @Size(3) float[] translation) {
3102             checkPreconditions(sc);
3103             nativeSetColorTransform(mNativeObject, sc.mNativeObject, matrix, translation);
3104             return this;
3105         }
3106 
3107         /**
3108          * Sets the Surface to be color space agnostic. If a surface is color space agnostic,
3109          * the color can be interpreted in any color space.
3110          * @param agnostic A boolean to indicate whether the surface is color space agnostic
3111          * @hide
3112          */
setColorSpaceAgnostic(SurfaceControl sc, boolean agnostic)3113         public Transaction setColorSpaceAgnostic(SurfaceControl sc, boolean agnostic) {
3114             checkPreconditions(sc);
3115             nativeSetColorSpaceAgnostic(mNativeObject, sc.mNativeObject, agnostic);
3116             return this;
3117         }
3118 
3119         /**
3120          * Bounds the surface and its children to the bounds specified. Size of the surface will be
3121          * ignored and only the crop and buffer size will be used to determine the bounds of the
3122          * surface. If no crop is specified and the surface has no buffer, the surface bounds is
3123          * only constrained by the size of its parent bounds.
3124          *
3125          * @param sc   SurfaceControl to set crop of.
3126          * @param crop Bounds of the crop to apply.
3127          * @hide
3128          * @deprecated Use {@link #setCrop(SurfaceControl, Rect)} instead.
3129          */
3130         @Deprecated
3131         @UnsupportedAppUsage
setWindowCrop(SurfaceControl sc, Rect crop)3132         public Transaction setWindowCrop(SurfaceControl sc, Rect crop) {
3133             checkPreconditions(sc);
3134             if (crop != null) {
3135                 nativeSetWindowCrop(mNativeObject, sc.mNativeObject,
3136                         crop.left, crop.top, crop.right, crop.bottom);
3137             } else {
3138                 nativeSetWindowCrop(mNativeObject, sc.mNativeObject, 0, 0, 0, 0);
3139             }
3140 
3141             return this;
3142         }
3143 
3144         /**
3145          * Bounds the surface and its children to the bounds specified. Size of the surface will be
3146          * ignored and only the crop and buffer size will be used to determine the bounds of the
3147          * surface. If no crop is specified and the surface has no buffer, the surface bounds is
3148          * only constrained by the size of its parent bounds.
3149          *
3150          * @param sc   SurfaceControl to set crop of.
3151          * @param crop Bounds of the crop to apply.
3152          * @return this This transaction for chaining
3153          */
setCrop(@onNull SurfaceControl sc, @Nullable Rect crop)3154         public @NonNull Transaction setCrop(@NonNull SurfaceControl sc, @Nullable Rect crop) {
3155             checkPreconditions(sc);
3156             if (crop != null) {
3157                 Preconditions.checkArgument(crop.isValid(), "Crop isn't valid.");
3158                 nativeSetWindowCrop(mNativeObject, sc.mNativeObject,
3159                         crop.left, crop.top, crop.right, crop.bottom);
3160             } else {
3161                 nativeSetWindowCrop(mNativeObject, sc.mNativeObject, 0, 0, 0, 0);
3162             }
3163 
3164             return this;
3165         }
3166 
3167         /**
3168          * Same as {@link Transaction#setWindowCrop(SurfaceControl, Rect)} but sets the crop rect
3169          * top left at 0, 0.
3170          *
3171          * @param sc     SurfaceControl to set crop of.
3172          * @param width  width of crop rect
3173          * @param height height of crop rect
3174          * @hide
3175          */
setWindowCrop(SurfaceControl sc, int width, int height)3176         public Transaction setWindowCrop(SurfaceControl sc, int width, int height) {
3177             checkPreconditions(sc);
3178             nativeSetWindowCrop(mNativeObject, sc.mNativeObject, 0, 0, width, height);
3179             return this;
3180         }
3181 
3182         /**
3183          * Sets the corner radius of a {@link SurfaceControl}.
3184          * @param sc SurfaceControl
3185          * @param cornerRadius Corner radius in pixels.
3186          * @return Itself.
3187          * @hide
3188          */
3189         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setCornerRadius(SurfaceControl sc, float cornerRadius)3190         public Transaction setCornerRadius(SurfaceControl sc, float cornerRadius) {
3191             checkPreconditions(sc);
3192             nativeSetCornerRadius(mNativeObject, sc.mNativeObject, cornerRadius);
3193 
3194             return this;
3195         }
3196 
3197         /**
3198          * Sets the background blur radius of the {@link SurfaceControl}.
3199          *
3200          * @param sc SurfaceControl.
3201          * @param radius Blur radius in pixels.
3202          * @return itself.
3203          * @hide
3204          */
setBackgroundBlurRadius(SurfaceControl sc, int radius)3205         public Transaction setBackgroundBlurRadius(SurfaceControl sc, int radius) {
3206             checkPreconditions(sc);
3207             nativeSetBackgroundBlurRadius(mNativeObject, sc.mNativeObject, radius);
3208             return this;
3209         }
3210 
3211         /**
3212          * Specify what regions should be blurred on the {@link SurfaceControl}.
3213          *
3214          * @param sc SurfaceControl.
3215          * @param regions List of regions that will have blurs.
3216          * @return itself.
3217          * @see BlurRegion#toFloatArray()
3218          * @hide
3219          */
setBlurRegions(SurfaceControl sc, float[][] regions)3220         public Transaction setBlurRegions(SurfaceControl sc, float[][] regions) {
3221             checkPreconditions(sc);
3222             nativeSetBlurRegions(mNativeObject, sc.mNativeObject, regions, regions.length);
3223             return this;
3224         }
3225 
3226         /**
3227          * @hide
3228          */
setStretchEffect(SurfaceControl sc, float width, float height, float vecX, float vecY, float maxStretchAmountX, float maxStretchAmountY, float childRelativeLeft, float childRelativeTop, float childRelativeRight, float childRelativeBottom)3229         public Transaction setStretchEffect(SurfaceControl sc, float width, float height,
3230                 float vecX, float vecY, float maxStretchAmountX,
3231                 float maxStretchAmountY, float childRelativeLeft, float childRelativeTop, float childRelativeRight,
3232                 float childRelativeBottom) {
3233             checkPreconditions(sc);
3234             nativeSetStretchEffect(mNativeObject, sc.mNativeObject, width, height,
3235                     vecX, vecY, maxStretchAmountX, maxStretchAmountY, childRelativeLeft, childRelativeTop,
3236                     childRelativeRight, childRelativeBottom);
3237             return this;
3238         }
3239 
3240         /**
3241          * @hide
3242          */
3243         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.O)
setLayerStack(SurfaceControl sc, int layerStack)3244         public Transaction setLayerStack(SurfaceControl sc, int layerStack) {
3245             checkPreconditions(sc);
3246             nativeSetLayerStack(mNativeObject, sc.mNativeObject, layerStack);
3247             return this;
3248         }
3249 
3250         /**
3251          * Re-parents a given layer to a new parent. Children inherit transform (position, scaling)
3252          * crop, visibility, and Z-ordering from their parents, as if the children were pixels within the
3253          * parent Surface.
3254          *
3255          * @param sc The SurfaceControl to reparent
3256          * @param newParent The new parent for the given control.
3257          * @return This Transaction
3258          */
3259         @NonNull
reparent(@onNull SurfaceControl sc, @Nullable SurfaceControl newParent)3260         public Transaction reparent(@NonNull SurfaceControl sc,
3261                 @Nullable SurfaceControl newParent) {
3262             checkPreconditions(sc);
3263             long otherObject = 0;
3264             if (newParent != null) {
3265                 newParent.checkNotReleased();
3266                 otherObject = newParent.mNativeObject;
3267             }
3268             nativeReparent(mNativeObject, sc.mNativeObject, otherObject);
3269             mReparentedSurfaces.put(sc, newParent);
3270             return this;
3271         }
3272 
3273         /**
3274          * Fills the surface with the specified color.
3275          * @param color A float array with three values to represent r, g, b in range [0..1]. An
3276          * invalid color will remove the color fill.
3277          * @hide
3278          */
3279         @UnsupportedAppUsage
setColor(SurfaceControl sc, @Size(3) float[] color)3280         public Transaction setColor(SurfaceControl sc, @Size(3) float[] color) {
3281             checkPreconditions(sc);
3282             nativeSetColor(mNativeObject, sc.mNativeObject, color);
3283             return this;
3284         }
3285 
3286         /**
3287          * Removes color fill.
3288         * @hide
3289         */
unsetColor(SurfaceControl sc)3290         public Transaction unsetColor(SurfaceControl sc) {
3291             checkPreconditions(sc);
3292             nativeSetColor(mNativeObject, sc.mNativeObject, INVALID_COLOR);
3293             return this;
3294         }
3295 
3296         /**
3297          * Sets the security of the surface.  Setting the flag is equivalent to creating the
3298          * Surface with the {@link #SECURE} flag.
3299          * @hide
3300          */
setSecure(SurfaceControl sc, boolean isSecure)3301         public Transaction setSecure(SurfaceControl sc, boolean isSecure) {
3302             checkPreconditions(sc);
3303             if (isSecure) {
3304                 nativeSetFlags(mNativeObject, sc.mNativeObject, SECURE, SECURE);
3305             } else {
3306                 nativeSetFlags(mNativeObject, sc.mNativeObject, 0, SECURE);
3307             }
3308             return this;
3309         }
3310 
3311         /**
3312          * Sets whether the surface should take advantage of display decoration optimizations.
3313          * @hide
3314          */
setDisplayDecoration(SurfaceControl sc, boolean displayDecoration)3315         public Transaction setDisplayDecoration(SurfaceControl sc, boolean displayDecoration) {
3316             checkPreconditions(sc);
3317             if (displayDecoration) {
3318                 nativeSetFlags(mNativeObject, sc.mNativeObject, DISPLAY_DECORATION,
3319                         DISPLAY_DECORATION);
3320             } else {
3321                 nativeSetFlags(mNativeObject, sc.mNativeObject, 0, DISPLAY_DECORATION);
3322             }
3323             return this;
3324         }
3325 
3326         /**
3327          * Indicates whether the surface must be considered opaque, even if its pixel format is
3328          * set to translucent. This can be useful if an application needs full RGBA 8888 support
3329          * for instance but will still draw every pixel opaque.
3330          * <p>
3331          * This flag only determines whether opacity will be sampled from the alpha channel.
3332          * Plane-alpha from calls to setAlpha() can still result in blended composition
3333          * regardless of the opaque setting.
3334          *
3335          * Combined effects are (assuming a buffer format with an alpha channel):
3336          * <ul>
3337          * <li>OPAQUE + alpha(1.0) == opaque composition
3338          * <li>OPAQUE + alpha(0.x) == blended composition
3339          * <li>OPAQUE + alpha(0.0) == no composition
3340          * <li>!OPAQUE + alpha(1.0) == blended composition
3341          * <li>!OPAQUE + alpha(0.x) == blended composition
3342          * <li>!OPAQUE + alpha(0.0) == no composition
3343          * </ul>
3344          * If the underlying buffer lacks an alpha channel, it is as if setOpaque(true)
3345          * were set automatically.
3346          *
3347          * @see Builder#setOpaque(boolean)
3348          *
3349          * @param sc The SurfaceControl to update
3350          * @param isOpaque true if the buffer's alpha should be ignored, false otherwise
3351          * @return this
3352          */
3353         @NonNull
setOpaque(@onNull SurfaceControl sc, boolean isOpaque)3354         public Transaction setOpaque(@NonNull SurfaceControl sc, boolean isOpaque) {
3355             checkPreconditions(sc);
3356             if (isOpaque) {
3357                 nativeSetFlags(mNativeObject, sc.mNativeObject, SURFACE_OPAQUE, SURFACE_OPAQUE);
3358             } else {
3359                 nativeSetFlags(mNativeObject, sc.mNativeObject, 0, SURFACE_OPAQUE);
3360             }
3361             return this;
3362         }
3363 
3364         /**
3365          * @hide
3366          */
setDisplaySurface(IBinder displayToken, Surface surface)3367         public Transaction setDisplaySurface(IBinder displayToken, Surface surface) {
3368             if (displayToken == null) {
3369                 throw new IllegalArgumentException("displayToken must not be null");
3370             }
3371 
3372             if (surface != null) {
3373                 synchronized (surface.mLock) {
3374                     nativeSetDisplaySurface(mNativeObject, displayToken, surface.mNativeObject);
3375                 }
3376             } else {
3377                 nativeSetDisplaySurface(mNativeObject, displayToken, 0);
3378             }
3379             return this;
3380         }
3381 
3382         /**
3383          * @hide
3384          */
setDisplayLayerStack(IBinder displayToken, int layerStack)3385         public Transaction setDisplayLayerStack(IBinder displayToken, int layerStack) {
3386             if (displayToken == null) {
3387                 throw new IllegalArgumentException("displayToken must not be null");
3388             }
3389             nativeSetDisplayLayerStack(mNativeObject, displayToken, layerStack);
3390             return this;
3391         }
3392 
3393         /**
3394          * @hide
3395          */
setDisplayFlags(IBinder displayToken, int flags)3396         public Transaction setDisplayFlags(IBinder displayToken, int flags) {
3397             if (displayToken == null) {
3398                 throw new IllegalArgumentException("displayToken must not be null");
3399             }
3400             nativeSetDisplayFlags(mNativeObject, displayToken, flags);
3401             return this;
3402         }
3403 
3404         /**
3405          * @hide
3406          */
setDisplayProjection(IBinder displayToken, int orientation, Rect layerStackRect, Rect displayRect)3407         public Transaction setDisplayProjection(IBinder displayToken,
3408                 int orientation, Rect layerStackRect, Rect displayRect) {
3409             if (displayToken == null) {
3410                 throw new IllegalArgumentException("displayToken must not be null");
3411             }
3412             if (layerStackRect == null) {
3413                 throw new IllegalArgumentException("layerStackRect must not be null");
3414             }
3415             if (displayRect == null) {
3416                 throw new IllegalArgumentException("displayRect must not be null");
3417             }
3418             nativeSetDisplayProjection(mNativeObject, displayToken, orientation,
3419                     layerStackRect.left, layerStackRect.top, layerStackRect.right, layerStackRect.bottom,
3420                     displayRect.left, displayRect.top, displayRect.right, displayRect.bottom);
3421             return this;
3422         }
3423 
3424         /**
3425          * @hide
3426          */
setDisplaySize(IBinder displayToken, int width, int height)3427         public Transaction setDisplaySize(IBinder displayToken, int width, int height) {
3428             if (displayToken == null) {
3429                 throw new IllegalArgumentException("displayToken must not be null");
3430             }
3431             if (width <= 0 || height <= 0) {
3432                 throw new IllegalArgumentException("width and height must be positive");
3433             }
3434 
3435             nativeSetDisplaySize(mNativeObject, displayToken, width, height);
3436             return this;
3437         }
3438 
3439         /** flag the transaction as an animation
3440          * @hide
3441          */
setAnimationTransaction()3442         public Transaction setAnimationTransaction() {
3443             nativeSetAnimationTransaction(mNativeObject);
3444             return this;
3445         }
3446 
3447          /**
3448           * Provides a hint to SurfaceFlinger to change its offset so that SurfaceFlinger wakes up
3449           * earlier to compose surfaces. The caller should use this as a hint to SurfaceFlinger
3450           * when the scene is complex enough to use GPU composition. The hint will remain active
3451           * until until the client calls {@link Transaction#setEarlyWakeupEnd}.
3452           *
3453           * @hide
3454           */
3455         @RequiresPermission(Manifest.permission.WAKEUP_SURFACE_FLINGER)
setEarlyWakeupStart()3456         public Transaction setEarlyWakeupStart() {
3457             nativeSetEarlyWakeupStart(mNativeObject);
3458             return this;
3459         }
3460 
3461         /**
3462          * Removes the early wake up hint set by {@link Transaction#setEarlyWakeupStart}.
3463          *
3464          * @hide
3465          */
3466         @RequiresPermission(Manifest.permission.WAKEUP_SURFACE_FLINGER)
setEarlyWakeupEnd()3467         public Transaction setEarlyWakeupEnd() {
3468             nativeSetEarlyWakeupEnd(mNativeObject);
3469             return this;
3470         }
3471 
3472         /**
3473          * @hide
3474          * @return The transaction's current id.
3475          *         The id changed every time the transaction is applied.
3476          */
getId()3477         public long getId() {
3478             return nativeGetTransactionId(mNativeObject);
3479         }
3480 
3481         /**
3482          * Sets an arbitrary piece of metadata on the surface. This is a helper for int data.
3483          * @hide
3484          */
setMetadata(SurfaceControl sc, int key, int data)3485         public Transaction setMetadata(SurfaceControl sc, int key, int data) {
3486             Parcel parcel = Parcel.obtain();
3487             parcel.writeInt(data);
3488             try {
3489                 setMetadata(sc, key, parcel);
3490             } finally {
3491                 parcel.recycle();
3492             }
3493             return this;
3494         }
3495 
3496         /**
3497          * Sets an arbitrary piece of metadata on the surface.
3498          * @hide
3499          */
setMetadata(SurfaceControl sc, int key, Parcel data)3500         public Transaction setMetadata(SurfaceControl sc, int key, Parcel data) {
3501             checkPreconditions(sc);
3502             nativeSetMetadata(mNativeObject, sc.mNativeObject, key, data);
3503             return this;
3504         }
3505 
3506          /**
3507           * Draws shadows of length {@code shadowRadius} around the surface {@link SurfaceControl}.
3508           * If the length is 0.0f then the shadows will not be drawn.
3509           *
3510           * Shadows are drawn around the screen bounds, these are the post transformed cropped
3511           * bounds. They can draw over their parent bounds and will be occluded by layers with a
3512           * higher z-order. The shadows will respect the surface's corner radius if the
3513           * rounded corner bounds (transformed source bounds) are within the screen bounds.
3514           *
3515           * A shadow will only be drawn on buffer and color layers. If the radius is applied on a
3516           * container layer, it will be passed down the hierarchy to be applied on buffer and color
3517           * layers but not its children. A scenario where this is useful is when SystemUI animates
3518           * a task by controlling a leash to it, can draw a shadow around the app surface by
3519           * setting a shadow on the leash. This is similar to how rounded corners are set.
3520           *
3521           * @hide
3522           */
setShadowRadius(SurfaceControl sc, float shadowRadius)3523         public Transaction setShadowRadius(SurfaceControl sc, float shadowRadius) {
3524             checkPreconditions(sc);
3525             nativeSetShadowRadius(mNativeObject, sc.mNativeObject, shadowRadius);
3526             return this;
3527         }
3528 
3529         /**
3530          * Sets the intended frame rate for this surface. Any switching of refresh rates is
3531          * most probably going to be seamless.
3532          *
3533          * @see #setFrameRate(SurfaceControl, float, int, int)
3534          */
3535         @NonNull
setFrameRate(@onNull SurfaceControl sc, @FloatRange(from = 0.0) float frameRate, @Surface.FrameRateCompatibility int compatibility)3536         public Transaction setFrameRate(@NonNull SurfaceControl sc,
3537                 @FloatRange(from = 0.0) float frameRate,
3538                 @Surface.FrameRateCompatibility int compatibility) {
3539             return setFrameRate(sc, frameRate, compatibility,
3540                     Surface.CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS);
3541         }
3542 
3543         /**
3544          * Sets the intended frame rate for the surface {@link SurfaceControl}.
3545          * <p>
3546          * On devices that are capable of running the display at different refresh rates, the system
3547          * may choose a display refresh rate to better match this surface's frame rate. Usage of
3548          * this API won't directly affect the application's frame production pipeline. However,
3549          * because the system may change the display refresh rate, calls to this function may result
3550          * in changes to Choreographer callback timings, and changes to the time interval at which
3551          * the system releases buffers back to the application.
3552          * <p>
3553          * Note that this only has an effect for surfaces presented on the display. If this
3554          * surface is consumed by something other than the system compositor, e.g. a media
3555          * codec, this call has no effect.
3556          *
3557          * @param sc The SurfaceControl to specify the frame rate of.
3558          * @param frameRate The intended frame rate for this surface, in frames per second. 0 is a
3559          *                  special value that indicates the app will accept the system's choice for
3560          *                  the display frame rate, which is the default behavior if this function
3561          *                  isn't called. The <code>frameRate</code> param does <em>not</em> need
3562          *                  to be a valid refresh rate for this device's display - e.g., it's fine
3563          *                  to pass 30fps to a device that can only run the display at 60fps.
3564          * @param compatibility The frame rate compatibility of this surface. The compatibility
3565          *                      value may influence the system's choice of display frame rate.
3566          *                      This parameter is ignored when <code>frameRate</code> is 0.
3567          * @param changeFrameRateStrategy Whether display refresh rate transitions caused by this
3568          *                                surface should be seamless. A seamless transition is one
3569          *                                that doesn't have any visual interruptions, such as a
3570          *                                black screen for a second or two. This parameter is
3571          *                                ignored when <code>frameRate</code> is 0.
3572          * @return This transaction object.
3573          *
3574          * @see #clearFrameRate(SurfaceControl)
3575          */
3576         @NonNull
setFrameRate(@onNull SurfaceControl sc, @FloatRange(from = 0.0) float frameRate, @Surface.FrameRateCompatibility int compatibility, @Surface.ChangeFrameRateStrategy int changeFrameRateStrategy)3577         public Transaction setFrameRate(@NonNull SurfaceControl sc,
3578                 @FloatRange(from = 0.0) float frameRate,
3579                 @Surface.FrameRateCompatibility int compatibility,
3580                 @Surface.ChangeFrameRateStrategy int changeFrameRateStrategy) {
3581             checkPreconditions(sc);
3582             nativeSetFrameRate(mNativeObject, sc.mNativeObject, frameRate, compatibility,
3583                     changeFrameRateStrategy);
3584             return this;
3585         }
3586 
3587         /**
3588          * Clears the frame rate which was set for the surface {@link SurfaceControl}.
3589          *
3590          * <p>This is equivalent to calling {@link #setFrameRate(SurfaceControl, float, int, int)}
3591          * using {@code 0} for {@code frameRate}.
3592          * <p>
3593          * Note that this only has an effect for surfaces presented on the display. If this
3594          * surface is consumed by something other than the system compositor, e.g. a media
3595          * codec, this call has no effect.
3596          *
3597          * @param sc The SurfaceControl to clear the frame rate of.
3598          * @return This transaction object.
3599          *
3600          * @see #setFrameRate(SurfaceControl, float, int)
3601          */
3602         @NonNull
clearFrameRate(@onNull SurfaceControl sc)3603         public Transaction clearFrameRate(@NonNull SurfaceControl sc) {
3604             checkPreconditions(sc);
3605             nativeSetFrameRate(mNativeObject, sc.mNativeObject, 0.0f,
3606                     Surface.FRAME_RATE_COMPATIBILITY_DEFAULT,
3607                     Surface.CHANGE_FRAME_RATE_ALWAYS);
3608             return this;
3609         }
3610 
3611         /**
3612          * Sets the default frame rate compatibility for the surface {@link SurfaceControl}
3613          *
3614          * @param sc The SurfaceControl to specify the frame rate of.
3615          * @param compatibility The frame rate compatibility of this surface. The compatibility
3616          *               value may influence the system's choice of display frame rate.
3617          *
3618          * @return This transaction object.
3619          *
3620          * @hide
3621          */
3622         @NonNull
setDefaultFrameRateCompatibility(@onNull SurfaceControl sc, @Surface.FrameRateCompatibility int compatibility)3623         public Transaction setDefaultFrameRateCompatibility(@NonNull SurfaceControl sc,
3624                 @Surface.FrameRateCompatibility int compatibility) {
3625             checkPreconditions(sc);
3626             nativeSetDefaultFrameRateCompatibility(mNativeObject, sc.mNativeObject, compatibility);
3627             return this;
3628         }
3629 
3630         /**
3631          * Sets focus on the window identified by the input {@code token} if the window is focusable
3632          * otherwise the request is dropped.
3633          *
3634          * If the window is not visible, the request will be queued until the window becomes
3635          * visible or the request is overrriden by another request. The currently focused window
3636          * will lose focus immediately. This is to send the newly focused window any focus
3637          * dispatched events that occur while it is completing its first draw.
3638          *
3639          * @hide
3640          */
setFocusedWindow(@onNull IBinder token, String windowName, int displayId)3641         public Transaction setFocusedWindow(@NonNull IBinder token, String windowName,
3642                 int displayId) {
3643             nativeSetFocusedWindow(mNativeObject, token, windowName, displayId);
3644             return this;
3645         }
3646 
3647         /**
3648          * Removes the input focus from the current window which is having the input focus. Should
3649          * only be called when the current focused app is not responding and the current focused
3650          * window is not beloged to the current focused app.
3651          * @hide
3652          */
removeCurrentInputFocus(int displayId)3653         public Transaction removeCurrentInputFocus(int displayId) {
3654             nativeRemoveCurrentInputFocus(mNativeObject, displayId);
3655             return this;
3656         }
3657 
3658         /**
3659          * Adds or removes the flag SKIP_SCREENSHOT of the surface.  Setting the flag is equivalent
3660          * to creating the Surface with the {@link #SKIP_SCREENSHOT} flag.
3661          *
3662          * @hide
3663          */
setSkipScreenshot(SurfaceControl sc, boolean skipScrenshot)3664         public Transaction setSkipScreenshot(SurfaceControl sc, boolean skipScrenshot) {
3665             checkPreconditions(sc);
3666             if (skipScrenshot) {
3667                 nativeSetFlags(mNativeObject, sc.mNativeObject, SKIP_SCREENSHOT, SKIP_SCREENSHOT);
3668             } else {
3669                 nativeSetFlags(mNativeObject, sc.mNativeObject, 0, SKIP_SCREENSHOT);
3670             }
3671             return this;
3672         }
3673 
3674         /**
3675          * Set a buffer for a SurfaceControl. This can only be used for SurfaceControls that were
3676          * created as type {@link #FX_SURFACE_BLAST}
3677          *
3678          * @hide
3679          * @deprecated Use {@link #setBuffer(SurfaceControl, HardwareBuffer)} instead
3680          */
3681         @Deprecated
setBuffer(SurfaceControl sc, GraphicBuffer buffer)3682         public Transaction setBuffer(SurfaceControl sc, GraphicBuffer buffer) {
3683             return setBuffer(sc, HardwareBuffer.createFromGraphicBuffer(buffer));
3684         }
3685 
3686         /**
3687          * Updates the HardwareBuffer displayed for the SurfaceControl.
3688          *
3689          * Note that the buffer must be allocated with {@link HardwareBuffer#USAGE_COMPOSER_OVERLAY}
3690          * as well as {@link HardwareBuffer#USAGE_GPU_SAMPLED_IMAGE} as the surface control might
3691          * be composited using either an overlay or using the GPU.
3692          *
3693          * @param sc The SurfaceControl to update
3694          * @param buffer The buffer to be displayed
3695          * @return this
3696          */
setBuffer(@onNull SurfaceControl sc, @Nullable HardwareBuffer buffer)3697         public @NonNull Transaction setBuffer(@NonNull SurfaceControl sc,
3698                 @Nullable HardwareBuffer buffer) {
3699             return setBuffer(sc, buffer, null);
3700         }
3701 
3702         /**
3703          * Unsets the buffer for the SurfaceControl in the current Transaction. This will not clear
3704          * the buffer being rendered, but resets the buffer state in the Transaction only. The call
3705          * will also invoke the release callback.
3706          *
3707          * Note, this call is different from passing a null buffer to
3708          * {@link SurfaceControl.Transaction#setBuffer} which will release the last displayed
3709          * buffer.
3710          *
3711          * @hide
3712          */
unsetBuffer(SurfaceControl sc)3713         public Transaction unsetBuffer(SurfaceControl sc) {
3714             nativeUnsetBuffer(mNativeObject, sc.mNativeObject);
3715             return this;
3716         }
3717 
3718         /**
3719          * Updates the HardwareBuffer displayed for the SurfaceControl.
3720          *
3721          * Note that the buffer must be allocated with {@link HardwareBuffer#USAGE_COMPOSER_OVERLAY}
3722          * as well as {@link HardwareBuffer#USAGE_GPU_SAMPLED_IMAGE} as the surface control might
3723          * be composited using either an overlay or using the GPU.
3724          *
3725          * A presentation fence may be passed to improve performance by allowing the buffer
3726          * to complete rendering while it is waiting for the transaction to be applied.
3727          * For example, if the buffer is being produced by rendering with OpenGL ES then
3728          * a fence created with
3729          * {@link android.opengl.EGLExt#eglDupNativeFenceFDANDROID(EGLDisplay, EGLSync)} can be
3730          * used to allow the GPU rendering to be concurrent with the transaction. The compositor
3731          * will wait for the fence to be signaled before the buffer is displayed. If multiple
3732          * buffers are set as part of the same transaction, the presentation fences of all of them
3733          * must signal before any buffer is displayed. That is, the entire transaction is delayed
3734          * until all presentation fences have signaled, ensuring the transaction remains consistent.
3735          *
3736          * @param sc The SurfaceControl to update
3737          * @param buffer The buffer to be displayed. Pass in a null buffer to release the last
3738          * displayed buffer.
3739          * @param fence The presentation fence. If null or invalid, this is equivalent to
3740          *              {@link #setBuffer(SurfaceControl, HardwareBuffer)}
3741          * @return this
3742          */
setBuffer(@onNull SurfaceControl sc, @Nullable HardwareBuffer buffer, @Nullable SyncFence fence)3743         public @NonNull Transaction setBuffer(@NonNull SurfaceControl sc,
3744                 @Nullable HardwareBuffer buffer, @Nullable SyncFence fence) {
3745             return setBuffer(sc, buffer, fence, null);
3746         }
3747 
3748         /**
3749          * Updates the HardwareBuffer displayed for the SurfaceControl.
3750          *
3751          * Note that the buffer must be allocated with {@link HardwareBuffer#USAGE_COMPOSER_OVERLAY}
3752          * as well as {@link HardwareBuffer#USAGE_GPU_SAMPLED_IMAGE} as the surface control might
3753          * be composited using either an overlay or using the GPU.
3754          *
3755          * A presentation fence may be passed to improve performance by allowing the buffer
3756          * to complete rendering while it is waiting for the transaction to be applied.
3757          * For example, if the buffer is being produced by rendering with OpenGL ES then
3758          * a fence created with
3759          * {@link android.opengl.EGLExt#eglDupNativeFenceFDANDROID(EGLDisplay, EGLSync)} can be
3760          * used to allow the GPU rendering to be concurrent with the transaction. The compositor
3761          * will wait for the fence to be signaled before the buffer is displayed. If multiple
3762          * buffers are set as part of the same transaction, the presentation fences of all of them
3763          * must signal before any buffer is displayed. That is, the entire transaction is delayed
3764          * until all presentation fences have signaled, ensuring the transaction remains consistent.
3765          *
3766          * A releaseCallback may be passed to know when the buffer is safe to be reused. This
3767          * is recommended when attempting to render continuously using SurfaceControl transactions
3768          * instead of through {@link Surface}, as it provides a safe & reliable way to know when
3769          * a buffer can be re-used. The callback will be invoked with a {@link SyncFence} which,
3770          * if {@link SyncFence#isValid() valid}, must be waited on prior to using the buffer. This
3771          * can either be done directly with {@link SyncFence#awaitForever()} or it may be done
3772          * indirectly such as passing it as a release fence to
3773          * {@link android.media.Image#setFence(SyncFence)} when using
3774          * {@link android.media.ImageReader}.
3775          *
3776          * @param sc The SurfaceControl to update
3777          * @param buffer The buffer to be displayed
3778          * @param fence The presentation fence. If null or invalid, this is equivalent to
3779          *              {@link #setBuffer(SurfaceControl, HardwareBuffer)}
3780          * @param releaseCallback The callback to invoke when the buffer being set has been released
3781          *                        by a later transaction. That is, the point at which it is safe
3782          *                        to re-use the buffer.
3783          * @return this
3784          */
setBuffer(@onNull SurfaceControl sc, @Nullable HardwareBuffer buffer, @Nullable SyncFence fence, @Nullable Consumer<SyncFence> releaseCallback)3785         public @NonNull Transaction setBuffer(@NonNull SurfaceControl sc,
3786                 @Nullable HardwareBuffer buffer, @Nullable SyncFence fence,
3787                 @Nullable Consumer<SyncFence> releaseCallback) {
3788             checkPreconditions(sc);
3789             if (fence != null) {
3790                 synchronized (fence.getLock()) {
3791                     nativeSetBuffer(mNativeObject, sc.mNativeObject, buffer,
3792                             fence.getNativeFence(), releaseCallback);
3793                 }
3794             } else {
3795                 nativeSetBuffer(mNativeObject, sc.mNativeObject, buffer, 0, releaseCallback);
3796             }
3797             return this;
3798         }
3799 
3800 
3801         /**
3802          * Sets the buffer transform that should be applied to the current buffer.
3803          *
3804          * This can be used in combination with
3805          * {@link AttachedSurfaceControl#addOnBufferTransformHintChangedListener(AttachedSurfaceControl.OnBufferTransformHintChangedListener)}
3806          * to pre-rotate the buffer for the current display orientation. This can
3807          * improve the performance of displaying the associated buffer.
3808          *
3809          * @param sc The SurfaceControl to update
3810          * @param transform The transform to apply to the buffer.
3811          * @return this
3812          */
setBufferTransform(@onNull SurfaceControl sc, @SurfaceControl.BufferTransform int transform)3813         public @NonNull Transaction setBufferTransform(@NonNull SurfaceControl sc,
3814                 @SurfaceControl.BufferTransform int transform) {
3815             checkPreconditions(sc);
3816             nativeSetBufferTransform(mNativeObject, sc.mNativeObject, transform);
3817             return this;
3818         }
3819 
3820         /**
3821          * Updates the region for the content on this surface updated in this transaction. The
3822          * damage region is the area of the buffer that has changed since the previously
3823          * sent buffer. This can be used to reduce the amount of recomposition that needs
3824          * to happen when only a small region of the buffer is being updated, such as for
3825          * a small blinking cursor or a loading indicator.
3826          *
3827          * @param sc The SurfaceControl on which to set the damage region
3828          * @param region The region to set. If null, the entire buffer is assumed dirty. This is
3829          *               equivalent to not setting a damage region at all.
3830          */
setDamageRegion(@onNull SurfaceControl sc, @Nullable Region region)3831         public @NonNull Transaction setDamageRegion(@NonNull SurfaceControl sc,
3832                 @Nullable Region region) {
3833             nativeSetDamageRegion(mNativeObject, sc.mNativeObject, region);
3834             return this;
3835         }
3836 
3837         /**
3838          * Set if the layer can be dimmed.
3839          *
3840          * <p>Dimming is to adjust brightness of the layer.
3841          * Default value is {@code true}, which means the layer can be dimmed.
3842          * Disabling dimming means the brightness of the layer can not be changed, i.e.,
3843          * keep the white point for the layer same as the display brightness.</p>
3844          *
3845          * @param sc The SurfaceControl on which to enable or disable dimming.
3846          * @param dimmingEnabled The dimming flag.
3847          * @return this.
3848          *
3849          * @hide
3850          */
setDimmingEnabled(@onNull SurfaceControl sc, boolean dimmingEnabled)3851         public @NonNull Transaction setDimmingEnabled(@NonNull SurfaceControl sc,
3852                 boolean dimmingEnabled) {
3853             checkPreconditions(sc);
3854             nativeSetDimmingEnabled(mNativeObject, sc.mNativeObject, dimmingEnabled);
3855             return this;
3856         }
3857 
3858         /**
3859          * Set the color space for the SurfaceControl. The supported color spaces are SRGB
3860          * and Display P3, other color spaces will be treated as SRGB. This can only be used for
3861          * SurfaceControls that were created as type {@link #FX_SURFACE_BLAST}
3862          *
3863          * @hide
3864          * @deprecated use {@link #setDataSpace(SurfaceControl, long)} instead
3865          */
3866         @Deprecated
setColorSpace(SurfaceControl sc, ColorSpace colorSpace)3867         public Transaction setColorSpace(SurfaceControl sc, ColorSpace colorSpace) {
3868             checkPreconditions(sc);
3869             if (colorSpace.getId() == ColorSpace.Named.DISPLAY_P3.ordinal()) {
3870                 setDataSpace(sc, DataSpace.DATASPACE_DISPLAY_P3);
3871             } else {
3872                 setDataSpace(sc, DataSpace.DATASPACE_SRGB);
3873             }
3874             return this;
3875         }
3876 
3877         /**
3878          * Set the dataspace for the SurfaceControl. This will control how the buffer
3879          * set with {@link #setBuffer(SurfaceControl, HardwareBuffer)} is displayed.
3880          *
3881          * @param sc The SurfaceControl to update
3882          * @param dataspace The dataspace to set it to
3883          * @return this
3884          */
setDataSpace(@onNull SurfaceControl sc, @DataSpace.NamedDataSpace int dataspace)3885         public @NonNull Transaction setDataSpace(@NonNull SurfaceControl sc,
3886                 @DataSpace.NamedDataSpace int dataspace) {
3887             checkPreconditions(sc);
3888             nativeSetDataSpace(mNativeObject, sc.mNativeObject, dataspace);
3889             return this;
3890         }
3891 
3892         /**
3893          * Sets the desired extended range brightness for the layer. This only applies for layers
3894          * whose dataspace has RANGE_EXTENDED.
3895          *
3896          * @param sc The layer whose extended range brightness is being specified
3897          * @param currentBufferRatio The current hdr/sdr ratio of the current buffer. For example
3898          *                           if the buffer was rendered with a target SDR whitepoint of
3899          *                           100 nits and a max display brightness of 200 nits, this should
3900          *                           be set to 2.0f.
3901          *
3902          *                           <p>Default value is 1.0f.
3903          *
3904          *                           <p>Transfer functions that encode their own brightness ranges,
3905          *                           such as HLG or PQ, should also set this to 1.0f and instead
3906          *                           communicate extended content brightness information via
3907          *                           metadata such as CTA861_3 or SMPTE2086.
3908          *
3909          *                           <p>Must be finite && >= 1.0f
3910          *
3911          * @param desiredRatio The desired hdr/sdr ratio. This can be used to communicate the max
3912          *                     desired brightness range. This is similar to the "max luminance"
3913          *                     value in other HDR metadata formats, but represented as a ratio of
3914          *                     the target SDR whitepoint to the max display brightness. The system
3915          *                     may not be able to, or may choose not to, deliver the
3916          *                     requested range.
3917          *
3918          *                     <p>While requesting a large desired ratio will result in the most
3919          *                     dynamic range, voluntarily reducing the requested range can help
3920          *                     improve battery life as well as can improve quality by ensuring
3921          *                     greater bit depth is allocated to the luminance range in use.
3922          *
3923          *                     <p>Default value is 1.0f and indicates that extended range brightness
3924          *                     is not being used, so the resulting SDR or HDR behavior will be
3925          *                     determined entirely by the dataspace being used (ie, typically SDR
3926          *                     however PQ or HLG transfer functions will still result in HDR)
3927          *
3928          *                     <p>Must be finite && >= 1.0f
3929          * @return this
3930          **/
setExtendedRangeBrightness(@onNull SurfaceControl sc, float currentBufferRatio, float desiredRatio)3931         public @NonNull Transaction setExtendedRangeBrightness(@NonNull SurfaceControl sc,
3932                 float currentBufferRatio, float desiredRatio) {
3933             checkPreconditions(sc);
3934             if (!Float.isFinite(currentBufferRatio) || currentBufferRatio < 1.0f) {
3935                 throw new IllegalArgumentException(
3936                         "currentBufferRatio must be finite && >= 1.0f; got " + currentBufferRatio);
3937             }
3938             if (!Float.isFinite(desiredRatio) || desiredRatio < 1.0f) {
3939                 throw new IllegalArgumentException(
3940                         "desiredRatio must be finite && >= 1.0f; got " + desiredRatio);
3941             }
3942             nativeSetExtendedRangeBrightness(mNativeObject, sc.mNativeObject, currentBufferRatio,
3943                     desiredRatio);
3944             return this;
3945         }
3946 
3947         /**
3948          * Sets the caching hint for the layer. By default, the caching hint is
3949          * {@link CACHING_ENABLED}.
3950          *
3951          * @param sc The SurfaceControl to update
3952          * @param cachingHint The caching hint to apply to the SurfaceControl. The CachingHint is
3953          *                    not applied to any children of this SurfaceControl.
3954          * @return this
3955          * @hide
3956          */
setCachingHint( @onNull SurfaceControl sc, @CachingHint int cachingHint)3957         public @NonNull Transaction setCachingHint(
3958                 @NonNull SurfaceControl sc, @CachingHint int cachingHint) {
3959             checkPreconditions(sc);
3960             nativeSetCachingHint(mNativeObject, sc.mNativeObject, cachingHint);
3961             return this;
3962         }
3963 
3964         /**
3965          * Sets the trusted overlay state on this SurfaceControl and it is inherited to all the
3966          * children. The caller must hold the ACCESS_SURFACE_FLINGER permission.
3967          * @hide
3968          */
setTrustedOverlay(SurfaceControl sc, boolean isTrustedOverlay)3969         public Transaction setTrustedOverlay(SurfaceControl sc, boolean isTrustedOverlay) {
3970             checkPreconditions(sc);
3971             nativeSetTrustedOverlay(mNativeObject, sc.mNativeObject, isTrustedOverlay);
3972             return this;
3973         }
3974 
3975         /**
3976          * Sets the input event drop mode on this SurfaceControl and its children. The caller must
3977          * hold the ACCESS_SURFACE_FLINGER permission. See {@code InputEventDropMode}.
3978          * @hide
3979          */
setDropInputMode(SurfaceControl sc, @DropInputMode int mode)3980         public Transaction setDropInputMode(SurfaceControl sc, @DropInputMode int mode) {
3981             checkPreconditions(sc);
3982             nativeSetDropInputMode(mNativeObject, sc.mNativeObject, mode);
3983             return this;
3984         }
3985 
3986         /**
3987          * Sends a flush jank data transaction for the given surface.
3988          * @hide
3989          */
sendSurfaceFlushJankData(SurfaceControl sc)3990         public static void sendSurfaceFlushJankData(SurfaceControl sc) {
3991             sc.checkNotReleased();
3992             nativeSurfaceFlushJankData(sc.mNativeObject);
3993         }
3994 
3995         /**
3996          * @hide
3997          */
sanitize(int pid, int uid)3998         public void sanitize(int pid, int uid) {
3999             nativeSanitize(mNativeObject, pid, uid);
4000         }
4001 
4002         /**
4003          * @hide
4004          */
setDesintationFrame(SurfaceControl sc, @NonNull Rect destinationFrame)4005         public Transaction setDesintationFrame(SurfaceControl sc, @NonNull Rect destinationFrame) {
4006             checkPreconditions(sc);
4007             nativeSetDestinationFrame(mNativeObject, sc.mNativeObject,
4008                     destinationFrame.left, destinationFrame.top, destinationFrame.right,
4009                     destinationFrame.bottom);
4010             return this;
4011         }
4012 
4013         /**
4014          * @hide
4015          */
setDesintationFrame(SurfaceControl sc, int width, int height)4016         public Transaction setDesintationFrame(SurfaceControl sc, int width, int height) {
4017             checkPreconditions(sc);
4018             nativeSetDestinationFrame(mNativeObject, sc.mNativeObject, 0, 0, width, height);
4019             return this;
4020         }
4021 
4022         /**
4023          * Merge the other transaction into this transaction, clearing the
4024          * other transaction as if it had been applied.
4025          *
4026          * @param other The transaction to merge in to this one.
4027          * @return This transaction.
4028          */
4029         @NonNull
merge(@onNull Transaction other)4030         public Transaction merge(@NonNull Transaction other) {
4031             if (this == other) {
4032                 return this;
4033             }
4034             mResizedSurfaces.putAll(other.mResizedSurfaces);
4035             other.mResizedSurfaces.clear();
4036             mReparentedSurfaces.putAll(other.mReparentedSurfaces);
4037             other.mReparentedSurfaces.clear();
4038             nativeMergeTransaction(mNativeObject, other.mNativeObject);
4039             return this;
4040         }
4041 
4042         /**
4043          * Equivalent to reparent with a null parent, in that it removes
4044          * the SurfaceControl from the scene, but it also releases
4045          * the local resources (by calling {@link SurfaceControl#release})
4046          * after this method returns, {@link SurfaceControl#isValid} will return
4047          * false for the argument.
4048          *
4049          * @param sc The surface to remove and release.
4050          * @return This transaction
4051          * @hide
4052          */
4053         @NonNull
remove(@onNull SurfaceControl sc)4054         public Transaction remove(@NonNull SurfaceControl sc) {
4055             reparent(sc, null);
4056             sc.release();
4057             return this;
4058         }
4059 
4060         /**
4061          * Sets the frame timeline vsync id received from choreographer
4062          * {@link Choreographer#getVsyncId()} that corresponds to the transaction submitted on that
4063          * surface control.
4064          *
4065          * @hide
4066          */
4067         @NonNull
setFrameTimelineVsync(long frameTimelineVsyncId)4068         public Transaction setFrameTimelineVsync(long frameTimelineVsyncId) {
4069             nativeSetFrameTimelineVsync(mNativeObject, frameTimelineVsyncId);
4070             return this;
4071         }
4072 
4073         /**
4074          * Request to add a {@link TransactionCommittedListener}.
4075          *
4076          * The callback is invoked when transaction is applied and the updates are ready to be
4077          * presented. This callback does not mean buffers have been released! It simply means that
4078          * any new transactions applied will not overwrite the transaction for which we are
4079          * receiving a callback and instead will be included in the next frame. If you are trying
4080          * to avoid dropping frames (overwriting transactions), and unable to use timestamps (Which
4081          * provide a more efficient solution), then this method provides a method to pace your
4082          * transaction application.
4083          *
4084          * @param executor The executor that the callback should be invoked on.
4085          * @param listener The callback that will be invoked when the transaction has been
4086          *                 committed.
4087          */
4088         @NonNull
addTransactionCommittedListener( @onNull @allbackExecutor Executor executor, @NonNull TransactionCommittedListener listener)4089         public Transaction addTransactionCommittedListener(
4090                 @NonNull @CallbackExecutor Executor executor,
4091                 @NonNull TransactionCommittedListener listener) {
4092             TransactionCommittedListener listenerInner =
4093                     () -> executor.execute(listener::onTransactionCommitted);
4094             nativeAddTransactionCommittedListener(mNativeObject, listenerInner);
4095             return this;
4096         }
4097 
4098         /**
4099          * Sets a callback to receive feedback about the presentation of a {@link SurfaceControl}.
4100          * When the {@link SurfaceControl} is presented according to the passed in
4101          * {@link TrustedPresentationThresholds}, it is said to "enter the state", and receives the
4102          * callback with {@code true}. When the conditions fall out of thresholds, it is then
4103          * said to leave the state.
4104          * <p>
4105          * There are a few simple thresholds:
4106          * <ul>
4107          *    <li>minAlpha: Lower bound on computed alpha</li>
4108          *    <li>minFractionRendered: Lower bounds on fraction of pixels that were rendered</li>
4109          *    <li>stabilityThresholdMs: A time that alpha and fraction rendered must remain within
4110          *    bounds before we can "enter the state" </li>
4111          * </ul>
4112          * <p>
4113          * The fraction of pixels rendered is a computation based on scale, crop
4114          * and occlusion. The calculation may be somewhat counterintuitive, so we
4115          * can work through an example. Imagine we have a SurfaceControl with a 100x100 buffer
4116          * which is occluded by (10x100) pixels on the left, and cropped by (100x10) pixels
4117          * on the top. Furthermore imagine this SurfaceControl is scaled by 0.9 in both dimensions.
4118          * (c=crop,o=occluded,b=both,x=none)
4119          *
4120          * <blockquote>
4121          * <table>
4122          *   <caption></caption>
4123          *   <tr><td>b</td><td>c</td><td>c</td><td>c</td></tr>
4124          *   <tr><td>o</td><td>x</td><td>x</td><td>x</td></tr>
4125          *   <tr><td>o</td><td>x</td><td>x</td><td>x</td></tr>
4126          *   <tr><td>o</td><td>x</td><td>x</td><td>x</td></tr>
4127          * </table>
4128          * </blockquote>
4129          *
4130          *<p>
4131          * We first start by computing fr=xscale*yscale=0.9*0.9=0.81, indicating
4132          * that "81%" of the pixels were rendered. This corresponds to what was 100
4133          * pixels being displayed in 81 pixels. This is somewhat of an abuse of
4134          * language, as the information of merged pixels isn't totally lost, but
4135          * we err on the conservative side.
4136          * <p>
4137          * We then repeat a similar process for the crop and covered regions and
4138          * accumulate the results: fr = fr * (fractionNotCropped) * (fractionNotCovered)
4139          * So for this example we would get 0.9*0.9*0.9*0.9=0.65...
4140          * <p>
4141          * Notice that this is not completely accurate, as we have double counted
4142          * the region marked as b. However we only wanted a "lower bound" and so it
4143          * is ok to err in this direction. Selection of the threshold will ultimately
4144          * be somewhat arbitrary, and so there are some somewhat arbitrary decisions in
4145          * this API as well.
4146          * <p>
4147          * @param sc         The {@link SurfaceControl} to set the
4148          *                   {@link TrustedPresentationCallback} on
4149          * @param thresholds The {@link TrustedPresentationThresholds} that will specify when the to
4150          *                   invoke the callback.
4151          * @param executor   The {@link Executor} where the callback will be invoked on.
4152          * @param listener   The {@link Consumer} that will receive the callbacks when entered or
4153          *                   exited the threshold.
4154          * @return This transaction
4155          * @see TrustedPresentationThresholds
4156          */
4157         @NonNull
setTrustedPresentationCallback(@onNull SurfaceControl sc, @NonNull TrustedPresentationThresholds thresholds, @NonNull Executor executor, @NonNull Consumer<Boolean> listener)4158         public Transaction setTrustedPresentationCallback(@NonNull SurfaceControl sc,
4159                 @NonNull TrustedPresentationThresholds thresholds, @NonNull Executor executor,
4160                 @NonNull Consumer<Boolean> listener) {
4161             checkPreconditions(sc);
4162             TrustedPresentationCallback tpc = new TrustedPresentationCallback() {
4163                 @Override
4164                 public void onTrustedPresentationChanged(boolean inTrustedPresentationState) {
4165                     executor.execute(
4166                             () -> listener.accept(inTrustedPresentationState));
4167                 }
4168             };
4169 
4170             if (sc.mTrustedPresentationCallback != null) {
4171                 sc.mTrustedPresentationCallback.mFreeNativeResources.run();
4172             }
4173 
4174             nativeSetTrustedPresentationCallback(mNativeObject, sc.mNativeObject,
4175                     tpc.mNativeObject, thresholds);
4176             sc.mTrustedPresentationCallback = tpc;
4177             return this;
4178         }
4179 
4180         /**
4181          * Clears the {@link TrustedPresentationCallback} for a specific {@link SurfaceControl}
4182          *
4183          * @param sc The SurfaceControl that the {@link TrustedPresentationCallback} should be
4184          *           cleared from
4185          * @return This transaction
4186          */
4187         @NonNull
clearTrustedPresentationCallback(@onNull SurfaceControl sc)4188         public Transaction clearTrustedPresentationCallback(@NonNull SurfaceControl sc) {
4189             checkPreconditions(sc);
4190             nativeClearTrustedPresentationCallback(mNativeObject, sc.mNativeObject);
4191             if (sc.mTrustedPresentationCallback != null) {
4192                 sc.mTrustedPresentationCallback.mFreeNativeResources.run();
4193                 sc.mTrustedPresentationCallback = null;
4194             }
4195             return this;
4196         }
4197 
4198         /**
4199          * Writes the transaction to parcel, clearing the transaction as if it had been applied so
4200          * it can be used to store future transactions. It's the responsibility of the parcel
4201          * reader to apply the original transaction.
4202          *
4203          * @param dest parcel to write the transaction to
4204          * @param flags
4205          */
4206         @Override
writeToParcel(@onNull Parcel dest, @WriteFlags int flags)4207         public void writeToParcel(@NonNull Parcel dest, @WriteFlags int flags) {
4208             if (mNativeObject == 0) {
4209                 dest.writeInt(0);
4210                 return;
4211             }
4212 
4213             dest.writeInt(1);
4214             nativeWriteTransactionToParcel(mNativeObject, dest);
4215             if ((flags & Parcelable.PARCELABLE_WRITE_RETURN_VALUE) != 0) {
4216                 nativeClearTransaction(mNativeObject);
4217             }
4218         }
4219 
readFromParcel(Parcel in)4220         private void readFromParcel(Parcel in) {
4221             mNativeObject = 0;
4222             if (in.readInt() != 0) {
4223                 mNativeObject = nativeReadTransactionFromParcel(in);
4224                 mFreeNativeResources = sRegistry.registerNativeAllocation(this, mNativeObject);
4225             }
4226         }
4227 
4228         @Override
describeContents()4229         public int describeContents() {
4230             return 0;
4231         }
4232 
4233         public static final @NonNull Creator<Transaction> CREATOR = new Creator<Transaction>() {
4234                     @Override
4235                     public Transaction createFromParcel(Parcel in) {
4236                         return new Transaction(in);
4237                     }
4238                     @Override
4239                     public Transaction[] newArray(int size) {
4240                         return new Transaction[size];
4241                     }
4242                 };
4243     }
4244 
4245     /**
4246      * A debugging utility subclass of SurfaceControl.Transaction. At construction
4247      * you can pass in a monitor object, and all the other methods will throw an exception
4248      * if the monitor is not held when they are called.
4249      * @hide
4250      */
4251     public static class LockDebuggingTransaction extends SurfaceControl.Transaction {
4252         Object mMonitor;
4253 
LockDebuggingTransaction(Object o)4254         public LockDebuggingTransaction(Object o) {
4255             mMonitor = o;
4256         }
4257 
4258         @Override
checkPreconditions(SurfaceControl sc)4259         protected void checkPreconditions(SurfaceControl sc) {
4260             super.checkPreconditions(sc);
4261             if (!Thread.holdsLock(mMonitor)) {
4262                 throw new RuntimeException(
4263                         "Unlocked access to synchronized SurfaceControl.Transaction");
4264             }
4265         }
4266     }
4267 
4268     /**
4269      * As part of eliminating usage of the global Transaction we expose
4270      * a SurfaceControl.getGlobalTransaction function. However calling
4271      * apply on this global transaction (rather than using closeTransaction)
4272      * would be very dangerous. So for the global transaction we use this
4273      * subclass of Transaction where the normal apply throws an exception.
4274      */
4275     private static class GlobalTransactionWrapper extends SurfaceControl.Transaction {
applyGlobalTransaction(boolean sync)4276         void applyGlobalTransaction(boolean sync) {
4277             applyResizedSurfaces();
4278             notifyReparentedSurfaces();
4279             nativeApplyTransaction(mNativeObject, sync);
4280         }
4281 
4282         @Override
apply(boolean sync)4283         public void apply(boolean sync) {
4284             throw new RuntimeException("Global transaction must be applied from closeTransaction");
4285         }
4286     }
4287 
4288     /**
4289      * This is a refactoring utility function to enable lower levels of code to be refactored
4290      * from using the global transaction (and instead use a passed in Transaction) without
4291      * having to refactor the higher levels at the same time.
4292      * The returned global transaction can't be applied, it must be applied from closeTransaction
4293      * Unless you are working on removing Global Transaction usage in the WindowManager, this
4294      * probably isn't a good function to use.
4295      * @hide
4296      */
getGlobalTransaction()4297     public static Transaction getGlobalTransaction() {
4298         return sGlobalTransaction;
4299     }
4300 
4301     /**
4302      * @hide
4303      */
resize(int w, int h)4304     public void resize(int w, int h) {
4305         mWidth = w;
4306         mHeight = h;
4307         nativeUpdateDefaultBufferSize(mNativeObject, w, h);
4308     }
4309 
4310     /**
4311      * @hide
4312      */
getTransformHint()4313     public @SurfaceControl.BufferTransform int getTransformHint() {
4314         checkNotReleased();
4315         return nativeGetTransformHint(mNativeObject);
4316     }
4317 
4318     /**
4319      * Update the transform hint of current SurfaceControl. Only affect if type is
4320      * {@link #FX_SURFACE_BLAST}
4321      *
4322      * The transform hint is used to prevent allocating a buffer of different size when a
4323      * layer is rotated. The producer can choose to consume the hint and allocate the buffer
4324      * with the same size.
4325      * @hide
4326      */
setTransformHint(@urfaceControl.BufferTransform int transformHint)4327     public void setTransformHint(@SurfaceControl.BufferTransform int transformHint) {
4328         nativeSetTransformHint(mNativeObject, transformHint);
4329     }
4330 
4331     /**
4332      * @hide
4333      */
getLayerId()4334     public int getLayerId() {
4335         if (mNativeObject != 0) {
4336             return nativeGetLayerId(mNativeObject);
4337         }
4338 
4339         return -1;
4340     }
4341 
4342     /**
4343      * Adds this surface control to the registry for this process if it is created.
4344      */
addToRegistry()4345     private void addToRegistry() {
4346         final SurfaceControlRegistry registry = SurfaceControlRegistry.getProcessInstance();
4347         if (registry != null) {
4348             registry.add(this);
4349         }
4350     }
4351 
4352     /**
4353      * Removes this surface control from the registry for this process.
4354      */
removeFromRegistry()4355     private void removeFromRegistry() {
4356         final SurfaceControlRegistry registry = SurfaceControlRegistry.getProcessInstance();
4357         if (registry != null) {
4358             registry.remove(this);
4359         }
4360     }
4361 
4362     // Called by native
invokeReleaseCallback(Consumer<SyncFence> callback, long nativeFencePtr)4363     private static void invokeReleaseCallback(Consumer<SyncFence> callback, long nativeFencePtr) {
4364         SyncFence fence = new SyncFence(nativeFencePtr);
4365         callback.accept(fence);
4366     }
4367 
4368     /**
4369      * @hide
4370      */
getStalledTransactionInfo(int pid)4371     public static StalledTransactionInfo getStalledTransactionInfo(int pid) {
4372         return nativeGetStalledTransactionInfo(pid);
4373     }
4374 
4375 }
4376