Debian Codegraph @

core/java/com/android/internal/util/ScreenshotHelper.java

raw symbols SCIP
1 package com.android.internal.util;
2
3 import static android.content.Intent.ACTION_USER_SWITCHED;
4 import static android.view.WindowManager.TAKE_SCREENSHOT_PROVIDED_IMAGE;
5
6 import android.annotation.NonNull;
7 import android.annotation.Nullable;
8 import android.content.BroadcastReceiver;
9 import android.content.ComponentName;
10 import android.content.Context;
11 import android.content.Intent;
12 import android.content.IntentFilter;
13 import android.content.ServiceConnection;
14 import android.graphics.Bitmap;
15 import android.graphics.ColorSpace;
16 import android.graphics.Insets;
17 import android.graphics.ParcelableColorSpace;
18 import android.graphics.Rect;
19 import android.hardware.HardwareBuffer;
20 import android.net.Uri;
21 import android.os.Bundle;
22 import android.os.Handler;
23 import android.os.IBinder;
24 import android.os.Message;
25 import android.os.Messenger;
26 import android.os.Parcel;
27 import android.os.Parcelable;
28 import android.os.RemoteException;
29 import android.os.UserHandle;
30 import android.util.Log;
31 import android.view.WindowManager.ScreenshotSource;
32 import android.view.WindowManager.ScreenshotType;
33
34 import com.android.internal.annotations.VisibleForTesting;
35
36 import java.util.Objects;
37 import java.util.function.Consumer;
38
39 public class ScreenshotHelper {
40
41 public static final int SCREENSHOT_MSG_URI = 1;
42 public static final int SCREENSHOT_MSG_PROCESS_COMPLETE = 2;
43
44 /**
45 * Describes a screenshot request.
46 */
47 public static class ScreenshotRequest implements Parcelable {
48 @ScreenshotType
49 private final int mType;
50
51 @ScreenshotSource
52 private final int mSource;
53
54 private final Bundle mBitmapBundle;
55 private final Rect mBoundsInScreen;
56 private final Insets mInsets;
57 private final int mTaskId;
58 private final int mUserId;
59 private final ComponentName mTopComponent;
60
61
62 public ScreenshotRequest(@ScreenshotType int type, @ScreenshotSource int source) {
63 this(type, source, /* topComponent */ null);
64 }
65
66 public ScreenshotRequest(@ScreenshotType int type, @ScreenshotSource int source,
67 ComponentName topComponent) {
68 this(type,
69 source,
70 /* bitmapBundle*/ null,
71 /* boundsInScreen */ null,
72 /* insets */ null,
73 /* taskId */ -1,
74 /* userId */ -1,
75 topComponent);
76 }
77
78 public ScreenshotRequest(@ScreenshotType int type, @ScreenshotSource int source,
79 Bundle bitmapBundle, Rect boundsInScreen, Insets insets, int taskId, int userId,
80 ComponentName topComponent) {
81 mType = type;
82 mSource = source;
83 mBitmapBundle = bitmapBundle;
84 mBoundsInScreen = boundsInScreen;
85 mInsets = insets;
86 mTaskId = taskId;
87 mUserId = userId;
88 mTopComponent = topComponent;
89 }
90
91 ScreenshotRequest(Parcel in) {
92 mType = in.readInt();
93 mSource = in.readInt();
94 if (in.readInt() == 1) {
95 mBitmapBundle = in.readBundle(getClass().getClassLoader());
96 mBoundsInScreen = in.readParcelable(Rect.class.getClassLoader(), Rect.class);
97 mInsets = in.readParcelable(Insets.class.getClassLoader(), Insets.class);
98 mTaskId = in.readInt();
99 mUserId = in.readInt();
100 mTopComponent = in.readParcelable(ComponentName.class.getClassLoader(),
101 ComponentName.class);
102 } else {
103 mBitmapBundle = null;
104 mBoundsInScreen = null;
105 mInsets = null;
106 mTaskId = -1;
107 mUserId = -1;
108 mTopComponent = null;
109 }
110 }
111
112 @ScreenshotType
113 public int getType() {
114 return mType;
115 }
116
117 @ScreenshotSource
118 public int getSource() {
119 return mSource;
120 }
121
122 public Bundle getBitmapBundle() {
123 return mBitmapBundle;
124 }
125
126 public Rect getBoundsInScreen() {
127 return mBoundsInScreen;
128 }
129
130 public Insets getInsets() {
131 return mInsets;
132 }
133
134 public int getTaskId() {
135 return mTaskId;
136 }
137
138 public int getUserId() {
139 return mUserId;
140 }
141
142 public ComponentName getTopComponent() {
143 return mTopComponent;
144 }
145
146 @Override
147 public int describeContents() {
148 return 0;
149 }
150
151 @Override
152 public void writeToParcel(Parcel dest, int flags) {
153 dest.writeInt(mType);
154 dest.writeInt(mSource);
155 if (mBitmapBundle == null) {
156 dest.writeInt(0);
157 } else {
158 dest.writeInt(1);
159 dest.writeBundle(mBitmapBundle);
160 dest.writeParcelable(mBoundsInScreen, 0);
161 dest.writeParcelable(mInsets, 0);
162 dest.writeInt(mTaskId);
163 dest.writeInt(mUserId);
164 dest.writeParcelable(mTopComponent, 0);
165 }
166 }
167
168 @NonNull
169 public static final Parcelable.Creator<ScreenshotRequest> CREATOR =
170 new Parcelable.Creator<ScreenshotRequest>() {
171
172 @Override
173 public ScreenshotRequest createFromParcel(Parcel source) {
174 return new ScreenshotRequest(source);
175 }
176
177 @Override
178 public ScreenshotRequest[] newArray(int size) {
179 return new ScreenshotRequest[size];
180 }
181 };
182 }
183
184 /**
185 * Bundler used to convert between a hardware bitmap and a bundle without copying the internal
186 * content. This is expected to be used together with {@link #provideScreenshot} to handle a
187 * hardware bitmap as a screenshot.
188 */
189 public static final class HardwareBitmapBundler {
190 private static final String KEY_BUFFER = "bitmap_util_buffer";
191 private static final String KEY_COLOR_SPACE = "bitmap_util_color_space";
192
193 private HardwareBitmapBundler() {
194 }
195
196 /**
197 * Creates a Bundle that represents the given Bitmap.
198 * <p>The Bundle will contain a wrapped version of the Bitmaps HardwareBuffer, so will avoid
199 * copies when passing across processes, only pass to processes you trust.
200 *
201 * <p>Returns a new Bundle rather than modifying an exiting one to avoid key collisions, the
202 * returned Bundle should be treated as a standalone object.
203 *
204 * @param bitmap to convert to bundle
205 * @return a Bundle representing the bitmap, should only be parsed by
206 * {@link #bundleToHardwareBitmap(Bundle)}
207 */
208 public static Bundle hardwareBitmapToBundle(Bitmap bitmap) {
209 if (bitmap.getConfig() != Bitmap.Config.HARDWARE) {
210 throw new IllegalArgumentException(
211 "Passed bitmap must have hardware config, found: " + bitmap.getConfig());
212 }
213
214 // Bitmap assumes SRGB for null color space
215 ParcelableColorSpace colorSpace =
216 bitmap.getColorSpace() == null
217 ? new ParcelableColorSpace(ColorSpace.get(ColorSpace.Named.SRGB))
218 : new ParcelableColorSpace(bitmap.getColorSpace());
219
220 Bundle bundle = new Bundle();
221 bundle.putParcelable(KEY_BUFFER, bitmap.getHardwareBuffer());
222 bundle.putParcelable(KEY_COLOR_SPACE, colorSpace);
223
224 return bundle;
225 }
226
227 /**
228 * Extracts the Bitmap added to a Bundle with {@link #hardwareBitmapToBundle(Bitmap)} .}
229 *
230 * <p>This Bitmap contains the HardwareBuffer from the original caller, be careful passing
231 * this Bitmap on to any other source.
232 *
233 * @param bundle containing the bitmap
234 * @return a hardware Bitmap
235 */
236 public static Bitmap bundleToHardwareBitmap(Bundle bundle) {
237 if (!bundle.containsKey(KEY_BUFFER) || !bundle.containsKey(KEY_COLOR_SPACE)) {
238 throw new IllegalArgumentException("Bundle does not contain a hardware bitmap");
239 }
240
241 HardwareBuffer buffer = bundle.getParcelable(KEY_BUFFER, HardwareBuffer.class);
242 ParcelableColorSpace colorSpace = bundle.getParcelable(KEY_COLOR_SPACE,
243 ParcelableColorSpace.class);
244
245 return Bitmap.wrapHardwareBuffer(Objects.requireNonNull(buffer),
246 colorSpace.getColorSpace());
247 }
248 }
249
250 private static final String TAG = "ScreenshotHelper";
251
252 // Time until we give up on the screenshot & show an error instead.
253 private final int SCREENSHOT_TIMEOUT_MS = 10000;
254
255 private final Object mScreenshotLock = new Object();
256 private IBinder mScreenshotService = null;
257 private ServiceConnection mScreenshotConnection = null;
258 private final Context mContext;
259
260 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
261 @Override
262 public void onReceive(Context context, Intent intent) {
263 synchronized (mScreenshotLock) {
264 if (ACTION_USER_SWITCHED.equals(intent.getAction())) {
265 resetConnection();
266 }
267 }
268 }
269 };
270
271 public ScreenshotHelper(Context context) {
272 mContext = context;
273 IntentFilter filter = new IntentFilter(ACTION_USER_SWITCHED);
274 mContext.registerReceiver(mBroadcastReceiver, filter, Context.RECEIVER_EXPORTED);
275 }
276
277 /**
278 * Request a screenshot be taken.
279 * <p>
280 * Added to support reducing unit test duration; the method variant without a timeout argument
281 * is recommended for general use.
282 *
283 * @param type The type of screenshot, defined by {@link ScreenshotType}
284 * @param source The source of the screenshot request, defined by {@link ScreenshotSource}
285 * @param handler used to process messages received from the screenshot service
286 * @param completionConsumer receives the URI of the captured screenshot, once saved or
287 * null if no screenshot was saved
288 */
289 public void takeScreenshot(@ScreenshotType int type, @ScreenshotSource int source,
290 @NonNull Handler handler, @Nullable Consumer<Uri> completionConsumer) {
291 ScreenshotRequest screenshotRequest = new ScreenshotRequest(type, source);
292 takeScreenshot(handler, screenshotRequest, SCREENSHOT_TIMEOUT_MS,
293 completionConsumer);
294 }
295
296 /**
297 * Request a screenshot be taken.
298 * <p>
299 * Added to support reducing unit test duration; the method variant without a timeout argument
300 * is recommended for general use.
301 *
302 * @param type The type of screenshot, defined by {@link ScreenshotType}
303 * @param source The source of the screenshot request, defined by {@link ScreenshotSource}
304 * @param handler used to process messages received from the screenshot service
305 * @param timeoutMs time limit for processing, intended only for testing
306 * @param completionConsumer receives the URI of the captured screenshot, once saved or
307 * null if no screenshot was saved
308 */
309 @VisibleForTesting
310 public void takeScreenshot(@ScreenshotType int type, @ScreenshotSource int source,
311 @NonNull Handler handler, long timeoutMs, @Nullable Consumer<Uri> completionConsumer) {
312 ScreenshotRequest screenshotRequest = new ScreenshotRequest(type, source);
313 takeScreenshot(handler, screenshotRequest, timeoutMs, completionConsumer);
314 }
315
316 /**
317 * Request that provided image be handled as if it was a screenshot.
318 *
319 * @param screenshotBundle Bundle containing the buffer and color space of the screenshot.
320 * @param boundsInScreen The bounds in screen coordinates that the bitmap originated from.
321 * @param insets The insets that the image was shown with, inside the screen bounds.
322 * @param taskId The taskId of the task that the screen shot was taken of.
323 * @param userId The userId of user running the task provided in taskId.
324 * @param topComponent The component name of the top component running in the task.
325 * @param source The source of the screenshot request, defined by {@link ScreenshotSource}
326 * @param handler A handler used in case the screenshot times out
327 * @param completionConsumer receives the URI of the captured screenshot, once saved or
328 * null if no screenshot was saved
329 */
330 public void provideScreenshot(@NonNull Bundle screenshotBundle, @NonNull Rect boundsInScreen,
331 @NonNull Insets insets, int taskId, int userId, ComponentName topComponent,
332 @ScreenshotSource int source, @NonNull Handler handler,
333 @Nullable Consumer<Uri> completionConsumer) {
334 ScreenshotRequest screenshotRequest = new ScreenshotRequest(TAKE_SCREENSHOT_PROVIDED_IMAGE,
335 source, screenshotBundle, boundsInScreen, insets, taskId, userId, topComponent);
336 takeScreenshot(handler, screenshotRequest, SCREENSHOT_TIMEOUT_MS, completionConsumer);
337 }
338
339 private void takeScreenshot(@NonNull Handler handler,
340 ScreenshotRequest screenshotRequest, long timeoutMs,
341 @Nullable Consumer<Uri> completionConsumer) {
342 synchronized (mScreenshotLock) {
343
344 final Runnable mScreenshotTimeout = () -> {
345 synchronized (mScreenshotLock) {
346 if (mScreenshotConnection != null) {
347 Log.e(TAG, "Timed out before getting screenshot capture response");
348 resetConnection();
349 notifyScreenshotError();
350 }
351 }
352 if (completionConsumer != null) {
353 completionConsumer.accept(null);
354 }
355 };
356
357 Message msg = Message.obtain(null, 0, screenshotRequest);
358
359 Handler h = new Handler(handler.getLooper()) {
360 @Override
361 public void handleMessage(Message msg) {
362 switch (msg.what) {
363 case SCREENSHOT_MSG_URI:
364 if (completionConsumer != null) {
365 completionConsumer.accept((Uri) msg.obj);
366 }
367 handler.removeCallbacks(mScreenshotTimeout);
368 break;
369 case SCREENSHOT_MSG_PROCESS_COMPLETE:
370 synchronized (mScreenshotLock) {
371 resetConnection();
372 }
373 break;
374 }
375 }
376 };
377 msg.replyTo = new Messenger(h);
378
379 if (mScreenshotConnection == null || mScreenshotService == null) {
380 if (mScreenshotConnection != null) {
381 resetConnection();
382 }
383 final ComponentName serviceComponent = ComponentName.unflattenFromString(
384 mContext.getResources().getString(
385 com.android.internal.R.string.config_screenshotServiceComponent));
386 final Intent serviceIntent = new Intent();
387
388 serviceIntent.setComponent(serviceComponent);
389 ServiceConnection conn = new ServiceConnection() {
390 @Override
391 public void onServiceConnected(ComponentName name, IBinder service) {
392 synchronized (mScreenshotLock) {
393 if (mScreenshotConnection != this) {
394 return;
395 }
396 mScreenshotService = service;
397 Messenger messenger = new Messenger(mScreenshotService);
398
399 try {
400 messenger.send(msg);
401 } catch (RemoteException e) {
402 Log.e(TAG, "Couldn't take screenshot: " + e);
403 if (completionConsumer != null) {
404 completionConsumer.accept(null);
405 }
406 }
407 }
408 }
409
410 @Override
411 public void onServiceDisconnected(ComponentName name) {
412 synchronized (mScreenshotLock) {
413 if (mScreenshotConnection != null) {
414 resetConnection();
415 // only log an error if we're still within the timeout period
416 if (handler.hasCallbacks(mScreenshotTimeout)) {
417 Log.e(TAG, "Screenshot service disconnected");
418 handler.removeCallbacks(mScreenshotTimeout);
419 notifyScreenshotError();
420 }
421 }
422 }
423 }
424 };
425 if (mContext.bindServiceAsUser(serviceIntent, conn,
426 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
427 UserHandle.CURRENT)) {
428 mScreenshotConnection = conn;
429 handler.postDelayed(mScreenshotTimeout, timeoutMs);
430 }
431 } else {
432 Messenger messenger = new Messenger(mScreenshotService);
433
434 try {
435 messenger.send(msg);
436 } catch (RemoteException e) {
437 Log.e(TAG, "Couldn't take screenshot: " + e);
438 if (completionConsumer != null) {
439 completionConsumer.accept(null);
440 }
441 }
442 handler.postDelayed(mScreenshotTimeout, timeoutMs);
443 }
444 }
445 }
446
447 /**
448 * Unbinds the current screenshot connection (if any).
449 */
450 private void resetConnection() {
451 if (mScreenshotConnection != null) {
452 mContext.unbindService(mScreenshotConnection);
453 mScreenshotConnection = null;
454 mScreenshotService = null;
455 }
456 }
457
458 /**
459 * Notifies the screenshot service to show an error.
460 */
461 private void notifyScreenshotError() {
462 // If the service process is killed, then ask it to clean up after itself
463 final ComponentName errorComponent = ComponentName.unflattenFromString(
464 mContext.getResources().getString(
465 com.android.internal.R.string.config_screenshotErrorReceiverComponent));
466 // Broadcast needs to have a valid action. We'll just pick
467 // a generic one, since the receiver here doesn't care.
468 Intent errorIntent = new Intent(Intent.ACTION_USER_PRESENT);
469 errorIntent.setComponent(errorComponent);
470 errorIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT |
471 Intent.FLAG_RECEIVER_FOREGROUND);
472 mContext.sendBroadcastAsUser(errorIntent, UserHandle.CURRENT);
473 }
474
475 }