Debian Codegraph @

core/java/com/android/internal/app/ChooserActivity.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2008 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 com.android.internal.app;
18
19 import static android.app.admin.DevicePolicyResources.Strings.Core.RESOLVER_CANT_ACCESS_PERSONAL;
20 import static android.app.admin.DevicePolicyResources.Strings.Core.RESOLVER_CANT_ACCESS_WORK;
21 import static android.app.admin.DevicePolicyResources.Strings.Core.RESOLVER_CANT_SHARE_WITH_PERSONAL;
22 import static android.app.admin.DevicePolicyResources.Strings.Core.RESOLVER_CANT_SHARE_WITH_WORK;
23 import static android.app.admin.DevicePolicyResources.Strings.Core.RESOLVER_CROSS_PROFILE_BLOCKED_TITLE;
24 import static android.stats.devicepolicy.DevicePolicyEnums.RESOLVER_EMPTY_STATE_NO_SHARING_TO_PERSONAL;
25 import static android.stats.devicepolicy.DevicePolicyEnums.RESOLVER_EMPTY_STATE_NO_SHARING_TO_WORK;
26
27 import static com.android.internal.util.LatencyTracker.ACTION_LOAD_SHARE_SHEET;
28
29 import static java.lang.annotation.RetentionPolicy.SOURCE;
30
31 import android.animation.Animator;
32 import android.animation.AnimatorListenerAdapter;
33 import android.animation.AnimatorSet;
34 import android.animation.ObjectAnimator;
35 import android.animation.ValueAnimator;
36 import android.annotation.IntDef;
37 import android.annotation.NonNull;
38 import android.annotation.Nullable;
39 import android.app.Activity;
40 import android.app.ActivityManager;
41 import android.app.ActivityOptions;
42 import android.app.SharedElementCallback;
43 import android.app.prediction.AppPredictionContext;
44 import android.app.prediction.AppPredictionManager;
45 import android.app.prediction.AppPredictor;
46 import android.app.prediction.AppTarget;
47 import android.app.prediction.AppTargetEvent;
48 import android.app.prediction.AppTargetId;
49 import android.compat.annotation.UnsupportedAppUsage;
50 import android.content.ClipData;
51 import android.content.ClipboardManager;
52 import android.content.ComponentName;
53 import android.content.ContentResolver;
54 import android.content.Context;
55 import android.content.Intent;
56 import android.content.IntentFilter;
57 import android.content.IntentSender;
58 import android.content.IntentSender.SendIntentException;
59 import android.content.SharedPreferences;
60 import android.content.pm.ActivityInfo;
61 import android.content.pm.ApplicationInfo;
62 import android.content.pm.PackageManager;
63 import android.content.pm.PackageManager.NameNotFoundException;
64 import android.content.pm.ResolveInfo;
65 import android.content.pm.ShortcutInfo;
66 import android.content.pm.ShortcutManager;
67 import android.content.res.Configuration;
68 import android.content.res.Resources;
69 import android.database.Cursor;
70 import android.database.DataSetObserver;
71 import android.graphics.Bitmap;
72 import android.graphics.Canvas;
73 import android.graphics.Color;
74 import android.graphics.Insets;
75 import android.graphics.Paint;
76 import android.graphics.Path;
77 import android.graphics.drawable.AnimatedVectorDrawable;
78 import android.graphics.drawable.Drawable;
79 import android.metrics.LogMaker;
80 import android.net.Uri;
81 import android.os.AsyncTask;
82 import android.os.Bundle;
83 import android.os.Environment;
84 import android.os.Handler;
85 import android.os.Message;
86 import android.os.Parcelable;
87 import android.os.PatternMatcher;
88 import android.os.ResultReceiver;
89 import android.os.UserHandle;
90 import android.os.UserManager;
91 import android.os.storage.StorageManager;
92 import android.provider.DeviceConfig;
93 import android.provider.DocumentsContract;
94 import android.provider.Downloads;
95 import android.provider.OpenableColumns;
96 import android.provider.Settings;
97 import android.service.chooser.ChooserTarget;
98 import android.text.TextUtils;
99 import android.util.AttributeSet;
100 import android.util.HashedStringCache;
101 import android.util.Log;
102 import android.util.PluralsMessageFormatter;
103 import android.util.Size;
104 import android.util.Slog;
105 import android.view.LayoutInflater;
106 import android.view.View;
107 import android.view.View.MeasureSpec;
108 import android.view.View.OnClickListener;
109 import android.view.ViewGroup;
110 import android.view.ViewGroup.LayoutParams;
111 import android.view.ViewTreeObserver;
112 import android.view.WindowInsets;
113 import android.view.animation.AccelerateInterpolator;
114 import android.view.animation.AlphaAnimation;
115 import android.view.animation.Animation;
116 import android.view.animation.DecelerateInterpolator;
117 import android.view.animation.LinearInterpolator;
118 import android.widget.Button;
119 import android.widget.ImageView;
120 import android.widget.Space;
121 import android.widget.TextView;
122
123 import com.android.internal.R;
124 import com.android.internal.annotations.VisibleForTesting;
125 import com.android.internal.app.AbstractMultiProfilePagerAdapter.EmptyState;
126 import com.android.internal.app.AbstractMultiProfilePagerAdapter.EmptyStateProvider;
127 import com.android.internal.app.NoCrossProfileEmptyStateProvider.DevicePolicyBlockerEmptyState;
128 import com.android.internal.app.ResolverListAdapter.ActivityInfoPresentationGetter;
129 import com.android.internal.app.ResolverListAdapter.ViewHolder;
130 import com.android.internal.app.chooser.ChooserTargetInfo;
131 import com.android.internal.app.chooser.DisplayResolveInfo;
132 import com.android.internal.app.chooser.MultiDisplayResolveInfo;
133 import com.android.internal.app.chooser.NotSelectableTargetInfo;
134 import com.android.internal.app.chooser.SelectableTargetInfo;
135 import com.android.internal.app.chooser.SelectableTargetInfo.SelectableTargetInfoCommunicator;
136 import com.android.internal.app.chooser.TargetInfo;
137 import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
138 import com.android.internal.content.PackageMonitor;
139 import com.android.internal.logging.MetricsLogger;
140 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
141 import com.android.internal.util.FrameworkStatsLog;
142 import com.android.internal.widget.GridLayoutManager;
143 import com.android.internal.widget.RecyclerView;
144 import com.android.internal.widget.ResolverDrawerLayout;
145 import com.android.internal.widget.ViewPager;
146
147 import com.google.android.collect.Lists;
148
149 import java.io.File;
150 import java.io.IOException;
151 import java.lang.annotation.Retention;
152 import java.lang.annotation.RetentionPolicy;
153 import java.net.URISyntaxException;
154 import java.text.Collator;
155 import java.util.ArrayList;
156 import java.util.Arrays;
157 import java.util.Collections;
158 import java.util.Comparator;
159 import java.util.HashMap;
160 import java.util.List;
161 import java.util.Map;
162 import java.util.Objects;
163 import java.util.function.Supplier;
164
165 /**
166 * The Chooser Activity handles intent resolution specifically for sharing intents -
167 * for example, those generated by @see android.content.Intent#createChooser(Intent, CharSequence).
168 *
169 */
170 public class ChooserActivity extends ResolverActivity implements
171 ChooserListAdapter.ChooserListCommunicator,
172 SelectableTargetInfoCommunicator {
173 private static final String TAG = "ChooserActivity";
174
175 private AppPredictor mPersonalAppPredictor;
176 private AppPredictor mWorkAppPredictor;
177 private boolean mShouldDisplayLandscape;
178
179 @UnsupportedAppUsage
180 public ChooserActivity() {
181 }
182 /**
183 * Boolean extra to change the following behavior: Normally, ChooserActivity finishes itself
184 * in onStop when launched in a new task. If this extra is set to true, we do not finish
185 * ourselves when onStop gets called.
186 */
187 public static final String EXTRA_PRIVATE_RETAIN_IN_ON_STOP
188 = "com.android.internal.app.ChooserActivity.EXTRA_PRIVATE_RETAIN_IN_ON_STOP";
189
190
191 /**
192 * Transition name for the first image preview.
193 * To be used for shared element transition into this activity.
194 * @hide
195 */
196 public static final String FIRST_IMAGE_PREVIEW_TRANSITION_NAME = "screenshot_preview_image";
197
198 private static final String PREF_NUM_SHEET_EXPANSIONS = "pref_num_sheet_expansions";
199
200 private static final String CHIP_LABEL_METADATA_KEY = "android.service.chooser.chip_label";
201 private static final String CHIP_ICON_METADATA_KEY = "android.service.chooser.chip_icon";
202
203 private static final boolean DEBUG = true;
204
205 private static final boolean USE_PREDICTION_MANAGER_FOR_SHARE_ACTIVITIES = true;
206 // TODO(b/123088566) Share these in a better way.
207 private static final String APP_PREDICTION_SHARE_UI_SURFACE = "share";
208 public static final String LAUNCH_LOCATION_DIRECT_SHARE = "direct_share";
209 public static final String CHOOSER_TARGET = "chooser_target";
210 private static final String SHORTCUT_TARGET = "shortcut_target";
211 private static final int APP_PREDICTION_SHARE_TARGET_QUERY_PACKAGE_LIMIT = 20;
212 public static final String APP_PREDICTION_INTENT_FILTER_KEY = "intent_filter";
213 private static final String SHARED_TEXT_KEY = "shared_text";
214
215 private static final String PLURALS_COUNT = "count";
216 private static final String PLURALS_FILE_NAME = "file_name";
217
218 private static final String IMAGE_EDITOR_SHARED_ELEMENT = "screenshot_preview_image";
219
220 private boolean mIsAppPredictorComponentAvailable;
221 private Map<ChooserTarget, AppTarget> mDirectShareAppTargetCache;
222 private Map<ChooserTarget, ShortcutInfo> mDirectShareShortcutInfoCache;
223
224 public static final int TARGET_TYPE_DEFAULT = 0;
225 public static final int TARGET_TYPE_CHOOSER_TARGET = 1;
226 public static final int TARGET_TYPE_SHORTCUTS_FROM_SHORTCUT_MANAGER = 2;
227 public static final int TARGET_TYPE_SHORTCUTS_FROM_PREDICTION_SERVICE = 3;
228
229 public static final int SELECTION_TYPE_SERVICE = 1;
230 public static final int SELECTION_TYPE_APP = 2;
231 public static final int SELECTION_TYPE_STANDARD = 3;
232 public static final int SELECTION_TYPE_COPY = 4;
233 public static final int SELECTION_TYPE_NEARBY = 5;
234 public static final int SELECTION_TYPE_EDIT = 6;
235
236 private static final int SCROLL_STATUS_IDLE = 0;
237 private static final int SCROLL_STATUS_SCROLLING_VERTICAL = 1;
238 private static final int SCROLL_STATUS_SCROLLING_HORIZONTAL = 2;
239
240 // statsd logger wrapper
241 protected ChooserActivityLogger mChooserActivityLogger;
242
243 @IntDef(flag = false, prefix = { "TARGET_TYPE_" }, value = {
244 TARGET_TYPE_DEFAULT,
245 TARGET_TYPE_CHOOSER_TARGET,
246 TARGET_TYPE_SHORTCUTS_FROM_SHORTCUT_MANAGER,
247 TARGET_TYPE_SHORTCUTS_FROM_PREDICTION_SERVICE
248 })
249 @Retention(RetentionPolicy.SOURCE)
250 public @interface ShareTargetType {}
251
252 /**
253 * The transition time between placeholders for direct share to a message
254 * indicating that non are available.
255 */
256 private static final int NO_DIRECT_SHARE_ANIM_IN_MILLIS = 200;
257
258 private static final float DIRECT_SHARE_EXPANSION_RATE = 0.78f;
259
260 private static final int DEFAULT_SALT_EXPIRATION_DAYS = 7;
261 private int mMaxHashSaltDays = DeviceConfig.getInt(DeviceConfig.NAMESPACE_SYSTEMUI,
262 SystemUiDeviceConfigFlags.HASH_SALT_MAX_DAYS,
263 DEFAULT_SALT_EXPIRATION_DAYS);
264
265 private static final boolean DEFAULT_IS_NEARBY_SHARE_FIRST_TARGET_IN_RANKED_APP = false;
266 private boolean mIsNearbyShareFirstTargetInRankedApp =
267 DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_SYSTEMUI,
268 SystemUiDeviceConfigFlags.IS_NEARBY_SHARE_FIRST_TARGET_IN_RANKED_APP,
269 DEFAULT_IS_NEARBY_SHARE_FIRST_TARGET_IN_RANKED_APP);
270
271 private static final int DEFAULT_LIST_VIEW_UPDATE_DELAY_MS = 0;
272
273 private static final int URI_PERMISSION_INTENT_FLAGS = Intent.FLAG_GRANT_READ_URI_PERMISSION
274 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
275 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
276 | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
277
278 @VisibleForTesting
279 int mListViewUpdateDelayMs = DeviceConfig.getInt(DeviceConfig.NAMESPACE_SYSTEMUI,
280 SystemUiDeviceConfigFlags.SHARESHEET_LIST_VIEW_UPDATE_DELAY,
281 DEFAULT_LIST_VIEW_UPDATE_DELAY_MS);
282
283 private Bundle mReplacementExtras;
284 private IntentSender mChosenComponentSender;
285 private IntentSender mRefinementIntentSender;
286 private RefinementResultReceiver mRefinementResultReceiver;
287 private ChooserTarget[] mCallerChooserTargets;
288 private ComponentName[] mFilteredComponentNames;
289
290 private Intent mReferrerFillInIntent;
291
292 private long mChooserShownTime;
293 protected boolean mIsSuccessfullySelected;
294
295 private long mQueriedSharingShortcutsTimeMs;
296
297 private int mCurrAvailableWidth = 0;
298 private Insets mLastAppliedInsets = null;
299 private int mLastNumberOfChildren = -1;
300 private int mMaxTargetsPerRow = 1;
301
302 private static final String TARGET_DETAILS_FRAGMENT_TAG = "targetDetailsFragment";
303
304 private static final int MAX_LOG_RANK_POSITION = 12;
305
306 private static final int MAX_EXTRA_INITIAL_INTENTS = 2;
307 private static final int MAX_EXTRA_CHOOSER_TARGETS = 2;
308
309 private SharedPreferences mPinnedSharedPrefs;
310 private static final String PINNED_SHARED_PREFS_NAME = "chooser_pin_settings";
311
312 @Retention(SOURCE)
313 @IntDef({CONTENT_PREVIEW_FILE, CONTENT_PREVIEW_IMAGE, CONTENT_PREVIEW_TEXT})
314 private @interface ContentPreviewType {
315 }
316
317 // Starting at 1 since 0 is considered "undefined" for some of the database transformations
318 // of tron logs.
319 protected static final int CONTENT_PREVIEW_IMAGE = 1;
320 protected static final int CONTENT_PREVIEW_FILE = 2;
321 protected static final int CONTENT_PREVIEW_TEXT = 3;
322 protected MetricsLogger mMetricsLogger;
323
324 private ContentPreviewCoordinator mPreviewCoord;
325 private int mScrollStatus = SCROLL_STATUS_IDLE;
326
327 @VisibleForTesting
328 protected ChooserMultiProfilePagerAdapter mChooserMultiProfilePagerAdapter;
329 private final EnterTransitionAnimationDelegate mEnterTransitionAnimationDelegate =
330 new EnterTransitionAnimationDelegate();
331
332 private boolean mRemoveSharedElements = false;
333
334 private View mContentView = null;
335
336 private class ContentPreviewCoordinator {
337 private static final int IMAGE_FADE_IN_MILLIS = 150;
338 private static final int IMAGE_LOAD_TIMEOUT = 1;
339 private static final int IMAGE_LOAD_INTO_VIEW = 2;
340
341 private final int mImageLoadTimeoutMillis =
342 getResources().getInteger(R.integer.config_shortAnimTime);
343
344 private final View mParentView;
345 private boolean mHideParentOnFail;
346 private boolean mAtLeastOneLoaded = false;
347
348 class LoadUriTask {
349 public final Uri mUri;
350 public final int mImageResourceId;
351 public final int mExtraCount;
352 public final Bitmap mBmp;
353
354 LoadUriTask(int imageResourceId, Uri uri, int extraCount, Bitmap bmp) {
355 this.mImageResourceId = imageResourceId;
356 this.mUri = uri;
357 this.mExtraCount = extraCount;
358 this.mBmp = bmp;
359 }
360 }
361
362 // If at least one image loads within the timeout period, allow other
363 // loads to continue. Otherwise terminate and optionally hide
364 // the parent area
365 private final Handler mHandler = new Handler() {
366 @Override
367 public void handleMessage(Message msg) {
368 switch (msg.what) {
369 case IMAGE_LOAD_TIMEOUT:
370 maybeHideContentPreview();
371 break;
372
373 case IMAGE_LOAD_INTO_VIEW:
374 if (isFinishing()) break;
375
376 LoadUriTask task = (LoadUriTask) msg.obj;
377 RoundedRectImageView imageView = mParentView.findViewById(
378 task.mImageResourceId);
379 if (task.mBmp == null) {
380 imageView.setVisibility(View.GONE);
381 maybeHideContentPreview();
382 return;
383 }
384
385 mAtLeastOneLoaded = true;
386 imageView.setVisibility(View.VISIBLE);
387 imageView.setAlpha(0.0f);
388 imageView.setImageBitmap(task.mBmp);
389
390 ValueAnimator fadeAnim = ObjectAnimator.ofFloat(imageView, "alpha", 0.0f,
391 1.0f);
392 fadeAnim.setInterpolator(new DecelerateInterpolator(1.0f));
393 fadeAnim.setDuration(IMAGE_FADE_IN_MILLIS);
394 fadeAnim.start();
395
396 if (task.mExtraCount > 0) {
397 imageView.setExtraImageCount(task.mExtraCount);
398 }
399
400 setupPreDrawForSharedElementTransition(imageView);
401 }
402 }
403 };
404
405 private void setupPreDrawForSharedElementTransition(View v) {
406 v.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
407 @Override
408 public boolean onPreDraw() {
409 v.getViewTreeObserver().removeOnPreDrawListener(this);
410
411 if (!mRemoveSharedElements && isActivityTransitionRunning()) {
412 // Disable the window animations as it interferes with the
413 // transition animation.
414 getWindow().setWindowAnimations(0);
415 }
416 mEnterTransitionAnimationDelegate.markImagePreviewReady();
417 return true;
418 }
419 });
420 }
421
422 ContentPreviewCoordinator(View parentView, boolean hideParentOnFail) {
423 super();
424
425 this.mParentView = parentView;
426 this.mHideParentOnFail = hideParentOnFail;
427 }
428
429 private void loadUriIntoView(final int imageResourceId, final Uri uri,
430 final int extraImages) {
431 mHandler.sendEmptyMessageDelayed(IMAGE_LOAD_TIMEOUT, mImageLoadTimeoutMillis);
432
433 AsyncTask.THREAD_POOL_EXECUTOR.execute(() -> {
434 int size = getResources().getDimensionPixelSize(
435 R.dimen.chooser_preview_image_max_dimen);
436 final Bitmap bmp = loadThumbnail(uri, new Size(size, size));
437 final Message msg = Message.obtain();
438 msg.what = IMAGE_LOAD_INTO_VIEW;
439 msg.obj = new LoadUriTask(imageResourceId, uri, extraImages, bmp);
440 mHandler.sendMessage(msg);
441 });
442 }
443
444 private void cancelLoads() {
445 mHandler.removeMessages(IMAGE_LOAD_INTO_VIEW);
446 mHandler.removeMessages(IMAGE_LOAD_TIMEOUT);
447 }
448
449 private void maybeHideContentPreview() {
450 if (!mAtLeastOneLoaded) {
451 if (mHideParentOnFail) {
452 Log.i(TAG, "Hiding image preview area. Timed out waiting for preview to load"
453 + " within " + mImageLoadTimeoutMillis + "ms.");
454 collapseParentView();
455 if (shouldShowTabs()) {
456 hideStickyContentPreview();
457 } else if (mChooserMultiProfilePagerAdapter.getCurrentRootAdapter() != null) {
458 mChooserMultiProfilePagerAdapter.getCurrentRootAdapter()
459 .hideContentPreview();
460 }
461 mHideParentOnFail = false;
462 }
463 mRemoveSharedElements = true;
464 mEnterTransitionAnimationDelegate.markImagePreviewReady();
465 }
466 }
467
468 private void collapseParentView() {
469 // This will effectively hide the content preview row by forcing the height
470 // to zero. It is faster than forcing a relayout of the listview
471 final View v = mParentView;
472 int widthSpec = MeasureSpec.makeMeasureSpec(v.getWidth(), MeasureSpec.EXACTLY);
473 int heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.EXACTLY);
474 v.measure(widthSpec, heightSpec);
475 v.getLayoutParams().height = 0;
476 v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getTop());
477 v.invalidate();
478 }
479 }
480
481 private final ChooserHandler mChooserHandler = new ChooserHandler();
482
483 private class ChooserHandler extends Handler {
484 private static final int LIST_VIEW_UPDATE_MESSAGE = 6;
485 private static final int SHORTCUT_MANAGER_ALL_SHARE_TARGET_RESULTS = 7;
486
487 private void removeAllMessages() {
488 removeMessages(LIST_VIEW_UPDATE_MESSAGE);
489 removeMessages(SHORTCUT_MANAGER_ALL_SHARE_TARGET_RESULTS);
490 }
491
492 @Override
493 public void handleMessage(Message msg) {
494 if (mChooserMultiProfilePagerAdapter.getActiveListAdapter() == null || isDestroyed()) {
495 return;
496 }
497
498 switch (msg.what) {
499 case LIST_VIEW_UPDATE_MESSAGE:
500 if (DEBUG) {
501 Log.d(TAG, "LIST_VIEW_UPDATE_MESSAGE; ");
502 }
503
504 UserHandle userHandle = (UserHandle) msg.obj;
505 mChooserMultiProfilePagerAdapter.getListAdapterForUserHandle(userHandle)
506 .refreshListView();
507 break;
508
509 case SHORTCUT_MANAGER_ALL_SHARE_TARGET_RESULTS:
510 if (DEBUG) Log.d(TAG, "SHORTCUT_MANAGER_ALL_SHARE_TARGET_RESULTS");
511 final ServiceResultInfo[] resultInfos = (ServiceResultInfo[]) msg.obj;
512 for (ServiceResultInfo resultInfo : resultInfos) {
513 if (resultInfo.resultTargets != null) {
514 ChooserListAdapter adapterForUserHandle =
515 mChooserMultiProfilePagerAdapter.getListAdapterForUserHandle(
516 resultInfo.userHandle);
517 if (adapterForUserHandle != null) {
518 adapterForUserHandle.addServiceResults(
519 resultInfo.originalTarget,
520 resultInfo.resultTargets, msg.arg1,
521 mDirectShareShortcutInfoCache);
522 }
523 }
524 }
525
526 logDirectShareTargetReceived(
527 MetricsEvent.ACTION_DIRECT_SHARE_TARGETS_LOADED_SHORTCUT_MANAGER);
528 sendVoiceChoicesIfNeeded();
529 getChooserActivityLogger().logSharesheetDirectLoadComplete();
530
531 mChooserMultiProfilePagerAdapter.getActiveListAdapter()
532 .completeServiceTargetLoading();
533 break;
534
535 default:
536 super.handleMessage(msg);
537 }
538 }
539 };
540
541 @Override
542 protected void onCreate(Bundle savedInstanceState) {
543 final long intentReceivedTime = System.currentTimeMillis();
544 mLatencyTracker.onActionStart(ACTION_LOAD_SHARE_SHEET);
545
546 getChooserActivityLogger().logSharesheetTriggered();
547 // This is the only place this value is being set. Effectively final.
548 mIsAppPredictorComponentAvailable = isAppPredictionServiceAvailable();
549
550 mIsSuccessfullySelected = false;
551 Intent intent = getIntent();
552 Parcelable targetParcelable = intent.getParcelableExtra(Intent.EXTRA_INTENT);
553 if (targetParcelable instanceof Uri) {
554 try {
555 targetParcelable = Intent.parseUri(targetParcelable.toString(),
556 Intent.URI_INTENT_SCHEME);
557 } catch (URISyntaxException ex) {
558 // doesn't parse as an intent; let the next test fail and error out
559 }
560 }
561
562 if (!(targetParcelable instanceof Intent)) {
563 Log.w("ChooserActivity", "Target is not an intent: " + targetParcelable);
564 finish();
565 super.onCreate(null);
566 return;
567 }
568 Intent target = (Intent) targetParcelable;
569 if (target != null) {
570 modifyTargetIntent(target);
571 }
572 Parcelable[] targetsParcelable
573 = intent.getParcelableArrayExtra(Intent.EXTRA_ALTERNATE_INTENTS);
574 if (targetsParcelable != null) {
575 final boolean offset = target == null;
576 Intent[] additionalTargets =
577 new Intent[offset ? targetsParcelable.length - 1 : targetsParcelable.length];
578 for (int i = 0; i < targetsParcelable.length; i++) {
579 if (!(targetsParcelable[i] instanceof Intent)) {
580 Log.w(TAG, "EXTRA_ALTERNATE_INTENTS array entry #" + i + " is not an Intent: "
581 + targetsParcelable[i]);
582 finish();
583 super.onCreate(null);
584 return;
585 }
586 final Intent additionalTarget = (Intent) targetsParcelable[i];
587 if (i == 0 && target == null) {
588 target = additionalTarget;
589 modifyTargetIntent(target);
590 } else {
591 additionalTargets[offset ? i - 1 : i] = additionalTarget;
592 modifyTargetIntent(additionalTarget);
593 }
594 }
595 setAdditionalTargets(additionalTargets);
596 }
597
598 mReplacementExtras = intent.getBundleExtra(Intent.EXTRA_REPLACEMENT_EXTRAS);
599
600 // Do not allow the title to be changed when sharing content
601 CharSequence title = null;
602 if (target != null) {
603 if (!isSendAction(target)) {
604 title = intent.getCharSequenceExtra(Intent.EXTRA_TITLE);
605 } else {
606 Log.w(TAG, "Ignoring intent's EXTRA_TITLE, deprecated in P. You may wish to set a"
607 + " preview title by using EXTRA_TITLE property of the wrapped"
608 + " EXTRA_INTENT.");
609 }
610 }
611
612 int defaultTitleRes = 0;
613 if (title == null) {
614 defaultTitleRes = com.android.internal.R.string.chooseActivity;
615 }
616
617 Parcelable[] pa = intent.getParcelableArrayExtra(Intent.EXTRA_INITIAL_INTENTS);
618 Intent[] initialIntents = null;
619 if (pa != null) {
620 int count = Math.min(pa.length, MAX_EXTRA_INITIAL_INTENTS);
621 initialIntents = new Intent[count];
622 for (int i = 0; i < count; i++) {
623 if (!(pa[i] instanceof Intent)) {
624 Log.w(TAG, "Initial intent #" + i + " not an Intent: " + pa[i]);
625 finish();
626 super.onCreate(null);
627 return;
628 }
629 final Intent in = (Intent) pa[i];
630 modifyTargetIntent(in);
631 initialIntents[i] = in;
632 }
633 }
634
635 mReferrerFillInIntent = new Intent().putExtra(Intent.EXTRA_REFERRER, getReferrer());
636
637 mChosenComponentSender = intent.getParcelableExtra(
638 Intent.EXTRA_CHOSEN_COMPONENT_INTENT_SENDER);
639 mRefinementIntentSender = intent.getParcelableExtra(
640 Intent.EXTRA_CHOOSER_REFINEMENT_INTENT_SENDER);
641 setSafeForwardingMode(true);
642
643 mPinnedSharedPrefs = getPinnedSharedPrefs(this);
644
645 pa = intent.getParcelableArrayExtra(Intent.EXTRA_EXCLUDE_COMPONENTS);
646
647
648 // Exclude out Nearby from main list if chip is present, to avoid duplication
649 ComponentName nearbySharingComponent = getNearbySharingComponent();
650 boolean shouldFilterNearby = !shouldNearbyShareBeFirstInRankedRow()
651 && nearbySharingComponent != null;
652
653 if (pa != null) {
654 ComponentName[] names = new ComponentName[pa.length + (shouldFilterNearby ? 1 : 0)];
655 for (int i = 0; i < pa.length; i++) {
656 if (!(pa[i] instanceof ComponentName)) {
657 Log.w(TAG, "Filtered component #" + i + " not a ComponentName: " + pa[i]);
658 names = null;
659 break;
660 }
661 names[i] = (ComponentName) pa[i];
662 }
663 if (shouldFilterNearby) {
664 names[names.length - 1] = nearbySharingComponent;
665 }
666
667 mFilteredComponentNames = names;
668 } else if (shouldFilterNearby) {
669 mFilteredComponentNames = new ComponentName[1];
670 mFilteredComponentNames[0] = nearbySharingComponent;
671 }
672
673 pa = intent.getParcelableArrayExtra(Intent.EXTRA_CHOOSER_TARGETS);
674 if (pa != null) {
675 int count = Math.min(pa.length, MAX_EXTRA_CHOOSER_TARGETS);
676 ChooserTarget[] targets = new ChooserTarget[count];
677 for (int i = 0; i < count; i++) {
678 if (!(pa[i] instanceof ChooserTarget)) {
679 Log.w(TAG, "Chooser target #" + i + " not a ChooserTarget: " + pa[i]);
680 targets = null;
681 break;
682 }
683 targets[i] = (ChooserTarget) pa[i];
684 }
685 mCallerChooserTargets = targets;
686 }
687
688 mMaxTargetsPerRow = getResources().getInteger(R.integer.config_chooser_max_targets_per_row);
689 mShouldDisplayLandscape =
690 shouldDisplayLandscape(getResources().getConfiguration().orientation);
691 setRetainInOnStop(intent.getBooleanExtra(EXTRA_PRIVATE_RETAIN_IN_ON_STOP, false));
692 super.onCreate(savedInstanceState, target, title, defaultTitleRes, initialIntents,
693 null, false);
694
695 mChooserShownTime = System.currentTimeMillis();
696 final long systemCost = mChooserShownTime - intentReceivedTime;
697
698 getMetricsLogger().write(new LogMaker(MetricsEvent.ACTION_ACTIVITY_CHOOSER_SHOWN)
699 .setSubtype(isWorkProfile() ? MetricsEvent.MANAGED_PROFILE :
700 MetricsEvent.PARENT_PROFILE)
701 .addTaggedData(MetricsEvent.FIELD_SHARESHEET_MIMETYPE, target.getType())
702 .addTaggedData(MetricsEvent.FIELD_TIME_TO_APP_TARGETS, systemCost));
703
704 if (mResolverDrawerLayout != null) {
705 mResolverDrawerLayout.addOnLayoutChangeListener(this::handleLayoutChange);
706
707 // expand/shrink direct share 4 -> 8 viewgroup
708 if (isSendAction(target)) {
709 mResolverDrawerLayout.setOnScrollChangeListener(this::handleScroll);
710 }
711
712 mResolverDrawerLayout.setOnCollapsedChangedListener(
713 new ResolverDrawerLayout.OnCollapsedChangedListener() {
714
715 // Only consider one expansion per activity creation
716 private boolean mWrittenOnce = false;
717
718 @Override
719 public void onCollapsedChanged(boolean isCollapsed) {
720 if (!isCollapsed && !mWrittenOnce) {
721 incrementNumSheetExpansions();
722 mWrittenOnce = true;
723 }
724 getChooserActivityLogger()
725 .logSharesheetExpansionChanged(isCollapsed);
726 }
727 });
728 }
729
730 if (DEBUG) {
731 Log.d(TAG, "System Time Cost is " + systemCost);
732 }
733
734 getChooserActivityLogger().logShareStarted(
735 FrameworkStatsLog.SHARESHEET_STARTED,
736 getReferrerPackageName(),
737 target.getType(),
738 mCallerChooserTargets == null ? 0 : mCallerChooserTargets.length,
739 initialIntents == null ? 0 : initialIntents.length,
740 isWorkProfile(),
741 findPreferredContentPreview(getTargetIntent(), getContentResolver()),
742 target.getAction()
743 );
744 mDirectShareShortcutInfoCache = new HashMap<>();
745
746 setEnterSharedElementCallback(new SharedElementCallback() {
747 @Override
748 public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
749 if (mRemoveSharedElements) {
750 names.remove(FIRST_IMAGE_PREVIEW_TRANSITION_NAME);
751 sharedElements.remove(FIRST_IMAGE_PREVIEW_TRANSITION_NAME);
752 }
753 super.onMapSharedElements(names, sharedElements);
754 mRemoveSharedElements = false;
755 }
756 });
757 mEnterTransitionAnimationDelegate.postponeTransition();
758 }
759
760 @Override
761 protected int appliedThemeResId() {
762 return R.style.Theme_DeviceDefault_Chooser;
763 }
764
765 private AppPredictor setupAppPredictorForUser(UserHandle userHandle,
766 AppPredictor.Callback appPredictorCallback) {
767 AppPredictor appPredictor = getAppPredictorForDirectShareIfEnabled(userHandle);
768 if (appPredictor == null) {
769 return null;
770 }
771 mDirectShareAppTargetCache = new HashMap<>();
772 appPredictor.registerPredictionUpdates(this.getMainExecutor(), appPredictorCallback);
773 return appPredictor;
774 }
775
776 private AppPredictor.Callback createAppPredictorCallback(
777 ChooserListAdapter chooserListAdapter) {
778 return resultList -> {
779 if (isFinishing() || isDestroyed()) {
780 return;
781 }
782 if (chooserListAdapter.getCount() == 0) {
783 return;
784 }
785 if (resultList.isEmpty()
786 && shouldQueryShortcutManager(chooserListAdapter.getUserHandle())) {
787 // APS may be disabled, so try querying targets ourselves.
788 queryDirectShareTargets(chooserListAdapter, true);
789 return;
790 }
791 final List<ShortcutManager.ShareShortcutInfo> shareShortcutInfos =
792 new ArrayList<>();
793
794 List<AppTarget> shortcutResults = new ArrayList<>();
795 for (AppTarget appTarget : resultList) {
796 if (appTarget.getShortcutInfo() == null) {
797 continue;
798 }
799 shortcutResults.add(appTarget);
800 }
801 resultList = shortcutResults;
802 for (AppTarget appTarget : resultList) {
803 shareShortcutInfos.add(new ShortcutManager.ShareShortcutInfo(
804 appTarget.getShortcutInfo(),
805 new ComponentName(
806 appTarget.getPackageName(), appTarget.getClassName())));
807 }
808 sendShareShortcutInfoList(shareShortcutInfos, chooserListAdapter, resultList,
809 chooserListAdapter.getUserHandle());
810 };
811 }
812
813 static SharedPreferences getPinnedSharedPrefs(Context context) {
814 // The code below is because in the android:ui process, no one can hear you scream.
815 // The package info in the context isn't initialized in the way it is for normal apps,
816 // so the standard, name-based context.getSharedPreferences doesn't work. Instead, we
817 // build the path manually below using the same policy that appears in ContextImpl.
818 // This fails silently under the hood if there's a problem, so if we find ourselves in
819 // the case where we don't have access to credential encrypted storage we just won't
820 // have our pinned target info.
821 final File prefsFile = new File(new File(
822 Environment.getDataUserCePackageDirectory(StorageManager.UUID_PRIVATE_INTERNAL,
823 context.getUserId(), context.getPackageName()),
824 "shared_prefs"),
825 PINNED_SHARED_PREFS_NAME + ".xml");
826 return context.getSharedPreferences(prefsFile, MODE_PRIVATE);
827 }
828
829 @Override
830 protected AbstractMultiProfilePagerAdapter createMultiProfilePagerAdapter(
831 Intent[] initialIntents,
832 List<ResolveInfo> rList,
833 boolean filterLastUsed) {
834 if (shouldShowTabs()) {
835 mChooserMultiProfilePagerAdapter = createChooserMultiProfilePagerAdapterForTwoProfiles(
836 initialIntents, rList, filterLastUsed);
837 } else {
838 mChooserMultiProfilePagerAdapter = createChooserMultiProfilePagerAdapterForOneProfile(
839 initialIntents, rList, filterLastUsed);
840 }
841 return mChooserMultiProfilePagerAdapter;
842 }
843
844 @Override
845 protected EmptyStateProvider createBlockerEmptyStateProvider() {
846 final boolean isSendAction = isSendAction(getTargetIntent());
847
848 final EmptyState noWorkToPersonalEmptyState =
849 new DevicePolicyBlockerEmptyState(
850 /* context= */ this,
851 /* devicePolicyStringTitleId= */ RESOLVER_CROSS_PROFILE_BLOCKED_TITLE,
852 /* defaultTitleResource= */ R.string.resolver_cross_profile_blocked,
853 /* devicePolicyStringSubtitleId= */
854 isSendAction ? RESOLVER_CANT_SHARE_WITH_PERSONAL : RESOLVER_CANT_ACCESS_PERSONAL,
855 /* defaultSubtitleResource= */
856 isSendAction ? R.string.resolver_cant_share_with_personal_apps_explanation
857 : R.string.resolver_cant_access_personal_apps_explanation,
858 /* devicePolicyEventId= */ RESOLVER_EMPTY_STATE_NO_SHARING_TO_PERSONAL,
859 /* devicePolicyEventCategory= */ ResolverActivity.METRICS_CATEGORY_CHOOSER);
860
861 final EmptyState noPersonalToWorkEmptyState =
862 new DevicePolicyBlockerEmptyState(
863 /* context= */ this,
864 /* devicePolicyStringTitleId= */ RESOLVER_CROSS_PROFILE_BLOCKED_TITLE,
865 /* defaultTitleResource= */ R.string.resolver_cross_profile_blocked,
866 /* devicePolicyStringSubtitleId= */
867 isSendAction ? RESOLVER_CANT_SHARE_WITH_WORK : RESOLVER_CANT_ACCESS_WORK,
868 /* defaultSubtitleResource= */
869 isSendAction ? R.string.resolver_cant_share_with_work_apps_explanation
870 : R.string.resolver_cant_access_work_apps_explanation,
871 /* devicePolicyEventId= */ RESOLVER_EMPTY_STATE_NO_SHARING_TO_WORK,
872 /* devicePolicyEventCategory= */ ResolverActivity.METRICS_CATEGORY_CHOOSER);
873
874 return new NoCrossProfileEmptyStateProvider(getPersonalProfileUserHandle(),
875 noWorkToPersonalEmptyState, noPersonalToWorkEmptyState,
876 createCrossProfileIntentsChecker(), createMyUserIdProvider());
877 }
878
879 private ChooserMultiProfilePagerAdapter createChooserMultiProfilePagerAdapterForOneProfile(
880 Intent[] initialIntents,
881 List<ResolveInfo> rList,
882 boolean filterLastUsed) {
883 ChooserGridAdapter adapter = createChooserGridAdapter(
884 /* context */ this,
885 /* payloadIntents */ mIntents,
886 initialIntents,
887 rList,
888 filterLastUsed,
889 /* userHandle */ UserHandle.of(UserHandle.myUserId()));
890 return new ChooserMultiProfilePagerAdapter(
891 /* context */ this,
892 adapter,
893 createEmptyStateProvider(/* workProfileUserHandle= */ null),
894 mQuietModeManager,
895 /* workProfileUserHandle= */ null,
896 mMaxTargetsPerRow);
897 }
898
899 private ChooserMultiProfilePagerAdapter createChooserMultiProfilePagerAdapterForTwoProfiles(
900 Intent[] initialIntents,
901 List<ResolveInfo> rList,
902 boolean filterLastUsed) {
903 int selectedProfile = findSelectedProfile();
904 ChooserGridAdapter personalAdapter = createChooserGridAdapter(
905 /* context */ this,
906 /* payloadIntents */ mIntents,
907 selectedProfile == PROFILE_PERSONAL ? initialIntents : null,
908 rList,
909 filterLastUsed,
910 /* userHandle */ getPersonalProfileUserHandle());
911 ChooserGridAdapter workAdapter = createChooserGridAdapter(
912 /* context */ this,
913 /* payloadIntents */ mIntents,
914 selectedProfile == PROFILE_WORK ? initialIntents : null,
915 rList,
916 filterLastUsed,
917 /* userHandle */ getWorkProfileUserHandle());
918 return new ChooserMultiProfilePagerAdapter(
919 /* context */ this,
920 personalAdapter,
921 workAdapter,
922 createEmptyStateProvider(/* workProfileUserHandle= */ getWorkProfileUserHandle()),
923 mQuietModeManager,
924 selectedProfile,
925 getWorkProfileUserHandle(),
926 mMaxTargetsPerRow);
927 }
928
929 private int findSelectedProfile() {
930 int selectedProfile = getSelectedProfileExtra();
931 if (selectedProfile == -1) {
932 selectedProfile = getProfileForUser(getUser());
933 }
934 return selectedProfile;
935 }
936
937 @Override
938 protected boolean postRebuildList(boolean rebuildCompleted) {
939 updateStickyContentPreview();
940 if (shouldShowStickyContentPreview()
941 || mChooserMultiProfilePagerAdapter
942 .getCurrentRootAdapter().getSystemRowCount() != 0) {
943 logActionShareWithPreview();
944 }
945 return postRebuildListInternal(rebuildCompleted);
946 }
947
948 /**
949 * Returns true if app prediction service is defined and the component exists on device.
950 */
951 private boolean isAppPredictionServiceAvailable() {
952 return getPackageManager().getAppPredictionServicePackageName() != null;
953 }
954
955 /**
956 * Check if the profile currently used is a work profile.
957 * @return true if it is work profile, false if it is parent profile (or no work profile is
958 * set up)
959 */
960 protected boolean isWorkProfile() {
961 return getSystemService(UserManager.class)
962 .getUserInfo(UserHandle.myUserId()).isManagedProfile();
963 }
964
965 @Override
966 protected PackageMonitor createPackageMonitor(ResolverListAdapter listAdapter) {
967 return new PackageMonitor() {
968 @Override
969 public void onSomePackagesChanged() {
970 handlePackagesChanged(listAdapter);
971 }
972 };
973 }
974
975 /**
976 * Update UI to reflect changes in data.
977 */
978 public void handlePackagesChanged() {
979 handlePackagesChanged(/* listAdapter */ null);
980 }
981
982 /**
983 * Update UI to reflect changes in data.
984 * <p>If {@code listAdapter} is {@code null}, both profile list adapters are updated if
985 * available.
986 */
987 private void handlePackagesChanged(@Nullable ResolverListAdapter listAdapter) {
988 // Refresh pinned items
989 mPinnedSharedPrefs = getPinnedSharedPrefs(this);
990 if (listAdapter == null) {
991 mChooserMultiProfilePagerAdapter.getActiveListAdapter().handlePackagesChanged();
992 if (mChooserMultiProfilePagerAdapter.getCount() > 1) {
993 mChooserMultiProfilePagerAdapter.getInactiveListAdapter().handlePackagesChanged();
994 }
995 } else {
996 listAdapter.handlePackagesChanged();
997 }
998 updateProfileViewButton();
999 }
1000
1001 private void onCopyButtonClicked(View v) {
1002 Intent targetIntent = getTargetIntent();
1003 if (targetIntent == null) {
1004 finish();
1005 } else {
1006 final String action = targetIntent.getAction();
1007
1008 ClipData clipData = null;
1009 if (Intent.ACTION_SEND.equals(action)) {
1010 String extraText = targetIntent.getStringExtra(Intent.EXTRA_TEXT);
1011 Uri extraStream = targetIntent.getParcelableExtra(Intent.EXTRA_STREAM);
1012
1013 if (extraText != null) {
1014 clipData = ClipData.newPlainText(null, extraText);
1015 } else if (extraStream != null) {
1016 clipData = ClipData.newUri(getContentResolver(), null, extraStream);
1017 } else {
1018 Log.w(TAG, "No data available to copy to clipboard");
1019 return;
1020 }
1021 } else if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
1022 final ArrayList<Uri> streams = targetIntent.getParcelableArrayListExtra(
1023 Intent.EXTRA_STREAM);
1024 clipData = ClipData.newUri(getContentResolver(), null, streams.get(0));
1025 for (int i = 1; i < streams.size(); i++) {
1026 clipData.addItem(getContentResolver(), new ClipData.Item(streams.get(i)));
1027 }
1028 } else {
1029 // expected to only be visible with ACTION_SEND or ACTION_SEND_MULTIPLE
1030 // so warn about unexpected action
1031 Log.w(TAG, "Action (" + action + ") not supported for copying to clipboard");
1032 return;
1033 }
1034
1035 ClipboardManager clipboardManager = (ClipboardManager) getSystemService(
1036 Context.CLIPBOARD_SERVICE);
1037 clipboardManager.setPrimaryClipAsPackage(clipData, getReferrerPackageName());
1038
1039 // Log share completion via copy
1040 LogMaker targetLogMaker = new LogMaker(
1041 MetricsEvent.ACTION_ACTIVITY_CHOOSER_PICKED_SYSTEM_TARGET).setSubtype(1);
1042 getMetricsLogger().write(targetLogMaker);
1043 getChooserActivityLogger().logShareTargetSelected(
1044 SELECTION_TYPE_COPY,
1045 "",
1046 -1,
1047 false);
1048
1049 setResult(RESULT_OK);
1050 finish();
1051 }
1052 }
1053
1054 @Override
1055 protected void onResume() {
1056 super.onResume();
1057 Log.d(TAG, "onResume: " + getComponentName().flattenToShortString());
1058 maybeCancelFinishAnimation();
1059 }
1060
1061 @Override
1062 public void onConfigurationChanged(Configuration newConfig) {
1063 super.onConfigurationChanged(newConfig);
1064 ViewPager viewPager = findViewById(R.id.profile_pager);
1065 if (viewPager.isLayoutRtl()) {
1066 mMultiProfilePagerAdapter.setupViewPager(viewPager);
1067 }
1068
1069 mShouldDisplayLandscape = shouldDisplayLandscape(newConfig.orientation);
1070 mMaxTargetsPerRow = getResources().getInteger(R.integer.config_chooser_max_targets_per_row);
1071 mChooserMultiProfilePagerAdapter.setMaxTargetsPerRow(mMaxTargetsPerRow);
1072 adjustPreviewWidth(newConfig.orientation, null);
1073 updateStickyContentPreview();
1074 updateTabPadding();
1075 }
1076
1077 private boolean shouldDisplayLandscape(int orientation) {
1078 // Sharesheet fixes the # of items per row and therefore can not correctly lay out
1079 // when in the restricted size of multi-window mode. In the future, would be nice
1080 // to use minimum dp size requirements instead
1081 return orientation == Configuration.ORIENTATION_LANDSCAPE && !isInMultiWindowMode();
1082 }
1083
1084 private void adjustPreviewWidth(int orientation, View parent) {
1085 int width = -1;
1086 if (mShouldDisplayLandscape) {
1087 width = getResources().getDimensionPixelSize(R.dimen.chooser_preview_width);
1088 }
1089
1090 parent = parent == null ? getWindow().getDecorView() : parent;
1091
1092 updateLayoutWidth(R.id.content_preview_text_layout, width, parent);
1093 updateLayoutWidth(R.id.content_preview_title_layout, width, parent);
1094 updateLayoutWidth(R.id.content_preview_file_layout, width, parent);
1095 }
1096
1097 private void updateTabPadding() {
1098 if (shouldShowTabs()) {
1099 View tabs = findViewById(R.id.tabs);
1100 float iconSize = getResources().getDimension(R.dimen.chooser_icon_size);
1101 // The entire width consists of icons or padding. Divide the item padding in half to get
1102 // paddingHorizontal.
1103 float padding = (tabs.getWidth() - mMaxTargetsPerRow * iconSize)
1104 / mMaxTargetsPerRow / 2;
1105 // Subtract the margin the buttons already have.
1106 padding -= getResources().getDimension(R.dimen.resolver_profile_tab_margin);
1107 tabs.setPadding((int) padding, 0, (int) padding, 0);
1108 }
1109 }
1110
1111 private void updateLayoutWidth(int layoutResourceId, int width, View parent) {
1112 View view = parent.findViewById(layoutResourceId);
1113 if (view != null && view.getLayoutParams() != null) {
1114 LayoutParams params = view.getLayoutParams();
1115 params.width = width;
1116 view.setLayoutParams(params);
1117 }
1118 }
1119
1120 /**
1121 * Create a view that will be shown in the content preview area
1122 * @param parent reference to the parent container where the view should be attached to
1123 * @return content preview view
1124 */
1125 protected ViewGroup createContentPreviewView(ViewGroup parent) {
1126 Intent targetIntent = getTargetIntent();
1127 int previewType = findPreferredContentPreview(targetIntent, getContentResolver());
1128 return displayContentPreview(previewType, targetIntent, getLayoutInflater(), parent);
1129 }
1130
1131 @VisibleForTesting
1132 protected ComponentName getNearbySharingComponent() {
1133 String nearbyComponent = Settings.Secure.getString(
1134 getContentResolver(),
1135 Settings.Secure.NEARBY_SHARING_COMPONENT);
1136 if (TextUtils.isEmpty(nearbyComponent)) {
1137 nearbyComponent = getString(R.string.config_defaultNearbySharingComponent);
1138 }
1139 if (TextUtils.isEmpty(nearbyComponent)) {
1140 return null;
1141 }
1142 return ComponentName.unflattenFromString(nearbyComponent);
1143 }
1144
1145 @VisibleForTesting
1146 protected @Nullable ComponentName getEditSharingComponent() {
1147 String editorPackage = getApplicationContext().getString(R.string.config_systemImageEditor);
1148 if (editorPackage == null || TextUtils.isEmpty(editorPackage)) {
1149 return null;
1150 }
1151 return ComponentName.unflattenFromString(editorPackage);
1152 }
1153
1154 @VisibleForTesting
1155 protected TargetInfo getEditSharingTarget(Intent originalIntent) {
1156 final ComponentName cn = getEditSharingComponent();
1157
1158 final Intent resolveIntent = new Intent(originalIntent);
1159 // Retain only URI permission grant flags if present. Other flags may prevent the scene
1160 // transition animation from running (i.e FLAG_ACTIVITY_NO_ANIMATION,
1161 // FLAG_ACTIVITY_NEW_TASK, FLAG_ACTIVITY_NEW_DOCUMENT) but also not needed.
1162 resolveIntent.setFlags(originalIntent.getFlags() & URI_PERMISSION_INTENT_FLAGS);
1163 resolveIntent.setComponent(cn);
1164 resolveIntent.setAction(Intent.ACTION_EDIT);
1165 String originalAction = originalIntent.getAction();
1166 if (Intent.ACTION_SEND.equals(originalAction)) {
1167 if (resolveIntent.getData() == null) {
1168 Uri uri = resolveIntent.getParcelableExtra(Intent.EXTRA_STREAM);
1169 if (uri != null) {
1170 String mimeType = getContentResolver().getType(uri);
1171 resolveIntent.setDataAndType(uri, mimeType);
1172 }
1173 }
1174 } else {
1175 Log.e(TAG, originalAction + " is not supported.");
1176 return null;
1177 }
1178 final ResolveInfo ri = getPackageManager().resolveActivity(
1179 resolveIntent, PackageManager.GET_META_DATA);
1180 if (ri == null || ri.activityInfo == null) {
1181 Log.e(TAG, "Device-specified image edit component (" + cn
1182 + ") not available");
1183 return null;
1184 }
1185
1186 final DisplayResolveInfo dri = new DisplayResolveInfo(
1187 originalIntent, ri, getString(R.string.screenshot_edit), "", resolveIntent, null);
1188 dri.setDisplayIcon(getDrawable(R.drawable.ic_screenshot_edit));
1189 return dri;
1190 }
1191
1192 @VisibleForTesting
1193 protected TargetInfo getNearbySharingTarget(Intent originalIntent) {
1194 final ComponentName cn = getNearbySharingComponent();
1195 if (cn == null) return null;
1196
1197 final Intent resolveIntent = new Intent(originalIntent);
1198 resolveIntent.setComponent(cn);
1199 final ResolveInfo ri = getPackageManager().resolveActivity(
1200 resolveIntent, PackageManager.GET_META_DATA);
1201 if (ri == null || ri.activityInfo == null) {
1202 Log.e(TAG, "Device-specified nearby sharing component (" + cn
1203 + ") not available");
1204 return null;
1205 }
1206
1207 // Allow the nearby sharing component to provide a more appropriate icon and label
1208 // for the chip.
1209 CharSequence name = null;
1210 Drawable icon = null;
1211 final Bundle metaData = ri.activityInfo.metaData;
1212 if (metaData != null) {
1213 try {
1214 final Resources pkgRes = getPackageManager().getResourcesForActivity(cn);
1215 final int nameResId = metaData.getInt(CHIP_LABEL_METADATA_KEY);
1216 name = pkgRes.getString(nameResId);
1217 final int resId = metaData.getInt(CHIP_ICON_METADATA_KEY);
1218 icon = pkgRes.getDrawable(resId);
1219 } catch (Resources.NotFoundException ex) {
1220 } catch (NameNotFoundException ex) {
1221 }
1222 }
1223 if (TextUtils.isEmpty(name)) {
1224 name = ri.loadLabel(getPackageManager());
1225 }
1226 if (icon == null) {
1227 icon = ri.loadIcon(getPackageManager());
1228 }
1229
1230 final DisplayResolveInfo dri = new DisplayResolveInfo(
1231 originalIntent, ri, name, "", resolveIntent, null);
1232 dri.setDisplayIcon(icon);
1233 return dri;
1234 }
1235
1236 private Button createActionButton(Drawable icon, CharSequence title, View.OnClickListener r) {
1237 Button b = (Button) LayoutInflater.from(this).inflate(R.layout.chooser_action_button, null);
1238 if (icon != null) {
1239 final int size = getResources()
1240 .getDimensionPixelSize(R.dimen.chooser_action_button_icon_size);
1241 icon.setBounds(0, 0, size, size);
1242 b.setCompoundDrawablesRelative(icon, null, null, null);
1243 }
1244 b.setText(title);
1245 b.setOnClickListener(r);
1246 return b;
1247 }
1248
1249 private Button createCopyButton() {
1250 final Button b = createActionButton(
1251 getDrawable(R.drawable.ic_menu_copy_material),
1252 getString(R.string.copy), this::onCopyButtonClicked);
1253 b.setId(R.id.chooser_copy_button);
1254 return b;
1255 }
1256
1257 private @Nullable Button createNearbyButton(Intent originalIntent) {
1258 final TargetInfo ti = getNearbySharingTarget(originalIntent);
1259 if (ti == null) return null;
1260
1261 final Button b = createActionButton(
1262 ti.getDisplayIcon(this),
1263 ti.getDisplayLabel(),
1264 (View unused) -> {
1265 // Log share completion via nearby
1266 getChooserActivityLogger().logShareTargetSelected(
1267 SELECTION_TYPE_NEARBY,
1268 "",
1269 -1,
1270 false);
1271 // Action bar is user-independent, always start as primary
1272 safelyStartActivityAsUser(ti, getPersonalProfileUserHandle());
1273 finish();
1274 }
1275 );
1276 b.setId(R.id.chooser_nearby_button);
1277 return b;
1278 }
1279
1280 private @Nullable Button createEditButton(Intent originalIntent) {
1281 final TargetInfo ti = getEditSharingTarget(originalIntent);
1282 if (ti == null) return null;
1283
1284 final Button b = createActionButton(
1285 ti.getDisplayIcon(this),
1286 ti.getDisplayLabel(),
1287 (View unused) -> {
1288 // Log share completion via edit
1289 getChooserActivityLogger().logShareTargetSelected(
1290 SELECTION_TYPE_EDIT,
1291 "",
1292 -1,
1293 false);
1294 View firstImgView = getFirstVisibleImgPreviewView();
1295 // Action bar is user-independent, always start as primary
1296 if (firstImgView == null) {
1297 safelyStartActivityAsUser(ti, getPersonalProfileUserHandle());
1298 finish();
1299 } else {
1300 ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(
1301 this, firstImgView, IMAGE_EDITOR_SHARED_ELEMENT);
1302 safelyStartActivityAsUser(
1303 ti, getPersonalProfileUserHandle(), options.toBundle());
1304 startFinishAnimation();
1305 }
1306 }
1307 );
1308 b.setId(R.id.chooser_edit_button);
1309 return b;
1310 }
1311
1312 @Nullable
1313 private View getFirstVisibleImgPreviewView() {
1314 View firstImage = findViewById(R.id.content_preview_image_1_large);
1315 return firstImage != null && firstImage.isVisibleToUser() ? firstImage : null;
1316 }
1317
1318 private void addActionButton(ViewGroup parent, Button b) {
1319 if (b == null) return;
1320 final ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
1321 LayoutParams.WRAP_CONTENT,
1322 LayoutParams.WRAP_CONTENT
1323 );
1324 final int gap = getResources().getDimensionPixelSize(R.dimen.resolver_icon_margin) / 2;
1325 lp.setMarginsRelative(gap, 0, gap, 0);
1326 parent.addView(b, lp);
1327 }
1328
1329 private ViewGroup displayContentPreview(@ContentPreviewType int previewType,
1330 Intent targetIntent, LayoutInflater layoutInflater, ViewGroup parent) {
1331 ViewGroup layout = null;
1332
1333 switch (previewType) {
1334 case CONTENT_PREVIEW_TEXT:
1335 layout = displayTextContentPreview(targetIntent, layoutInflater, parent);
1336 break;
1337 case CONTENT_PREVIEW_IMAGE:
1338 layout = displayImageContentPreview(targetIntent, layoutInflater, parent);
1339 break;
1340 case CONTENT_PREVIEW_FILE:
1341 layout = displayFileContentPreview(targetIntent, layoutInflater, parent);
1342 break;
1343 default:
1344 Log.e(TAG, "Unexpected content preview type: " + previewType);
1345 }
1346
1347 if (layout != null) {
1348 adjustPreviewWidth(getResources().getConfiguration().orientation, layout);
1349 }
1350 if (previewType != CONTENT_PREVIEW_IMAGE) {
1351 mEnterTransitionAnimationDelegate.markImagePreviewReady();
1352 }
1353
1354 return layout;
1355 }
1356
1357 private ViewGroup displayTextContentPreview(Intent targetIntent, LayoutInflater layoutInflater,
1358 ViewGroup parent) {
1359 ViewGroup contentPreviewLayout = (ViewGroup) layoutInflater.inflate(
1360 R.layout.chooser_grid_preview_text, parent, false);
1361
1362 final ViewGroup actionRow =
1363 (ViewGroup) contentPreviewLayout.findViewById(R.id.chooser_action_row);
1364 addActionButton(actionRow, createCopyButton());
1365 if (shouldNearbyShareBeIncludedAsActionButton()) {
1366 addActionButton(actionRow, createNearbyButton(targetIntent));
1367 }
1368
1369 CharSequence sharingText = targetIntent.getCharSequenceExtra(Intent.EXTRA_TEXT);
1370 if (sharingText == null) {
1371 contentPreviewLayout.findViewById(R.id.content_preview_text_layout).setVisibility(
1372 View.GONE);
1373 } else {
1374 TextView textView = contentPreviewLayout.findViewById(R.id.content_preview_text);
1375 textView.setText(sharingText);
1376 }
1377
1378 String previewTitle = targetIntent.getStringExtra(Intent.EXTRA_TITLE);
1379 if (TextUtils.isEmpty(previewTitle)) {
1380 contentPreviewLayout.findViewById(R.id.content_preview_title_layout).setVisibility(
1381 View.GONE);
1382 } else {
1383 TextView previewTitleView = contentPreviewLayout.findViewById(
1384 R.id.content_preview_title);
1385 previewTitleView.setText(previewTitle);
1386
1387 ClipData previewData = targetIntent.getClipData();
1388 Uri previewThumbnail = null;
1389 if (previewData != null) {
1390 if (previewData.getItemCount() > 0) {
1391 ClipData.Item previewDataItem = previewData.getItemAt(0);
1392 previewThumbnail = previewDataItem.getUri();
1393 }
1394 }
1395
1396 ImageView previewThumbnailView = contentPreviewLayout.findViewById(
1397 R.id.content_preview_thumbnail);
1398 if (previewThumbnail == null) {
1399 previewThumbnailView.setVisibility(View.GONE);
1400 } else {
1401 mPreviewCoord = new ContentPreviewCoordinator(contentPreviewLayout, false);
1402 mPreviewCoord.loadUriIntoView(R.id.content_preview_thumbnail, previewThumbnail, 0);
1403 }
1404 }
1405
1406 return contentPreviewLayout;
1407 }
1408
1409 private ViewGroup displayImageContentPreview(Intent targetIntent, LayoutInflater layoutInflater,
1410 ViewGroup parent) {
1411 ViewGroup contentPreviewLayout = (ViewGroup) layoutInflater.inflate(
1412 R.layout.chooser_grid_preview_image, parent, false);
1413 ViewGroup imagePreview = contentPreviewLayout.findViewById(R.id.content_preview_image_area);
1414
1415 final ViewGroup actionRow =
1416 (ViewGroup) contentPreviewLayout.findViewById(R.id.chooser_action_row);
1417 //TODO: addActionButton(actionRow, createCopyButton());
1418 if (shouldNearbyShareBeIncludedAsActionButton()) {
1419 addActionButton(actionRow, createNearbyButton(targetIntent));
1420 }
1421 addActionButton(actionRow, createEditButton(targetIntent));
1422
1423 mPreviewCoord = new ContentPreviewCoordinator(contentPreviewLayout, false);
1424
1425 String action = targetIntent.getAction();
1426 if (Intent.ACTION_SEND.equals(action)) {
1427 Uri uri = targetIntent.getParcelableExtra(Intent.EXTRA_STREAM);
1428 imagePreview.findViewById(R.id.content_preview_image_1_large)
1429 .setTransitionName(ChooserActivity.FIRST_IMAGE_PREVIEW_TRANSITION_NAME);
1430 mPreviewCoord.loadUriIntoView(R.id.content_preview_image_1_large, uri, 0);
1431 } else {
1432 ContentResolver resolver = getContentResolver();
1433
1434 List<Uri> uris = targetIntent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
1435 List<Uri> imageUris = new ArrayList<>();
1436 for (Uri uri : uris) {
1437 if (isImageType(resolver.getType(uri))) {
1438 imageUris.add(uri);
1439 }
1440 }
1441
1442 if (imageUris.size() == 0) {
1443 Log.i(TAG, "Attempted to display image preview area with zero"
1444 + " available images detected in EXTRA_STREAM list");
1445 imagePreview.setVisibility(View.GONE);
1446 return contentPreviewLayout;
1447 }
1448
1449 imagePreview.findViewById(R.id.content_preview_image_1_large)
1450 .setTransitionName(ChooserActivity.FIRST_IMAGE_PREVIEW_TRANSITION_NAME);
1451 mPreviewCoord.loadUriIntoView(R.id.content_preview_image_1_large, imageUris.get(0), 0);
1452
1453 if (imageUris.size() == 2) {
1454 mPreviewCoord.loadUriIntoView(R.id.content_preview_image_2_large,
1455 imageUris.get(1), 0);
1456 } else if (imageUris.size() > 2) {
1457 mPreviewCoord.loadUriIntoView(R.id.content_preview_image_2_small,
1458 imageUris.get(1), 0);
1459 mPreviewCoord.loadUriIntoView(R.id.content_preview_image_3_small,
1460 imageUris.get(2), imageUris.size() - 3);
1461 }
1462 }
1463
1464 return contentPreviewLayout;
1465 }
1466
1467 private static class FileInfo {
1468 public final String name;
1469 public final boolean hasThumbnail;
1470
1471 FileInfo(String name, boolean hasThumbnail) {
1472 this.name = name;
1473 this.hasThumbnail = hasThumbnail;
1474 }
1475 }
1476
1477 /**
1478 * Wrapping the ContentResolver call to expose for easier mocking,
1479 * and to avoid mocking Android core classes.
1480 */
1481 @VisibleForTesting
1482 public Cursor queryResolver(ContentResolver resolver, Uri uri) {
1483 return resolver.query(uri, null, null, null, null);
1484 }
1485
1486 private FileInfo extractFileInfo(Uri uri, ContentResolver resolver) {
1487 String fileName = null;
1488 boolean hasThumbnail = false;
1489
1490 try (Cursor cursor = queryResolver(resolver, uri)) {
1491 if (cursor != null && cursor.getCount() > 0) {
1492 int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
1493 int titleIndex = cursor.getColumnIndex(Downloads.Impl.COLUMN_TITLE);
1494 int flagsIndex = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_FLAGS);
1495
1496 cursor.moveToFirst();
1497 if (nameIndex != -1) {
1498 fileName = cursor.getString(nameIndex);
1499 } else if (titleIndex != -1) {
1500 fileName = cursor.getString(titleIndex);
1501 }
1502
1503 if (flagsIndex != -1) {
1504 hasThumbnail = (cursor.getInt(flagsIndex)
1505 & DocumentsContract.Document.FLAG_SUPPORTS_THUMBNAIL) != 0;
1506 }
1507 }
1508 } catch (SecurityException | NullPointerException e) {
1509 logContentPreviewWarning(uri);
1510 }
1511
1512 if (TextUtils.isEmpty(fileName)) {
1513 fileName = uri.getPath();
1514 int index = fileName.lastIndexOf('/');
1515 if (index != -1) {
1516 fileName = fileName.substring(index + 1);
1517 }
1518 }
1519
1520 return new FileInfo(fileName, hasThumbnail);
1521 }
1522
1523 private void logContentPreviewWarning(Uri uri) {
1524 // The ContentResolver already logs the exception. Log something more informative.
1525 Log.w(TAG, "Could not load (" + uri.toString() + ") thumbnail/name for preview. If "
1526 + "desired, consider using Intent#createChooser to launch the ChooserActivity, "
1527 + "and set your Intent's clipData and flags in accordance with that method's "
1528 + "documentation");
1529 }
1530
1531 private ViewGroup displayFileContentPreview(Intent targetIntent, LayoutInflater layoutInflater,
1532 ViewGroup parent) {
1533
1534 ViewGroup contentPreviewLayout = (ViewGroup) layoutInflater.inflate(
1535 R.layout.chooser_grid_preview_file, parent, false);
1536
1537 final ViewGroup actionRow =
1538 (ViewGroup) contentPreviewLayout.findViewById(R.id.chooser_action_row);
1539 //TODO(b/120417119): addActionButton(actionRow, createCopyButton());
1540 if (shouldNearbyShareBeIncludedAsActionButton()) {
1541 addActionButton(actionRow, createNearbyButton(targetIntent));
1542 }
1543
1544 String action = targetIntent.getAction();
1545 if (Intent.ACTION_SEND.equals(action)) {
1546 Uri uri = targetIntent.getParcelableExtra(Intent.EXTRA_STREAM);
1547 loadFileUriIntoView(uri, contentPreviewLayout);
1548 } else {
1549 List<Uri> uris = targetIntent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
1550 int uriCount = uris.size();
1551
1552 if (uriCount == 0) {
1553 contentPreviewLayout.setVisibility(View.GONE);
1554 Log.i(TAG,
1555 "Appears to be no uris available in EXTRA_STREAM, removing "
1556 + "preview area");
1557 return contentPreviewLayout;
1558 } else if (uriCount == 1) {
1559 loadFileUriIntoView(uris.get(0), contentPreviewLayout);
1560 } else {
1561 FileInfo fileInfo = extractFileInfo(uris.get(0), getContentResolver());
1562 int remUriCount = uriCount - 1;
1563 Map<String, Object> arguments = new HashMap<>();
1564 arguments.put(PLURALS_COUNT, remUriCount);
1565 arguments.put(PLURALS_FILE_NAME, fileInfo.name);
1566 String fileName = PluralsMessageFormatter.format(
1567 getResources(),
1568 arguments,
1569 R.string.file_count);
1570
1571 TextView fileNameView = contentPreviewLayout.findViewById(
1572 R.id.content_preview_filename);
1573 fileNameView.setText(fileName);
1574
1575 View thumbnailView = contentPreviewLayout.findViewById(
1576 R.id.content_preview_file_thumbnail);
1577 thumbnailView.setVisibility(View.GONE);
1578
1579 ImageView fileIconView = contentPreviewLayout.findViewById(
1580 R.id.content_preview_file_icon);
1581 fileIconView.setVisibility(View.VISIBLE);
1582 fileIconView.setImageResource(R.drawable.ic_file_copy);
1583 }
1584 }
1585
1586 return contentPreviewLayout;
1587 }
1588
1589 private void loadFileUriIntoView(final Uri uri, final View parent) {
1590 FileInfo fileInfo = extractFileInfo(uri, getContentResolver());
1591
1592 TextView fileNameView = parent.findViewById(R.id.content_preview_filename);
1593 fileNameView.setText(fileInfo.name);
1594
1595 if (fileInfo.hasThumbnail) {
1596 mPreviewCoord = new ContentPreviewCoordinator(parent, false);
1597 mPreviewCoord.loadUriIntoView(R.id.content_preview_file_thumbnail, uri, 0);
1598 } else {
1599 View thumbnailView = parent.findViewById(R.id.content_preview_file_thumbnail);
1600 thumbnailView.setVisibility(View.GONE);
1601
1602 ImageView fileIconView = parent.findViewById(R.id.content_preview_file_icon);
1603 fileIconView.setVisibility(View.VISIBLE);
1604 fileIconView.setImageResource(R.drawable.chooser_file_generic);
1605 }
1606 }
1607
1608 @VisibleForTesting
1609 protected boolean isImageType(String mimeType) {
1610 return mimeType != null && mimeType.startsWith("image/");
1611 }
1612
1613 @ContentPreviewType
1614 private int findPreferredContentPreview(Uri uri, ContentResolver resolver) {
1615 if (uri == null) {
1616 return CONTENT_PREVIEW_TEXT;
1617 }
1618
1619 String mimeType = resolver.getType(uri);
1620 return isImageType(mimeType) ? CONTENT_PREVIEW_IMAGE : CONTENT_PREVIEW_FILE;
1621 }
1622
1623 /**
1624 * In {@link android.content.Intent#getType}, the app may specify a very general
1625 * mime-type that broadly covers all data being shared, such as {@literal *}/*
1626 * when sending an image and text. We therefore should inspect each item for the
1627 * the preferred type, in order of IMAGE, FILE, TEXT.
1628 */
1629 @ContentPreviewType
1630 private int findPreferredContentPreview(Intent targetIntent, ContentResolver resolver) {
1631 String action = targetIntent.getAction();
1632 if (Intent.ACTION_SEND.equals(action)) {
1633 Uri uri = targetIntent.getParcelableExtra(Intent.EXTRA_STREAM);
1634 return findPreferredContentPreview(uri, resolver);
1635 } else if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
1636 List<Uri> uris = targetIntent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
1637 if (uris == null || uris.isEmpty()) {
1638 return CONTENT_PREVIEW_TEXT;
1639 }
1640
1641 for (Uri uri : uris) {
1642 // Defaulting to file preview when there are mixed image/file types is
1643 // preferable, as it shows the user the correct number of items being shared
1644 if (findPreferredContentPreview(uri, resolver) == CONTENT_PREVIEW_FILE) {
1645 return CONTENT_PREVIEW_FILE;
1646 }
1647 }
1648
1649 return CONTENT_PREVIEW_IMAGE;
1650 }
1651
1652 return CONTENT_PREVIEW_TEXT;
1653 }
1654
1655 private int getNumSheetExpansions() {
1656 return getPreferences(Context.MODE_PRIVATE).getInt(PREF_NUM_SHEET_EXPANSIONS, 0);
1657 }
1658
1659 private void incrementNumSheetExpansions() {
1660 getPreferences(Context.MODE_PRIVATE).edit().putInt(PREF_NUM_SHEET_EXPANSIONS,
1661 getNumSheetExpansions() + 1).apply();
1662 }
1663
1664 @Override
1665 protected void onStop() {
1666 super.onStop();
1667 if (maybeCancelFinishAnimation()) {
1668 finish();
1669 }
1670 }
1671
1672 @Override
1673 protected void onDestroy() {
1674 super.onDestroy();
1675
1676 if (isFinishing()) {
1677 mLatencyTracker.onActionCancel(ACTION_LOAD_SHARE_SHEET);
1678 }
1679
1680 if (mRefinementResultReceiver != null) {
1681 mRefinementResultReceiver.destroy();
1682 mRefinementResultReceiver = null;
1683 }
1684 mChooserHandler.removeAllMessages();
1685
1686 if (mPreviewCoord != null) mPreviewCoord.cancelLoads();
1687
1688 mChooserMultiProfilePagerAdapter.getActiveListAdapter().destroyAppPredictor();
1689 if (mChooserMultiProfilePagerAdapter.getInactiveListAdapter() != null) {
1690 mChooserMultiProfilePagerAdapter.getInactiveListAdapter().destroyAppPredictor();
1691 }
1692 mPersonalAppPredictor = null;
1693 mWorkAppPredictor = null;
1694 }
1695
1696 @Override // ResolverListCommunicator
1697 public Intent getReplacementIntent(ActivityInfo aInfo, Intent defIntent) {
1698 Intent result = defIntent;
1699 if (mReplacementExtras != null) {
1700 final Bundle replExtras = mReplacementExtras.getBundle(aInfo.packageName);
1701 if (replExtras != null) {
1702 result = new Intent(defIntent);
1703 result.putExtras(replExtras);
1704 }
1705 }
1706 if (aInfo.name.equals(IntentForwarderActivity.FORWARD_INTENT_TO_PARENT)
1707 || aInfo.name.equals(IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE)) {
1708 result = Intent.createChooser(result,
1709 getIntent().getCharSequenceExtra(Intent.EXTRA_TITLE));
1710
1711 // Don't auto-launch single intents if the intent is being forwarded. This is done
1712 // because automatically launching a resolving application as a response to the user
1713 // action of switching accounts is pretty unexpected.
1714 result.putExtra(Intent.EXTRA_AUTO_LAUNCH_SINGLE_CHOICE, false);
1715 }
1716 return result;
1717 }
1718
1719 @Override
1720 public void onActivityStarted(TargetInfo cti) {
1721 if (mChosenComponentSender != null) {
1722 final ComponentName target = cti.getResolvedComponentName();
1723 if (target != null) {
1724 final Intent fillIn = new Intent().putExtra(Intent.EXTRA_CHOSEN_COMPONENT, target);
1725 try {
1726 mChosenComponentSender.sendIntent(this, Activity.RESULT_OK, fillIn, null, null);
1727 } catch (IntentSender.SendIntentException e) {
1728 Slog.e(TAG, "Unable to launch supplied IntentSender to report "
1729 + "the chosen component: " + e);
1730 }
1731 }
1732 }
1733 }
1734
1735 @Override
1736 public void addUseDifferentAppLabelIfNecessary(ResolverListAdapter adapter) {
1737 if (mCallerChooserTargets != null && mCallerChooserTargets.length > 0) {
1738 mChooserMultiProfilePagerAdapter.getActiveListAdapter().addServiceResults(
1739 /* origTarget */ null,
1740 Lists.newArrayList(mCallerChooserTargets),
1741 TARGET_TYPE_DEFAULT,
1742 /* directShareShortcutInfoCache */ null);
1743 }
1744 }
1745
1746 @Override
1747 public int getLayoutResource() {
1748 return R.layout.chooser_grid;
1749 }
1750
1751 @Override // ResolverListCommunicator
1752 public boolean shouldGetActivityMetadata() {
1753 return true;
1754 }
1755
1756 @Override
1757 public boolean shouldAutoLaunchSingleChoice(TargetInfo target) {
1758 // Note that this is only safe because the Intent handled by the ChooserActivity is
1759 // guaranteed to contain no extras unknown to the local ClassLoader. That is why this
1760 // method can not be replaced in the ResolverActivity whole hog.
1761 if (!super.shouldAutoLaunchSingleChoice(target)) {
1762 return false;
1763 }
1764
1765 return getIntent().getBooleanExtra(Intent.EXTRA_AUTO_LAUNCH_SINGLE_CHOICE, true);
1766 }
1767
1768 private void showTargetDetails(TargetInfo targetInfo) {
1769 if (targetInfo == null) return;
1770
1771 ArrayList<DisplayResolveInfo> targetList;
1772 ChooserTargetActionsDialogFragment fragment = new ChooserTargetActionsDialogFragment();
1773 Bundle bundle = new Bundle();
1774
1775 if (targetInfo instanceof SelectableTargetInfo) {
1776 SelectableTargetInfo selectableTargetInfo = (SelectableTargetInfo) targetInfo;
1777 if (selectableTargetInfo.getDisplayResolveInfo() == null
1778 || selectableTargetInfo.getChooserTarget() == null) {
1779 Log.e(TAG, "displayResolveInfo or chooserTarget in selectableTargetInfo are null");
1780 return;
1781 }
1782 targetList = new ArrayList<>();
1783 targetList.add(selectableTargetInfo.getDisplayResolveInfo());
1784 bundle.putString(ChooserTargetActionsDialogFragment.SHORTCUT_ID_KEY,
1785 selectableTargetInfo.getChooserTarget().getIntentExtras().getString(
1786 Intent.EXTRA_SHORTCUT_ID));
1787 bundle.putBoolean(ChooserTargetActionsDialogFragment.IS_SHORTCUT_PINNED_KEY,
1788 selectableTargetInfo.isPinned());
1789 bundle.putParcelable(ChooserTargetActionsDialogFragment.INTENT_FILTER_KEY,
1790 getTargetIntentFilter());
1791 if (selectableTargetInfo.getDisplayLabel() != null) {
1792 bundle.putString(ChooserTargetActionsDialogFragment.SHORTCUT_TITLE_KEY,
1793 selectableTargetInfo.getDisplayLabel().toString());
1794 }
1795 } else if (targetInfo instanceof MultiDisplayResolveInfo) {
1796 // For multiple targets, include info on all targets
1797 MultiDisplayResolveInfo mti = (MultiDisplayResolveInfo) targetInfo;
1798 targetList = mti.getTargets();
1799 } else {
1800 targetList = new ArrayList<DisplayResolveInfo>();
1801 targetList.add((DisplayResolveInfo) targetInfo);
1802 }
1803 bundle.putParcelable(ChooserTargetActionsDialogFragment.USER_HANDLE_KEY,
1804 mChooserMultiProfilePagerAdapter.getCurrentUserHandle());
1805 bundle.putParcelableArrayList(ChooserTargetActionsDialogFragment.TARGET_INFOS_KEY,
1806 targetList);
1807 fragment.setArguments(bundle);
1808
1809 fragment.show(getFragmentManager(), TARGET_DETAILS_FRAGMENT_TAG);
1810 }
1811
1812 private void modifyTargetIntent(Intent in) {
1813 if (isSendAction(in)) {
1814 in.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
1815 Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
1816 }
1817 }
1818
1819 @Override
1820 protected boolean onTargetSelected(TargetInfo target, boolean alwaysCheck) {
1821 if (mRefinementIntentSender != null) {
1822 final Intent fillIn = new Intent();
1823 final List<Intent> sourceIntents = target.getAllSourceIntents();
1824 if (!sourceIntents.isEmpty()) {
1825 fillIn.putExtra(Intent.EXTRA_INTENT, sourceIntents.get(0));
1826 if (sourceIntents.size() > 1) {
1827 final Intent[] alts = new Intent[sourceIntents.size() - 1];
1828 for (int i = 1, N = sourceIntents.size(); i < N; i++) {
1829 alts[i - 1] = sourceIntents.get(i);
1830 }
1831 fillIn.putExtra(Intent.EXTRA_ALTERNATE_INTENTS, alts);
1832 }
1833 if (mRefinementResultReceiver != null) {
1834 mRefinementResultReceiver.destroy();
1835 }
1836 mRefinementResultReceiver = new RefinementResultReceiver(this, target, null);
1837 fillIn.putExtra(Intent.EXTRA_RESULT_RECEIVER,
1838 mRefinementResultReceiver);
1839 try {
1840 mRefinementIntentSender.sendIntent(this, 0, fillIn, null, null);
1841 return false;
1842 } catch (SendIntentException e) {
1843 Log.e(TAG, "Refinement IntentSender failed to send", e);
1844 }
1845 }
1846 }
1847 updateModelAndChooserCounts(target);
1848 return super.onTargetSelected(target, alwaysCheck);
1849 }
1850
1851 @Override
1852 public void startSelected(int which, boolean always, boolean filtered) {
1853 ChooserListAdapter currentListAdapter =
1854 mChooserMultiProfilePagerAdapter.getActiveListAdapter();
1855 TargetInfo targetInfo = currentListAdapter
1856 .targetInfoForPosition(which, filtered);
1857 if (targetInfo != null && targetInfo instanceof NotSelectableTargetInfo) {
1858 return;
1859 }
1860
1861 final long selectionCost = System.currentTimeMillis() - mChooserShownTime;
1862
1863 if (targetInfo instanceof MultiDisplayResolveInfo) {
1864 MultiDisplayResolveInfo mti = (MultiDisplayResolveInfo) targetInfo;
1865 if (!mti.hasSelected()) {
1866 ChooserStackedAppDialogFragment f = new ChooserStackedAppDialogFragment();
1867 Bundle b = new Bundle();
1868 b.putParcelable(ChooserTargetActionsDialogFragment.USER_HANDLE_KEY,
1869 mChooserMultiProfilePagerAdapter.getCurrentUserHandle());
1870 b.putObject(ChooserStackedAppDialogFragment.MULTI_DRI_KEY,
1871 mti);
1872 b.putInt(ChooserStackedAppDialogFragment.WHICH_KEY, which);
1873 f.setArguments(b);
1874
1875 f.show(getFragmentManager(), TARGET_DETAILS_FRAGMENT_TAG);
1876 return;
1877 }
1878 }
1879
1880 super.startSelected(which, always, filtered);
1881
1882 if (currentListAdapter.getCount() > 0) {
1883 // Log the index of which type of target the user picked.
1884 // Lower values mean the ranking was better.
1885 int cat = 0;
1886 int value = which;
1887 int directTargetAlsoRanked = -1;
1888 int numCallerProvided = 0;
1889 HashedStringCache.HashResult directTargetHashed = null;
1890 switch (currentListAdapter.getPositionTargetType(which)) {
1891 case ChooserListAdapter.TARGET_SERVICE:
1892 cat = MetricsEvent.ACTION_ACTIVITY_CHOOSER_PICKED_SERVICE_TARGET;
1893 // Log the package name + target name to answer the question if most users
1894 // share to mostly the same person or to a bunch of different people.
1895 ChooserTarget target = currentListAdapter.getChooserTargetForValue(value);
1896 directTargetHashed = HashedStringCache.getInstance().hashString(
1897 this,
1898 TAG,
1899 target.getComponentName().getPackageName()
1900 + target.getTitle().toString(),
1901 mMaxHashSaltDays);
1902 SelectableTargetInfo selectableTargetInfo = (SelectableTargetInfo) targetInfo;
1903 directTargetAlsoRanked = getRankedPosition(selectableTargetInfo);
1904
1905 if (mCallerChooserTargets != null) {
1906 numCallerProvided = mCallerChooserTargets.length;
1907 }
1908 getChooserActivityLogger().logShareTargetSelected(
1909 SELECTION_TYPE_SERVICE,
1910 targetInfo.getResolveInfo().activityInfo.processName,
1911 value,
1912 selectableTargetInfo.isPinned()
1913 );
1914 break;
1915 case ChooserListAdapter.TARGET_CALLER:
1916 case ChooserListAdapter.TARGET_STANDARD:
1917 cat = MetricsEvent.ACTION_ACTIVITY_CHOOSER_PICKED_APP_TARGET;
1918 value -= currentListAdapter.getSurfacedTargetInfo().size();
1919 numCallerProvided = currentListAdapter.getCallerTargetCount();
1920 getChooserActivityLogger().logShareTargetSelected(
1921 SELECTION_TYPE_APP,
1922 targetInfo.getResolveInfo().activityInfo.processName,
1923 value,
1924 targetInfo.isPinned()
1925 );
1926 break;
1927 case ChooserListAdapter.TARGET_STANDARD_AZ:
1928 // A-Z targets are unranked standard targets; we use -1 to mark that they
1929 // are from the alphabetical pool.
1930 value = -1;
1931 cat = MetricsEvent.ACTION_ACTIVITY_CHOOSER_PICKED_STANDARD_TARGET;
1932 getChooserActivityLogger().logShareTargetSelected(
1933 SELECTION_TYPE_STANDARD,
1934 targetInfo.getResolveInfo().activityInfo.processName,
1935 value,
1936 false
1937 );
1938 break;
1939 }
1940
1941 if (cat != 0) {
1942 LogMaker targetLogMaker = new LogMaker(cat).setSubtype(value);
1943 if (directTargetHashed != null) {
1944 targetLogMaker.addTaggedData(
1945 MetricsEvent.FIELD_HASHED_TARGET_NAME, directTargetHashed.hashedString);
1946 targetLogMaker.addTaggedData(
1947 MetricsEvent.FIELD_HASHED_TARGET_SALT_GEN,
1948 directTargetHashed.saltGeneration);
1949 targetLogMaker.addTaggedData(MetricsEvent.FIELD_RANKED_POSITION,
1950 directTargetAlsoRanked);
1951 }
1952 targetLogMaker.addTaggedData(MetricsEvent.FIELD_IS_CATEGORY_USED,
1953 numCallerProvided);
1954 getMetricsLogger().write(targetLogMaker);
1955 }
1956
1957 if (mIsSuccessfullySelected) {
1958 if (DEBUG) {
1959 Log.d(TAG, "User Selection Time Cost is " + selectionCost);
1960 Log.d(TAG, "position of selected app/service/caller is " +
1961 Integer.toString(value));
1962 }
1963 MetricsLogger.histogram(null, "user_selection_cost_for_smart_sharing",
1964 (int) selectionCost);
1965 MetricsLogger.histogram(null, "app_position_for_smart_sharing", value);
1966 }
1967 }
1968 }
1969
1970 private int getRankedPosition(SelectableTargetInfo targetInfo) {
1971 String targetPackageName =
1972 targetInfo.getChooserTarget().getComponentName().getPackageName();
1973 ChooserListAdapter currentListAdapter =
1974 mChooserMultiProfilePagerAdapter.getActiveListAdapter();
1975 int maxRankedResults = Math.min(currentListAdapter.mDisplayList.size(),
1976 MAX_LOG_RANK_POSITION);
1977
1978 for (int i = 0; i < maxRankedResults; i++) {
1979 if (currentListAdapter.mDisplayList.get(i)
1980 .getResolveInfo().activityInfo.packageName.equals(targetPackageName)) {
1981 return i;
1982 }
1983 }
1984 return -1;
1985 }
1986
1987 @Override
1988 protected boolean shouldAddFooterView() {
1989 // To accommodate for window insets
1990 return true;
1991 }
1992
1993 @Override
1994 protected void applyFooterView(int height) {
1995 int count = mChooserMultiProfilePagerAdapter.getItemCount();
1996
1997 for (int i = 0; i < count; i++) {
1998 mChooserMultiProfilePagerAdapter.getAdapterForIndex(i).setFooterHeight(height);
1999 }
2000 }
2001
2002 private IntentFilter getTargetIntentFilter() {
2003 try {
2004 final Intent intent = getTargetIntent();
2005 String dataString = intent.getDataString();
2006 if (intent.getType() == null) {
2007 if (!TextUtils.isEmpty(dataString)) {
2008 return new IntentFilter(intent.getAction(), dataString);
2009 }
2010 Log.e(TAG, "Failed to get target intent filter: intent data and type are null");
2011 return null;
2012 }
2013 IntentFilter intentFilter = new IntentFilter(intent.getAction(), intent.getType());
2014 List<Uri> contentUris = new ArrayList<>();
2015 if (Intent.ACTION_SEND.equals(intent.getAction())) {
2016 Uri uri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
2017 if (uri != null) {
2018 contentUris.add(uri);
2019 }
2020 } else {
2021 List<Uri> uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
2022 if (uris != null) {
2023 contentUris.addAll(uris);
2024 }
2025 }
2026 for (Uri uri : contentUris) {
2027 intentFilter.addDataScheme(uri.getScheme());
2028 intentFilter.addDataAuthority(uri.getAuthority(), null);
2029 intentFilter.addDataPath(uri.getPath(), PatternMatcher.PATTERN_LITERAL);
2030 }
2031 return intentFilter;
2032 } catch (Exception e) {
2033 Log.e(TAG, "Failed to get target intent filter", e);
2034 return null;
2035 }
2036 }
2037
2038 @VisibleForTesting
2039 protected void queryDirectShareTargets(
2040 ChooserListAdapter adapter, boolean skipAppPredictionService) {
2041 mQueriedSharingShortcutsTimeMs = System.currentTimeMillis();
2042 UserHandle userHandle = adapter.getUserHandle();
2043 if (!skipAppPredictionService) {
2044 AppPredictor appPredictor = getAppPredictorForDirectShareIfEnabled(userHandle);
2045 if (appPredictor != null) {
2046 appPredictor.requestPredictionUpdate();
2047 return;
2048 }
2049 }
2050 // Default to just querying ShortcutManager if AppPredictor not present.
2051 final IntentFilter filter = getTargetIntentFilter();
2052 if (filter == null) {
2053 return;
2054 }
2055
2056 AsyncTask.execute(() -> {
2057 Context selectedProfileContext = createContextAsUser(userHandle, 0 /* flags */);
2058 ShortcutManager sm = (ShortcutManager) selectedProfileContext
2059 .getSystemService(Context.SHORTCUT_SERVICE);
2060 List<ShortcutManager.ShareShortcutInfo> resultList = sm.getShareTargets(filter);
2061 sendShareShortcutInfoList(resultList, adapter, null, userHandle);
2062 });
2063 }
2064
2065 /**
2066 * Returns {@code false} if {@code userHandle} is the work profile and it's either
2067 * in quiet mode or not running.
2068 */
2069 private boolean shouldQueryShortcutManager(UserHandle userHandle) {
2070 if (!shouldShowTabs()) {
2071 return true;
2072 }
2073 if (!getWorkProfileUserHandle().equals(userHandle)) {
2074 return true;
2075 }
2076 if (!isUserRunning(userHandle)) {
2077 return false;
2078 }
2079 if (!isUserUnlocked(userHandle)) {
2080 return false;
2081 }
2082 if (isQuietModeEnabled(userHandle)) {
2083 return false;
2084 }
2085 return true;
2086 }
2087
2088 private void sendShareShortcutInfoList(
2089 List<ShortcutManager.ShareShortcutInfo> resultList,
2090 ChooserListAdapter chooserListAdapter,
2091 @Nullable List<AppTarget> appTargets, UserHandle userHandle) {
2092 if (appTargets != null && appTargets.size() != resultList.size()) {
2093 throw new RuntimeException("resultList and appTargets must have the same size."
2094 + " resultList.size()=" + resultList.size()
2095 + " appTargets.size()=" + appTargets.size());
2096 }
2097 Context selectedProfileContext = createContextAsUser(userHandle, 0 /* flags */);
2098 for (int i = resultList.size() - 1; i >= 0; i--) {
2099 final String packageName = resultList.get(i).getTargetComponent().getPackageName();
2100 if (!isPackageEnabled(selectedProfileContext, packageName)) {
2101 resultList.remove(i);
2102 if (appTargets != null) {
2103 appTargets.remove(i);
2104 }
2105 }
2106 }
2107
2108 // If |appTargets| is not null, results are from AppPredictionService and already sorted.
2109 final int shortcutType = (appTargets == null ? TARGET_TYPE_SHORTCUTS_FROM_SHORTCUT_MANAGER :
2110 TARGET_TYPE_SHORTCUTS_FROM_PREDICTION_SERVICE);
2111
2112 // Match ShareShortcutInfos with DisplayResolveInfos to be able to use the old code path
2113 // for direct share targets. After ShareSheet is refactored we should use the
2114 // ShareShortcutInfos directly.
2115 List<ServiceResultInfo> resultRecords = new ArrayList<>();
2116 for (int i = 0; i < chooserListAdapter.getDisplayResolveInfoCount(); i++) {
2117 DisplayResolveInfo displayResolveInfo = chooserListAdapter.getDisplayResolveInfo(i);
2118 List<ShortcutManager.ShareShortcutInfo> matchingShortcuts =
2119 filterShortcutsByTargetComponentName(
2120 resultList, displayResolveInfo.getResolvedComponentName());
2121 if (matchingShortcuts.isEmpty()) {
2122 continue;
2123 }
2124 List<ChooserTarget> chooserTargets = convertToChooserTarget(
2125 matchingShortcuts, resultList, appTargets, shortcutType);
2126
2127 ServiceResultInfo resultRecord = new ServiceResultInfo(
2128 displayResolveInfo, chooserTargets, userHandle);
2129 resultRecords.add(resultRecord);
2130 }
2131
2132 sendShortcutManagerShareTargetResults(
2133 shortcutType, resultRecords.toArray(new ServiceResultInfo[0]));
2134 }
2135
2136 private List<ShortcutManager.ShareShortcutInfo> filterShortcutsByTargetComponentName(
2137 List<ShortcutManager.ShareShortcutInfo> allShortcuts, ComponentName requiredTarget) {
2138 List<ShortcutManager.ShareShortcutInfo> matchingShortcuts = new ArrayList<>();
2139 for (ShortcutManager.ShareShortcutInfo shortcut : allShortcuts) {
2140 if (requiredTarget.equals(shortcut.getTargetComponent())) {
2141 matchingShortcuts.add(shortcut);
2142 }
2143 }
2144 return matchingShortcuts;
2145 }
2146
2147 @VisibleForTesting
2148 protected void sendShortcutManagerShareTargetResults(
2149 int shortcutType, ServiceResultInfo[] results) {
2150 final Message msg = Message.obtain();
2151 msg.what = ChooserHandler.SHORTCUT_MANAGER_ALL_SHARE_TARGET_RESULTS;
2152 msg.obj = results;
2153 msg.arg1 = shortcutType;
2154 mChooserHandler.sendMessage(msg);
2155 }
2156
2157 private boolean isPackageEnabled(Context context, String packageName) {
2158 if (TextUtils.isEmpty(packageName)) {
2159 return false;
2160 }
2161 ApplicationInfo appInfo;
2162 try {
2163 appInfo = context.getPackageManager().getApplicationInfo(packageName, 0);
2164 } catch (NameNotFoundException e) {
2165 return false;
2166 }
2167
2168 if (appInfo != null && appInfo.enabled
2169 && (appInfo.flags & ApplicationInfo.FLAG_SUSPENDED) == 0) {
2170 return true;
2171 }
2172 return false;
2173 }
2174
2175 /**
2176 * Converts a list of ShareShortcutInfos to ChooserTargets.
2177 * @param matchingShortcuts List of shortcuts, all from the same package, that match the current
2178 * share intent filter.
2179 * @param allShortcuts List of all the shortcuts from all the packages on the device that are
2180 * returned for the current sharing action.
2181 * @param allAppTargets List of AppTargets. Null if the results are not from prediction service.
2182 * @param shortcutType One of the values TARGET_TYPE_SHORTCUTS_FROM_SHORTCUT_MANAGER or
2183 * TARGET_TYPE_SHORTCUTS_FROM_PREDICTION_SERVICE
2184 * @return A list of ChooserTargets sorted by score in descending order.
2185 */
2186 @VisibleForTesting
2187 @NonNull
2188 public List<ChooserTarget> convertToChooserTarget(
2189 @NonNull List<ShortcutManager.ShareShortcutInfo> matchingShortcuts,
2190 @NonNull List<ShortcutManager.ShareShortcutInfo> allShortcuts,
2191 @Nullable List<AppTarget> allAppTargets, @ShareTargetType int shortcutType) {
2192 // A set of distinct scores for the matched shortcuts. We use index of a rank in the sorted
2193 // list instead of the actual rank value when converting a rank to a score.
2194 List<Integer> scoreList = new ArrayList<>();
2195 if (shortcutType == TARGET_TYPE_SHORTCUTS_FROM_SHORTCUT_MANAGER) {
2196 for (int i = 0; i < matchingShortcuts.size(); i++) {
2197 int shortcutRank = matchingShortcuts.get(i).getShortcutInfo().getRank();
2198 if (!scoreList.contains(shortcutRank)) {
2199 scoreList.add(shortcutRank);
2200 }
2201 }
2202 Collections.sort(scoreList);
2203 }
2204
2205 List<ChooserTarget> chooserTargetList = new ArrayList<>(matchingShortcuts.size());
2206 for (int i = 0; i < matchingShortcuts.size(); i++) {
2207 ShortcutInfo shortcutInfo = matchingShortcuts.get(i).getShortcutInfo();
2208 int indexInAllShortcuts = allShortcuts.indexOf(matchingShortcuts.get(i));
2209
2210 float score;
2211 if (shortcutType == TARGET_TYPE_SHORTCUTS_FROM_PREDICTION_SERVICE) {
2212 // Incoming results are ordered. Create a score based on index in the original list.
2213 score = Math.max(1.0f - (0.01f * indexInAllShortcuts), 0.0f);
2214 } else {
2215 // Create a score based on the rank of the shortcut.
2216 int rankIndex = scoreList.indexOf(shortcutInfo.getRank());
2217 score = Math.max(1.0f - (0.01f * rankIndex), 0.0f);
2218 }
2219
2220 Bundle extras = new Bundle();
2221 extras.putString(Intent.EXTRA_SHORTCUT_ID, shortcutInfo.getId());
2222
2223 ChooserTarget chooserTarget = new ChooserTarget(
2224 shortcutInfo.getLabel(),
2225 null, // Icon will be loaded later if this target is selected to be shown.
2226 score, matchingShortcuts.get(i).getTargetComponent().clone(), extras);
2227
2228 chooserTargetList.add(chooserTarget);
2229 if (mDirectShareAppTargetCache != null && allAppTargets != null) {
2230 mDirectShareAppTargetCache.put(chooserTarget,
2231 allAppTargets.get(indexInAllShortcuts));
2232 }
2233 if (mDirectShareShortcutInfoCache != null) {
2234 mDirectShareShortcutInfoCache.put(chooserTarget, shortcutInfo);
2235 }
2236 }
2237 // Sort ChooserTargets by score in descending order
2238 Comparator<ChooserTarget> byScore =
2239 (ChooserTarget a, ChooserTarget b) -> -Float.compare(a.getScore(), b.getScore());
2240 Collections.sort(chooserTargetList, byScore);
2241 return chooserTargetList;
2242 }
2243
2244 private void logDirectShareTargetReceived(int logCategory) {
2245 final int apiLatency = (int) (System.currentTimeMillis() - mQueriedSharingShortcutsTimeMs);
2246 getMetricsLogger().write(new LogMaker(logCategory).setSubtype(apiLatency));
2247 }
2248
2249 void updateModelAndChooserCounts(TargetInfo info) {
2250 if (info != null && info instanceof MultiDisplayResolveInfo) {
2251 info = ((MultiDisplayResolveInfo) info).getSelectedTarget();
2252 }
2253 if (info != null) {
2254 sendClickToAppPredictor(info);
2255 final ResolveInfo ri = info.getResolveInfo();
2256 Intent targetIntent = getTargetIntent();
2257 if (ri != null && ri.activityInfo != null && targetIntent != null) {
2258 ChooserListAdapter currentListAdapter =
2259 mChooserMultiProfilePagerAdapter.getActiveListAdapter();
2260 if (currentListAdapter != null) {
2261 sendImpressionToAppPredictor(info, currentListAdapter);
2262 currentListAdapter.updateModel(info.getResolvedComponentName());
2263 currentListAdapter.updateChooserCounts(ri.activityInfo.packageName,
2264 targetIntent.getAction());
2265 }
2266 if (DEBUG) {
2267 Log.d(TAG, "ResolveInfo Package is " + ri.activityInfo.packageName);
2268 Log.d(TAG, "Action to be updated is " + targetIntent.getAction());
2269 }
2270 } else if (DEBUG) {
2271 Log.d(TAG, "Can not log Chooser Counts of null ResovleInfo");
2272 }
2273 }
2274 mIsSuccessfullySelected = true;
2275 }
2276
2277 private void sendImpressionToAppPredictor(TargetInfo targetInfo, ChooserListAdapter adapter) {
2278 AppPredictor directShareAppPredictor = getAppPredictorForDirectShareIfEnabled(
2279 mChooserMultiProfilePagerAdapter.getCurrentUserHandle());
2280 if (directShareAppPredictor == null) {
2281 return;
2282 }
2283 // Send DS target impression info to AppPredictor, only when user chooses app share.
2284 if (targetInfo instanceof ChooserTargetInfo) {
2285 return;
2286 }
2287 List<ChooserTargetInfo> surfacedTargetInfo = adapter.getSurfacedTargetInfo();
2288 List<AppTargetId> targetIds = new ArrayList<>();
2289 for (ChooserTargetInfo chooserTargetInfo : surfacedTargetInfo) {
2290 ChooserTarget chooserTarget = chooserTargetInfo.getChooserTarget();
2291 ComponentName componentName = chooserTarget.getComponentName();
2292 if (mDirectShareShortcutInfoCache.containsKey(chooserTarget)) {
2293 String shortcutId = mDirectShareShortcutInfoCache.get(chooserTarget).getId();
2294 targetIds.add(new AppTargetId(
2295 String.format("%s/%s/%s", shortcutId, componentName.flattenToString(),
2296 SHORTCUT_TARGET)));
2297 }
2298 }
2299 directShareAppPredictor.notifyLaunchLocationShown(LAUNCH_LOCATION_DIRECT_SHARE, targetIds);
2300 }
2301
2302 private void sendClickToAppPredictor(TargetInfo targetInfo) {
2303 AppPredictor directShareAppPredictor = getAppPredictorForDirectShareIfEnabled(
2304 mChooserMultiProfilePagerAdapter.getCurrentUserHandle());
2305 if (directShareAppPredictor == null) {
2306 return;
2307 }
2308 if (!(targetInfo instanceof ChooserTargetInfo)) {
2309 return;
2310 }
2311 ChooserTarget chooserTarget = ((ChooserTargetInfo) targetInfo).getChooserTarget();
2312 AppTarget appTarget = null;
2313 if (mDirectShareAppTargetCache != null) {
2314 appTarget = mDirectShareAppTargetCache.get(chooserTarget);
2315 }
2316 // This is a direct share click that was provided by the APS
2317 if (appTarget != null) {
2318 directShareAppPredictor.notifyAppTargetEvent(
2319 new AppTargetEvent.Builder(appTarget, AppTargetEvent.ACTION_LAUNCH)
2320 .setLaunchLocation(LAUNCH_LOCATION_DIRECT_SHARE)
2321 .build());
2322 }
2323 }
2324
2325 @Nullable
2326 private AppPredictor createAppPredictor(UserHandle userHandle) {
2327 if (!mIsAppPredictorComponentAvailable) {
2328 return null;
2329 }
2330
2331 if (getPersonalProfileUserHandle().equals(userHandle)) {
2332 if (mPersonalAppPredictor != null) {
2333 return mPersonalAppPredictor;
2334 }
2335 } else {
2336 if (mWorkAppPredictor != null) {
2337 return mWorkAppPredictor;
2338 }
2339 }
2340
2341 // TODO(b/148230574): Currently AppPredictor fetches only the same-profile app targets.
2342 // Make AppPredictor work cross-profile.
2343 Context contextAsUser = createContextAsUser(userHandle, 0 /* flags */);
2344 final IntentFilter filter = getTargetIntentFilter();
2345 Bundle extras = new Bundle();
2346 extras.putParcelable(APP_PREDICTION_INTENT_FILTER_KEY, filter);
2347 populateTextContent(extras);
2348 AppPredictionContext appPredictionContext = new AppPredictionContext.Builder(contextAsUser)
2349 .setUiSurface(APP_PREDICTION_SHARE_UI_SURFACE)
2350 .setPredictedTargetCount(APP_PREDICTION_SHARE_TARGET_QUERY_PACKAGE_LIMIT)
2351 .setExtras(extras)
2352 .build();
2353 AppPredictionManager appPredictionManager =
2354 contextAsUser
2355 .getSystemService(AppPredictionManager.class);
2356 AppPredictor appPredictionSession = appPredictionManager.createAppPredictionSession(
2357 appPredictionContext);
2358 if (getPersonalProfileUserHandle().equals(userHandle)) {
2359 mPersonalAppPredictor = appPredictionSession;
2360 } else {
2361 mWorkAppPredictor = appPredictionSession;
2362 }
2363 return appPredictionSession;
2364 }
2365
2366 private void populateTextContent(Bundle extras) {
2367 final Intent intent = getTargetIntent();
2368 String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
2369 extras.putString(SHARED_TEXT_KEY, sharedText);
2370 }
2371
2372 /**
2373 * This will return an app predictor if it is enabled for direct share sorting
2374 * and if one exists. Otherwise, it returns null.
2375 * @param userHandle
2376 */
2377 @Nullable
2378 private AppPredictor getAppPredictorForDirectShareIfEnabled(UserHandle userHandle) {
2379 return ChooserFlags.USE_PREDICTION_MANAGER_FOR_DIRECT_TARGETS
2380 && !ActivityManager.isLowRamDeviceStatic() ? createAppPredictor(userHandle) : null;
2381 }
2382
2383 /**
2384 * This will return an app predictor if it is enabled for share activity sorting
2385 * and if one exists. Otherwise, it returns null.
2386 */
2387 @Nullable
2388 private AppPredictor getAppPredictorForShareActivitiesIfEnabled(UserHandle userHandle) {
2389 return USE_PREDICTION_MANAGER_FOR_SHARE_ACTIVITIES ? createAppPredictor(userHandle) : null;
2390 }
2391
2392 void onRefinementResult(TargetInfo selectedTarget, Intent matchingIntent) {
2393 if (mRefinementResultReceiver != null) {
2394 mRefinementResultReceiver.destroy();
2395 mRefinementResultReceiver = null;
2396 }
2397 if (selectedTarget == null) {
2398 Log.e(TAG, "Refinement result intent did not match any known targets; canceling");
2399 } else if (!checkTargetSourceIntent(selectedTarget, matchingIntent)) {
2400 Log.e(TAG, "onRefinementResult: Selected target " + selectedTarget
2401 + " cannot match refined source intent " + matchingIntent);
2402 } else {
2403 TargetInfo clonedTarget = selectedTarget.cloneFilledIn(matchingIntent, 0);
2404 if (super.onTargetSelected(clonedTarget, false)) {
2405 updateModelAndChooserCounts(clonedTarget);
2406 finish();
2407 return;
2408 }
2409 }
2410 onRefinementCanceled();
2411 }
2412
2413 void onRefinementCanceled() {
2414 if (mRefinementResultReceiver != null) {
2415 mRefinementResultReceiver.destroy();
2416 mRefinementResultReceiver = null;
2417 }
2418 finish();
2419 }
2420
2421 boolean checkTargetSourceIntent(TargetInfo target, Intent matchingIntent) {
2422 final List<Intent> targetIntents = target.getAllSourceIntents();
2423 for (int i = 0, N = targetIntents.size(); i < N; i++) {
2424 final Intent targetIntent = targetIntents.get(i);
2425 if (targetIntent.filterEquals(matchingIntent)) {
2426 return true;
2427 }
2428 }
2429 return false;
2430 }
2431
2432 /**
2433 * Sort intents alphabetically based on display label.
2434 */
2435 static class AzInfoComparator implements Comparator<DisplayResolveInfo> {
2436 Collator mCollator;
2437 AzInfoComparator(Context context) {
2438 mCollator = Collator.getInstance(context.getResources().getConfiguration().locale);
2439 }
2440
2441 @Override
2442 public int compare(
2443 DisplayResolveInfo lhsp, DisplayResolveInfo rhsp) {
2444 return mCollator.compare(lhsp.getDisplayLabel(), rhsp.getDisplayLabel());
2445 }
2446 }
2447
2448 protected MetricsLogger getMetricsLogger() {
2449 if (mMetricsLogger == null) {
2450 mMetricsLogger = new MetricsLogger();
2451 }
2452 return mMetricsLogger;
2453 }
2454
2455 protected ChooserActivityLogger getChooserActivityLogger() {
2456 if (mChooserActivityLogger == null) {
2457 mChooserActivityLogger = new ChooserActivityLoggerImpl();
2458 }
2459 return mChooserActivityLogger;
2460 }
2461
2462 public class ChooserListController extends ResolverListController {
2463 public ChooserListController(Context context,
2464 PackageManager pm,
2465 Intent targetIntent,
2466 String referrerPackageName,
2467 int launchedFromUid,
2468 UserHandle userId,
2469 AbstractResolverComparator resolverComparator) {
2470 super(context, pm, targetIntent, referrerPackageName, launchedFromUid, userId,
2471 resolverComparator);
2472 }
2473
2474 @Override
2475 boolean isComponentFiltered(ComponentName name) {
2476 if (mFilteredComponentNames == null) {
2477 return false;
2478 }
2479 for (ComponentName filteredComponentName : mFilteredComponentNames) {
2480 if (name.equals(filteredComponentName)) {
2481 return true;
2482 }
2483 }
2484 return false;
2485 }
2486
2487 @Override
2488 public boolean isComponentPinned(ComponentName name) {
2489 return mPinnedSharedPrefs.getBoolean(name.flattenToString(), false);
2490 }
2491
2492 @Override
2493 public boolean isFixedAtTop(ComponentName name) {
2494 return name != null && name.equals(getNearbySharingComponent())
2495 && shouldNearbyShareBeFirstInRankedRow();
2496 }
2497 }
2498
2499 @VisibleForTesting
2500 public ChooserGridAdapter createChooserGridAdapter(Context context,
2501 List<Intent> payloadIntents, Intent[] initialIntents, List<ResolveInfo> rList,
2502 boolean filterLastUsed, UserHandle userHandle) {
2503 ChooserListAdapter chooserListAdapter = createChooserListAdapter(context, payloadIntents,
2504 initialIntents, rList, filterLastUsed,
2505 createListController(userHandle));
2506 AppPredictor.Callback appPredictorCallback = createAppPredictorCallback(chooserListAdapter);
2507 AppPredictor appPredictor = setupAppPredictorForUser(userHandle, appPredictorCallback);
2508 chooserListAdapter.setAppPredictor(appPredictor);
2509 chooserListAdapter.setAppPredictorCallback(appPredictorCallback);
2510 return new ChooserGridAdapter(chooserListAdapter);
2511 }
2512
2513 @VisibleForTesting
2514 public ChooserListAdapter createChooserListAdapter(Context context,
2515 List<Intent> payloadIntents, Intent[] initialIntents, List<ResolveInfo> rList,
2516 boolean filterLastUsed, ResolverListController resolverListController) {
2517 return new ChooserListAdapter(context, payloadIntents, initialIntents, rList,
2518 filterLastUsed, resolverListController, this,
2519 this, context.getPackageManager(),
2520 getChooserActivityLogger());
2521 }
2522
2523 @VisibleForTesting
2524 protected ResolverListController createListController(UserHandle userHandle) {
2525 AppPredictor appPredictor = getAppPredictorForShareActivitiesIfEnabled(userHandle);
2526 AbstractResolverComparator resolverComparator;
2527 if (appPredictor != null) {
2528 resolverComparator = new AppPredictionServiceResolverComparator(this, getTargetIntent(),
2529 getReferrerPackageName(), appPredictor, userHandle, getChooserActivityLogger());
2530 } else {
2531 resolverComparator =
2532 new ResolverRankerServiceResolverComparator(this, getTargetIntent(),
2533 getReferrerPackageName(), null, getChooserActivityLogger());
2534 }
2535
2536 return new ChooserListController(
2537 this,
2538 mPm,
2539 getTargetIntent(),
2540 getReferrerPackageName(),
2541 mLaunchedFromUid,
2542 userHandle,
2543 resolverComparator);
2544 }
2545
2546 @VisibleForTesting
2547 protected Bitmap loadThumbnail(Uri uri, Size size) {
2548 if (uri == null || size == null) {
2549 return null;
2550 }
2551
2552 try {
2553 return getContentResolver().loadThumbnail(uri, size, null);
2554 } catch (IOException | NullPointerException | SecurityException ex) {
2555 logContentPreviewWarning(uri);
2556 }
2557 return null;
2558 }
2559
2560 static final class PlaceHolderTargetInfo extends NotSelectableTargetInfo {
2561 public Drawable getDisplayIcon(Context context) {
2562 AnimatedVectorDrawable avd = (AnimatedVectorDrawable)
2563 context.getDrawable(R.drawable.chooser_direct_share_icon_placeholder);
2564 avd.start(); // Start animation after generation
2565 return avd;
2566 }
2567 }
2568
2569 protected static final class EmptyTargetInfo extends NotSelectableTargetInfo {
2570 public EmptyTargetInfo() {}
2571
2572 public Drawable getDisplayIcon(Context context) {
2573 return null;
2574 }
2575 }
2576
2577 private void handleScroll(View view, int x, int y, int oldx, int oldy) {
2578 if (mChooserMultiProfilePagerAdapter.getCurrentRootAdapter() != null) {
2579 mChooserMultiProfilePagerAdapter.getCurrentRootAdapter().handleScroll(view, y, oldy);
2580 }
2581 }
2582
2583 /*
2584 * Need to dynamically adjust how many icons can fit per row before we add them,
2585 * which also means setting the correct offset to initially show the content
2586 * preview area + 2 rows of targets
2587 */
2588 private void handleLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft,
2589 int oldTop, int oldRight, int oldBottom) {
2590 if (mChooserMultiProfilePagerAdapter == null) {
2591 return;
2592 }
2593 RecyclerView recyclerView = mChooserMultiProfilePagerAdapter.getActiveAdapterView();
2594 ChooserGridAdapter gridAdapter = mChooserMultiProfilePagerAdapter.getCurrentRootAdapter();
2595 // Skip height calculation if recycler view was scrolled to prevent it inaccurately
2596 // calculating the height, as the logic below does not account for the scrolled offset.
2597 if (gridAdapter == null || recyclerView == null
2598 || recyclerView.computeVerticalScrollOffset() != 0) {
2599 return;
2600 }
2601
2602 final int availableWidth = right - left - v.getPaddingLeft() - v.getPaddingRight();
2603 boolean isLayoutUpdated = gridAdapter.consumeLayoutRequest()
2604 || gridAdapter.calculateChooserTargetWidth(availableWidth)
2605 || recyclerView.getAdapter() == null
2606 || availableWidth != mCurrAvailableWidth;
2607
2608 boolean insetsChanged = !Objects.equals(mLastAppliedInsets, mSystemWindowInsets);
2609
2610 if (isLayoutUpdated
2611 || insetsChanged
2612 || mLastNumberOfChildren != recyclerView.getChildCount()) {
2613 mCurrAvailableWidth = availableWidth;
2614 if (isLayoutUpdated) {
2615 // It is very important we call setAdapter from here. Otherwise in some cases
2616 // the resolver list doesn't get populated, such as b/150922090, b/150918223
2617 // and b/150936654
2618 recyclerView.setAdapter(gridAdapter);
2619 ((GridLayoutManager) recyclerView.getLayoutManager()).setSpanCount(
2620 mMaxTargetsPerRow);
2621
2622 updateTabPadding();
2623 }
2624
2625 UserHandle currentUserHandle = mChooserMultiProfilePagerAdapter.getCurrentUserHandle();
2626 int currentProfile = getProfileForUser(currentUserHandle);
2627 int initialProfile = findSelectedProfile();
2628 if (currentProfile != initialProfile) {
2629 return;
2630 }
2631
2632 if (mLastNumberOfChildren == recyclerView.getChildCount() && !insetsChanged) {
2633 return;
2634 }
2635
2636 getMainThreadHandler().post(() -> {
2637 if (mResolverDrawerLayout == null || gridAdapter == null) {
2638 return;
2639 }
2640 int offset = calculateDrawerOffset(top, bottom, recyclerView, gridAdapter);
2641 mResolverDrawerLayout.setCollapsibleHeightReserved(offset);
2642 mEnterTransitionAnimationDelegate.markOffsetCalculated();
2643 mLastAppliedInsets = mSystemWindowInsets;
2644 });
2645 }
2646 }
2647
2648 private int calculateDrawerOffset(
2649 int top, int bottom, RecyclerView recyclerView, ChooserGridAdapter gridAdapter) {
2650
2651 final int bottomInset = mSystemWindowInsets != null
2652 ? mSystemWindowInsets.bottom : 0;
2653 int offset = bottomInset;
2654 int rowsToShow = gridAdapter.getSystemRowCount()
2655 + gridAdapter.getProfileRowCount()
2656 + gridAdapter.getServiceTargetRowCount()
2657 + gridAdapter.getCallerAndRankedTargetRowCount();
2658
2659 // then this is most likely not a SEND_* action, so check
2660 // the app target count
2661 if (rowsToShow == 0) {
2662 rowsToShow = gridAdapter.getRowCount();
2663 }
2664
2665 // still zero? then use a default height and leave, which
2666 // can happen when there are no targets to show
2667 if (rowsToShow == 0 && !shouldShowStickyContentPreview()) {
2668 offset += getResources().getDimensionPixelSize(
2669 R.dimen.chooser_max_collapsed_height);
2670 return offset;
2671 }
2672
2673 View stickyContentPreview = findViewById(R.id.content_preview_container);
2674 if (shouldShowStickyContentPreview() && isStickyContentPreviewShowing()) {
2675 offset += stickyContentPreview.getHeight();
2676 }
2677
2678 if (shouldShowTabs()) {
2679 offset += findViewById(R.id.tabs).getHeight();
2680 }
2681
2682 if (recyclerView.getVisibility() == View.VISIBLE) {
2683 int directShareHeight = 0;
2684 rowsToShow = Math.min(4, rowsToShow);
2685 boolean shouldShowExtraRow = shouldShowExtraRow(rowsToShow);
2686 mLastNumberOfChildren = recyclerView.getChildCount();
2687 for (int i = 0, childCount = recyclerView.getChildCount();
2688 i < childCount && rowsToShow > 0; i++) {
2689 View child = recyclerView.getChildAt(i);
2690 if (((GridLayoutManager.LayoutParams)
2691 child.getLayoutParams()).getSpanIndex() != 0) {
2692 continue;
2693 }
2694 int height = child.getHeight();
2695 offset += height;
2696 if (shouldShowExtraRow) {
2697 offset += height;
2698 }
2699
2700 if (gridAdapter.getTargetType(
2701 recyclerView.getChildAdapterPosition(child))
2702 == ChooserListAdapter.TARGET_SERVICE) {
2703 directShareHeight = height;
2704 }
2705 rowsToShow--;
2706 }
2707
2708 boolean isExpandable = getResources().getConfiguration().orientation
2709 == Configuration.ORIENTATION_PORTRAIT && !isInMultiWindowMode();
2710 if (directShareHeight != 0 && shouldShowContentPreview()
2711 && isExpandable) {
2712 // make sure to leave room for direct share 4->8 expansion
2713 int requiredExpansionHeight =
2714 (int) (directShareHeight / DIRECT_SHARE_EXPANSION_RATE);
2715 int topInset = mSystemWindowInsets != null ? mSystemWindowInsets.top : 0;
2716 int minHeight = bottom - top - mResolverDrawerLayout.getAlwaysShowHeight()
2717 - requiredExpansionHeight - topInset - bottomInset;
2718
2719 offset = Math.min(offset, minHeight);
2720 }
2721 } else {
2722 ViewGroup currentEmptyStateView = getActiveEmptyStateView();
2723 if (currentEmptyStateView.getVisibility() == View.VISIBLE) {
2724 offset += currentEmptyStateView.getHeight();
2725 }
2726 }
2727
2728 return Math.min(offset, bottom - top);
2729 }
2730
2731 /**
2732 * If we have a tabbed view and are showing 1 row in the current profile and an empty
2733 * state screen in the other profile, to prevent cropping of the empty state screen we show
2734 * a second row in the current profile.
2735 */
2736 private boolean shouldShowExtraRow(int rowsToShow) {
2737 return shouldShowTabs()
2738 && rowsToShow == 1
2739 && mChooserMultiProfilePagerAdapter.shouldShowEmptyStateScreen(
2740 mChooserMultiProfilePagerAdapter.getInactiveListAdapter());
2741 }
2742
2743 /**
2744 * Returns {@link #PROFILE_PERSONAL}, {@link #PROFILE_WORK}, or -1 if the given user handle
2745 * does not match either the personal or work user handle.
2746 **/
2747 private int getProfileForUser(UserHandle currentUserHandle) {
2748 if (currentUserHandle.equals(getPersonalProfileUserHandle())) {
2749 return PROFILE_PERSONAL;
2750 } else if (currentUserHandle.equals(getWorkProfileUserHandle())) {
2751 return PROFILE_WORK;
2752 }
2753 Log.e(TAG, "User " + currentUserHandle + " does not belong to a personal or work profile.");
2754 return -1;
2755 }
2756
2757 private ViewGroup getActiveEmptyStateView() {
2758 int currentPage = mChooserMultiProfilePagerAdapter.getCurrentPage();
2759 return mChooserMultiProfilePagerAdapter.getItem(currentPage).getEmptyStateView();
2760 }
2761
2762 static class BaseChooserTargetComparator implements Comparator<ChooserTarget> {
2763 @Override
2764 public int compare(ChooserTarget lhs, ChooserTarget rhs) {
2765 // Descending order
2766 return (int) Math.signum(rhs.getScore() - lhs.getScore());
2767 }
2768 }
2769
2770 @Override // ResolverListCommunicator
2771 public void onHandlePackagesChanged(ResolverListAdapter listAdapter) {
2772 mChooserMultiProfilePagerAdapter.getActiveListAdapter().notifyDataSetChanged();
2773 super.onHandlePackagesChanged(listAdapter);
2774 }
2775
2776 @Override // SelectableTargetInfoCommunicator
2777 public ActivityInfoPresentationGetter makePresentationGetter(ActivityInfo info) {
2778 return mChooserMultiProfilePagerAdapter.getActiveListAdapter().makePresentationGetter(info);
2779 }
2780
2781 @Override // SelectableTargetInfoCommunicator
2782 public Intent getReferrerFillInIntent() {
2783 return mReferrerFillInIntent;
2784 }
2785
2786 @Override // ChooserListCommunicator
2787 public int getMaxRankedTargets() {
2788 return mMaxTargetsPerRow;
2789 }
2790
2791 @Override // ChooserListCommunicator
2792 public void sendListViewUpdateMessage(UserHandle userHandle) {
2793 Message msg = Message.obtain();
2794 msg.what = ChooserHandler.LIST_VIEW_UPDATE_MESSAGE;
2795 msg.obj = userHandle;
2796 mChooserHandler.sendMessageDelayed(msg, mListViewUpdateDelayMs);
2797 }
2798
2799 @Override
2800 public void onListRebuilt(ResolverListAdapter listAdapter, boolean rebuildComplete) {
2801 setupScrollListener();
2802 maybeSetupGlobalLayoutListener();
2803
2804 ChooserListAdapter chooserListAdapter = (ChooserListAdapter) listAdapter;
2805 if (chooserListAdapter.getUserHandle()
2806 .equals(mChooserMultiProfilePagerAdapter.getCurrentUserHandle())) {
2807 mChooserMultiProfilePagerAdapter.getActiveAdapterView()
2808 .setAdapter(mChooserMultiProfilePagerAdapter.getCurrentRootAdapter());
2809 mChooserMultiProfilePagerAdapter
2810 .setupListAdapter(mChooserMultiProfilePagerAdapter.getCurrentPage());
2811 }
2812
2813 if (chooserListAdapter.mDisplayList == null
2814 || chooserListAdapter.mDisplayList.isEmpty()) {
2815 chooserListAdapter.notifyDataSetChanged();
2816 } else {
2817 chooserListAdapter.updateAlphabeticalList();
2818 }
2819
2820 if (rebuildComplete) {
2821 getChooserActivityLogger().logSharesheetAppLoadComplete();
2822 maybeQueryAdditionalPostProcessingTargets(chooserListAdapter);
2823 mLatencyTracker.onActionEnd(ACTION_LOAD_SHARE_SHEET);
2824 }
2825 }
2826
2827 private void maybeQueryAdditionalPostProcessingTargets(ChooserListAdapter chooserListAdapter) {
2828 // don't support direct share on low ram devices
2829 if (ActivityManager.isLowRamDeviceStatic()) {
2830 return;
2831 }
2832
2833 // no need to query direct share for work profile when its locked or disabled
2834 if (!shouldQueryShortcutManager(chooserListAdapter.getUserHandle())) {
2835 return;
2836 }
2837
2838 if (ChooserFlags.USE_PREDICTION_MANAGER_FOR_DIRECT_TARGETS) {
2839 if (DEBUG) {
2840 Log.d(TAG, "querying direct share targets from ShortcutManager");
2841 }
2842
2843 queryDirectShareTargets(chooserListAdapter, false);
2844 }
2845 }
2846
2847 @VisibleForTesting
2848 protected boolean isUserRunning(UserHandle userHandle) {
2849 UserManager userManager = getSystemService(UserManager.class);
2850 return userManager.isUserRunning(userHandle);
2851 }
2852
2853 @VisibleForTesting
2854 protected boolean isUserUnlocked(UserHandle userHandle) {
2855 UserManager userManager = getSystemService(UserManager.class);
2856 return userManager.isUserUnlocked(userHandle);
2857 }
2858
2859 @VisibleForTesting
2860 protected boolean isQuietModeEnabled(UserHandle userHandle) {
2861 UserManager userManager = getSystemService(UserManager.class);
2862 return userManager.isQuietModeEnabled(userHandle);
2863 }
2864
2865 private void setupScrollListener() {
2866 if (mResolverDrawerLayout == null) {
2867 return;
2868 }
2869 int elevatedViewResId = shouldShowTabs() ? R.id.tabs : R.id.chooser_header;
2870 final View elevatedView = mResolverDrawerLayout.findViewById(elevatedViewResId);
2871 final float defaultElevation = elevatedView.getElevation();
2872 final float chooserHeaderScrollElevation =
2873 getResources().getDimensionPixelSize(R.dimen.chooser_header_scroll_elevation);
2874 mChooserMultiProfilePagerAdapter.getActiveAdapterView().addOnScrollListener(
2875 new RecyclerView.OnScrollListener() {
2876 public void onScrollStateChanged(RecyclerView view, int scrollState) {
2877 if (scrollState == RecyclerView.SCROLL_STATE_IDLE) {
2878 if (mScrollStatus == SCROLL_STATUS_SCROLLING_VERTICAL) {
2879 mScrollStatus = SCROLL_STATUS_IDLE;
2880 setHorizontalScrollingEnabled(true);
2881 }
2882 } else if (scrollState == RecyclerView.SCROLL_STATE_DRAGGING) {
2883 if (mScrollStatus == SCROLL_STATUS_IDLE) {
2884 mScrollStatus = SCROLL_STATUS_SCROLLING_VERTICAL;
2885 setHorizontalScrollingEnabled(false);
2886 }
2887 }
2888 }
2889
2890 public void onScrolled(RecyclerView view, int dx, int dy) {
2891 if (view.getChildCount() > 0) {
2892 View child = view.getLayoutManager().findViewByPosition(0);
2893 if (child == null || child.getTop() < 0) {
2894 elevatedView.setElevation(chooserHeaderScrollElevation);
2895 return;
2896 }
2897 }
2898
2899 elevatedView.setElevation(defaultElevation);
2900 }
2901 });
2902 }
2903
2904 private void maybeSetupGlobalLayoutListener() {
2905 if (shouldShowTabs()) {
2906 return;
2907 }
2908 final View recyclerView = mChooserMultiProfilePagerAdapter.getActiveAdapterView();
2909 recyclerView.getViewTreeObserver()
2910 .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
2911 @Override
2912 public void onGlobalLayout() {
2913 // Fixes an issue were the accessibility border disappears on list creation.
2914 recyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
2915 final TextView titleView = findViewById(R.id.title);
2916 if (titleView != null) {
2917 titleView.setFocusable(true);
2918 titleView.setFocusableInTouchMode(true);
2919 titleView.requestFocus();
2920 titleView.requestAccessibilityFocus();
2921 }
2922 }
2923 });
2924 }
2925
2926 @Override // ChooserListCommunicator
2927 public boolean isSendAction(Intent targetIntent) {
2928 if (targetIntent == null) {
2929 return false;
2930 }
2931
2932 String action = targetIntent.getAction();
2933 if (action == null) {
2934 return false;
2935 }
2936
2937 if (Intent.ACTION_SEND.equals(action) || Intent.ACTION_SEND_MULTIPLE.equals(action)) {
2938 return true;
2939 }
2940
2941 return false;
2942 }
2943
2944 /**
2945 * The sticky content preview is shown only when we have a tabbed view. It's shown above
2946 * the tabs so it is not part of the scrollable list. If we are not in tabbed view,
2947 * we instead show the content preview as a regular list item.
2948 */
2949 private boolean shouldShowStickyContentPreview() {
2950 return shouldShowStickyContentPreviewNoOrientationCheck()
2951 && !getResources().getBoolean(R.bool.resolver_landscape_phone);
2952 }
2953
2954 private boolean shouldShowStickyContentPreviewNoOrientationCheck() {
2955 return shouldShowTabs()
2956 && mMultiProfilePagerAdapter.getListAdapterForUserHandle(
2957 UserHandle.of(UserHandle.myUserId())).getCount() > 0
2958 && shouldShowContentPreview();
2959 }
2960
2961 /**
2962 * @return true if we want to show the content preview area
2963 */
2964 protected boolean shouldShowContentPreview() {
2965 return isSendAction(getTargetIntent());
2966 }
2967
2968 private void updateStickyContentPreview() {
2969 if (shouldShowStickyContentPreviewNoOrientationCheck()) {
2970 // The sticky content preview is only shown when we show the work and personal tabs.
2971 // We don't show it in landscape as otherwise there is no room for scrolling.
2972 // If the sticky content preview will be shown at some point with orientation change,
2973 // then always preload it to avoid subsequent resizing of the share sheet.
2974 ViewGroup contentPreviewContainer = findViewById(R.id.content_preview_container);
2975 if (contentPreviewContainer.getChildCount() == 0) {
2976 ViewGroup contentPreviewView = createContentPreviewView(contentPreviewContainer);
2977 contentPreviewContainer.addView(contentPreviewView);
2978 }
2979 }
2980 if (shouldShowStickyContentPreview()) {
2981 showStickyContentPreview();
2982 } else {
2983 hideStickyContentPreview();
2984 }
2985 }
2986
2987 private void showStickyContentPreview() {
2988 if (isStickyContentPreviewShowing()) {
2989 return;
2990 }
2991 ViewGroup contentPreviewContainer = findViewById(R.id.content_preview_container);
2992 contentPreviewContainer.setVisibility(View.VISIBLE);
2993 }
2994
2995 private boolean isStickyContentPreviewShowing() {
2996 ViewGroup contentPreviewContainer = findViewById(R.id.content_preview_container);
2997 return contentPreviewContainer.getVisibility() == View.VISIBLE;
2998 }
2999
3000 private void hideStickyContentPreview() {
3001 if (!isStickyContentPreviewShowing()) {
3002 return;
3003 }
3004 ViewGroup contentPreviewContainer = findViewById(R.id.content_preview_container);
3005 contentPreviewContainer.setVisibility(View.GONE);
3006 }
3007
3008 private void logActionShareWithPreview() {
3009 Intent targetIntent = getTargetIntent();
3010 int previewType = findPreferredContentPreview(targetIntent, getContentResolver());
3011 getMetricsLogger().write(new LogMaker(MetricsEvent.ACTION_SHARE_WITH_PREVIEW)
3012 .setSubtype(previewType));
3013 }
3014
3015 private void startFinishAnimation() {
3016 View rootView = findRootView();
3017 if (rootView != null) {
3018 rootView.startAnimation(new FinishAnimation(this, rootView));
3019 }
3020 }
3021
3022 private boolean maybeCancelFinishAnimation() {
3023 View rootView = findRootView();
3024 Animation animation = rootView == null ? null : rootView.getAnimation();
3025 if (animation instanceof FinishAnimation) {
3026 boolean hasEnded = animation.hasEnded();
3027 animation.cancel();
3028 rootView.clearAnimation();
3029 return !hasEnded;
3030 }
3031 return false;
3032 }
3033
3034 private View findRootView() {
3035 if (mContentView == null) {
3036 mContentView = findViewById(android.R.id.content);
3037 }
3038 return mContentView;
3039 }
3040
3041 abstract static class ViewHolderBase extends RecyclerView.ViewHolder {
3042 private int mViewType;
3043
3044 ViewHolderBase(View itemView, int viewType) {
3045 super(itemView);
3046 this.mViewType = viewType;
3047 }
3048
3049 int getViewType() {
3050 return mViewType;
3051 }
3052 }
3053
3054 /**
3055 * Used to bind types of individual item including
3056 * {@link ChooserGridAdapter#VIEW_TYPE_NORMAL},
3057 * {@link ChooserGridAdapter#VIEW_TYPE_CONTENT_PREVIEW},
3058 * {@link ChooserGridAdapter#VIEW_TYPE_PROFILE},
3059 * and {@link ChooserGridAdapter#VIEW_TYPE_AZ_LABEL}.
3060 */
3061 final class ItemViewHolder extends ViewHolderBase {
3062 ResolverListAdapter.ViewHolder mWrappedViewHolder;
3063 int mListPosition = ChooserListAdapter.NO_POSITION;
3064
3065 ItemViewHolder(View itemView, boolean isClickable, int viewType) {
3066 super(itemView, viewType);
3067 mWrappedViewHolder = new ResolverListAdapter.ViewHolder(itemView);
3068 if (isClickable) {
3069 itemView.setOnClickListener(v -> startSelected(mListPosition,
3070 false/* always */, true/* filterd */));
3071
3072 itemView.setOnLongClickListener(v -> {
3073 final TargetInfo ti = mChooserMultiProfilePagerAdapter.getActiveListAdapter()
3074 .targetInfoForPosition(mListPosition, /* filtered */ true);
3075
3076 // This should always be the case for ItemViewHolder, check for validity
3077 if (ti instanceof DisplayResolveInfo && shouldShowTargetDetails(ti)) {
3078 showTargetDetails((DisplayResolveInfo) ti);
3079 }
3080 return true;
3081 });
3082 }
3083 }
3084 }
3085
3086 private boolean shouldShowTargetDetails(TargetInfo ti) {
3087 ComponentName nearbyShare = getNearbySharingComponent();
3088 // Suppress target details for nearby share to hide pin/unpin action
3089 boolean isNearbyShare = nearbyShare != null && nearbyShare.equals(
3090 ti.getResolvedComponentName()) && shouldNearbyShareBeFirstInRankedRow();
3091 return ti instanceof SelectableTargetInfo
3092 || (ti instanceof DisplayResolveInfo && !isNearbyShare);
3093 }
3094
3095 /**
3096 * Add a footer to the list, to support scrolling behavior below the navbar.
3097 */
3098 static final class FooterViewHolder extends ViewHolderBase {
3099 FooterViewHolder(View itemView, int viewType) {
3100 super(itemView, viewType);
3101 }
3102 }
3103
3104 /**
3105 * Intentionally override the {@link ResolverActivity} implementation as we only need that
3106 * implementation for the intent resolver case.
3107 */
3108 @Override
3109 public void onButtonClick(View v) {}
3110
3111 /**
3112 * Intentionally override the {@link ResolverActivity} implementation as we only need that
3113 * implementation for the intent resolver case.
3114 */
3115 @Override
3116 protected void resetButtonBar() {}
3117
3118 @Override
3119 protected String getMetricsCategory() {
3120 return METRICS_CATEGORY_CHOOSER;
3121 }
3122
3123 @Override
3124 protected void onProfileTabSelected() {
3125 ChooserGridAdapter currentRootAdapter =
3126 mChooserMultiProfilePagerAdapter.getCurrentRootAdapter();
3127 currentRootAdapter.updateDirectShareExpansion();
3128 // This fixes an edge case where after performing a variety of gestures, vertical scrolling
3129 // ends up disabled. That's because at some point the old tab's vertical scrolling is
3130 // disabled and the new tab's is enabled. For context, see b/159997845
3131 setVerticalScrollEnabled(true);
3132 if (mResolverDrawerLayout != null) {
3133 mResolverDrawerLayout.scrollNestedScrollableChildBackToTop();
3134 }
3135 }
3136
3137 @Override
3138 protected WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
3139 if (shouldShowTabs()) {
3140 mChooserMultiProfilePagerAdapter
3141 .setEmptyStateBottomOffset(insets.getSystemWindowInsetBottom());
3142 mChooserMultiProfilePagerAdapter.setupContainerPadding(
3143 getActiveEmptyStateView().findViewById(R.id.resolver_empty_state_container));
3144 }
3145
3146 WindowInsets result = super.onApplyWindowInsets(v, insets);
3147 if (mResolverDrawerLayout != null) {
3148 mResolverDrawerLayout.requestLayout();
3149 }
3150 return result;
3151 }
3152
3153 private void setHorizontalScrollingEnabled(boolean enabled) {
3154 ResolverViewPager viewPager = findViewById(R.id.profile_pager);
3155 viewPager.setSwipingEnabled(enabled);
3156 }
3157
3158 private void setVerticalScrollEnabled(boolean enabled) {
3159 ChooserGridLayoutManager layoutManager =
3160 (ChooserGridLayoutManager) mChooserMultiProfilePagerAdapter.getActiveAdapterView()
3161 .getLayoutManager();
3162 layoutManager.setVerticalScrollEnabled(enabled);
3163 }
3164
3165 @Override
3166 void onHorizontalSwipeStateChanged(int state) {
3167 if (state == ViewPager.SCROLL_STATE_DRAGGING) {
3168 if (mScrollStatus == SCROLL_STATUS_IDLE) {
3169 mScrollStatus = SCROLL_STATUS_SCROLLING_HORIZONTAL;
3170 setVerticalScrollEnabled(false);
3171 }
3172 } else if (state == ViewPager.SCROLL_STATE_IDLE) {
3173 if (mScrollStatus == SCROLL_STATUS_SCROLLING_HORIZONTAL) {
3174 mScrollStatus = SCROLL_STATUS_IDLE;
3175 setVerticalScrollEnabled(true);
3176 }
3177 }
3178 }
3179
3180 /**
3181 * Adapter for all types of items and targets in ShareSheet.
3182 * Note that ranked sections like Direct Share - while appearing grid-like - are handled on the
3183 * row level by this adapter but not on the item level. Individual targets within the row are
3184 * handled by {@link ChooserListAdapter}
3185 */
3186 @VisibleForTesting
3187 public final class ChooserGridAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
3188 private ChooserListAdapter mChooserListAdapter;
3189 private final LayoutInflater mLayoutInflater;
3190
3191 private DirectShareViewHolder mDirectShareViewHolder;
3192 private int mChooserTargetWidth = 0;
3193 private boolean mShowAzLabelIfPoss;
3194 private boolean mLayoutRequested = false;
3195
3196 private int mFooterHeight = 0;
3197
3198 private static final int VIEW_TYPE_DIRECT_SHARE = 0;
3199 private static final int VIEW_TYPE_NORMAL = 1;
3200 private static final int VIEW_TYPE_CONTENT_PREVIEW = 2;
3201 private static final int VIEW_TYPE_PROFILE = 3;
3202 private static final int VIEW_TYPE_AZ_LABEL = 4;
3203 private static final int VIEW_TYPE_CALLER_AND_RANK = 5;
3204 private static final int VIEW_TYPE_FOOTER = 6;
3205
3206 private static final int NUM_EXPANSIONS_TO_HIDE_AZ_LABEL = 20;
3207
3208 ChooserGridAdapter(ChooserListAdapter wrappedAdapter) {
3209 super();
3210 mChooserListAdapter = wrappedAdapter;
3211 mLayoutInflater = LayoutInflater.from(ChooserActivity.this);
3212
3213 mShowAzLabelIfPoss = getNumSheetExpansions() < NUM_EXPANSIONS_TO_HIDE_AZ_LABEL;
3214
3215 wrappedAdapter.registerDataSetObserver(new DataSetObserver() {
3216 @Override
3217 public void onChanged() {
3218 super.onChanged();
3219 notifyDataSetChanged();
3220 }
3221
3222 @Override
3223 public void onInvalidated() {
3224 super.onInvalidated();
3225 notifyDataSetChanged();
3226 }
3227 });
3228 }
3229
3230 public void setFooterHeight(int height) {
3231 mFooterHeight = height;
3232 }
3233
3234 /**
3235 * Calculate the chooser target width to maximize space per item
3236 *
3237 * @param width The new row width to use for recalculation
3238 * @return true if the view width has changed
3239 */
3240 public boolean calculateChooserTargetWidth(int width) {
3241 if (width == 0) {
3242 return false;
3243 }
3244
3245 // Limit width to the maximum width of the chooser activity
3246 int maxWidth = getResources().getDimensionPixelSize(R.dimen.chooser_width);
3247 width = Math.min(maxWidth, width);
3248
3249 int newWidth = width / mMaxTargetsPerRow;
3250 if (newWidth != mChooserTargetWidth) {
3251 mChooserTargetWidth = newWidth;
3252 return true;
3253 }
3254
3255 return false;
3256 }
3257
3258 /**
3259 * Hides the list item content preview.
3260 * <p>Not to be confused with the sticky content preview which is above the
3261 * personal and work tabs.
3262 */
3263 public void hideContentPreview() {
3264 mLayoutRequested = true;
3265 notifyDataSetChanged();
3266 }
3267
3268 public boolean consumeLayoutRequest() {
3269 boolean oldValue = mLayoutRequested;
3270 mLayoutRequested = false;
3271 return oldValue;
3272 }
3273
3274 public int getRowCount() {
3275 return (int) (
3276 getSystemRowCount()
3277 + getProfileRowCount()
3278 + getServiceTargetRowCount()
3279 + getCallerAndRankedTargetRowCount()
3280 + getAzLabelRowCount()
3281 + Math.ceil(
3282 (float) mChooserListAdapter.getAlphaTargetCount()
3283 / mMaxTargetsPerRow)
3284 );
3285 }
3286
3287 /**
3288 * Whether the "system" row of targets is displayed.
3289 * This area includes the content preview (if present) and action row.
3290 */
3291 public int getSystemRowCount() {
3292 // For the tabbed case we show the sticky content preview above the tabs,
3293 // please refer to shouldShowStickyContentPreview
3294 if (shouldShowTabs()) {
3295 return 0;
3296 }
3297
3298 if (!shouldShowContentPreview()) {
3299 return 0;
3300 }
3301
3302 if (mChooserListAdapter == null || mChooserListAdapter.getCount() == 0) {
3303 return 0;
3304 }
3305
3306 return 1;
3307 }
3308
3309 public int getProfileRowCount() {
3310 if (shouldShowTabs()) {
3311 return 0;
3312 }
3313 return mChooserListAdapter.getOtherProfile() == null ? 0 : 1;
3314 }
3315
3316 public int getFooterRowCount() {
3317 return 1;
3318 }
3319
3320 public int getCallerAndRankedTargetRowCount() {
3321 return (int) Math.ceil(
3322 ((float) mChooserListAdapter.getCallerTargetCount()
3323 + mChooserListAdapter.getRankedTargetCount()) / mMaxTargetsPerRow);
3324 }
3325
3326 // There can be at most one row in the listview, that is internally
3327 // a ViewGroup with 2 rows
3328 public int getServiceTargetRowCount() {
3329 if (shouldShowContentPreview()
3330 && !ActivityManager.isLowRamDeviceStatic()) {
3331 return 1;
3332 }
3333 return 0;
3334 }
3335
3336 public int getAzLabelRowCount() {
3337 // Only show a label if the a-z list is showing
3338 return (mShowAzLabelIfPoss && mChooserListAdapter.getAlphaTargetCount() > 0) ? 1 : 0;
3339 }
3340
3341 @Override
3342 public int getItemCount() {
3343 return (int) (
3344 getSystemRowCount()
3345 + getProfileRowCount()
3346 + getServiceTargetRowCount()
3347 + getCallerAndRankedTargetRowCount()
3348 + getAzLabelRowCount()
3349 + mChooserListAdapter.getAlphaTargetCount()
3350 + getFooterRowCount()
3351 );
3352 }
3353
3354 @Override
3355 public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
3356 switch (viewType) {
3357 case VIEW_TYPE_CONTENT_PREVIEW:
3358 return new ItemViewHolder(createContentPreviewView(parent), false, viewType);
3359 case VIEW_TYPE_PROFILE:
3360 return new ItemViewHolder(createProfileView(parent), false, viewType);
3361 case VIEW_TYPE_AZ_LABEL:
3362 return new ItemViewHolder(createAzLabelView(parent), false, viewType);
3363 case VIEW_TYPE_NORMAL:
3364 return new ItemViewHolder(
3365 mChooserListAdapter.createView(parent), true, viewType);
3366 case VIEW_TYPE_DIRECT_SHARE:
3367 case VIEW_TYPE_CALLER_AND_RANK:
3368 return createItemGroupViewHolder(viewType, parent);
3369 case VIEW_TYPE_FOOTER:
3370 Space sp = new Space(parent.getContext());
3371 sp.setLayoutParams(new RecyclerView.LayoutParams(
3372 LayoutParams.MATCH_PARENT, mFooterHeight));
3373 return new FooterViewHolder(sp, viewType);
3374 default:
3375 // Since we catch all possible viewTypes above, no chance this is being called.
3376 return null;
3377 }
3378 }
3379
3380 @Override
3381 public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
3382 int viewType = ((ViewHolderBase) holder).getViewType();
3383 switch (viewType) {
3384 case VIEW_TYPE_DIRECT_SHARE:
3385 case VIEW_TYPE_CALLER_AND_RANK:
3386 bindItemGroupViewHolder(position, (ItemGroupViewHolder) holder);
3387 break;
3388 case VIEW_TYPE_NORMAL:
3389 bindItemViewHolder(position, (ItemViewHolder) holder);
3390 break;
3391 default:
3392 }
3393 }
3394
3395 @Override
3396 public int getItemViewType(int position) {
3397 int count;
3398
3399 int countSum = (count = getSystemRowCount());
3400 if (count > 0 && position < countSum) return VIEW_TYPE_CONTENT_PREVIEW;
3401
3402 countSum += (count = getProfileRowCount());
3403 if (count > 0 && position < countSum) return VIEW_TYPE_PROFILE;
3404
3405 countSum += (count = getServiceTargetRowCount());
3406 if (count > 0 && position < countSum) return VIEW_TYPE_DIRECT_SHARE;
3407
3408 countSum += (count = getCallerAndRankedTargetRowCount());
3409 if (count > 0 && position < countSum) return VIEW_TYPE_CALLER_AND_RANK;
3410
3411 countSum += (count = getAzLabelRowCount());
3412 if (count > 0 && position < countSum) return VIEW_TYPE_AZ_LABEL;
3413
3414 if (position == getItemCount() - 1) return VIEW_TYPE_FOOTER;
3415
3416 return VIEW_TYPE_NORMAL;
3417 }
3418
3419 public int getTargetType(int position) {
3420 return mChooserListAdapter.getPositionTargetType(getListPosition(position));
3421 }
3422
3423 private View createProfileView(ViewGroup parent) {
3424 View profileRow = mLayoutInflater.inflate(R.layout.chooser_profile_row, parent, false);
3425 mProfileView = profileRow.findViewById(R.id.profile_button);
3426 mProfileView.setOnClickListener(ChooserActivity.this::onProfileClick);
3427 updateProfileViewButton();
3428 return profileRow;
3429 }
3430
3431 private View createAzLabelView(ViewGroup parent) {
3432 return mLayoutInflater.inflate(R.layout.chooser_az_label_row, parent, false);
3433 }
3434
3435 private ItemGroupViewHolder loadViewsIntoGroup(ItemGroupViewHolder holder) {
3436 final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
3437 final int exactSpec = MeasureSpec.makeMeasureSpec(mChooserTargetWidth,
3438 MeasureSpec.EXACTLY);
3439 int columnCount = holder.getColumnCount();
3440
3441 final boolean isDirectShare = holder instanceof DirectShareViewHolder;
3442
3443 for (int i = 0; i < columnCount; i++) {
3444 final View v = mChooserListAdapter.createView(holder.getRowByIndex(i));
3445 final int column = i;
3446 v.setOnClickListener(new OnClickListener() {
3447 @Override
3448 public void onClick(View v) {
3449 startSelected(holder.getItemIndex(column), false, true);
3450 }
3451 });
3452
3453 // Show menu for both direct share and app share targets after long click.
3454 v.setOnLongClickListener(v1 -> {
3455 TargetInfo ti = mChooserListAdapter.targetInfoForPosition(
3456 holder.getItemIndex(column), true);
3457 if (shouldShowTargetDetails(ti)) {
3458 showTargetDetails(ti);
3459 }
3460 return true;
3461 });
3462
3463 holder.addView(i, v);
3464
3465 // Force Direct Share to be 2 lines and auto-wrap to second line via hoz scroll =
3466 // false. TextView#setHorizontallyScrolling must be reset after #setLines. Must be
3467 // done before measuring.
3468 if (isDirectShare) {
3469 final ViewHolder vh = (ViewHolder) v.getTag();
3470 vh.text.setLines(2);
3471 vh.text.setHorizontallyScrolling(false);
3472 vh.text2.setVisibility(View.GONE);
3473 }
3474
3475 // Force height to be a given so we don't have visual disruption during scaling.
3476 v.measure(exactSpec, spec);
3477 setViewBounds(v, v.getMeasuredWidth(), v.getMeasuredHeight());
3478 }
3479
3480 final ViewGroup viewGroup = holder.getViewGroup();
3481
3482 // Pre-measure and fix height so we can scale later.
3483 holder.measure();
3484 setViewBounds(viewGroup, LayoutParams.MATCH_PARENT, holder.getMeasuredRowHeight());
3485
3486 if (isDirectShare) {
3487 DirectShareViewHolder dsvh = (DirectShareViewHolder) holder;
3488 setViewBounds(dsvh.getRow(0), LayoutParams.MATCH_PARENT, dsvh.getMinRowHeight());
3489 setViewBounds(dsvh.getRow(1), LayoutParams.MATCH_PARENT, dsvh.getMinRowHeight());
3490 }
3491
3492 viewGroup.setTag(holder);
3493 return holder;
3494 }
3495
3496 private void setViewBounds(View view, int widthPx, int heightPx) {
3497 LayoutParams lp = view.getLayoutParams();
3498 if (lp == null) {
3499 lp = new LayoutParams(widthPx, heightPx);
3500 view.setLayoutParams(lp);
3501 } else {
3502 lp.height = heightPx;
3503 lp.width = widthPx;
3504 }
3505 }
3506
3507 ItemGroupViewHolder createItemGroupViewHolder(int viewType, ViewGroup parent) {
3508 if (viewType == VIEW_TYPE_DIRECT_SHARE) {
3509 ViewGroup parentGroup = (ViewGroup) mLayoutInflater.inflate(
3510 R.layout.chooser_row_direct_share, parent, false);
3511 ViewGroup row1 = (ViewGroup) mLayoutInflater.inflate(R.layout.chooser_row,
3512 parentGroup, false);
3513 ViewGroup row2 = (ViewGroup) mLayoutInflater.inflate(R.layout.chooser_row,
3514 parentGroup, false);
3515 parentGroup.addView(row1);
3516 parentGroup.addView(row2);
3517
3518 mDirectShareViewHolder = new DirectShareViewHolder(parentGroup,
3519 Lists.newArrayList(row1, row2), mMaxTargetsPerRow, viewType,
3520 mChooserMultiProfilePagerAdapter::getActiveListAdapter);
3521 loadViewsIntoGroup(mDirectShareViewHolder);
3522
3523 return mDirectShareViewHolder;
3524 } else {
3525 ViewGroup row = (ViewGroup) mLayoutInflater.inflate(R.layout.chooser_row, parent,
3526 false);
3527 ItemGroupViewHolder holder =
3528 new SingleRowViewHolder(row, mMaxTargetsPerRow, viewType);
3529 loadViewsIntoGroup(holder);
3530
3531 return holder;
3532 }
3533 }
3534
3535 /**
3536 * Need to merge CALLER + ranked STANDARD into a single row and prevent a separator from
3537 * showing on top of the AZ list if the AZ label is visible. All other types are placed into
3538 * their own row as determined by their target type, and dividers are added in the list to
3539 * separate each type.
3540 */
3541 int getRowType(int rowPosition) {
3542 // Merge caller and ranked standard into a single row
3543 int positionType = mChooserListAdapter.getPositionTargetType(rowPosition);
3544 if (positionType == ChooserListAdapter.TARGET_CALLER) {
3545 return ChooserListAdapter.TARGET_STANDARD;
3546 }
3547
3548 // If an the A-Z label is shown, prevent a separator from appearing by making the A-Z
3549 // row type the same as the suggestion row type
3550 if (getAzLabelRowCount() > 0 && positionType == ChooserListAdapter.TARGET_STANDARD_AZ) {
3551 return ChooserListAdapter.TARGET_STANDARD;
3552 }
3553
3554 return positionType;
3555 }
3556
3557 void bindItemViewHolder(int position, ItemViewHolder holder) {
3558 View v = holder.itemView;
3559 int listPosition = getListPosition(position);
3560 holder.mListPosition = listPosition;
3561 mChooserListAdapter.bindView(listPosition, v);
3562 }
3563
3564 void bindItemGroupViewHolder(int position, ItemGroupViewHolder holder) {
3565 final ViewGroup viewGroup = (ViewGroup) holder.itemView;
3566 int start = getListPosition(position);
3567 int startType = getRowType(start);
3568
3569 int columnCount = holder.getColumnCount();
3570 int end = start + columnCount - 1;
3571 while (getRowType(end) != startType && end >= start) {
3572 end--;
3573 }
3574
3575 if (end == start && mChooserListAdapter.getItem(start) instanceof EmptyTargetInfo) {
3576 final TextView textView = viewGroup.findViewById(R.id.chooser_row_text_option);
3577
3578 if (textView.getVisibility() != View.VISIBLE) {
3579 textView.setAlpha(0.0f);
3580 textView.setVisibility(View.VISIBLE);
3581 textView.setText(R.string.chooser_no_direct_share_targets);
3582
3583 ValueAnimator fadeAnim = ObjectAnimator.ofFloat(textView, "alpha", 0.0f, 1.0f);
3584 fadeAnim.setInterpolator(new DecelerateInterpolator(1.0f));
3585
3586 float translationInPx = getResources().getDimensionPixelSize(
3587 R.dimen.chooser_row_text_option_translate);
3588 textView.setTranslationY(translationInPx);
3589 ValueAnimator translateAnim = ObjectAnimator.ofFloat(textView, "translationY",
3590 0.0f);
3591 translateAnim.setInterpolator(new DecelerateInterpolator(1.0f));
3592
3593 AnimatorSet animSet = new AnimatorSet();
3594 animSet.setDuration(NO_DIRECT_SHARE_ANIM_IN_MILLIS);
3595 animSet.setStartDelay(NO_DIRECT_SHARE_ANIM_IN_MILLIS);
3596 animSet.playTogether(fadeAnim, translateAnim);
3597 animSet.start();
3598 }
3599 }
3600
3601 for (int i = 0; i < columnCount; i++) {
3602 final View v = holder.getView(i);
3603
3604 if (start + i <= end) {
3605 holder.setViewVisibility(i, View.VISIBLE);
3606 holder.setItemIndex(i, start + i);
3607 mChooserListAdapter.bindView(holder.getItemIndex(i), v);
3608 } else {
3609 holder.setViewVisibility(i, View.INVISIBLE);
3610 }
3611 }
3612 }
3613
3614 int getListPosition(int position) {
3615 position -= getSystemRowCount() + getProfileRowCount();
3616
3617 final int serviceCount = mChooserListAdapter.getServiceTargetCount();
3618 final int serviceRows = (int) Math.ceil((float) serviceCount / getMaxRankedTargets());
3619 if (position < serviceRows) {
3620 return position * mMaxTargetsPerRow;
3621 }
3622
3623 position -= serviceRows;
3624
3625 final int callerAndRankedCount = mChooserListAdapter.getCallerTargetCount()
3626 + mChooserListAdapter.getRankedTargetCount();
3627 final int callerAndRankedRows = getCallerAndRankedTargetRowCount();
3628 if (position < callerAndRankedRows) {
3629 return serviceCount + position * mMaxTargetsPerRow;
3630 }
3631
3632 position -= getAzLabelRowCount() + callerAndRankedRows;
3633
3634 return callerAndRankedCount + serviceCount + position;
3635 }
3636
3637 public void handleScroll(View v, int y, int oldy) {
3638 boolean canExpandDirectShare = canExpandDirectShare();
3639 if (mDirectShareViewHolder != null && canExpandDirectShare) {
3640 mDirectShareViewHolder.handleScroll(
3641 mChooserMultiProfilePagerAdapter.getActiveAdapterView(), y, oldy,
3642 mMaxTargetsPerRow);
3643 }
3644 }
3645
3646 /**
3647 * Only expand direct share area if there is a minimum number of targets.
3648 */
3649 private boolean canExpandDirectShare() {
3650 // Do not enable until we have confirmed more apps are using sharing shortcuts
3651 // Check git history for enablement logic
3652 return false;
3653 }
3654
3655 public ChooserListAdapter getListAdapter() {
3656 return mChooserListAdapter;
3657 }
3658
3659 boolean shouldCellSpan(int position) {
3660 return getItemViewType(position) == VIEW_TYPE_NORMAL;
3661 }
3662
3663 void updateDirectShareExpansion() {
3664 if (mDirectShareViewHolder == null || !canExpandDirectShare()) {
3665 return;
3666 }
3667 RecyclerView activeAdapterView =
3668 mChooserMultiProfilePagerAdapter.getActiveAdapterView();
3669 if (mResolverDrawerLayout.isCollapsed()) {
3670 mDirectShareViewHolder.collapse(activeAdapterView);
3671 } else {
3672 mDirectShareViewHolder.expand(activeAdapterView);
3673 }
3674 }
3675 }
3676
3677 /**
3678 * Used to bind types for group of items including:
3679 * {@link ChooserGridAdapter#VIEW_TYPE_DIRECT_SHARE},
3680 * and {@link ChooserGridAdapter#VIEW_TYPE_CALLER_AND_RANK}.
3681 */
3682 abstract static class ItemGroupViewHolder extends ViewHolderBase {
3683 protected int mMeasuredRowHeight;
3684 private int[] mItemIndices;
3685 protected final View[] mCells;
3686 private final int mColumnCount;
3687
3688 ItemGroupViewHolder(int cellCount, View itemView, int viewType) {
3689 super(itemView, viewType);
3690 this.mCells = new View[cellCount];
3691 this.mItemIndices = new int[cellCount];
3692 this.mColumnCount = cellCount;
3693 }
3694
3695 abstract ViewGroup addView(int index, View v);
3696
3697 abstract ViewGroup getViewGroup();
3698
3699 abstract ViewGroup getRowByIndex(int index);
3700
3701 abstract ViewGroup getRow(int rowNumber);
3702
3703 abstract void setViewVisibility(int i, int visibility);
3704
3705 public int getColumnCount() {
3706 return mColumnCount;
3707 }
3708
3709 public void measure() {
3710 final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
3711 getViewGroup().measure(spec, spec);
3712 mMeasuredRowHeight = getViewGroup().getMeasuredHeight();
3713 }
3714
3715 public int getMeasuredRowHeight() {
3716 return mMeasuredRowHeight;
3717 }
3718
3719 public void setItemIndex(int itemIndex, int listIndex) {
3720 mItemIndices[itemIndex] = listIndex;
3721 }
3722
3723 public int getItemIndex(int itemIndex) {
3724 return mItemIndices[itemIndex];
3725 }
3726
3727 public View getView(int index) {
3728 return mCells[index];
3729 }
3730 }
3731
3732 static class SingleRowViewHolder extends ItemGroupViewHolder {
3733 private final ViewGroup mRow;
3734
3735 SingleRowViewHolder(ViewGroup row, int cellCount, int viewType) {
3736 super(cellCount, row, viewType);
3737
3738 this.mRow = row;
3739 }
3740
3741 public ViewGroup getViewGroup() {
3742 return mRow;
3743 }
3744
3745 public ViewGroup getRowByIndex(int index) {
3746 return mRow;
3747 }
3748
3749 public ViewGroup getRow(int rowNumber) {
3750 if (rowNumber == 0) return mRow;
3751 return null;
3752 }
3753
3754 public ViewGroup addView(int index, View v) {
3755 mRow.addView(v);
3756 mCells[index] = v;
3757
3758 return mRow;
3759 }
3760
3761 public void setViewVisibility(int i, int visibility) {
3762 getView(i).setVisibility(visibility);
3763 }
3764 }
3765
3766 static class DirectShareViewHolder extends ItemGroupViewHolder {
3767 private final ViewGroup mParent;
3768 private final List<ViewGroup> mRows;
3769 private int mCellCountPerRow;
3770
3771 private boolean mHideDirectShareExpansion = false;
3772 private int mDirectShareMinHeight = 0;
3773 private int mDirectShareCurrHeight = 0;
3774 private int mDirectShareMaxHeight = 0;
3775
3776 private final boolean[] mCellVisibility;
3777
3778 private final Supplier<ChooserListAdapter> mListAdapterSupplier;
3779
3780 DirectShareViewHolder(ViewGroup parent, List<ViewGroup> rows, int cellCountPerRow,
3781 int viewType, Supplier<ChooserListAdapter> listAdapterSupplier) {
3782 super(rows.size() * cellCountPerRow, parent, viewType);
3783
3784 this.mParent = parent;
3785 this.mRows = rows;
3786 this.mCellCountPerRow = cellCountPerRow;
3787 this.mCellVisibility = new boolean[rows.size() * cellCountPerRow];
3788 Arrays.fill(mCellVisibility, true);
3789 this.mListAdapterSupplier = listAdapterSupplier;
3790 }
3791
3792 public ViewGroup addView(int index, View v) {
3793 ViewGroup row = getRowByIndex(index);
3794 row.addView(v);
3795 mCells[index] = v;
3796
3797 return row;
3798 }
3799
3800 public ViewGroup getViewGroup() {
3801 return mParent;
3802 }
3803
3804 public ViewGroup getRowByIndex(int index) {
3805 return mRows.get(index / mCellCountPerRow);
3806 }
3807
3808 public ViewGroup getRow(int rowNumber) {
3809 return mRows.get(rowNumber);
3810 }
3811
3812 public void measure() {
3813 final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
3814 getRow(0).measure(spec, spec);
3815 getRow(1).measure(spec, spec);
3816
3817 mDirectShareMinHeight = getRow(0).getMeasuredHeight();
3818 mDirectShareCurrHeight = mDirectShareCurrHeight > 0
3819 ? mDirectShareCurrHeight : mDirectShareMinHeight;
3820 mDirectShareMaxHeight = 2 * mDirectShareMinHeight;
3821 }
3822
3823 public int getMeasuredRowHeight() {
3824 return mDirectShareCurrHeight;
3825 }
3826
3827 public int getMinRowHeight() {
3828 return mDirectShareMinHeight;
3829 }
3830
3831 public void setViewVisibility(int i, int visibility) {
3832 final View v = getView(i);
3833 if (visibility == View.VISIBLE) {
3834 mCellVisibility[i] = true;
3835 v.setVisibility(visibility);
3836 v.setAlpha(1.0f);
3837 } else if (visibility == View.INVISIBLE && mCellVisibility[i]) {
3838 mCellVisibility[i] = false;
3839
3840 ValueAnimator fadeAnim = ObjectAnimator.ofFloat(v, "alpha", 1.0f, 0f);
3841 fadeAnim.setDuration(NO_DIRECT_SHARE_ANIM_IN_MILLIS);
3842 fadeAnim.setInterpolator(new AccelerateInterpolator(1.0f));
3843 fadeAnim.addListener(new AnimatorListenerAdapter() {
3844 public void onAnimationEnd(Animator animation) {
3845 v.setVisibility(View.INVISIBLE);
3846 }
3847 });
3848 fadeAnim.start();
3849 }
3850 }
3851
3852 public void handleScroll(RecyclerView view, int y, int oldy, int maxTargetsPerRow) {
3853 // only exit early if fully collapsed, otherwise onListRebuilt() with shifting
3854 // targets can lock us into an expanded mode
3855 boolean notExpanded = mDirectShareCurrHeight == mDirectShareMinHeight;
3856 if (notExpanded) {
3857 if (mHideDirectShareExpansion) {
3858 return;
3859 }
3860
3861 // only expand if we have more than maxTargetsPerRow, and delay that decision
3862 // until they start to scroll
3863 ChooserListAdapter adapter = mListAdapterSupplier.get();
3864 int validTargets = adapter.getSelectableServiceTargetCount();
3865 if (validTargets <= maxTargetsPerRow) {
3866 mHideDirectShareExpansion = true;
3867 return;
3868 }
3869 }
3870
3871 int yDiff = (int) ((oldy - y) * DIRECT_SHARE_EXPANSION_RATE);
3872
3873 int prevHeight = mDirectShareCurrHeight;
3874 int newHeight = Math.min(prevHeight + yDiff, mDirectShareMaxHeight);
3875 newHeight = Math.max(newHeight, mDirectShareMinHeight);
3876 yDiff = newHeight - prevHeight;
3877
3878 updateDirectShareRowHeight(view, yDiff, newHeight);
3879 }
3880
3881 void expand(RecyclerView view) {
3882 updateDirectShareRowHeight(view, mDirectShareMaxHeight - mDirectShareCurrHeight,
3883 mDirectShareMaxHeight);
3884 }
3885
3886 void collapse(RecyclerView view) {
3887 updateDirectShareRowHeight(view, mDirectShareMinHeight - mDirectShareCurrHeight,
3888 mDirectShareMinHeight);
3889 }
3890
3891 private void updateDirectShareRowHeight(RecyclerView view, int yDiff, int newHeight) {
3892 if (view == null || view.getChildCount() == 0 || yDiff == 0) {
3893 return;
3894 }
3895
3896 // locate the item to expand, and offset the rows below that one
3897 boolean foundExpansion = false;
3898 for (int i = 0; i < view.getChildCount(); i++) {
3899 View child = view.getChildAt(i);
3900
3901 if (foundExpansion) {
3902 child.offsetTopAndBottom(yDiff);
3903 } else {
3904 if (child.getTag() != null && child.getTag() instanceof DirectShareViewHolder) {
3905 int widthSpec = MeasureSpec.makeMeasureSpec(child.getWidth(),
3906 MeasureSpec.EXACTLY);
3907 int heightSpec = MeasureSpec.makeMeasureSpec(newHeight,
3908 MeasureSpec.EXACTLY);
3909 child.measure(widthSpec, heightSpec);
3910 child.getLayoutParams().height = child.getMeasuredHeight();
3911 child.layout(child.getLeft(), child.getTop(), child.getRight(),
3912 child.getTop() + child.getMeasuredHeight());
3913
3914 foundExpansion = true;
3915 }
3916 }
3917 }
3918
3919 if (foundExpansion) {
3920 mDirectShareCurrHeight = newHeight;
3921 }
3922 }
3923 }
3924
3925 /**
3926 * Shortcuts grouped by application.
3927 */
3928 @VisibleForTesting
3929 public static class ServiceResultInfo {
3930 public final DisplayResolveInfo originalTarget;
3931 public final List<ChooserTarget> resultTargets;
3932 public final UserHandle userHandle;
3933
3934 public ServiceResultInfo(DisplayResolveInfo ot, List<ChooserTarget> rt,
3935 UserHandle userHandle) {
3936 originalTarget = ot;
3937 resultTargets = rt;
3938 this.userHandle = userHandle;
3939 }
3940 }
3941
3942 static class ChooserTargetRankingInfo {
3943 public final List<AppTarget> scores;
3944 public final UserHandle userHandle;
3945
3946 ChooserTargetRankingInfo(List<AppTarget> chooserTargetScores,
3947 UserHandle userHandle) {
3948 this.scores = chooserTargetScores;
3949 this.userHandle = userHandle;
3950 }
3951 }
3952
3953 static class RefinementResultReceiver extends ResultReceiver {
3954 private ChooserActivity mChooserActivity;
3955 private TargetInfo mSelectedTarget;
3956
3957 public RefinementResultReceiver(ChooserActivity host, TargetInfo target,
3958 Handler handler) {
3959 super(handler);
3960 mChooserActivity = host;
3961 mSelectedTarget = target;
3962 }
3963
3964 @Override
3965 protected void onReceiveResult(int resultCode, Bundle resultData) {
3966 if (mChooserActivity == null) {
3967 Log.e(TAG, "Destroyed RefinementResultReceiver received a result");
3968 return;
3969 }
3970 if (resultData == null) {
3971 Log.e(TAG, "RefinementResultReceiver received null resultData");
3972 return;
3973 }
3974
3975 switch (resultCode) {
3976 case RESULT_CANCELED:
3977 mChooserActivity.onRefinementCanceled();
3978 break;
3979 case RESULT_OK:
3980 Parcelable intentParcelable = resultData.getParcelable(Intent.EXTRA_INTENT);
3981 if (intentParcelable instanceof Intent) {
3982 mChooserActivity.onRefinementResult(mSelectedTarget,
3983 (Intent) intentParcelable);
3984 } else {
3985 Log.e(TAG, "RefinementResultReceiver received RESULT_OK but no Intent"
3986 + " in resultData with key Intent.EXTRA_INTENT");
3987 }
3988 break;
3989 default:
3990 Log.w(TAG, "Unknown result code " + resultCode
3991 + " sent to RefinementResultReceiver");
3992 break;
3993 }
3994 }
3995
3996 public void destroy() {
3997 mChooserActivity = null;
3998 mSelectedTarget = null;
3999 }
4000 }
4001
4002 /**
4003 * Used internally to round image corners while obeying view padding.
4004 */
4005 public static class RoundedRectImageView extends ImageView {
4006 private int mRadius = 0;
4007 private Path mPath = new Path();
4008 private Paint mOverlayPaint = new Paint(0);
4009 private Paint mRoundRectPaint = new Paint(0);
4010 private Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
4011 private String mExtraImageCount = null;
4012
4013 public RoundedRectImageView(Context context) {
4014 super(context);
4015 }
4016
4017 public RoundedRectImageView(Context context, AttributeSet attrs) {
4018 this(context, attrs, 0);
4019 }
4020
4021 public RoundedRectImageView(Context context, AttributeSet attrs, int defStyleAttr) {
4022 this(context, attrs, defStyleAttr, 0);
4023 }
4024
4025 public RoundedRectImageView(Context context, AttributeSet attrs, int defStyleAttr,
4026 int defStyleRes) {
4027 super(context, attrs, defStyleAttr, defStyleRes);
4028 mRadius = context.getResources().getDimensionPixelSize(R.dimen.chooser_corner_radius);
4029
4030 mOverlayPaint.setColor(0x99000000);
4031 mOverlayPaint.setStyle(Paint.Style.FILL);
4032
4033 mRoundRectPaint.setColor(context.getResources().getColor(R.color.chooser_row_divider));
4034 mRoundRectPaint.setStyle(Paint.Style.STROKE);
4035 mRoundRectPaint.setStrokeWidth(context.getResources()
4036 .getDimensionPixelSize(R.dimen.chooser_preview_image_border));
4037
4038 mTextPaint.setColor(Color.WHITE);
4039 mTextPaint.setTextSize(context.getResources()
4040 .getDimensionPixelSize(R.dimen.chooser_preview_image_font_size));
4041 mTextPaint.setTextAlign(Paint.Align.CENTER);
4042 }
4043
4044 private void updatePath(int width, int height) {
4045 mPath.reset();
4046
4047 int imageWidth = width - getPaddingRight() - getPaddingLeft();
4048 int imageHeight = height - getPaddingBottom() - getPaddingTop();
4049 mPath.addRoundRect(getPaddingLeft(), getPaddingTop(), imageWidth, imageHeight, mRadius,
4050 mRadius, Path.Direction.CW);
4051 }
4052
4053 /**
4054 * Sets the corner radius on all corners
4055 *
4056 * param radius 0 for no radius, &gt; 0 for a visible corner radius
4057 */
4058 public void setRadius(int radius) {
4059 mRadius = radius;
4060 updatePath(getWidth(), getHeight());
4061 }
4062
4063 /**
4064 * Display an overlay with extra image count on 3rd image
4065 */
4066 public void setExtraImageCount(int count) {
4067 if (count > 0) {
4068 this.mExtraImageCount = "+" + count;
4069 } else {
4070 this.mExtraImageCount = null;
4071 }
4072 }
4073
4074 @Override
4075 protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
4076 super.onSizeChanged(width, height, oldWidth, oldHeight);
4077 updatePath(width, height);
4078 }
4079
4080 @Override
4081 protected void onDraw(Canvas canvas) {
4082 if (mRadius != 0) {
4083 canvas.clipPath(mPath);
4084 }
4085
4086 super.onDraw(canvas);
4087
4088 int x = getPaddingLeft();
4089 int y = getPaddingRight();
4090 int width = getWidth() - getPaddingRight() - getPaddingLeft();
4091 int height = getHeight() - getPaddingBottom() - getPaddingTop();
4092 if (mExtraImageCount != null) {
4093 canvas.drawRect(x, y, width, height, mOverlayPaint);
4094
4095 int xPos = canvas.getWidth() / 2;
4096 int yPos = (int) ((canvas.getHeight() / 2.0f)
4097 - ((mTextPaint.descent() + mTextPaint.ascent()) / 2.0f));
4098
4099 canvas.drawText(mExtraImageCount, xPos, yPos, mTextPaint);
4100 }
4101
4102 canvas.drawRoundRect(x, y, width, height, mRadius, mRadius, mRoundRectPaint);
4103 }
4104 }
4105
4106 /**
4107 * A helper class to track app's readiness for the scene transition animation.
4108 * The app is ready when both the image is laid out and the drawer offset is calculated.
4109 */
4110 private class EnterTransitionAnimationDelegate implements View.OnLayoutChangeListener {
4111 private boolean mPreviewReady = false;
4112 private boolean mOffsetCalculated = false;
4113
4114 void postponeTransition() {
4115 postponeEnterTransition();
4116 }
4117
4118 void markImagePreviewReady() {
4119 if (!mPreviewReady) {
4120 mPreviewReady = true;
4121 maybeStartListenForLayout();
4122 }
4123 }
4124
4125 void markOffsetCalculated() {
4126 if (!mOffsetCalculated) {
4127 mOffsetCalculated = true;
4128 maybeStartListenForLayout();
4129 }
4130 }
4131
4132 private void maybeStartListenForLayout() {
4133 if (mPreviewReady && mOffsetCalculated && mResolverDrawerLayout != null) {
4134 if (mResolverDrawerLayout.isInLayout()) {
4135 startPostponedEnterTransition();
4136 } else {
4137 mResolverDrawerLayout.addOnLayoutChangeListener(this);
4138 mResolverDrawerLayout.requestLayout();
4139 }
4140 }
4141 }
4142
4143 @Override
4144 public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft,
4145 int oldTop, int oldRight, int oldBottom) {
4146 v.removeOnLayoutChangeListener(this);
4147 startPostponedEnterTransition();
4148 }
4149 }
4150
4151 /**
4152 * Used in combination with the scene transition when launching the image editor
4153 */
4154 private static class FinishAnimation extends AlphaAnimation implements
4155 Animation.AnimationListener {
4156 @Nullable
4157 private Activity mActivity;
4158 @Nullable
4159 private View mRootView;
4160 private final float mFromAlpha;
4161
4162 FinishAnimation(@NonNull Activity activity, @NonNull View rootView) {
4163 super(rootView.getAlpha(), 0.0f);
4164 mActivity = activity;
4165 mRootView = rootView;
4166 mFromAlpha = rootView.getAlpha();
4167 setInterpolator(new LinearInterpolator());
4168 long duration = activity.getWindow().getTransitionBackgroundFadeDuration();
4169 setDuration(duration);
4170 // The scene transition animation looks better when it's not overlapped with this
4171 // fade-out animation thus the delay.
4172 // It is most likely that the image editor will cause this activity to stop and this
4173 // animation will be cancelled in the background without running (i.e. we'll animate
4174 // only when this activity remains partially visible after the image editor launch).
4175 setStartOffset(duration);
4176 super.setAnimationListener(this);
4177 }
4178
4179 @Override
4180 public void setAnimationListener(AnimationListener listener) {
4181 throw new UnsupportedOperationException();
4182 }
4183
4184 @Override
4185 public void cancel() {
4186 if (mRootView != null) {
4187 mRootView.setAlpha(mFromAlpha);
4188 }
4189 cleanup();
4190 super.cancel();
4191 }
4192
4193 @Override
4194 public void onAnimationStart(Animation animation) {
4195 }
4196
4197 @Override
4198 public void onAnimationEnd(Animation animation) {
4199 Activity activity = mActivity;
4200 cleanup();
4201 if (activity != null) {
4202 activity.finish();
4203 }
4204 }
4205
4206 @Override
4207 public void onAnimationRepeat(Animation animation) {
4208 }
4209
4210 private void cleanup() {
4211 mActivity = null;
4212 mRootView = null;
4213 }
4214 }
4215
4216 @Override
4217 protected void maybeLogProfileChange() {
4218 getChooserActivityLogger().logShareheetProfileChanged();
4219 }
4220
4221 private boolean shouldNearbyShareBeFirstInRankedRow() {
4222 return ActivityManager.isLowRamDeviceStatic() && mIsNearbyShareFirstTargetInRankedApp;
4223 }
4224
4225 private boolean shouldNearbyShareBeIncludedAsActionButton() {
4226 return !shouldNearbyShareBeFirstInRankedRow();
4227 }
4228 }