1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
|
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.screenshot;
import android.app.Activity;
import android.app.ActivityOptions;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.HardwareRenderer;
import android.graphics.Matrix;
import android.graphics.RecordingCanvas;
import android.graphics.Rect;
import android.graphics.RenderNode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Process;
import android.os.UserHandle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ScrollCaptureResponse;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.android.internal.app.ChooserActivity;
import com.android.internal.logging.UiEventLogger;
import com.android.systemui.R;
import com.android.systemui.dagger.qualifiers.Background;
import com.android.systemui.dagger.qualifiers.Main;
import com.android.systemui.flags.FeatureFlags;
import com.android.systemui.flags.Flags;
import com.android.systemui.screenshot.ScrollCaptureController.LongScreenshot;
import com.android.systemui.settings.UserTracker;
import com.google.common.util.concurrent.ListenableFuture;
import java.io.File;
import java.time.ZonedDateTime;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import javax.inject.Inject;
/**
* LongScreenshotActivity acquires bitmap data for a long screenshot and lets the user trim the top
* and bottom before saving/sharing/editing.
*/
public class LongScreenshotActivity extends Activity {
private static final String TAG = LogConfig.logTag(LongScreenshotActivity.class);
public static final String EXTRA_CAPTURE_RESPONSE = "capture-response";
public static final String EXTRA_SCREENSHOT_USER_HANDLE = "screenshot-userhandle";
private static final String KEY_SAVED_IMAGE_PATH = "saved-image-path";
private final UiEventLogger mUiEventLogger;
private final Executor mUiExecutor;
private final Executor mBackgroundExecutor;
private final ImageExporter mImageExporter;
private final LongScreenshotData mLongScreenshotHolder;
private final ActionIntentExecutor mActionExecutor;
private final FeatureFlags mFeatureFlags;
private final UserTracker mUserTracker;
private ImageView mPreview;
private ImageView mTransitionView;
private ImageView mEnterTransitionView;
private View mSave;
private View mCancel;
private View mEdit;
private View mShare;
private CropView mCropView;
private MagnifierView mMagnifierView;
private ScrollCaptureResponse mScrollCaptureResponse;
private UserHandle mScreenshotUserHandle;
private File mSavedImagePath;
private ListenableFuture<File> mCacheSaveFuture;
private ListenableFuture<ImageLoader.Result> mCacheLoadFuture;
private Bitmap mOutputBitmap;
private LongScreenshot mLongScreenshot;
private boolean mTransitionStarted;
private enum PendingAction {
SHARE,
EDIT,
SAVE
}
@Inject
public LongScreenshotActivity(UiEventLogger uiEventLogger, ImageExporter imageExporter,
@Main Executor mainExecutor, @Background Executor bgExecutor,
LongScreenshotData longScreenshotHolder, ActionIntentExecutor actionExecutor,
FeatureFlags featureFlags, UserTracker userTracker) {
mUiEventLogger = uiEventLogger;
mUiExecutor = mainExecutor;
mBackgroundExecutor = bgExecutor;
mImageExporter = imageExporter;
mLongScreenshotHolder = longScreenshotHolder;
mActionExecutor = actionExecutor;
mFeatureFlags = featureFlags;
mUserTracker = userTracker;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.long_screenshot);
mPreview = requireViewById(R.id.preview);
mSave = requireViewById(R.id.save);
mEdit = requireViewById(R.id.edit);
mShare = requireViewById(R.id.share);
mCancel = requireViewById(R.id.cancel);
mCropView = requireViewById(R.id.crop_view);
mMagnifierView = requireViewById(R.id.magnifier);
mCropView.setCropInteractionListener(mMagnifierView);
mTransitionView = requireViewById(R.id.transition);
mEnterTransitionView = requireViewById(R.id.enter_transition);
mSave.setOnClickListener(this::onClicked);
mCancel.setOnClickListener(this::onClicked);
mEdit.setOnClickListener(this::onClicked);
mShare.setOnClickListener(this::onClicked);
mPreview.addOnLayoutChangeListener(
(v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) ->
updateImageDimensions());
Intent intent = getIntent();
mScrollCaptureResponse = intent.getParcelableExtra(EXTRA_CAPTURE_RESPONSE);
mScreenshotUserHandle = intent.getParcelableExtra(EXTRA_SCREENSHOT_USER_HANDLE,
UserHandle.class);
if (mScreenshotUserHandle == null) {
mScreenshotUserHandle = Process.myUserHandle();
}
if (savedInstanceState != null) {
String savedImagePath = savedInstanceState.getString(KEY_SAVED_IMAGE_PATH);
if (savedImagePath == null) {
Log.e(TAG, "Missing saved state entry with key '" + KEY_SAVED_IMAGE_PATH + "'!");
finishAndRemoveTask();
return;
}
mSavedImagePath = new File(savedImagePath);
ImageLoader imageLoader = new ImageLoader(getContentResolver());
mCacheLoadFuture = imageLoader.load(mSavedImagePath);
}
}
@Override
public void onStart() {
super.onStart();
mUiEventLogger.log(ScreenshotEvent.SCREENSHOT_LONG_SCREENSHOT_ACTIVITY_STARTED);
if (mPreview.getDrawable() != null) {
// We already have an image, so no need to try to load again.
return;
}
if (mCacheLoadFuture != null) {
Log.d(TAG, "mCacheLoadFuture != null");
final ListenableFuture<ImageLoader.Result> future = mCacheLoadFuture;
mCacheLoadFuture.addListener(() -> {
Log.d(TAG, "cached bitmap load complete");
try {
onCachedImageLoaded(future.get());
} catch (CancellationException | ExecutionException | InterruptedException e) {
Log.e(TAG, "Failed to load cached image", e);
if (mSavedImagePath != null) {
//noinspection ResultOfMethodCallIgnored
mSavedImagePath.delete();
mSavedImagePath = null;
}
finishAndRemoveTask();
}
}, mUiExecutor);
mCacheLoadFuture = null;
} else {
LongScreenshot longScreenshot = mLongScreenshotHolder.takeLongScreenshot();
setMagnification(mLongScreenshotHolder.getNeedsMagnification());
if (longScreenshot != null) {
onLongScreenshotReceived(longScreenshot);
} else {
Log.e(TAG, "No long screenshot available!");
finishAndRemoveTask();
}
}
}
private void setMagnification(boolean status) {
if (status) {
mCropView.setCropInteractionListener(mMagnifierView);
} else {
mCropView.setCropInteractionListener(null);
}
}
private void onLongScreenshotReceived(LongScreenshot longScreenshot) {
Log.i(TAG, "Completed: " + longScreenshot);
mLongScreenshot = longScreenshot;
Drawable drawable = mLongScreenshot.getDrawable();
mPreview.setImageDrawable(drawable);
mMagnifierView.setDrawable(mLongScreenshot.getDrawable(),
mLongScreenshot.getWidth(), mLongScreenshot.getHeight());
// Original boundaries go from the image tile set's y=0 to y=pageSize, so
// we animate to that as a starting crop position.
float topFraction = Math.max(0,
-mLongScreenshot.getTop() / (float) mLongScreenshot.getHeight());
float bottomFraction = Math.min(1f,
1 - (mLongScreenshot.getBottom() - mLongScreenshot.getPageHeight())
/ (float) mLongScreenshot.getHeight());
mEnterTransitionView.setImageDrawable(drawable);
mEnterTransitionView.getViewTreeObserver().addOnPreDrawListener(
new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
mEnterTransitionView.getViewTreeObserver().removeOnPreDrawListener(this);
updateImageDimensions();
mEnterTransitionView.post(() -> {
Rect dest = new Rect();
mEnterTransitionView.getBoundsOnScreen(dest);
mLongScreenshotHolder.takeTransitionDestinationCallback()
.setTransitionDestination(dest, () -> {
mPreview.animate().alpha(1f);
mCropView.setBoundaryPosition(
CropView.CropBoundary.TOP, topFraction);
mCropView.setBoundaryPosition(
CropView.CropBoundary.BOTTOM, bottomFraction);
mCropView.animateEntrance();
mCropView.setVisibility(View.VISIBLE);
setButtonsEnabled(true);
});
});
return true;
}
});
// Immediately export to temp image file for saved state
mCacheSaveFuture = mImageExporter.exportToRawFile(mBackgroundExecutor,
mLongScreenshot.toBitmap(), new File(getCacheDir(), "long_screenshot_cache.png"));
mCacheSaveFuture.addListener(() -> {
try {
// Get the temp file path to persist, used in onSavedInstanceState
mSavedImagePath = mCacheSaveFuture.get();
} catch (CancellationException | InterruptedException | ExecutionException e) {
Log.e(TAG, "Error saving temp image file", e);
finishAndRemoveTask();
}
}, mUiExecutor);
}
private void onCachedImageLoaded(ImageLoader.Result imageResult) {
mUiEventLogger.log(ScreenshotEvent.SCREENSHOT_LONG_SCREENSHOT_ACTIVITY_CACHED_IMAGE_LOADED);
BitmapDrawable drawable = new BitmapDrawable(getResources(), imageResult.bitmap);
mPreview.setImageDrawable(drawable);
mPreview.setAlpha(1f);
mMagnifierView.setDrawable(drawable, imageResult.bitmap.getWidth(),
imageResult.bitmap.getHeight());
mCropView.setVisibility(View.VISIBLE);
mSavedImagePath = imageResult.fileName;
setButtonsEnabled(true);
}
private static Bitmap renderBitmap(Drawable drawable, Rect bounds) {
final RenderNode output = new RenderNode("Bitmap Export");
output.setPosition(0, 0, bounds.width(), bounds.height());
RecordingCanvas canvas = output.beginRecording();
canvas.translate(-bounds.left, -bounds.top);
canvas.clipRect(bounds);
drawable.draw(canvas);
output.endRecording();
return HardwareRenderer.createHardwareBitmap(output, bounds.width(), bounds.height());
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mSavedImagePath != null) {
outState.putString(KEY_SAVED_IMAGE_PATH, mSavedImagePath.getPath());
}
}
@Override
protected void onStop() {
super.onStop();
if (mTransitionStarted) {
finish();
}
if (isFinishing()) {
mUiEventLogger.log(ScreenshotEvent.SCREENSHOT_LONG_SCREENSHOT_ACTIVITY_FINISHED);
if (mScrollCaptureResponse != null) {
mScrollCaptureResponse.close();
}
cleanupCache();
if (mLongScreenshot != null) {
mLongScreenshot.release();
}
}
}
void cleanupCache() {
if (mCacheSaveFuture != null) {
mCacheSaveFuture.cancel(true);
}
if (mSavedImagePath != null) {
//noinspection ResultOfMethodCallIgnored
mSavedImagePath.delete();
mSavedImagePath = null;
}
}
private void setButtonsEnabled(boolean enabled) {
mSave.setEnabled(enabled);
mEdit.setEnabled(enabled);
mShare.setEnabled(enabled);
}
private void doEdit(Uri uri) {
if (mFeatureFlags.isEnabled(Flags.SCREENSHOT_WORK_PROFILE_POLICY) && mScreenshotUserHandle
!= Process.myUserHandle()) {
// TODO: Fix transition for work profile. Omitting it in the meantime.
mActionExecutor.launchIntentAsync(
ActionIntentCreator.INSTANCE.createEditIntent(uri, this),
null,
mScreenshotUserHandle.getIdentifier(), false);
} else {
String editorPackage = getString(R.string.config_screenshotEditor);
Intent intent = new Intent(Intent.ACTION_EDIT);
if (!TextUtils.isEmpty(editorPackage)) {
intent.setComponent(ComponentName.unflattenFromString(editorPackage));
}
intent.setDataAndType(uri, "image/png");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
mTransitionView.setImageBitmap(mOutputBitmap);
mTransitionView.setVisibility(View.VISIBLE);
mTransitionView.setTransitionName(
ChooserActivity.FIRST_IMAGE_PREVIEW_TRANSITION_NAME);
// TODO: listen for transition completing instead of finishing onStop
mTransitionStarted = true;
startActivity(intent,
ActivityOptions.makeSceneTransitionAnimation(this, mTransitionView,
ChooserActivity.FIRST_IMAGE_PREVIEW_TRANSITION_NAME).toBundle());
}
}
private void doShare(Uri uri) {
if (mFeatureFlags.isEnabled(Flags.SCREENSHOT_WORK_PROFILE_POLICY)) {
Intent shareIntent = ActionIntentCreator.INSTANCE.createShareIntent(uri);
mActionExecutor.launchIntentAsync(shareIntent, null,
mScreenshotUserHandle.getIdentifier(), false);
} else {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/png");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_GRANT_READ_URI_PERMISSION);
Intent sharingChooserIntent = Intent.createChooser(intent, null)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityAsUser(sharingChooserIntent, mUserTracker.getUserHandle());
}
}
private void onClicked(View v) {
int id = v.getId();
v.setPressed(true);
setButtonsEnabled(false);
if (id == R.id.save) {
mUiEventLogger.log(ScreenshotEvent.SCREENSHOT_LONG_SCREENSHOT_SAVED);
startExport(PendingAction.SAVE);
} else if (id == R.id.edit) {
mUiEventLogger.log(ScreenshotEvent.SCREENSHOT_LONG_SCREENSHOT_EDIT);
startExport(PendingAction.EDIT);
} else if (id == R.id.share) {
mUiEventLogger.log(ScreenshotEvent.SCREENSHOT_LONG_SCREENSHOT_SHARE);
startExport(PendingAction.SHARE);
} else if (id == R.id.cancel) {
mUiEventLogger.log(ScreenshotEvent.SCREENSHOT_LONG_SCREENSHOT_EXIT);
finishAndRemoveTask();
}
}
private void startExport(PendingAction action) {
Drawable drawable = mPreview.getDrawable();
if (drawable == null) {
Log.e(TAG, "No drawable, skipping export!");
return;
}
Rect bounds = mCropView.getCropBoundaries(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
if (bounds.isEmpty()) {
Log.w(TAG, "Crop bounds empty, skipping export.");
return;
}
updateImageDimensions();
mOutputBitmap = renderBitmap(drawable, bounds);
ListenableFuture<ImageExporter.Result> exportFuture = mImageExporter.export(
mBackgroundExecutor, UUID.randomUUID(), mOutputBitmap, ZonedDateTime.now(),
mFeatureFlags.isEnabled(Flags.SCREENSHOT_WORK_PROFILE_POLICY)
? mScreenshotUserHandle : Process.myUserHandle(),
mLongScreenshotHolder.getForegroundAppName());
exportFuture.addListener(() -> onExportCompleted(action, exportFuture), mUiExecutor);
}
private void onExportCompleted(PendingAction action,
ListenableFuture<ImageExporter.Result> exportFuture) {
setButtonsEnabled(true);
ImageExporter.Result result;
try {
result = exportFuture.get();
} catch (CancellationException | InterruptedException | ExecutionException e) {
Log.e(TAG, "failed to export", e);
return;
}
switch (action) {
case EDIT:
doEdit(result.uri);
break;
case SHARE:
doShare(result.uri);
break;
case SAVE:
// Nothing more to do
finishAndRemoveTask();
break;
}
}
private void updateImageDimensions() {
Drawable drawable = mPreview.getDrawable();
if (drawable == null) {
return;
}
Rect bounds = drawable.getBounds();
float imageRatio = bounds.width() / (float) bounds.height();
int previewWidth = mPreview.getWidth() - mPreview.getPaddingLeft()
- mPreview.getPaddingRight();
int previewHeight = mPreview.getHeight() - mPreview.getPaddingTop()
- mPreview.getPaddingBottom();
float viewRatio = previewWidth / (float) previewHeight;
// Top and left offsets of the image relative to mPreview.
int imageLeft = mPreview.getPaddingLeft();
int imageTop = mPreview.getPaddingTop();
// The image width and height on screen
int imageHeight = previewHeight;
int imageWidth = previewWidth;
float scale;
int extraPadding = 0;
if (imageRatio > viewRatio) {
// Image is full width and height is constrained, compute extra padding to inform
// CropView
imageHeight = (int) (previewHeight * viewRatio / imageRatio);
extraPadding = (previewHeight - imageHeight) / 2;
mCropView.setExtraPadding(extraPadding + mPreview.getPaddingTop(),
extraPadding + mPreview.getPaddingBottom());
imageTop += (previewHeight - imageHeight) / 2;
mCropView.setImageWidth(previewWidth);
scale = previewWidth / (float) mPreview.getDrawable().getIntrinsicWidth();
} else {
imageWidth = (int) (previewWidth * imageRatio / viewRatio);
imageLeft += (previewWidth - imageWidth) / 2;
// Image is full height
mCropView.setExtraPadding(mPreview.getPaddingTop(), mPreview.getPaddingBottom());
mCropView.setImageWidth((int) (previewHeight * imageRatio));
scale = previewHeight / (float) mPreview.getDrawable().getIntrinsicHeight();
}
// Update transition view's position and scale.
Rect boundaries = mCropView.getCropBoundaries(imageWidth, imageHeight);
mTransitionView.setTranslationX(imageLeft + boundaries.left);
mTransitionView.setTranslationY(imageTop + boundaries.top);
ConstraintLayout.LayoutParams params =
(ConstraintLayout.LayoutParams) mTransitionView.getLayoutParams();
params.width = boundaries.width();
params.height = boundaries.height();
mTransitionView.setLayoutParams(params);
if (mLongScreenshot != null) {
ConstraintLayout.LayoutParams enterTransitionParams =
(ConstraintLayout.LayoutParams) mEnterTransitionView.getLayoutParams();
float topFraction = Math.max(0,
-mLongScreenshot.getTop() / (float) mLongScreenshot.getHeight());
enterTransitionParams.width = (int) (scale * drawable.getIntrinsicWidth());
enterTransitionParams.height = (int) (scale * mLongScreenshot.getPageHeight());
mEnterTransitionView.setLayoutParams(enterTransitionParams);
Matrix matrix = new Matrix();
matrix.setScale(scale, scale);
matrix.postTranslate(0, -scale * drawable.getIntrinsicHeight() * topFraction);
mEnterTransitionView.setImageMatrix(matrix);
mEnterTransitionView.setTranslationY(
topFraction * previewHeight + mPreview.getPaddingTop() + extraPadding);
}
}
}
|