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