summaryrefslogtreecommitdiff
path: root/packages/SystemUI/src/com/android/systemui/screenshot/SaveImageInBackgroundTask.java
blob: d8edf58a0b143c1dfc8b4ba4b398732ce335bdb1 (plain)
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
/*
 * Copyright (C) 2019 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 static com.android.systemui.screenshot.LogConfig.DEBUG_ACTIONS;
import static com.android.systemui.screenshot.LogConfig.DEBUG_CALLBACK;
import static com.android.systemui.screenshot.LogConfig.DEBUG_STORAGE;
import static com.android.systemui.screenshot.LogConfig.logTag;
import static com.android.systemui.screenshot.ScreenshotNotificationSmartActionsProvider.ScreenshotSmartActionType;

import android.app.ActivityTaskManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.UserInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Process;
import android.os.RemoteException;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.DeviceConfig;
import android.text.TextUtils;
import android.util.Log;

import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
import com.android.systemui.R;
import com.android.systemui.flags.FeatureFlags;
import com.android.systemui.flags.Flags;
import com.android.systemui.screenshot.ScreenshotController.SavedImageData.ActionTransition;

import com.google.common.util.concurrent.ListenableFuture;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;

/**
 * An AsyncTask that saves an image to the media store in the background.
 */
class SaveImageInBackgroundTask extends AsyncTask<String, Void, Void> {
    private static final String TAG = logTag(SaveImageInBackgroundTask.class);

    private static final String SCREENSHOT_ID_TEMPLATE = "Screenshot_%s";
    private static final String SCREENSHOT_SHARE_SUBJECT_TEMPLATE = "Screenshot (%s)";

    private final Context mContext;
    private FeatureFlags mFlags;
    private final ScreenshotSmartActions mScreenshotSmartActions;
    private final ScreenshotController.SaveImageInBackgroundData mParams;
    private final ScreenshotController.SavedImageData mImageData;
    private final ScreenshotController.QuickShareData mQuickShareData;

    private final ScreenshotNotificationSmartActionsProvider mSmartActionsProvider;
    private String mScreenshotId;
    private final Random mRandom = new Random();
    private final Supplier<ActionTransition> mSharedElementTransition;
    private final ImageExporter mImageExporter;
    private long mImageTime;

    SaveImageInBackgroundTask(
            Context context,
            FeatureFlags flags,
            ImageExporter exporter,
            ScreenshotSmartActions screenshotSmartActions,
            ScreenshotController.SaveImageInBackgroundData data,
            Supplier<ActionTransition> sharedElementTransition,
            ScreenshotNotificationSmartActionsProvider
                    screenshotNotificationSmartActionsProvider
    ) {
        mContext = context;
        mFlags = flags;
        mScreenshotSmartActions = screenshotSmartActions;
        mImageData = new ScreenshotController.SavedImageData();
        mQuickShareData = new ScreenshotController.QuickShareData();
        mSharedElementTransition = sharedElementTransition;
        mImageExporter = exporter;

        // Prepare all the output metadata
        mParams = data;

        // Initialize screenshot notification smart actions provider.
        mSmartActionsProvider = screenshotNotificationSmartActionsProvider;
    }

    @Override
    protected Void doInBackground(String... params) {
        if (isCancelled()) {
            if (DEBUG_STORAGE) {
                Log.d(TAG, "cancelled! returning null");
            }
            return null;
        }
        // TODO: move to constructor / from ScreenshotRequest
        final UUID requestId = UUID.randomUUID();
        final UserHandle user = mFlags.isEnabled(Flags.SCREENSHOT_WORK_PROFILE_POLICY)
                ? mParams.owner : getUserHandleOfForegroundApplication(mContext);

        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

        Bitmap image = mParams.image;
        mScreenshotId = String.format(SCREENSHOT_ID_TEMPLATE, requestId);

        boolean savingToOtherUser = mFlags.isEnabled(Flags.SCREENSHOT_WORK_PROFILE_POLICY)
                && (user != Process.myUserHandle());
        // Smart actions don't yet work for cross-user saves.
        boolean smartActionsEnabled = !savingToOtherUser
                && DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_SYSTEMUI,
                SystemUiDeviceConfigFlags.ENABLE_SCREENSHOT_NOTIFICATION_SMART_ACTIONS,
                true);
        try {
            if (smartActionsEnabled && mParams.mQuickShareActionsReadyListener != null) {
                // Since Quick Share target recommendation does not rely on image URL, it is
                // queried and surfaced before image compress/export. Action intent would not be
                // used, because it does not contain image URL.
                Notification.Action quickShare =
                        queryQuickShareAction(mScreenshotId, image, user, null);
                if (quickShare != null) {
                    mQuickShareData.quickShareAction = quickShare;
                    mParams.mQuickShareActionsReadyListener.onActionsReady(mQuickShareData);
                }
            }

            // Call synchronously here since already on a background thread.
            ListenableFuture<ImageExporter.Result> future =
                    mImageExporter.export(Runnable::run, requestId, image, mParams.owner,
                            params != null ? params[0] : null);
            ImageExporter.Result result = future.get();
            Log.d(TAG, "Saved screenshot: " + result);
            final Uri uri = result.uri;
            mImageTime = result.timestamp;

            CompletableFuture<List<Notification.Action>> smartActionsFuture =
                    mScreenshotSmartActions.getSmartActionsFuture(
                            mScreenshotId, uri, image, mSmartActionsProvider,
                            ScreenshotSmartActionType.REGULAR_SMART_ACTIONS,
                            smartActionsEnabled, user);
            List<Notification.Action> smartActions = new ArrayList<>();
            if (smartActionsEnabled) {
                int timeoutMs = DeviceConfig.getInt(
                        DeviceConfig.NAMESPACE_SYSTEMUI,
                        SystemUiDeviceConfigFlags.SCREENSHOT_NOTIFICATION_SMART_ACTIONS_TIMEOUT_MS,
                        1000);
                smartActions.addAll(buildSmartActions(
                        mScreenshotSmartActions.getSmartActions(
                                mScreenshotId, smartActionsFuture, timeoutMs,
                                mSmartActionsProvider,
                                ScreenshotSmartActionType.REGULAR_SMART_ACTIONS),
                        mContext));
            }

            mImageData.uri = uri;
            mImageData.owner = user;
            mImageData.smartActions = smartActions;
            mImageData.viewTransition = createViewAction(mContext, mContext.getResources(), uri);
            mImageData.shareTransition = createShareAction(mContext, mContext.getResources(), uri,
                    smartActionsEnabled);
            mImageData.editTransition = createEditAction(mContext, mContext.getResources(), uri,
                    smartActionsEnabled);
            mImageData.deleteAction = createDeleteAction(mContext, mContext.getResources(), uri,
                    smartActionsEnabled);
            mImageData.lensAction = createLensAction(mContext, mContext.getResources(), uri,
                    smartActionsEnabled);
            mImageData.quickShareAction = createQuickShareAction(
                    mQuickShareData.quickShareAction, mScreenshotId, uri, mImageTime, image,
                    user);
            mImageData.subject = getSubjectString(mImageTime);

            mParams.mActionsReadyListener.onActionsReady(mImageData);
            if (DEBUG_CALLBACK) {
                Log.d(TAG, "finished background processing, Calling (Consumer<Uri>) "
                        + "finisher.accept(\"" + mImageData.uri + "\"");
            }
            mParams.finisher.accept(mImageData.uri);
            mParams.image = null;
        } catch (Exception e) {
            // IOException/UnsupportedOperationException may be thrown if external storage is
            // not mounted
            if (DEBUG_STORAGE) {
                Log.d(TAG, "Failed to store screenshot", e);
            }
            mParams.clearImage();
            mImageData.reset();
            mQuickShareData.reset();
            mParams.mActionsReadyListener.onActionsReady(mImageData);
            if (DEBUG_CALLBACK) {
                Log.d(TAG, "Calling (Consumer<Uri>) finisher.accept(null)");
            }
            mParams.finisher.accept(null);
        }

        return null;
    }

    /**
     * Update the listener run when the saving task completes. Used to avoid showing UI for the
     * first screenshot when a second one is taken.
     */
    void setActionsReadyListener(ScreenshotController.ActionsReadyListener listener) {
        mParams.mActionsReadyListener = listener;
    }

    @Override
    protected void onCancelled(Void params) {
        // If we are cancelled while the task is running in the background, we may get null
        // params. The finisher is expected to always be called back, so just use the baked-in
        // params from the ctor in any case.
        mImageData.reset();
        mQuickShareData.reset();
        mParams.mActionsReadyListener.onActionsReady(mImageData);
        if (DEBUG_CALLBACK) {
            Log.d(TAG, "onCancelled, calling (Consumer<Uri>) finisher.accept(null)");
        }
        mParams.finisher.accept(null);
        mParams.clearImage();
    }

    @VisibleForTesting
    Supplier<ActionTransition> createViewAction(Context context, Resources r, Uri uri) {
        return () -> {
            ActionTransition transition = mSharedElementTransition.get();
            // Note: the view, share and edit actions are proxied through ActionProxyReceiver in
            // order to do some common work like dismissing the keyguard and sending
            // closeSystemWindows

            // Create an edit intent, if a specific package is provided as the editor, then
            // launch that directly
            Intent viewIntent = new Intent(Intent.ACTION_VIEW);
            viewIntent.setDataAndType(uri, "image/png");
            viewIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            viewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

            PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
                    context, 0, viewIntent, PendingIntent.FLAG_IMMUTABLE,
                    transition.bundle, UserHandle.CURRENT);

            // Make sure pending intents for the system user are still unique across users
            // by setting the (otherwise unused) request code to the current user id.
            int requestCode = mContext.getUserId();

            // Create a view action
            PendingIntent viewAction = PendingIntent.getBroadcastAsUser(context, requestCode,
                    new Intent(context, ActionProxyReceiver.class)
                            .putExtra(ScreenshotController.EXTRA_ACTION_INTENT, pendingIntent)
                            .putExtra(ScreenshotController.EXTRA_ID, mScreenshotId)
                            .putExtra(ScreenshotController.EXTRA_SMART_ACTIONS_ENABLED,
                                    true)
                            .putExtra(ScreenshotController.EXTRA_OVERRIDE_TRANSITION, true)
                            .setAction(Intent.ACTION_VIEW)
                            .addFlags(Intent.FLAG_RECEIVER_FOREGROUND),
                    PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE,
                    UserHandle.SYSTEM);
            Notification.Action.Builder editActionBuilder = new Notification.Action.Builder(
                    Icon.createWithResource(r, com.android.internal.R.drawable.ic_screenshot),
                    r.getString(com.android.internal.R.string.global_action_screenshot),
                    viewAction);

            transition.action = editActionBuilder.build();
            return transition;
        };
    }

    /**
     * Assumes that the action intent is sent immediately after being supplied.
     */
    @VisibleForTesting
    Supplier<ActionTransition> createShareAction(Context context, Resources r, Uri uri,
            boolean smartActionsEnabled) {
        return () -> {
            ActionTransition transition = mSharedElementTransition.get();

            // Note: Both the share and edit actions are proxied through ActionProxyReceiver in
            // order to do some common work like dismissing the keyguard and sending
            // closeSystemWindows

            // Create a share intent, this will always go through the chooser activity first
            // which should not trigger auto-enter PiP
            Intent sharingIntent = new Intent(Intent.ACTION_SEND);
            sharingIntent.setDataAndType(uri, "image/png");
            sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
            // Include URI in ClipData also, so that grantPermission picks it up.
            // We don't use setData here because some apps interpret this as "to:".
            ClipData clipdata = new ClipData(new ClipDescription("content",
                    new String[]{ClipDescription.MIMETYPE_TEXT_PLAIN}),
                    new ClipData.Item(uri));
            sharingIntent.setClipData(clipdata);
            sharingIntent.putExtra(Intent.EXTRA_SUBJECT, getSubjectString(mImageTime));
            sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                    .addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);


            // Make sure pending intents for the system user are still unique across users
            // by setting the (otherwise unused) request code to the current user id.
            int requestCode = context.getUserId();

            Intent sharingChooserIntent = Intent.createChooser(sharingIntent, null)
                    .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK)
                    .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);


            // cancel current pending intent (if any) since clipData isn't used for matching
            PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
                    context, 0, sharingChooserIntent,
                    PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE,
                    transition.bundle, UserHandle.CURRENT);

            // Create a share action for the notification
            PendingIntent shareAction = PendingIntent.getBroadcastAsUser(context, requestCode,
                    new Intent(context, ActionProxyReceiver.class)
                            .putExtra(ScreenshotController.EXTRA_ACTION_INTENT, pendingIntent)
                            .putExtra(ScreenshotController.EXTRA_DISALLOW_ENTER_PIP, true)
                            .putExtra(ScreenshotController.EXTRA_ID, mScreenshotId)
                            .putExtra(ScreenshotController.EXTRA_SMART_ACTIONS_ENABLED,
                                    smartActionsEnabled)
                            .setAction(Intent.ACTION_SEND)
                            .addFlags(Intent.FLAG_RECEIVER_FOREGROUND),
                    PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE,
                    UserHandle.SYSTEM);

            Notification.Action.Builder shareActionBuilder = new Notification.Action.Builder(
                    Icon.createWithResource(r, R.drawable.ic_screenshot_share),
                    r.getString(com.android.internal.R.string.share), shareAction);

            transition.action = shareActionBuilder.build();
            return transition;
        };
    }

    @VisibleForTesting
    Supplier<ActionTransition> createEditAction(Context context, Resources r, Uri uri,
            boolean smartActionsEnabled) {
        return () -> {
            ActionTransition transition = mSharedElementTransition.get();
            // Note: Both the share and edit actions are proxied through ActionProxyReceiver in
            // order to do some common work like dismissing the keyguard and sending
            // closeSystemWindows

            // Create an edit intent, if a specific package is provided as the editor, then
            // launch that directly
            String editorPackage = context.getString(R.string.config_screenshotEditor);
            Intent editIntent = new Intent(Intent.ACTION_EDIT);
            if (!TextUtils.isEmpty(editorPackage)) {
                editIntent.setComponent(ComponentName.unflattenFromString(editorPackage));
            }
            editIntent.setDataAndType(uri, "image/png");
            editIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            editIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            editIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

            PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
                    context, 0, editIntent, PendingIntent.FLAG_IMMUTABLE,
                    transition.bundle, UserHandle.CURRENT);

            // Make sure pending intents for the system user are still unique across users
            // by setting the (otherwise unused) request code to the current user id.
            int requestCode = mContext.getUserId();

            // Create an edit action
            PendingIntent editAction = PendingIntent.getBroadcastAsUser(context, requestCode,
                    new Intent(context, ActionProxyReceiver.class)
                            .putExtra(ScreenshotController.EXTRA_ACTION_INTENT, pendingIntent)
                            .putExtra(ScreenshotController.EXTRA_ID, mScreenshotId)
                            .putExtra(ScreenshotController.EXTRA_SMART_ACTIONS_ENABLED,
                                    smartActionsEnabled)
                            .putExtra(ScreenshotController.EXTRA_OVERRIDE_TRANSITION, true)
                            .setAction(Intent.ACTION_EDIT)
                            .addFlags(Intent.FLAG_RECEIVER_FOREGROUND),
                    PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE,
                    UserHandle.SYSTEM);
            Notification.Action.Builder editActionBuilder = new Notification.Action.Builder(
                    Icon.createWithResource(r, R.drawable.ic_screenshot_edit),
                    r.getString(com.android.internal.R.string.screenshot_edit), editAction);

            transition.action = editActionBuilder.build();
            return transition;
        };
    }

    @VisibleForTesting
    Notification.Action createDeleteAction(Context context, Resources r, Uri uri,
            boolean smartActionsEnabled) {
        // Make sure pending intents for the system user are still unique across users
        // by setting the (otherwise unused) request code to the current user id.
        int requestCode = mContext.getUserId();

        // Create a delete action for the notification
        PendingIntent deleteAction = PendingIntent.getBroadcast(context, requestCode,
                new Intent(context, DeleteScreenshotReceiver.class)
                        .putExtra(ScreenshotController.SCREENSHOT_URI_ID, uri.toString())
                        .putExtra(ScreenshotController.EXTRA_ID, mScreenshotId)
                        .putExtra(ScreenshotController.EXTRA_SMART_ACTIONS_ENABLED,
                                smartActionsEnabled)
                        .addFlags(Intent.FLAG_RECEIVER_FOREGROUND),
                PendingIntent.FLAG_CANCEL_CURRENT
                        | PendingIntent.FLAG_ONE_SHOT
                        | PendingIntent.FLAG_IMMUTABLE);
        Notification.Action.Builder deleteActionBuilder = new Notification.Action.Builder(
                Icon.createWithResource(r, R.drawable.ic_screenshot_delete),
                r.getString(com.android.internal.R.string.delete), deleteAction);

        return deleteActionBuilder.build();
    }

    Notification.Action createLensAction(Context context, Resources r, Uri uri,
            boolean smartActionsEnabled) {
        // Make sure pending intents for the system user are still unique across users
        // by setting the (otherwise unused) request code to the current user id.
        int requestCode = mContext.getUserId();

        // Create a lens action for the notification
        PendingIntent lensAction = PendingIntent.getBroadcast(context, requestCode,
                new Intent(context, LensScreenshotReceiver.class)
                        .putExtra(ScreenshotController.SCREENSHOT_URI_ID, uri.toString())
                        .putExtra(ScreenshotController.EXTRA_ID, mScreenshotId)
                        .putExtra(ScreenshotController.EXTRA_SMART_ACTIONS_ENABLED,
                                smartActionsEnabled)
                        .addFlags(Intent.FLAG_RECEIVER_FOREGROUND),
                PendingIntent.FLAG_CANCEL_CURRENT
                        | PendingIntent.FLAG_ONE_SHOT
                        | PendingIntent.FLAG_IMMUTABLE);
        Notification.Action.Builder lensActionBuilder = new Notification.Action.Builder(
                Icon.createWithResource(r, R.drawable.ic_screenshot_lensss),
                r.getString(R.string.lensss), lensAction);

        return lensActionBuilder.build();
    }

    private UserHandle getUserHandleOfForegroundApplication(Context context) {
        UserManager manager = UserManager.get(context);
        int result;
        // This logic matches
        // com.android.systemui.statusbar.phone.PhoneStatusBarPolicy#updateManagedProfile
        try {
            result = ActivityTaskManager.getService().getLastResumedActivityUserId();
        } catch (RemoteException e) {
            if (DEBUG_ACTIONS) {
                Log.d(TAG, "Failed to get UserHandle of foreground app: ", e);
            }
            result = context.getUserId();
        }
        UserInfo userInfo = manager.getUserInfo(result);
        return userInfo.getUserHandle();
    }

    private List<Notification.Action> buildSmartActions(
            List<Notification.Action> actions, Context context) {
        List<Notification.Action> broadcastActions = new ArrayList<>();
        for (Notification.Action action : actions) {
            // Proxy smart actions through {@link SmartActionsReceiver} for logging smart actions.
            Bundle extras = action.getExtras();
            String actionType = extras.getString(
                    ScreenshotNotificationSmartActionsProvider.ACTION_TYPE,
                    ScreenshotNotificationSmartActionsProvider.DEFAULT_ACTION_TYPE);
            Intent intent = new Intent(context, SmartActionsReceiver.class)
                    .putExtra(ScreenshotController.EXTRA_ACTION_INTENT, action.actionIntent)
                    .addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
            addIntentExtras(mScreenshotId, intent, actionType, true /* smartActionsEnabled */);
            PendingIntent broadcastIntent = PendingIntent.getBroadcast(context,
                    mRandom.nextInt(),
                    intent,
                    PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
            broadcastActions.add(new Notification.Action.Builder(action.getIcon(), action.title,
                    broadcastIntent).setContextual(true).addExtras(extras).build());
        }
        return broadcastActions;
    }

    private static void addIntentExtras(String screenshotId, Intent intent, String actionType,
            boolean smartActionsEnabled) {
        intent
                .putExtra(ScreenshotController.EXTRA_ACTION_TYPE, actionType)
                .putExtra(ScreenshotController.EXTRA_ID, screenshotId)
                .putExtra(ScreenshotController.EXTRA_SMART_ACTIONS_ENABLED, smartActionsEnabled);
    }

    /**
     * Wrap the quickshare intent and populate the fillin intent with the URI
     */
    @VisibleForTesting
    Notification.Action createQuickShareAction(
            Notification.Action quickShare, String screenshotId, Uri uri, long imageTime,
            Bitmap image, UserHandle user) {
        if (quickShare == null) {
            return null;
        } else if (quickShare.actionIntent.isImmutable()) {
            Notification.Action quickShareWithUri =
                    queryQuickShareAction(screenshotId, image, user, uri);
            if (quickShareWithUri == null
                    || !quickShareWithUri.title.toString().contentEquals(quickShare.title)) {
                return null;
            }
            quickShare = quickShareWithUri;
        }

        Intent wrappedIntent = new Intent(mContext, SmartActionsReceiver.class)
                .putExtra(ScreenshotController.EXTRA_ACTION_INTENT, quickShare.actionIntent)
                .putExtra(ScreenshotController.EXTRA_ACTION_INTENT_FILLIN,
                        createFillInIntent(uri, imageTime))
                .addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        Bundle extras = quickShare.getExtras();
        String actionType = extras.getString(
                ScreenshotNotificationSmartActionsProvider.ACTION_TYPE,
                ScreenshotNotificationSmartActionsProvider.DEFAULT_ACTION_TYPE);
        // We only query for quick share actions when smart actions are enabled, so we can assert
        // that it's true here.
        addIntentExtras(screenshotId, wrappedIntent, actionType, true /* smartActionsEnabled */);
        PendingIntent broadcastIntent =
                PendingIntent.getBroadcast(mContext, mRandom.nextInt(), wrappedIntent,
                        PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
        return new Notification.Action.Builder(quickShare.getIcon(), quickShare.title,
                broadcastIntent)
                .setContextual(true)
                .addExtras(extras)
                .build();
    }

    private Intent createFillInIntent(Uri uri, long imageTime) {
        Intent fillIn = new Intent();
        fillIn.setType("image/png");
        fillIn.putExtra(Intent.EXTRA_STREAM, uri);
        fillIn.putExtra(Intent.EXTRA_SUBJECT, getSubjectString(imageTime));
        // Include URI in ClipData also, so that grantPermission picks it up.
        // We don't use setData here because some apps interpret this as "to:".
        ClipData clipData = new ClipData(
                new ClipDescription("content", new String[]{"image/png"}),
                new ClipData.Item(uri));
        fillIn.setClipData(clipData);
        fillIn.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        return fillIn;
    }

    /**
     * Query and surface Quick Share chip if it is available. Action intent would not be used,
     * because it does not contain image URL which would be populated in {@link
     * #createQuickShareAction(Notification.Action, String, Uri, long, Bitmap, UserHandle)}
     */

    @VisibleForTesting
    Notification.Action queryQuickShareAction(
            String screenshotId, Bitmap image, UserHandle user, Uri uri) {
        CompletableFuture<List<Notification.Action>> quickShareActionsFuture =
                mScreenshotSmartActions.getSmartActionsFuture(
                        screenshotId, uri, image, mSmartActionsProvider,
                        ScreenshotSmartActionType.QUICK_SHARE_ACTION,
                        true /* smartActionsEnabled */, user);
        int timeoutMs = DeviceConfig.getInt(
                DeviceConfig.NAMESPACE_SYSTEMUI,
                SystemUiDeviceConfigFlags.SCREENSHOT_NOTIFICATION_QUICK_SHARE_ACTIONS_TIMEOUT_MS,
                500);
        List<Notification.Action> quickShareActions =
                mScreenshotSmartActions.getSmartActions(
                        screenshotId, quickShareActionsFuture, timeoutMs,
                        mSmartActionsProvider,
                        ScreenshotSmartActionType.QUICK_SHARE_ACTION);
        if (!quickShareActions.isEmpty()) {
            return quickShareActions.get(0);
        }
        return null;
    }

    private static String getSubjectString(long imageTime) {
        String subjectDate = DateFormat.getDateTimeInstance().format(new Date(imageTime));
        return String.format(SCREENSHOT_SHARE_SUBJECT_TEMPLATE, subjectDate);
    }
}