blob: 3696c83d566b2d00209f53349badcf7ee9896573 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
Adam Powelle7c74cc2016-01-28 16:42:27 +000017package com.android.internal.app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080018
Matt Pietal0ea391b2019-01-30 10:44:15 -050019import static java.lang.annotation.RetentionPolicy.SOURCE;
20
Matt Pietalcdfcd9a2019-03-05 08:31:47 -050021import android.animation.Animator;
22import android.animation.AnimatorListenerAdapter;
23import android.animation.AnimatorSet;
24import android.animation.ObjectAnimator;
25import android.animation.ValueAnimator;
Matt Pietal0ea391b2019-01-30 10:44:15 -050026import android.annotation.IntDef;
Mehdi Alizadeh707c0cf2019-09-03 18:11:48 -070027import android.annotation.NonNull;
George Hodulik145b3a52019-03-27 11:18:43 -070028import android.annotation.Nullable;
Adam Powell0b3c1122014-10-09 12:50:14 -070029import android.app.Activity;
Ng Zhi And3ec5fc2018-05-10 09:13:00 -070030import android.app.ActivityManager;
George Hodulik69d4a082019-01-18 11:27:03 -080031import android.app.prediction.AppPredictionContext;
32import android.app.prediction.AppPredictionManager;
33import android.app.prediction.AppPredictor;
34import android.app.prediction.AppTarget;
George Hodulikf2b0d342019-01-25 12:43:54 -080035import android.app.prediction.AppTargetEvent;
Artur Satayeved5a6ae2019-12-10 17:47:54 +000036import android.compat.annotation.UnsupportedAppUsage;
Matt Pietal26038402019-01-08 07:29:34 -050037import android.content.ClipData;
Matt Pietal1fa7d802019-01-30 10:44:15 -050038import android.content.ClipboardManager;
Adam Powell0b3c1122014-10-09 12:50:14 -070039import android.content.ComponentName;
Matt Pietal0ea391b2019-01-30 10:44:15 -050040import android.content.ContentResolver;
Adam Powell24428412015-04-01 17:19:56 -070041import android.content.Context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.Intent;
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -080043import android.content.IntentFilter;
Adam Powell0b3c1122014-10-09 12:50:14 -070044import android.content.IntentSender;
Adam Powell2ed547e2015-04-29 18:45:04 -070045import android.content.IntentSender.SendIntentException;
Adam Powell24428412015-04-01 17:19:56 -070046import android.content.ServiceConnection;
Alison Cichowlas1fd47152019-11-14 19:50:55 -050047import android.content.SharedPreferences;
Nicolas Prevot0e2b73f2014-10-27 10:06:11 +000048import android.content.pm.ActivityInfo;
Matt Pietala4b30072019-04-04 13:44:36 -040049import android.content.pm.ApplicationInfo;
Adam Powell24428412015-04-01 17:19:56 -070050import android.content.pm.PackageManager;
51import android.content.pm.PackageManager.NameNotFoundException;
52import android.content.pm.ResolveInfo;
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -080053import android.content.pm.ShortcutInfo;
54import android.content.pm.ShortcutManager;
Matt Pietal18bbd822019-02-12 15:21:36 -050055import android.content.res.Configuration;
Dan Sandlere3d19932019-11-22 11:58:58 -050056import android.content.res.Resources;
Matt Pietal46d828c2019-02-05 08:07:07 -050057import android.database.Cursor;
Adam Powell7d758002015-05-06 17:49:36 -070058import android.database.DataSetObserver;
Matt Pietal26038402019-01-08 07:29:34 -050059import android.graphics.Bitmap;
60import android.graphics.Canvas;
Adam Powell63b31692015-09-28 10:45:00 -070061import android.graphics.Color;
Matt Pietal0ea391b2019-01-30 10:44:15 -050062import android.graphics.Paint;
Matt Pietal26038402019-01-08 07:29:34 -050063import android.graphics.Path;
Mike Digmanac1d88c2019-04-18 15:15:55 -070064import android.graphics.drawable.AnimatedVectorDrawable;
Adam Powell24428412015-04-01 17:19:56 -070065import android.graphics.drawable.Drawable;
Susi Kharraz-Post7e2115d2019-02-01 16:51:22 -050066import android.metrics.LogMaker;
Matt Pietal26038402019-01-08 07:29:34 -050067import android.net.Uri;
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -080068import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.os.Bundle;
Alison Cichowlas1fd47152019-11-14 19:50:55 -050070import android.os.Environment;
Adam Powell24428412015-04-01 17:19:56 -070071import android.os.Handler;
72import android.os.IBinder;
73import android.os.Message;
Dianne Hackborneb034652009-09-07 00:49:58 -070074import android.os.Parcelable;
Katsiaryna Naliuka66cd0562020-01-16 18:01:30 +010075import android.os.PatternMatcher;
Adam Powell24428412015-04-01 17:19:56 -070076import android.os.RemoteException;
Adam Powell2ed547e2015-04-29 18:45:04 -070077import android.os.ResultReceiver;
Adam Powell24428412015-04-01 17:19:56 -070078import android.os.UserHandle;
Adam Powell7d758002015-05-06 17:49:36 -070079import android.os.UserManager;
Alison Cichowlas1fd47152019-11-14 19:50:55 -050080import android.os.storage.StorageManager;
Susi Kharraz-Post14cbfcd2019-04-01 11:07:59 -040081import android.provider.DeviceConfig;
Matt Pietal46d828c2019-02-05 08:07:07 -050082import android.provider.DocumentsContract;
Matt Pietalf38e9d22019-02-15 10:01:03 -050083import android.provider.Downloads;
Matt Pietal46d828c2019-02-05 08:07:07 -050084import android.provider.OpenableColumns;
Dan Sandlere3d19932019-11-22 11:58:58 -050085import android.provider.Settings;
Adam Powell24428412015-04-01 17:19:56 -070086import android.service.chooser.ChooserTarget;
87import android.service.chooser.ChooserTargetService;
88import android.service.chooser.IChooserTargetResult;
89import android.service.chooser.IChooserTargetService;
90import android.text.TextUtils;
Matt Pietal26038402019-01-08 07:29:34 -050091import android.util.AttributeSet;
Susi Kharraz-Post14cbfcd2019-04-01 11:07:59 -040092import android.util.HashedStringCache;
Dianne Hackborneb034652009-09-07 00:49:58 -070093import android.util.Log;
arangelov5fc9e7d2020-01-07 17:59:14 +000094import android.util.Pair;
Matt Pietal26038402019-01-08 07:29:34 -050095import android.util.Size;
Adam Powell0b3c1122014-10-09 12:50:14 -070096import android.util.Slog;
Adam Powell7d758002015-05-06 17:49:36 -070097import android.view.LayoutInflater;
Adam Powell24428412015-04-01 17:19:56 -070098import android.view.View;
Adam Powell63b31692015-09-28 10:45:00 -070099import android.view.View.MeasureSpec;
Adam Powell7d758002015-05-06 17:49:36 -0700100import android.view.View.OnClickListener;
Adam Powell98b7f892015-06-19 12:38:45 -0700101import android.view.View.OnLongClickListener;
Adam Powell24428412015-04-01 17:19:56 -0700102import android.view.ViewGroup;
Adam Powell63b31692015-09-28 10:45:00 -0700103import android.view.ViewGroup.LayoutParams;
Matt Pietalcdfcd9a2019-03-05 08:31:47 -0500104import android.view.animation.AccelerateInterpolator;
105import android.view.animation.DecelerateInterpolator;
Dan Sandlere3d19932019-11-22 11:58:58 -0500106import android.widget.Button;
Matt Pietal26038402019-01-08 07:29:34 -0500107import android.widget.ImageView;
Matt Pietal9236adc2019-12-12 09:24:23 -0500108import android.widget.Space;
Matt Pietal26038402019-01-08 07:29:34 -0500109import android.widget.TextView;
Matt Pietal1fa7d802019-01-30 10:44:15 -0500110import android.widget.Toast;
Jason Monk027dcfa2017-06-27 18:37:35 -0400111
Adam Powell7d758002015-05-06 17:49:36 -0700112import com.android.internal.R;
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -0800113import com.android.internal.annotations.VisibleForTesting;
arangelovb0802dc2019-10-18 18:03:44 +0100114import com.android.internal.app.ResolverListAdapter.ActivityInfoPresentationGetter;
115import com.android.internal.app.ResolverListAdapter.ViewHolder;
116import com.android.internal.app.chooser.ChooserTargetInfo;
117import com.android.internal.app.chooser.DisplayResolveInfo;
Alison Cichowlas19ee2922019-12-16 19:43:12 -0500118import com.android.internal.app.chooser.MultiDisplayResolveInfo;
arangelovb0802dc2019-10-18 18:03:44 +0100119import com.android.internal.app.chooser.NotSelectableTargetInfo;
120import com.android.internal.app.chooser.SelectableTargetInfo;
121import com.android.internal.app.chooser.SelectableTargetInfo.SelectableTargetInfoCommunicator;
122import com.android.internal.app.chooser.TargetInfo;
Susi Kharraz-Post14cbfcd2019-04-01 11:07:59 -0400123import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
Matt Pietalab73a882019-06-05 07:04:55 -0400124import com.android.internal.content.PackageMonitor;
Adam Powell98b7f892015-06-19 12:38:45 -0700125import com.android.internal.logging.MetricsLogger;
Tamas Berghammer383db5eb2016-06-22 15:21:38 +0100126import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Zhen Zhangbde7b462019-11-11 11:49:33 -0800127import com.android.internal.widget.GridLayoutManager;
128import com.android.internal.widget.RecyclerView;
Mike Digman849a9d12019-04-29 11:20:48 -0700129import com.android.internal.widget.ResolverDrawerLayout;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400130
Adam Powell52c39212016-04-07 15:14:18 -0700131import com.google.android.collect.Lists;
Adam Powell24428412015-04-01 17:19:56 -0700132
Alison Cichowlas1fd47152019-11-14 19:50:55 -0500133import java.io.File;
Matt Pietal26038402019-01-08 07:29:34 -0500134import java.io.IOException;
Matt Pietal0ea391b2019-01-30 10:44:15 -0500135import java.lang.annotation.Retention;
Mehdi Alizadeh06955f62019-09-11 17:23:10 -0700136import java.lang.annotation.RetentionPolicy;
Dan Sandlere3d19932019-11-22 11:58:58 -0500137import java.net.URISyntaxException;
Alison Cichowlas1c8816c2019-04-03 17:43:22 -0400138import java.text.Collator;
Adam Powell24428412015-04-01 17:19:56 -0700139import java.util.ArrayList;
Adam Powella182e452015-07-06 16:57:56 -0700140import java.util.Collections;
141import java.util.Comparator;
George Hodulikaa5238c2019-04-18 14:17:51 -0700142import java.util.HashMap;
Matt Pietalab73a882019-06-05 07:04:55 -0400143import java.util.HashSet;
Adam Powell24428412015-04-01 17:19:56 -0700144import java.util.List;
George Hodulikaa5238c2019-04-18 14:17:51 -0700145import java.util.Map;
Matt Pietalab73a882019-06-05 07:04:55 -0400146import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147
Alison Cichowlas1c8816c2019-04-03 17:43:22 -0400148/**
149 * The Chooser Activity handles intent resolution specifically for sharing intents -
150 * for example, those generated by @see android.content.Intent#createChooser(Intent, CharSequence).
151 *
152 */
arangelovb0802dc2019-10-18 18:03:44 +0100153public class ChooserActivity extends ResolverActivity implements
154 ChooserListAdapter.ChooserListCommunicator,
155 SelectableTargetInfoCommunicator {
Adam Powell0b3c1122014-10-09 12:50:14 -0700156 private static final String TAG = "ChooserActivity";
arangelov5fc9e7d2020-01-07 17:59:14 +0000157 private AppPredictor mPersonalAppPredictor;
158 private AppPredictor mWorkAppPredictor;
Adam Powell0b3c1122014-10-09 12:50:14 -0700159
Artur Satayev751e5512019-11-15 19:12:49 +0000160 @UnsupportedAppUsage
161 public ChooserActivity() {
162 }
Jorim Jaggif631ef72017-02-24 13:49:47 +0100163 /**
164 * Boolean extra to change the following behavior: Normally, ChooserActivity finishes itself
165 * in onStop when launched in a new task. If this extra is set to true, we do not finish
166 * ourselves when onStop gets called.
167 */
168 public static final String EXTRA_PRIVATE_RETAIN_IN_ON_STOP
169 = "com.android.internal.app.ChooserActivity.EXTRA_PRIVATE_RETAIN_IN_ON_STOP";
170
Mike Digman849a9d12019-04-29 11:20:48 -0700171 private static final String PREF_NUM_SHEET_EXPANSIONS = "pref_num_sheet_expansions";
172
Dan Sandlere3d19932019-11-22 11:58:58 -0500173 private static final String CHIP_LABEL_METADATA_KEY = "android.service.chooser.chip_label";
174 private static final String CHIP_ICON_METADATA_KEY = "android.service.chooser.chip_icon";
175
arangelov5fc9e7d2020-01-07 17:59:14 +0000176 private static final boolean DEBUG = true;
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -0800177
George Hodulik1428beb2019-05-01 17:04:23 -0700178 private static final boolean USE_PREDICTION_MANAGER_FOR_SHARE_ACTIVITIES = true;
George Hodulik69d4a082019-01-18 11:27:03 -0800179 // TODO(b/123088566) Share these in a better way.
180 private static final String APP_PREDICTION_SHARE_UI_SURFACE = "share";
George Hodulikf2b0d342019-01-25 12:43:54 -0800181 public static final String LAUNCH_LOCATON_DIRECT_SHARE = "direct_share";
George Hodulik69d4a082019-01-18 11:27:03 -0800182 private static final int APP_PREDICTION_SHARE_TARGET_QUERY_PACKAGE_LIMIT = 20;
183 public static final String APP_PREDICTION_INTENT_FILTER_KEY = "intent_filter";
Mehdi Alizadeha1c18a82019-08-15 16:31:38 -0700184
arangelovb0802dc2019-10-18 18:03:44 +0100185 @VisibleForTesting
186 public static final int LIST_VIEW_UPDATE_INTERVAL_IN_MILLIS = 250;
187
Mehdi Alizadeha1c18a82019-08-15 16:31:38 -0700188 private boolean mIsAppPredictorComponentAvailable;
George Hodulikaa5238c2019-04-18 14:17:51 -0700189 private Map<ChooserTarget, AppTarget> mDirectShareAppTargetCache;
arangelov5fc9e7d2020-01-07 17:59:14 +0000190 private Map<ChooserTarget, ShortcutInfo> mDirectShareShortcutInfoCache;
George Hodulik69d4a082019-01-18 11:27:03 -0800191
Mehdi Alizadeh06955f62019-09-11 17:23:10 -0700192 public static final int TARGET_TYPE_DEFAULT = 0;
193 public static final int TARGET_TYPE_CHOOSER_TARGET = 1;
194 public static final int TARGET_TYPE_SHORTCUTS_FROM_SHORTCUT_MANAGER = 2;
195 public static final int TARGET_TYPE_SHORTCUTS_FROM_PREDICTION_SERVICE = 3;
196
arangelovb0802dc2019-10-18 18:03:44 +0100197 private static final boolean USE_CHOOSER_TARGET_SERVICE_FOR_DIRECT_TARGETS = true;
198
Mehdi Alizadeh06955f62019-09-11 17:23:10 -0700199 @IntDef(flag = false, prefix = { "TARGET_TYPE_" }, value = {
200 TARGET_TYPE_DEFAULT,
201 TARGET_TYPE_CHOOSER_TARGET,
202 TARGET_TYPE_SHORTCUTS_FROM_SHORTCUT_MANAGER,
203 TARGET_TYPE_SHORTCUTS_FROM_PREDICTION_SERVICE
204 })
205 @Retention(RetentionPolicy.SOURCE)
206 public @interface ShareTargetType {}
207
Matt Pietalcdfcd9a2019-03-05 08:31:47 -0500208 /**
209 * The transition time between placeholders for direct share to a message
210 * indicating that non are available.
211 */
212 private static final int NO_DIRECT_SHARE_ANIM_IN_MILLIS = 200;
213
Matt Pietal394ebd02019-05-03 07:36:21 -0400214 private static final float DIRECT_SHARE_EXPANSION_RATE = 0.78f;
Matt Pietalfe28f9a2019-03-22 07:59:58 -0400215
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -0800216 // TODO(b/121287224): Re-evaluate this limit
217 private static final int SHARE_TARGET_QUERY_PACKAGE_LIMIT = 20;
Adam Powell24428412015-04-01 17:19:56 -0700218
Adam Powell2ed547e2015-04-29 18:45:04 -0700219 private static final int QUERY_TARGET_SERVICE_LIMIT = 5;
Adam Powell24428412015-04-01 17:19:56 -0700220
Susi Kharraz-Post14cbfcd2019-04-01 11:07:59 -0400221 private static final int DEFAULT_SALT_EXPIRATION_DAYS = 7;
222 private int mMaxHashSaltDays = DeviceConfig.getInt(DeviceConfig.NAMESPACE_SYSTEMUI,
223 SystemUiDeviceConfigFlags.HASH_SALT_MAX_DAYS,
224 DEFAULT_SALT_EXPIRATION_DAYS);
225
Song Hue2deffd2020-03-09 15:22:29 -0700226 private boolean mAppendDirectShareEnabled = DeviceConfig.getBoolean(
227 DeviceConfig.NAMESPACE_SYSTEMUI,
228 SystemUiDeviceConfigFlags.APPEND_DIRECT_SHARE_ENABLED,
229 false);
230
Adam Powelle49d9392014-07-17 18:45:19 -0700231 private Bundle mReplacementExtras;
Adam Powell0b3c1122014-10-09 12:50:14 -0700232 private IntentSender mChosenComponentSender;
Adam Powell2ed547e2015-04-29 18:45:04 -0700233 private IntentSender mRefinementIntentSender;
234 private RefinementResultReceiver mRefinementResultReceiver;
Adam Powell52c39212016-04-07 15:14:18 -0700235 private ChooserTarget[] mCallerChooserTargets;
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -0800236 private ComponentName[] mFilteredComponentNames;
Adam Powelle49d9392014-07-17 18:45:19 -0700237
Adam Powell13036be2015-05-12 14:43:56 -0700238 private Intent mReferrerFillInIntent;
239
Kang Li9082f5b2016-12-02 10:56:21 -0800240 private long mChooserShownTime;
Kang Li64b018e2017-01-05 17:30:06 -0800241 protected boolean mIsSuccessfullySelected;
Kang Li9082f5b2016-12-02 10:56:21 -0800242
Mehdi Alizadeh97fb3ed2019-04-25 14:52:02 -0700243 private long mQueriedTargetServicesTimeMs;
244 private long mQueriedSharingShortcutsTimeMs;
245
Matt Pietalcdfcd9a2019-03-05 08:31:47 -0500246 private int mChooserRowServiceSpacing;
Adam Powell24428412015-04-01 17:19:56 -0700247
Matt Pietalab73a882019-06-05 07:04:55 -0400248 private int mCurrAvailableWidth = 0;
arangelovc4dbdbd2020-02-18 20:54:16 +0000249 private int mLastNumberOfChildren = -1;
Matt Pietalab73a882019-06-05 07:04:55 -0400250
Adam Powell23882512016-01-29 10:21:00 -0800251 private static final String TARGET_DETAILS_FRAGMENT_TAG = "targetDetailsFragment";
Alison Cichowlas1c8816c2019-04-03 17:43:22 -0400252 // TODO: Update to handle landscape instead of using static value
253 private static final int MAX_RANKED_TARGETS = 4;
Adam Powell23882512016-01-29 10:21:00 -0800254
Adam Powell24428412015-04-01 17:19:56 -0700255 private final List<ChooserTargetServiceConnection> mServiceConnections = new ArrayList<>();
arangelov5fc9e7d2020-01-07 17:59:14 +0000256 private final Set<Pair<ComponentName, UserHandle>> mServicesRequested = new HashSet<>();
Matt Pietalaf044ae2019-03-29 06:53:53 -0400257
Susi Kharraz-Post8c14f772019-04-17 16:33:41 -0400258 private static final int MAX_LOG_RANK_POSITION = 12;
259
Matt Pietal4e2e3632019-04-05 08:32:47 -0400260 private static final int MAX_EXTRA_INITIAL_INTENTS = 2;
Matt Pietal9a6b23d2019-04-19 14:47:14 -0400261 private static final int MAX_EXTRA_CHOOSER_TARGETS = 2;
Matt Pietal4e2e3632019-04-05 08:32:47 -0400262
Alison Cichowlas1fd47152019-11-14 19:50:55 -0500263 private SharedPreferences mPinnedSharedPrefs;
264 private static final String PINNED_SHARED_PREFS_NAME = "chooser_pin_settings";
265
Matt Pietal0ea391b2019-01-30 10:44:15 -0500266 @Retention(SOURCE)
267 @IntDef({CONTENT_PREVIEW_FILE, CONTENT_PREVIEW_IMAGE, CONTENT_PREVIEW_TEXT})
268 private @interface ContentPreviewType {
269 }
270
Susi Kharraz-Post7e2115d2019-02-01 16:51:22 -0500271 // Starting at 1 since 0 is considered "undefined" for some of the database transformations
272 // of tron logs.
273 private static final int CONTENT_PREVIEW_IMAGE = 1;
274 private static final int CONTENT_PREVIEW_FILE = 2;
275 private static final int CONTENT_PREVIEW_TEXT = 3;
276 protected MetricsLogger mMetricsLogger;
Matt Pietal0ea391b2019-01-30 10:44:15 -0500277
Matt Pietale7cacab2019-05-23 07:21:36 -0400278 private ContentPreviewCoordinator mPreviewCoord;
279
arangelov38a6fce2019-12-02 18:21:22 +0000280 @VisibleForTesting
281 protected ChooserMultiProfilePagerAdapter mChooserMultiProfilePagerAdapter;
282
Matt Pietale7cacab2019-05-23 07:21:36 -0400283 private class ContentPreviewCoordinator {
Matt Pietale7cacab2019-05-23 07:21:36 -0400284 private static final int IMAGE_FADE_IN_MILLIS = 150;
285 private static final int IMAGE_LOAD_TIMEOUT = 1;
286 private static final int IMAGE_LOAD_INTO_VIEW = 2;
287
Matt Pietalab73a882019-06-05 07:04:55 -0400288 private final int mImageLoadTimeoutMillis =
289 getResources().getInteger(R.integer.config_shortAnimTime);
290
Matt Pietale7cacab2019-05-23 07:21:36 -0400291 private final View mParentView;
292 private boolean mHideParentOnFail;
293 private boolean mAtLeastOneLoaded = false;
294
295 class LoadUriTask {
296 public final Uri mUri;
297 public final int mImageResourceId;
298 public final int mExtraCount;
299 public final Bitmap mBmp;
300
301 LoadUriTask(int imageResourceId, Uri uri, int extraCount, Bitmap bmp) {
302 this.mImageResourceId = imageResourceId;
303 this.mUri = uri;
304 this.mExtraCount = extraCount;
305 this.mBmp = bmp;
306 }
307 }
308
309 // If at least one image loads within the timeout period, allow other
310 // loads to continue. Otherwise terminate and optionally hide
311 // the parent area
312 private final Handler mHandler = new Handler() {
313 @Override
314 public void handleMessage(Message msg) {
315 switch (msg.what) {
316 case IMAGE_LOAD_TIMEOUT:
317 maybeHideContentPreview();
318 break;
319
320 case IMAGE_LOAD_INTO_VIEW:
321 if (isFinishing()) break;
322
323 LoadUriTask task = (LoadUriTask) msg.obj;
324 RoundedRectImageView imageView = mParentView.findViewById(
325 task.mImageResourceId);
326 if (task.mBmp == null) {
327 imageView.setVisibility(View.GONE);
328 maybeHideContentPreview();
329 return;
330 }
331
332 mAtLeastOneLoaded = true;
333 imageView.setVisibility(View.VISIBLE);
334 imageView.setAlpha(0.0f);
335 imageView.setImageBitmap(task.mBmp);
336
337 ValueAnimator fadeAnim = ObjectAnimator.ofFloat(imageView, "alpha", 0.0f,
338 1.0f);
339 fadeAnim.setInterpolator(new DecelerateInterpolator(1.0f));
340 fadeAnim.setDuration(IMAGE_FADE_IN_MILLIS);
341 fadeAnim.start();
342
343 if (task.mExtraCount > 0) {
344 imageView.setExtraImageCount(task.mExtraCount);
345 }
346 }
347 }
348 };
349
350 ContentPreviewCoordinator(View parentView, boolean hideParentOnFail) {
351 super();
352
353 this.mParentView = parentView;
354 this.mHideParentOnFail = hideParentOnFail;
355 }
356
357 private void loadUriIntoView(final int imageResourceId, final Uri uri,
358 final int extraImages) {
Matt Pietalab73a882019-06-05 07:04:55 -0400359 mHandler.sendEmptyMessageDelayed(IMAGE_LOAD_TIMEOUT, mImageLoadTimeoutMillis);
Matt Pietale7cacab2019-05-23 07:21:36 -0400360
361 AsyncTask.THREAD_POOL_EXECUTOR.execute(() -> {
Alison Cichowlas07acade2019-12-20 11:26:23 -0500362 int size = getResources().getDimensionPixelSize(
363 R.dimen.chooser_preview_image_max_dimen);
364 final Bitmap bmp = loadThumbnail(uri, new Size(size, size));
Matt Pietale7cacab2019-05-23 07:21:36 -0400365 final Message msg = Message.obtain();
366 msg.what = IMAGE_LOAD_INTO_VIEW;
367 msg.obj = new LoadUriTask(imageResourceId, uri, extraImages, bmp);
368 mHandler.sendMessage(msg);
369 });
370 }
371
372 private void cancelLoads() {
373 mHandler.removeMessages(IMAGE_LOAD_INTO_VIEW);
374 mHandler.removeMessages(IMAGE_LOAD_TIMEOUT);
375 }
376
377 private void maybeHideContentPreview() {
378 if (!mAtLeastOneLoaded && mHideParentOnFail) {
379 Log.i(TAG, "Hiding image preview area. Timed out waiting for preview to load"
Matt Pietalab73a882019-06-05 07:04:55 -0400380 + " within " + mImageLoadTimeoutMillis + "ms.");
Matt Pietale7cacab2019-05-23 07:21:36 -0400381 collapseParentView();
arangelovf163a882020-02-18 17:18:47 +0000382 if (shouldShowTabs()) {
arangelov590fba32020-02-11 18:05:42 +0000383 hideStickyContentPreview();
384 } else if (mChooserMultiProfilePagerAdapter.getCurrentRootAdapter() != null) {
385 mChooserMultiProfilePagerAdapter.getCurrentRootAdapter().hideContentPreview();
386 }
Matt Pietale7cacab2019-05-23 07:21:36 -0400387 mHideParentOnFail = false;
388 }
389 }
390
391 private void collapseParentView() {
392 // This will effectively hide the content preview row by forcing the height
393 // to zero. It is faster than forcing a relayout of the listview
394 final View v = mParentView;
395 int widthSpec = MeasureSpec.makeMeasureSpec(v.getWidth(), MeasureSpec.EXACTLY);
396 int heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.EXACTLY);
397 v.measure(widthSpec, heightSpec);
398 v.getLayoutParams().height = 0;
399 v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getTop());
400 v.invalidate();
401 }
402 }
403
Matt Pietalab73a882019-06-05 07:04:55 -0400404 private final ChooserHandler mChooserHandler = new ChooserHandler();
405
406 private class ChooserHandler extends Handler {
407 private static final int CHOOSER_TARGET_SERVICE_RESULT = 1;
408 private static final int CHOOSER_TARGET_SERVICE_WATCHDOG_MIN_TIMEOUT = 2;
409 private static final int CHOOSER_TARGET_SERVICE_WATCHDOG_MAX_TIMEOUT = 3;
410 private static final int SHORTCUT_MANAGER_SHARE_TARGET_RESULT = 4;
411 private static final int SHORTCUT_MANAGER_SHARE_TARGET_RESULT_COMPLETED = 5;
412 private static final int LIST_VIEW_UPDATE_MESSAGE = 6;
413
414 private static final int WATCHDOG_TIMEOUT_MAX_MILLIS = 10000;
415 private static final int WATCHDOG_TIMEOUT_MIN_MILLIS = 3000;
416
Song Hue2deffd2020-03-09 15:22:29 -0700417 private static final int DEFAULT_DIRECT_SHARE_TIMEOUT_MILLIS = 1500;
418 private int mDirectShareTimeout = DeviceConfig.getInt(DeviceConfig.NAMESPACE_SYSTEMUI,
419 SystemUiDeviceConfigFlags.SHARE_SHEET_DIRECT_SHARE_TIMEOUT,
420 DEFAULT_DIRECT_SHARE_TIMEOUT_MILLIS);
421
Matt Pietalab73a882019-06-05 07:04:55 -0400422 private boolean mMinTimeoutPassed = false;
423
424 private void removeAllMessages() {
425 removeMessages(LIST_VIEW_UPDATE_MESSAGE);
426 removeMessages(CHOOSER_TARGET_SERVICE_WATCHDOG_MIN_TIMEOUT);
427 removeMessages(CHOOSER_TARGET_SERVICE_WATCHDOG_MAX_TIMEOUT);
428 removeMessages(CHOOSER_TARGET_SERVICE_RESULT);
429 removeMessages(SHORTCUT_MANAGER_SHARE_TARGET_RESULT);
430 removeMessages(SHORTCUT_MANAGER_SHARE_TARGET_RESULT_COMPLETED);
431 }
432
433 private void restartServiceRequestTimer() {
434 mMinTimeoutPassed = false;
435 removeMessages(CHOOSER_TARGET_SERVICE_WATCHDOG_MIN_TIMEOUT);
436 removeMessages(CHOOSER_TARGET_SERVICE_WATCHDOG_MAX_TIMEOUT);
437
438 if (DEBUG) {
439 Log.d(TAG, "queryTargets setting watchdog timer for "
Song Hue2deffd2020-03-09 15:22:29 -0700440 + mDirectShareTimeout + "-"
Matt Pietalab73a882019-06-05 07:04:55 -0400441 + WATCHDOG_TIMEOUT_MAX_MILLIS + "ms");
442 }
443
444 sendEmptyMessageDelayed(CHOOSER_TARGET_SERVICE_WATCHDOG_MIN_TIMEOUT,
445 WATCHDOG_TIMEOUT_MIN_MILLIS);
446 sendEmptyMessageDelayed(CHOOSER_TARGET_SERVICE_WATCHDOG_MAX_TIMEOUT,
Song Hue2deffd2020-03-09 15:22:29 -0700447 mAppendDirectShareEnabled ? mDirectShareTimeout : WATCHDOG_TIMEOUT_MAX_MILLIS);
Matt Pietalab73a882019-06-05 07:04:55 -0400448 }
449
450 private void maybeStopServiceRequestTimer() {
451 // Set a minimum timeout threshold, to ensure both apis, sharing shortcuts
452 // and older-style direct share services, have had time to load, otherwise
453 // just checking mServiceConnections could force us to end prematurely
454 if (mMinTimeoutPassed && mServiceConnections.isEmpty()) {
455 logDirectShareTargetReceived(
456 MetricsEvent.ACTION_DIRECT_SHARE_TARGETS_LOADED_CHOOSER_SERVICE);
457 sendVoiceChoicesIfNeeded();
arangelova3912cf2019-12-13 14:34:45 +0000458 mChooserMultiProfilePagerAdapter.getActiveListAdapter()
arangelov38a6fce2019-12-02 18:21:22 +0000459 .completeServiceTargetLoading();
Matt Pietalab73a882019-06-05 07:04:55 -0400460 }
461 }
462
Adam Powell24428412015-04-01 17:19:56 -0700463 @Override
464 public void handleMessage(Message msg) {
arangelova3912cf2019-12-13 14:34:45 +0000465 if (mChooserMultiProfilePagerAdapter.getActiveListAdapter() == null || isDestroyed()) {
Matt Pietalaf044ae2019-03-29 06:53:53 -0400466 return;
467 }
468
Adam Powell24428412015-04-01 17:19:56 -0700469 switch (msg.what) {
470 case CHOOSER_TARGET_SERVICE_RESULT:
471 if (DEBUG) Log.d(TAG, "CHOOSER_TARGET_SERVICE_RESULT");
Adam Powell24428412015-04-01 17:19:56 -0700472 final ServiceResultInfo sri = (ServiceResultInfo) msg.obj;
473 if (!mServiceConnections.contains(sri.connection)) {
474 Log.w(TAG, "ChooserTargetServiceConnection " + sri.connection
Song Hue2deffd2020-03-09 15:22:29 -0700475 + sri.originalTarget.getResolveInfo().activityInfo.packageName
Adam Powell24428412015-04-01 17:19:56 -0700476 + " returned after being removed from active connections."
477 + " Have you considered returning results faster?");
478 break;
479 }
Adam Powella182e452015-07-06 16:57:56 -0700480 if (sri.resultTargets != null) {
arangelov5fc9e7d2020-01-07 17:59:14 +0000481 ChooserListAdapter adapterForUserHandle =
482 mChooserMultiProfilePagerAdapter.getListAdapterForUserHandle(
483 sri.userHandle);
484 if (adapterForUserHandle != null) {
485 adapterForUserHandle.addServiceResults(sri.originalTarget,
486 sri.resultTargets, TARGET_TYPE_CHOOSER_TARGET,
Song Hue2deffd2020-03-09 15:22:29 -0700487 /* directShareShortcutInfoCache */ null, mServiceConnections);
arangelov5fc9e7d2020-01-07 17:59:14 +0000488 }
Adam Powella182e452015-07-06 16:57:56 -0700489 }
Adam Powell24428412015-04-01 17:19:56 -0700490 unbindService(sri.connection);
Adam Powell9761ab22015-09-08 17:01:49 -0700491 sri.connection.destroy();
Adam Powell24428412015-04-01 17:19:56 -0700492 mServiceConnections.remove(sri.connection);
Matt Pietalab73a882019-06-05 07:04:55 -0400493 maybeStopServiceRequestTimer();
Adam Powell24428412015-04-01 17:19:56 -0700494 break;
495
Matt Pietalab73a882019-06-05 07:04:55 -0400496 case CHOOSER_TARGET_SERVICE_WATCHDOG_MIN_TIMEOUT:
497 mMinTimeoutPassed = true;
498 maybeStopServiceRequestTimer();
499 break;
Matt Pietalaf044ae2019-03-29 06:53:53 -0400500
Matt Pietalab73a882019-06-05 07:04:55 -0400501 case CHOOSER_TARGET_SERVICE_WATCHDOG_MAX_TIMEOUT:
Song Hue2deffd2020-03-09 15:22:29 -0700502 mMinTimeoutPassed = true;
Adam Powell24428412015-04-01 17:19:56 -0700503 unbindRemainingServices();
Matt Pietalab73a882019-06-05 07:04:55 -0400504 maybeStopServiceRequestTimer();
Adam Powell24428412015-04-01 17:19:56 -0700505 break;
506
Matt Pietalaf044ae2019-03-29 06:53:53 -0400507 case LIST_VIEW_UPDATE_MESSAGE:
508 if (DEBUG) {
509 Log.d(TAG, "LIST_VIEW_UPDATE_MESSAGE; ");
510 }
511
arangelov5fc9e7d2020-01-07 17:59:14 +0000512 UserHandle userHandle = (UserHandle) msg.obj;
513 mChooserMultiProfilePagerAdapter.getListAdapterForUserHandle(userHandle)
514 .refreshListView();
Matt Pietalaf044ae2019-03-29 06:53:53 -0400515 break;
516
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -0800517 case SHORTCUT_MANAGER_SHARE_TARGET_RESULT:
518 if (DEBUG) Log.d(TAG, "SHORTCUT_MANAGER_SHARE_TARGET_RESULT");
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -0800519 final ServiceResultInfo resultInfo = (ServiceResultInfo) msg.obj;
520 if (resultInfo.resultTargets != null) {
arangelov5fc9e7d2020-01-07 17:59:14 +0000521 ChooserListAdapter adapterForUserHandle =
522 mChooserMultiProfilePagerAdapter.getListAdapterForUserHandle(
523 resultInfo.userHandle);
524 if (adapterForUserHandle != null) {
525 adapterForUserHandle.addServiceResults(
526 resultInfo.originalTarget, resultInfo.resultTargets, msg.arg1,
Song Hue2deffd2020-03-09 15:22:29 -0700527 mDirectShareShortcutInfoCache, mServiceConnections);
arangelov5fc9e7d2020-01-07 17:59:14 +0000528 }
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -0800529 }
Mehdi Alizadeh8e248ad2019-01-17 11:41:49 -0800530 break;
531
532 case SHORTCUT_MANAGER_SHARE_TARGET_RESULT_COMPLETED:
Mehdi Alizadeh97fb3ed2019-04-25 14:52:02 -0700533 logDirectShareTargetReceived(
534 MetricsEvent.ACTION_DIRECT_SHARE_TARGETS_LOADED_SHORTCUT_MANAGER);
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -0800535 sendVoiceChoicesIfNeeded();
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -0800536 break;
537
Adam Powell24428412015-04-01 17:19:56 -0700538 default:
539 super.handleMessage(msg);
540 }
541 }
542 };
543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 @Override
545 protected void onCreate(Bundle savedInstanceState) {
Kang Li9082f5b2016-12-02 10:56:21 -0800546 final long intentReceivedTime = System.currentTimeMillis();
Mehdi Alizadeh5cc5f712019-09-06 12:17:52 -0700547 // This is the only place this value is being set. Effectively final.
548 mIsAppPredictorComponentAvailable = isAppPredictionServiceAvailable();
549
Kang Li9082f5b2016-12-02 10:56:21 -0800550 mIsSuccessfullySelected = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551 Intent intent = getIntent();
Dianne Hackborneb034652009-09-07 00:49:58 -0700552 Parcelable targetParcelable = intent.getParcelableExtra(Intent.EXTRA_INTENT);
Dan Sandlere3d19932019-11-22 11:58:58 -0500553 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
Dianne Hackborneb034652009-09-07 00:49:58 -0700562 if (!(targetParcelable instanceof Intent)) {
Christopher Tate9d6376a2014-02-12 13:14:10 -0800563 Log.w("ChooserActivity", "Target is not an intent: " + targetParcelable);
Dianne Hackborneb034652009-09-07 00:49:58 -0700564 finish();
Christopher Tate9d6376a2014-02-12 13:14:10 -0800565 super.onCreate(null);
Dianne Hackborneb034652009-09-07 00:49:58 -0700566 return;
567 }
Adam Powell24428412015-04-01 17:19:56 -0700568 Intent target = (Intent) targetParcelable;
Craig Mautner411d2aed2014-05-08 09:07:43 -0700569 if (target != null) {
Adam Powelle49d9392014-07-17 18:45:19 -0700570 modifyTargetIntent(target);
Craig Mautner411d2aed2014-05-08 09:07:43 -0700571 }
Adam Powell2ed547e2015-04-29 18:45:04 -0700572 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
Adam Powelle49d9392014-07-17 18:45:19 -0700598 mReplacementExtras = intent.getBundleExtra(Intent.EXTRA_REPLACEMENT_EXTRAS);
Matt Pietal26038402019-01-08 07:29:34 -0500599
600 // Do not allow the title to be changed when sharing content
601 CharSequence title = null;
602 if (target != null) {
Matt Pietal95574b02019-03-13 08:12:25 -0400603 if (!isSendAction(target)) {
Matt Pietal26038402019-01-08 07:29:34 -0500604 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
Adam Powell278902c2014-07-12 18:33:22 -0700612 int defaultTitleRes = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 if (title == null) {
Adam Powell278902c2014-07-12 18:33:22 -0700614 defaultTitleRes = com.android.internal.R.string.chooseActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 }
Matt Pietal26038402019-01-08 07:29:34 -0500616
Dianne Hackborneb034652009-09-07 00:49:58 -0700617 Parcelable[] pa = intent.getParcelableArrayExtra(Intent.EXTRA_INITIAL_INTENTS);
618 Intent[] initialIntents = null;
619 if (pa != null) {
Matt Pietal4e2e3632019-04-05 08:32:47 -0400620 int count = Math.min(pa.length, MAX_EXTRA_INITIAL_INTENTS);
621 initialIntents = new Intent[count];
622 for (int i = 0; i < count; i++) {
Dianne Hackborneb034652009-09-07 00:49:58 -0700623 if (!(pa[i] instanceof Intent)) {
Adam Powell2ed547e2015-04-29 18:45:04 -0700624 Log.w(TAG, "Initial intent #" + i + " not an Intent: " + pa[i]);
Dianne Hackborneb034652009-09-07 00:49:58 -0700625 finish();
Christopher Tate9d6376a2014-02-12 13:14:10 -0800626 super.onCreate(null);
Dianne Hackborneb034652009-09-07 00:49:58 -0700627 return;
628 }
Craig Mautner411d2aed2014-05-08 09:07:43 -0700629 final Intent in = (Intent) pa[i];
Adam Powelle49d9392014-07-17 18:45:19 -0700630 modifyTargetIntent(in);
Craig Mautner411d2aed2014-05-08 09:07:43 -0700631 initialIntents[i] = in;
Dianne Hackborneb034652009-09-07 00:49:58 -0700632 }
633 }
Adam Powell24428412015-04-01 17:19:56 -0700634
Adam Powell13036be2015-05-12 14:43:56 -0700635 mReferrerFillInIntent = new Intent().putExtra(Intent.EXTRA_REFERRER, getReferrer());
636
Adam Powell0b3c1122014-10-09 12:50:14 -0700637 mChosenComponentSender = intent.getParcelableExtra(
638 Intent.EXTRA_CHOSEN_COMPONENT_INTENT_SENDER);
Adam Powell2ed547e2015-04-29 18:45:04 -0700639 mRefinementIntentSender = intent.getParcelableExtra(
640 Intent.EXTRA_CHOOSER_REFINEMENT_INTENT_SENDER);
Dianne Hackborn028ceeb2014-08-17 17:45:48 -0700641 setSafeForwardingMode(true);
Adam Powell23882512016-01-29 10:21:00 -0800642
Alison Cichowlas1fd47152019-11-14 19:50:55 -0500643 mPinnedSharedPrefs = getPinnedSharedPrefs(this);
644
Adam Powell52c39212016-04-07 15:14:18 -0700645 pa = intent.getParcelableArrayExtra(Intent.EXTRA_EXCLUDE_COMPONENTS);
646 if (pa != null) {
647 ComponentName[] names = new ComponentName[pa.length];
648 for (int i = 0; i < pa.length; i++) {
649 if (!(pa[i] instanceof ComponentName)) {
650 Log.w(TAG, "Filtered component #" + i + " not a ComponentName: " + pa[i]);
651 names = null;
652 break;
653 }
654 names[i] = (ComponentName) pa[i];
655 }
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -0800656 mFilteredComponentNames = names;
Adam Powell52c39212016-04-07 15:14:18 -0700657 }
658
659 pa = intent.getParcelableArrayExtra(Intent.EXTRA_CHOOSER_TARGETS);
660 if (pa != null) {
Matt Pietal9a6b23d2019-04-19 14:47:14 -0400661 int count = Math.min(pa.length, MAX_EXTRA_CHOOSER_TARGETS);
662 ChooserTarget[] targets = new ChooserTarget[count];
663 for (int i = 0; i < count; i++) {
Adam Powell52c39212016-04-07 15:14:18 -0700664 if (!(pa[i] instanceof ChooserTarget)) {
665 Log.w(TAG, "Chooser target #" + i + " not a ChooserTarget: " + pa[i]);
666 targets = null;
667 break;
668 }
669 targets[i] = (ChooserTarget) pa[i];
670 }
671 mCallerChooserTargets = targets;
672 }
673
Jorim Jaggif631ef72017-02-24 13:49:47 +0100674 setRetainInOnStop(intent.getBooleanExtra(EXTRA_PRIVATE_RETAIN_IN_ON_STOP, false));
Adam Powell278902c2014-07-12 18:33:22 -0700675 super.onCreate(savedInstanceState, target, title, defaultTitleRes, initialIntents,
676 null, false);
Adam Powell98b7f892015-06-19 12:38:45 -0700677
Kang Li9082f5b2016-12-02 10:56:21 -0800678 mChooserShownTime = System.currentTimeMillis();
679 final long systemCost = mChooserShownTime - intentReceivedTime;
Susi Kharraz-Post7e2115d2019-02-01 16:51:22 -0500680
681 getMetricsLogger().write(new LogMaker(MetricsEvent.ACTION_ACTIVITY_CHOOSER_SHOWN)
Susi Kharraz-Post0446fab2019-02-21 09:42:31 -0500682 .setSubtype(isWorkProfile() ? MetricsEvent.MANAGED_PROFILE :
683 MetricsEvent.PARENT_PROFILE)
Susi Kharraz-Post7e2115d2019-02-01 16:51:22 -0500684 .addTaggedData(MetricsEvent.FIELD_SHARESHEET_MIMETYPE, target.getType())
685 .addTaggedData(MetricsEvent.FIELD_TIME_TO_APP_TARGETS, systemCost));
George Hodulik69d4a082019-01-18 11:27:03 -0800686
Matt Pietalcdfcd9a2019-03-05 08:31:47 -0500687 mChooserRowServiceSpacing = getResources()
688 .getDimensionPixelSize(R.dimen.chooser_service_spacing);
689
Matt Pietalfe28f9a2019-03-22 07:59:58 -0400690 if (mResolverDrawerLayout != null) {
691 mResolverDrawerLayout.addOnLayoutChangeListener(this::handleLayoutChange);
692
693 // expand/shrink direct share 4 -> 8 viewgroup
694 if (isSendAction(target)) {
695 mResolverDrawerLayout.setOnScrollChangeListener(this::handleScroll);
696 }
Matt Pietalb1d629d2019-04-23 11:35:53 -0400697
Mike Digman849a9d12019-04-29 11:20:48 -0700698 mResolverDrawerLayout.setOnCollapsedChangedListener(
699 new ResolverDrawerLayout.OnCollapsedChangedListener() {
700
701 // Only consider one expansion per activity creation
702 private boolean mWrittenOnce = false;
703
704 @Override
705 public void onCollapsedChanged(boolean isCollapsed) {
706 if (!isCollapsed && !mWrittenOnce) {
707 incrementNumSheetExpansions();
708 mWrittenOnce = true;
709 }
710 }
711 });
Matt Pietal5b648562019-03-12 07:40:26 -0400712 }
713
Kang Li9082f5b2016-12-02 10:56:21 -0800714 if (DEBUG) {
715 Log.d(TAG, "System Time Cost is " + systemCost);
716 }
arangelov5fc9e7d2020-01-07 17:59:14 +0000717
718 mDirectShareShortcutInfoCache = new HashMap<>();
719 }
720
721 private AppPredictor setupAppPredictorForUser(UserHandle userHandle,
722 AppPredictor.Callback appPredictorCallback) {
723 AppPredictor appPredictor = getAppPredictorForDirectShareIfEnabled(userHandle);
724 if (appPredictor == null) {
725 return null;
726 }
727 mDirectShareAppTargetCache = new HashMap<>();
728 appPredictor.registerPredictionUpdates(this.getMainExecutor(), appPredictorCallback);
729 return appPredictor;
730 }
731
732 private AppPredictor.Callback createAppPredictorCallback(
733 ChooserListAdapter chooserListAdapter) {
734 return resultList -> {
735 //TODO(arangelov) Take care of edge case when callback called after swiping tabs
736 if (isFinishing() || isDestroyed()) {
737 return;
738 }
739 if (chooserListAdapter.getCount() == 0) {
740 return;
741 }
742 if (resultList.isEmpty()) {
743 // APS may be disabled, so try querying targets ourselves.
744 //TODO(arangelov) queryDirectShareTargets indirectly uses mIntents.
745 // Investigate implications for work tab.
746 queryDirectShareTargets(chooserListAdapter, true);
747 return;
748 }
749 final List<DisplayResolveInfo> driList =
750 getDisplayResolveInfos(chooserListAdapter);
751 final List<ShortcutManager.ShareShortcutInfo> shareShortcutInfos =
752 new ArrayList<>();
753 for (AppTarget appTarget : resultList) {
754 if (appTarget.getShortcutInfo() == null) {
755 continue;
756 }
757 shareShortcutInfos.add(new ShortcutManager.ShareShortcutInfo(
758 appTarget.getShortcutInfo(),
759 new ComponentName(
760 appTarget.getPackageName(), appTarget.getClassName())));
761 }
762 sendShareShortcutInfoList(shareShortcutInfos, driList, resultList,
763 chooserListAdapter.getUserHandle());
764 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 }
Adam Powelle49d9392014-07-17 18:45:19 -0700766
Alison Cichowlas1fd47152019-11-14 19:50:55 -0500767 static SharedPreferences getPinnedSharedPrefs(Context context) {
768 // The code below is because in the android:ui process, no one can hear you scream.
769 // The package info in the context isn't initialized in the way it is for normal apps,
770 // so the standard, name-based context.getSharedPreferences doesn't work. Instead, we
771 // build the path manually below using the same policy that appears in ContextImpl.
772 // This fails silently under the hood if there's a problem, so if we find ourselves in
773 // the case where we don't have access to credential encrypted storage we just won't
774 // have our pinned target info.
775 final File prefsFile = new File(new File(
776 Environment.getDataUserCePackageDirectory(StorageManager.UUID_PRIVATE_INTERNAL,
777 context.getUserId(), context.getPackageName()),
778 "shared_prefs"),
779 PINNED_SHARED_PREFS_NAME + ".xml");
780 return context.getSharedPreferences(prefsFile, MODE_PRIVATE);
781 }
782
arangelov38a6fce2019-12-02 18:21:22 +0000783 @Override
784 protected AbstractMultiProfilePagerAdapter createMultiProfilePagerAdapter(
785 Intent[] initialIntents,
786 List<ResolveInfo> rList,
787 boolean filterLastUsed) {
arangelovf163a882020-02-18 17:18:47 +0000788 if (shouldShowTabs()) {
arangelov38a6fce2019-12-02 18:21:22 +0000789 mChooserMultiProfilePagerAdapter = createChooserMultiProfilePagerAdapterForTwoProfiles(
790 initialIntents, rList, filterLastUsed);
791 } else {
792 mChooserMultiProfilePagerAdapter = createChooserMultiProfilePagerAdapterForOneProfile(
793 initialIntents, rList, filterLastUsed);
794 }
795 return mChooserMultiProfilePagerAdapter;
796 }
797
798 private ChooserMultiProfilePagerAdapter createChooserMultiProfilePagerAdapterForOneProfile(
799 Intent[] initialIntents,
800 List<ResolveInfo> rList,
801 boolean filterLastUsed) {
802 ChooserGridAdapter adapter = createChooserGridAdapter(
803 /* context */ this,
804 /* payloadIntents */ mIntents,
805 initialIntents,
806 rList,
807 filterLastUsed,
808 mUseLayoutForBrowsables,
809 /* userHandle */ UserHandle.of(UserHandle.myUserId()));
810 return new ChooserMultiProfilePagerAdapter(
811 /* context */ this,
arangelov7981b122020-01-16 10:58:27 +0000812 adapter,
813 getPersonalProfileUserHandle(),
814 /* workProfileUserHandle= */ null);
arangelov38a6fce2019-12-02 18:21:22 +0000815 }
816
817 private ChooserMultiProfilePagerAdapter createChooserMultiProfilePagerAdapterForTwoProfiles(
818 Intent[] initialIntents,
819 List<ResolveInfo> rList,
820 boolean filterLastUsed) {
821 ChooserGridAdapter personalAdapter = createChooserGridAdapter(
822 /* context */ this,
823 /* payloadIntents */ mIntents,
824 initialIntents,
825 rList,
826 filterLastUsed,
827 mUseLayoutForBrowsables,
828 /* userHandle */ getPersonalProfileUserHandle());
829 ChooserGridAdapter workAdapter = createChooserGridAdapter(
830 /* context */ this,
831 /* payloadIntents */ mIntents,
832 initialIntents,
833 rList,
834 filterLastUsed,
835 mUseLayoutForBrowsables,
836 /* userHandle */ getWorkProfileUserHandle());
837 return new ChooserMultiProfilePagerAdapter(
838 /* context */ this,
839 personalAdapter,
840 workAdapter,
arangelov7981b122020-01-16 10:58:27 +0000841 /* defaultProfile */ getCurrentProfile(),
842 getPersonalProfileUserHandle(),
843 getWorkProfileUserHandle());
arangelov38a6fce2019-12-02 18:21:22 +0000844 }
845
846 @Override
847 protected boolean postRebuildList(boolean rebuildCompleted) {
arangelov590fba32020-02-11 18:05:42 +0000848 updateStickyContentPreview();
849 if (shouldShowStickyContentPreview()
850 || mChooserMultiProfilePagerAdapter
851 .getCurrentRootAdapter().getContentPreviewRowCount() != 0) {
852 logActionShareWithPreview();
853 }
arangelov38a6fce2019-12-02 18:21:22 +0000854 return postRebuildListInternal(rebuildCompleted);
855 }
856
Matt Pietal26038402019-01-08 07:29:34 -0500857 /**
Mehdi Alizadeha1c18a82019-08-15 16:31:38 -0700858 * Returns true if app prediction service is defined and the component exists on device.
859 */
Mehdi Alizadehe870e972019-09-11 17:54:15 -0700860 @VisibleForTesting
861 public boolean isAppPredictionServiceAvailable() {
862 if (getPackageManager().getAppPredictionServicePackageName() == null) {
863 // Default AppPredictionService is not defined.
864 return false;
865 }
866
Mehdi Alizadeha1c18a82019-08-15 16:31:38 -0700867 final String appPredictionServiceName =
868 getString(R.string.config_defaultAppPredictionService);
869 if (appPredictionServiceName == null) {
870 return false;
871 }
872 final ComponentName appPredictionComponentName =
873 ComponentName.unflattenFromString(appPredictionServiceName);
874 if (appPredictionComponentName == null) {
875 return false;
876 }
877
878 // Check if the app prediction component actually exists on the device.
879 Intent intent = new Intent();
880 intent.setComponent(appPredictionComponentName);
881 if (getPackageManager().resolveService(intent, PackageManager.MATCH_ALL) == null) {
882 Log.e(TAG, "App prediction service is defined, but does not exist: "
883 + appPredictionServiceName);
884 return false;
885 }
886 return true;
887 }
888
889 /**
Susi Kharraz-Post0446fab2019-02-21 09:42:31 -0500890 * Check if the profile currently used is a work profile.
891 * @return true if it is work profile, false if it is parent profile (or no work profile is
892 * set up)
893 */
894 protected boolean isWorkProfile() {
arangelov38a6fce2019-12-02 18:21:22 +0000895 return getSystemService(UserManager.class)
Susi Kharraz-Post0446fab2019-02-21 09:42:31 -0500896 .getUserInfo(UserHandle.myUserId()).isManagedProfile();
897 }
898
Matt Pietalab73a882019-06-05 07:04:55 -0400899 @Override
arangelov7981b122020-01-16 10:58:27 +0000900 protected PackageMonitor createPackageMonitor(ResolverListAdapter listAdapter) {
Matt Pietalab73a882019-06-05 07:04:55 -0400901 return new PackageMonitor() {
902 @Override
903 public void onSomePackagesChanged() {
arangelov7981b122020-01-16 10:58:27 +0000904 handlePackagesChanged(listAdapter);
Matt Pietalab73a882019-06-05 07:04:55 -0400905 }
906 };
907 }
908
Alison Cichowlasbc290812019-12-17 19:42:29 -0500909 /**
910 * Update UI to reflect changes in data.
911 */
912 public void handlePackagesChanged() {
arangelov7981b122020-01-16 10:58:27 +0000913 handlePackagesChanged(/* listAdapter */ null);
914 }
915
916 /**
917 * Update UI to reflect changes in data.
918 * <p>If {@code listAdapter} is {@code null}, both profile list adapters are updated.
919 */
920 private void handlePackagesChanged(@Nullable ResolverListAdapter listAdapter) {
921 if (listAdapter == null) {
922 mChooserMultiProfilePagerAdapter.getActiveListAdapter().handlePackagesChanged();
923 } else {
924 listAdapter.handlePackagesChanged();
925 }
Alison Cichowlasbc290812019-12-17 19:42:29 -0500926 updateProfileViewButton();
927 }
928
Matt Pietal46d828c2019-02-05 08:07:07 -0500929 private void onCopyButtonClicked(View v) {
930 Intent targetIntent = getTargetIntent();
931 if (targetIntent == null) {
932 finish();
933 } else {
934 final String action = targetIntent.getAction();
935
936 ClipData clipData = null;
937 if (Intent.ACTION_SEND.equals(action)) {
938 String extraText = targetIntent.getStringExtra(Intent.EXTRA_TEXT);
939 Uri extraStream = targetIntent.getParcelableExtra(Intent.EXTRA_STREAM);
940
941 if (extraText != null) {
942 clipData = ClipData.newPlainText(null, extraText);
943 } else if (extraStream != null) {
944 clipData = ClipData.newUri(getContentResolver(), null, extraStream);
945 } else {
946 Log.w(TAG, "No data available to copy to clipboard");
947 return;
948 }
949 } else if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
950 final ArrayList<Uri> streams = targetIntent.getParcelableArrayListExtra(
951 Intent.EXTRA_STREAM);
952 clipData = ClipData.newUri(getContentResolver(), null, streams.get(0));
953 for (int i = 1; i < streams.size(); i++) {
954 clipData.addItem(getContentResolver(), new ClipData.Item(streams.get(i)));
955 }
956 } else {
957 // expected to only be visible with ACTION_SEND or ACTION_SEND_MULTIPLE
958 // so warn about unexpected action
959 Log.w(TAG, "Action (" + action + ") not supported for copying to clipboard");
960 return;
961 }
962
963 ClipboardManager clipboardManager = (ClipboardManager) getSystemService(
964 Context.CLIPBOARD_SERVICE);
965 clipboardManager.setPrimaryClip(clipData);
966 Toast.makeText(getApplicationContext(), R.string.copied, Toast.LENGTH_SHORT).show();
967
Alison Cichowlasaa7f79f2019-09-12 15:57:26 -0400968 // Log share completion via copy
969 LogMaker targetLogMaker = new LogMaker(
970 MetricsEvent.ACTION_ACTIVITY_CHOOSER_PICKED_SYSTEM_TARGET).setSubtype(1);
971 getMetricsLogger().write(targetLogMaker);
972
Matt Pietal46d828c2019-02-05 08:07:07 -0500973 finish();
974 }
975 }
976
Matt Pietal18bbd822019-02-12 15:21:36 -0500977 @Override
978 public void onConfigurationChanged(Configuration newConfig) {
979 super.onConfigurationChanged(newConfig);
980
Matt Pietal3e4b56f2019-05-31 12:06:17 -0400981 adjustPreviewWidth(newConfig.orientation, null);
arangelovc4dbdbd2020-02-18 20:54:16 +0000982 updateStickyContentPreview();
Matt Pietal3e4b56f2019-05-31 12:06:17 -0400983 }
984
985 private boolean shouldDisplayLandscape(int orientation) {
986 // Sharesheet fixes the # of items per row and therefore can not correctly lay out
987 // when in the restricted size of multi-window mode. In the future, would be nice
988 // to use minimum dp size requirements instead
989 return orientation == Configuration.ORIENTATION_LANDSCAPE && !isInMultiWindowMode();
990 }
991
992 private void adjustPreviewWidth(int orientation, View parent) {
Matt Pietal18bbd822019-02-12 15:21:36 -0500993 int width = -1;
Matt Pietal3e4b56f2019-05-31 12:06:17 -0400994 if (shouldDisplayLandscape(orientation)) {
Matt Pietal18bbd822019-02-12 15:21:36 -0500995 width = getResources().getDimensionPixelSize(R.dimen.chooser_preview_width);
996 }
997
Matt Pietal3e4b56f2019-05-31 12:06:17 -0400998 parent = parent == null ? getWindow().getDecorView() : parent;
999
1000 updateLayoutWidth(R.id.content_preview_text_layout, width, parent);
1001 updateLayoutWidth(R.id.content_preview_title_layout, width, parent);
1002 updateLayoutWidth(R.id.content_preview_file_layout, width, parent);
Matt Pietal18bbd822019-02-12 15:21:36 -05001003 }
1004
Matt Pietal3e4b56f2019-05-31 12:06:17 -04001005 private void updateLayoutWidth(int layoutResourceId, int width, View parent) {
1006 View view = parent.findViewById(layoutResourceId);
Matt Pietal1ef88002019-03-13 10:43:18 -04001007 if (view != null && view.getLayoutParams() != null) {
1008 LayoutParams params = view.getLayoutParams();
1009 params.width = width;
1010 view.setLayoutParams(params);
Matt Pietal0ea391b2019-01-30 10:44:15 -05001011 }
1012 }
1013
arangelova3912cf2019-12-13 14:34:45 +00001014 private ViewGroup createContentPreviewView(ViewGroup parent) {
1015 Intent targetIntent = getTargetIntent();
1016 int previewType = findPreferredContentPreview(targetIntent, getContentResolver());
1017 return displayContentPreview(previewType, targetIntent, getLayoutInflater(), parent);
1018 }
1019
Dan Sandlere3d19932019-11-22 11:58:58 -05001020 private ComponentName getNearbySharingComponent() {
1021 String nearbyComponent = Settings.Secure.getString(
1022 getContentResolver(),
1023 Settings.Secure.NEARBY_SHARING_COMPONENT);
1024 if (TextUtils.isEmpty(nearbyComponent)) {
1025 nearbyComponent = getString(R.string.config_defaultNearbySharingComponent);
1026 }
1027 if (TextUtils.isEmpty(nearbyComponent)) {
1028 return null;
1029 }
1030 return ComponentName.unflattenFromString(nearbyComponent);
1031 }
1032
1033 private TargetInfo getNearbySharingTarget(Intent originalIntent) {
1034 final ComponentName cn = getNearbySharingComponent();
1035 if (cn == null) return null;
1036
1037 final Intent resolveIntent = new Intent();
1038 resolveIntent.setComponent(cn);
1039 final ResolveInfo ri = getPackageManager().resolveActivity(
1040 resolveIntent, PackageManager.GET_META_DATA);
1041 if (ri == null || ri.activityInfo == null) {
1042 Log.e(TAG, "Device-specified nearby sharing component (" + cn
1043 + ") not available");
1044 return null;
1045 }
1046
1047 // Allow the nearby sharing component to provide a more appropriate icon and label
1048 // for the chip.
1049 CharSequence name = null;
1050 Drawable icon = null;
1051 final Bundle metaData = ri.activityInfo.metaData;
1052 if (metaData != null) {
1053 try {
1054 final Resources pkgRes = getPackageManager().getResourcesForActivity(cn);
1055 final int nameResId = metaData.getInt(CHIP_LABEL_METADATA_KEY);
1056 name = pkgRes.getString(nameResId);
1057 final int resId = metaData.getInt(CHIP_ICON_METADATA_KEY);
1058 icon = pkgRes.getDrawable(resId);
1059 } catch (Resources.NotFoundException ex) {
1060 } catch (NameNotFoundException ex) {
1061 }
1062 }
1063 if (TextUtils.isEmpty(name)) {
1064 name = ri.loadLabel(getPackageManager());
1065 }
1066 if (icon == null) {
1067 icon = ri.loadIcon(getPackageManager());
1068 }
1069
1070 final DisplayResolveInfo dri = new DisplayResolveInfo(
1071 originalIntent, ri, name, "", resolveIntent, null);
1072 dri.setDisplayIcon(icon);
1073 return dri;
1074 }
1075
1076 private Button createActionButton(Drawable icon, CharSequence title, View.OnClickListener r) {
1077 Button b = (Button) LayoutInflater.from(this).inflate(R.layout.chooser_action_button, null);
1078 if (icon != null) {
1079 final int size = getResources()
1080 .getDimensionPixelSize(R.dimen.chooser_action_button_icon_size);
1081 icon.setBounds(0, 0, size, size);
1082 b.setCompoundDrawablesRelative(icon, null, null, null);
1083 }
1084 b.setText(title);
1085 b.setOnClickListener(r);
1086 return b;
1087 }
1088
1089 private Button createCopyButton() {
1090 final Button b = createActionButton(
1091 getDrawable(R.drawable.ic_menu_copy_material),
1092 getString(R.string.copy), this::onCopyButtonClicked);
1093 b.setId(R.id.chooser_copy_button);
1094 return b;
1095 }
1096
1097 private @Nullable Button createNearbyButton(Intent originalIntent) {
1098 final TargetInfo ti = getNearbySharingTarget(originalIntent);
1099 if (ti == null) return null;
1100
1101 return createActionButton(
1102 ti.getDisplayIcon(this),
1103 ti.getDisplayLabel(),
1104 (View unused) -> {
1105 safelyStartActivity(ti);
1106 finish();
1107 }
1108 );
1109 }
1110
1111 private void addActionButton(ViewGroup parent, Button b) {
1112 if (b == null) return;
1113 final ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
1114 LayoutParams.WRAP_CONTENT,
1115 LayoutParams.WRAP_CONTENT
1116 );
1117 final int gap = getResources().getDimensionPixelSize(R.dimen.resolver_icon_margin) / 2;
1118 lp.setMarginsRelative(gap, 0, gap, 0);
1119 parent.addView(b, lp);
1120 }
1121
Matt Pietal1ef88002019-03-13 10:43:18 -04001122 private ViewGroup displayContentPreview(@ContentPreviewType int previewType,
Zhen Zhangbde7b462019-11-11 11:49:33 -08001123 Intent targetIntent, LayoutInflater layoutInflater, ViewGroup parent) {
Matt Pietal3e4b56f2019-05-31 12:06:17 -04001124 ViewGroup layout = null;
1125
Matt Pietal1ef88002019-03-13 10:43:18 -04001126 switch (previewType) {
1127 case CONTENT_PREVIEW_TEXT:
Matt Pietal3e4b56f2019-05-31 12:06:17 -04001128 layout = displayTextContentPreview(targetIntent, layoutInflater, parent);
1129 break;
Matt Pietal1ef88002019-03-13 10:43:18 -04001130 case CONTENT_PREVIEW_IMAGE:
Matt Pietal3e4b56f2019-05-31 12:06:17 -04001131 layout = displayImageContentPreview(targetIntent, layoutInflater, parent);
1132 break;
Matt Pietal1ef88002019-03-13 10:43:18 -04001133 case CONTENT_PREVIEW_FILE:
Matt Pietal3e4b56f2019-05-31 12:06:17 -04001134 layout = displayFileContentPreview(targetIntent, layoutInflater, parent);
1135 break;
Matt Pietal1ef88002019-03-13 10:43:18 -04001136 default:
1137 Log.e(TAG, "Unexpected content preview type: " + previewType);
1138 }
Matt Pietal0ea391b2019-01-30 10:44:15 -05001139
Matt Pietal3e4b56f2019-05-31 12:06:17 -04001140 if (layout != null) {
1141 adjustPreviewWidth(getResources().getConfiguration().orientation, layout);
1142 }
1143
1144 return layout;
Matt Pietal1ef88002019-03-13 10:43:18 -04001145 }
1146
1147 private ViewGroup displayTextContentPreview(Intent targetIntent, LayoutInflater layoutInflater,
Matt Pietale7cacab2019-05-23 07:21:36 -04001148 ViewGroup parent) {
1149 ViewGroup contentPreviewLayout = (ViewGroup) layoutInflater.inflate(
1150 R.layout.chooser_grid_preview_text, parent, false);
Matt Pietal1ef88002019-03-13 10:43:18 -04001151
Dan Sandlere3d19932019-11-22 11:58:58 -05001152 final ViewGroup actionRow =
1153 (ViewGroup) contentPreviewLayout.findViewById(R.id.chooser_action_row);
1154 addActionButton(actionRow, createCopyButton());
1155 addActionButton(actionRow, createNearbyButton(targetIntent));
Matt Pietal46d828c2019-02-05 08:07:07 -05001156
Matt Pietal26038402019-01-08 07:29:34 -05001157 CharSequence sharingText = targetIntent.getCharSequenceExtra(Intent.EXTRA_TEXT);
Matt Pietal26038402019-01-08 07:29:34 -05001158 if (sharingText == null) {
Matt Pietal1ef88002019-03-13 10:43:18 -04001159 contentPreviewLayout.findViewById(R.id.content_preview_text_layout).setVisibility(
1160 View.GONE);
Matt Pietal26038402019-01-08 07:29:34 -05001161 } else {
Matt Pietal1ef88002019-03-13 10:43:18 -04001162 TextView textView = contentPreviewLayout.findViewById(R.id.content_preview_text);
Matt Pietal1fa7d802019-01-30 10:44:15 -05001163 textView.setText(sharingText);
Matt Pietal26038402019-01-08 07:29:34 -05001164 }
1165
1166 String previewTitle = targetIntent.getStringExtra(Intent.EXTRA_TITLE);
Matt Pietal46d828c2019-02-05 08:07:07 -05001167 if (TextUtils.isEmpty(previewTitle)) {
Matt Pietal1ef88002019-03-13 10:43:18 -04001168 contentPreviewLayout.findViewById(R.id.content_preview_title_layout).setVisibility(
1169 View.GONE);
Matt Pietal26038402019-01-08 07:29:34 -05001170 } else {
Matt Pietal1ef88002019-03-13 10:43:18 -04001171 TextView previewTitleView = contentPreviewLayout.findViewById(
1172 R.id.content_preview_title);
Matt Pietal26038402019-01-08 07:29:34 -05001173 previewTitleView.setText(previewTitle);
Matt Pietal26038402019-01-08 07:29:34 -05001174
Matt Pietal1fa7d802019-01-30 10:44:15 -05001175 ClipData previewData = targetIntent.getClipData();
1176 Uri previewThumbnail = null;
1177 if (previewData != null) {
1178 if (previewData.getItemCount() > 0) {
1179 ClipData.Item previewDataItem = previewData.getItemAt(0);
1180 previewThumbnail = previewDataItem.getUri();
1181 }
Matt Pietal26038402019-01-08 07:29:34 -05001182 }
Matt Pietal26038402019-01-08 07:29:34 -05001183
Matt Pietal1ef88002019-03-13 10:43:18 -04001184 ImageView previewThumbnailView = contentPreviewLayout.findViewById(
1185 R.id.content_preview_thumbnail);
Matt Pietal1fa7d802019-01-30 10:44:15 -05001186 if (previewThumbnail == null) {
Matt Pietal26038402019-01-08 07:29:34 -05001187 previewThumbnailView.setVisibility(View.GONE);
1188 } else {
Matt Pietale7cacab2019-05-23 07:21:36 -04001189 mPreviewCoord = new ContentPreviewCoordinator(contentPreviewLayout, false);
1190 mPreviewCoord.loadUriIntoView(R.id.content_preview_thumbnail, previewThumbnail, 0);
Matt Pietal26038402019-01-08 07:29:34 -05001191 }
1192 }
Matt Pietal1ef88002019-03-13 10:43:18 -04001193
1194 return contentPreviewLayout;
Matt Pietal26038402019-01-08 07:29:34 -05001195 }
1196
Matt Pietal1ef88002019-03-13 10:43:18 -04001197 private ViewGroup displayImageContentPreview(Intent targetIntent, LayoutInflater layoutInflater,
Matt Pietale7cacab2019-05-23 07:21:36 -04001198 ViewGroup parent) {
1199 ViewGroup contentPreviewLayout = (ViewGroup) layoutInflater.inflate(
1200 R.layout.chooser_grid_preview_image, parent, false);
1201 mPreviewCoord = new ContentPreviewCoordinator(contentPreviewLayout, true);
Matt Pietal0ea391b2019-01-30 10:44:15 -05001202
1203 String action = targetIntent.getAction();
1204 if (Intent.ACTION_SEND.equals(action)) {
1205 Uri uri = targetIntent.getParcelableExtra(Intent.EXTRA_STREAM);
Matt Pietale7cacab2019-05-23 07:21:36 -04001206 mPreviewCoord.loadUriIntoView(R.id.content_preview_image_1_large, uri, 0);
Matt Pietal0ea391b2019-01-30 10:44:15 -05001207 } else {
1208 ContentResolver resolver = getContentResolver();
1209
1210 List<Uri> uris = targetIntent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
1211 List<Uri> imageUris = new ArrayList<>();
1212 for (Uri uri : uris) {
1213 if (isImageType(resolver.getType(uri))) {
1214 imageUris.add(uri);
1215 }
1216 }
1217
1218 if (imageUris.size() == 0) {
1219 Log.i(TAG, "Attempted to display image preview area with zero"
1220 + " available images detected in EXTRA_STREAM list");
Matt Pietal46d828c2019-02-05 08:07:07 -05001221 contentPreviewLayout.setVisibility(View.GONE);
Matt Pietal1ef88002019-03-13 10:43:18 -04001222 return contentPreviewLayout;
Matt Pietal0ea391b2019-01-30 10:44:15 -05001223 }
1224
Matt Pietale7cacab2019-05-23 07:21:36 -04001225 mPreviewCoord.loadUriIntoView(R.id.content_preview_image_1_large, imageUris.get(0), 0);
Matt Pietal0ea391b2019-01-30 10:44:15 -05001226
1227 if (imageUris.size() == 2) {
Matt Pietale7cacab2019-05-23 07:21:36 -04001228 mPreviewCoord.loadUriIntoView(R.id.content_preview_image_2_large,
1229 imageUris.get(1), 0);
Matt Pietal0ea391b2019-01-30 10:44:15 -05001230 } else if (imageUris.size() > 2) {
Matt Pietale7cacab2019-05-23 07:21:36 -04001231 mPreviewCoord.loadUriIntoView(R.id.content_preview_image_2_small,
1232 imageUris.get(1), 0);
1233 mPreviewCoord.loadUriIntoView(R.id.content_preview_image_3_small,
1234 imageUris.get(2), imageUris.size() - 3);
Matt Pietal0ea391b2019-01-30 10:44:15 -05001235 }
1236 }
Matt Pietal1ef88002019-03-13 10:43:18 -04001237
1238 return contentPreviewLayout;
Matt Pietal0ea391b2019-01-30 10:44:15 -05001239 }
1240
Matt Pietal46d828c2019-02-05 08:07:07 -05001241 private static class FileInfo {
1242 public final String name;
1243 public final boolean hasThumbnail;
1244
1245 FileInfo(String name, boolean hasThumbnail) {
1246 this.name = name;
1247 this.hasThumbnail = hasThumbnail;
1248 }
1249 }
1250
Matt Pietalf38e9d22019-02-15 10:01:03 -05001251 /**
1252 * Wrapping the ContentResolver call to expose for easier mocking,
1253 * and to avoid mocking Android core classes.
1254 */
1255 @VisibleForTesting
1256 public Cursor queryResolver(ContentResolver resolver, Uri uri) {
1257 return resolver.query(uri, null, null, null, null);
1258 }
1259
Matt Pietal46d828c2019-02-05 08:07:07 -05001260 private FileInfo extractFileInfo(Uri uri, ContentResolver resolver) {
1261 String fileName = null;
1262 boolean hasThumbnail = false;
Matt Pietal3087bca2019-02-14 12:19:16 -05001263
Matt Pietalf38e9d22019-02-15 10:01:03 -05001264 try (Cursor cursor = queryResolver(resolver, uri)) {
1265 if (cursor != null && cursor.getCount() > 0) {
1266 int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
1267 int titleIndex = cursor.getColumnIndex(Downloads.Impl.COLUMN_TITLE);
1268 int flagsIndex = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_FLAGS);
1269
1270 cursor.moveToFirst();
1271 if (nameIndex != -1) {
1272 fileName = cursor.getString(nameIndex);
1273 } else if (titleIndex != -1) {
1274 fileName = cursor.getString(titleIndex);
1275 }
1276
1277 if (flagsIndex != -1) {
1278 hasThumbnail = (cursor.getInt(flagsIndex)
1279 & DocumentsContract.Document.FLAG_SUPPORTS_THUMBNAIL) != 0;
1280 }
1281 }
Matt Pietal73a873f2019-03-15 08:46:20 -04001282 } catch (SecurityException | NullPointerException e) {
Matt Pietal62532e52019-05-07 09:51:37 -04001283 logContentPreviewWarning(uri);
Matt Pietal3087bca2019-02-14 12:19:16 -05001284 }
1285
Matt Pietal46d828c2019-02-05 08:07:07 -05001286 if (TextUtils.isEmpty(fileName)) {
1287 fileName = uri.getPath();
1288 int index = fileName.lastIndexOf('/');
1289 if (index != -1) {
1290 fileName = fileName.substring(index + 1);
1291 }
1292 }
1293
1294 return new FileInfo(fileName, hasThumbnail);
1295 }
1296
Matt Pietal62532e52019-05-07 09:51:37 -04001297 private void logContentPreviewWarning(Uri uri) {
1298 // The ContentResolver already logs the exception. Log something more informative.
1299 Log.w(TAG, "Could not load (" + uri.toString() + ") thumbnail/name for preview. If "
1300 + "desired, consider using Intent#createChooser to launch the ChooserActivity, "
1301 + "and set your Intent's clipData and flags in accordance with that method's "
1302 + "documentation");
1303 }
1304
Matt Pietal1ef88002019-03-13 10:43:18 -04001305 private ViewGroup displayFileContentPreview(Intent targetIntent, LayoutInflater layoutInflater,
Matt Pietale7cacab2019-05-23 07:21:36 -04001306 ViewGroup parent) {
Matt Pietal1ef88002019-03-13 10:43:18 -04001307
Matt Pietale7cacab2019-05-23 07:21:36 -04001308 ViewGroup contentPreviewLayout = (ViewGroup) layoutInflater.inflate(
1309 R.layout.chooser_grid_preview_file, parent, false);
Matt Pietal46d828c2019-02-05 08:07:07 -05001310
1311 // TODO(b/120417119): Disable file copy until after moving to sysui,
1312 // due to permissions issues
Dan Sandlere3d19932019-11-22 11:58:58 -05001313 //((ViewGroup) contentPreviewLayout.findViewById(R.id.chooser_action_row))
1314 // .addView(createCopyButton());
Matt Pietal46d828c2019-02-05 08:07:07 -05001315
Matt Pietal3087bca2019-02-14 12:19:16 -05001316 String action = targetIntent.getAction();
1317 if (Intent.ACTION_SEND.equals(action)) {
1318 Uri uri = targetIntent.getParcelableExtra(Intent.EXTRA_STREAM);
Matt Pietal1ef88002019-03-13 10:43:18 -04001319 loadFileUriIntoView(uri, contentPreviewLayout);
Matt Pietal3087bca2019-02-14 12:19:16 -05001320 } else {
1321 List<Uri> uris = targetIntent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
1322 int uriCount = uris.size();
Matt Pietal46d828c2019-02-05 08:07:07 -05001323
Matt Pietal3087bca2019-02-14 12:19:16 -05001324 if (uriCount == 0) {
1325 contentPreviewLayout.setVisibility(View.GONE);
1326 Log.i(TAG,
1327 "Appears to be no uris available in EXTRA_STREAM, removing "
1328 + "preview area");
Matt Pietal1ef88002019-03-13 10:43:18 -04001329 return contentPreviewLayout;
Matt Pietal3087bca2019-02-14 12:19:16 -05001330 } else if (uriCount == 1) {
Matt Pietal1ef88002019-03-13 10:43:18 -04001331 loadFileUriIntoView(uris.get(0), contentPreviewLayout);
Matt Pietal46d828c2019-02-05 08:07:07 -05001332 } else {
Matt Pietal3087bca2019-02-14 12:19:16 -05001333 FileInfo fileInfo = extractFileInfo(uris.get(0), getContentResolver());
1334 int remUriCount = uriCount - 1;
Matt Pietalacabc572019-02-14 11:02:05 -05001335 String fileName = getResources().getQuantityString(R.plurals.file_count,
Matt Pietal3087bca2019-02-14 12:19:16 -05001336 remUriCount, fileInfo.name, remUriCount);
Matt Pietalacabc572019-02-14 11:02:05 -05001337
Matt Pietal1ef88002019-03-13 10:43:18 -04001338 TextView fileNameView = contentPreviewLayout.findViewById(
1339 R.id.content_preview_filename);
Matt Pietalacabc572019-02-14 11:02:05 -05001340 fileNameView.setText(fileName);
Matt Pietal3087bca2019-02-14 12:19:16 -05001341
Matt Pietale7cacab2019-05-23 07:21:36 -04001342 View thumbnailView = contentPreviewLayout.findViewById(
1343 R.id.content_preview_file_thumbnail);
1344 thumbnailView.setVisibility(View.GONE);
1345
Matt Pietal1ef88002019-03-13 10:43:18 -04001346 ImageView fileIconView = contentPreviewLayout.findViewById(
1347 R.id.content_preview_file_icon);
Matt Pietal46d828c2019-02-05 08:07:07 -05001348 fileIconView.setVisibility(View.VISIBLE);
Matt Pietalacabc572019-02-14 11:02:05 -05001349 fileIconView.setImageResource(R.drawable.ic_file_copy);
Matt Pietal46d828c2019-02-05 08:07:07 -05001350 }
Matt Pietal3087bca2019-02-14 12:19:16 -05001351 }
Matt Pietal1ef88002019-03-13 10:43:18 -04001352
1353 return contentPreviewLayout;
Matt Pietal3087bca2019-02-14 12:19:16 -05001354 }
1355
Matt Pietale7cacab2019-05-23 07:21:36 -04001356 private void loadFileUriIntoView(final Uri uri, final View parent) {
Matt Pietal3087bca2019-02-14 12:19:16 -05001357 FileInfo fileInfo = extractFileInfo(uri, getContentResolver());
1358
Matt Pietal1ef88002019-03-13 10:43:18 -04001359 TextView fileNameView = parent.findViewById(R.id.content_preview_filename);
Matt Pietal3087bca2019-02-14 12:19:16 -05001360 fileNameView.setText(fileInfo.name);
1361
1362 if (fileInfo.hasThumbnail) {
Matt Pietale7cacab2019-05-23 07:21:36 -04001363 mPreviewCoord = new ContentPreviewCoordinator(parent, false);
1364 mPreviewCoord.loadUriIntoView(R.id.content_preview_file_thumbnail, uri, 0);
Matt Pietal3087bca2019-02-14 12:19:16 -05001365 } else {
Matt Pietale7cacab2019-05-23 07:21:36 -04001366 View thumbnailView = parent.findViewById(R.id.content_preview_file_thumbnail);
1367 thumbnailView.setVisibility(View.GONE);
1368
Matt Pietal1ef88002019-03-13 10:43:18 -04001369 ImageView fileIconView = parent.findViewById(R.id.content_preview_file_icon);
Matt Pietal3087bca2019-02-14 12:19:16 -05001370 fileIconView.setVisibility(View.VISIBLE);
Matt Pietal832cdbf2019-04-05 13:20:31 -04001371 fileIconView.setImageResource(R.drawable.chooser_file_generic);
Matt Pietal46d828c2019-02-05 08:07:07 -05001372 }
Matt Pietal0ea391b2019-01-30 10:44:15 -05001373 }
1374
Matt Pietal0ea391b2019-01-30 10:44:15 -05001375 @VisibleForTesting
1376 protected boolean isImageType(String mimeType) {
1377 return mimeType != null && mimeType.startsWith("image/");
1378 }
1379
1380 @ContentPreviewType
1381 private int findPreferredContentPreview(Uri uri, ContentResolver resolver) {
1382 if (uri == null) {
1383 return CONTENT_PREVIEW_TEXT;
1384 }
1385
1386 String mimeType = resolver.getType(uri);
1387 return isImageType(mimeType) ? CONTENT_PREVIEW_IMAGE : CONTENT_PREVIEW_FILE;
1388 }
1389
1390 /**
1391 * In {@link android.content.Intent#getType}, the app may specify a very general
1392 * mime-type that broadly covers all data being shared, such as {@literal *}/*
1393 * when sending an image and text. We therefore should inspect each item for the
1394 * the preferred type, in order of IMAGE, FILE, TEXT.
1395 */
1396 @ContentPreviewType
1397 private int findPreferredContentPreview(Intent targetIntent, ContentResolver resolver) {
1398 String action = targetIntent.getAction();
1399 if (Intent.ACTION_SEND.equals(action)) {
1400 Uri uri = targetIntent.getParcelableExtra(Intent.EXTRA_STREAM);
1401 return findPreferredContentPreview(uri, resolver);
1402 } else if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
1403 List<Uri> uris = targetIntent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
1404 if (uris == null || uris.isEmpty()) {
1405 return CONTENT_PREVIEW_TEXT;
1406 }
1407
1408 for (Uri uri : uris) {
Matt Pietal832cdbf2019-04-05 13:20:31 -04001409 // Defaulting to file preview when there are mixed image/file types is
1410 // preferable, as it shows the user the correct number of items being shared
1411 if (findPreferredContentPreview(uri, resolver) == CONTENT_PREVIEW_FILE) {
1412 return CONTENT_PREVIEW_FILE;
Matt Pietal0ea391b2019-01-30 10:44:15 -05001413 }
1414 }
1415
Matt Pietal832cdbf2019-04-05 13:20:31 -04001416 return CONTENT_PREVIEW_IMAGE;
Matt Pietal0ea391b2019-01-30 10:44:15 -05001417 }
1418
1419 return CONTENT_PREVIEW_TEXT;
1420 }
1421
Mike Digman849a9d12019-04-29 11:20:48 -07001422 private int getNumSheetExpansions() {
1423 return getPreferences(Context.MODE_PRIVATE).getInt(PREF_NUM_SHEET_EXPANSIONS, 0);
1424 }
1425
1426 private void incrementNumSheetExpansions() {
1427 getPreferences(Context.MODE_PRIVATE).edit().putInt(PREF_NUM_SHEET_EXPANSIONS,
1428 getNumSheetExpansions() + 1).apply();
1429 }
1430
Adam Powell0b3c1122014-10-09 12:50:14 -07001431 @Override
Adam Powell2ed547e2015-04-29 18:45:04 -07001432 protected void onDestroy() {
1433 super.onDestroy();
1434 if (mRefinementResultReceiver != null) {
1435 mRefinementResultReceiver.destroy();
1436 mRefinementResultReceiver = null;
1437 }
Adam Powell9761ab22015-09-08 17:01:49 -07001438 unbindRemainingServices();
Matt Pietalab73a882019-06-05 07:04:55 -04001439 mChooserHandler.removeAllMessages();
Matt Pietale7cacab2019-05-23 07:21:36 -04001440
1441 if (mPreviewCoord != null) mPreviewCoord.cancelLoads();
1442
arangelov5fc9e7d2020-01-07 17:59:14 +00001443 mChooserMultiProfilePagerAdapter.getActiveListAdapter().destroyAppPredictor();
1444 if (mChooserMultiProfilePagerAdapter.getInactiveListAdapter() != null) {
1445 mChooserMultiProfilePagerAdapter.getInactiveListAdapter().destroyAppPredictor();
George Hodulik69d4a082019-01-18 11:27:03 -08001446 }
Adam Powell2ed547e2015-04-29 18:45:04 -07001447 }
1448
arangelovb0802dc2019-10-18 18:03:44 +01001449 @Override // ResolverListCommunicator
Nicolas Prevot0e2b73f2014-10-27 10:06:11 +00001450 public Intent getReplacementIntent(ActivityInfo aInfo, Intent defIntent) {
1451 Intent result = defIntent;
Adam Powelle49d9392014-07-17 18:45:19 -07001452 if (mReplacementExtras != null) {
Nicolas Prevot0e2b73f2014-10-27 10:06:11 +00001453 final Bundle replExtras = mReplacementExtras.getBundle(aInfo.packageName);
Adam Powelle49d9392014-07-17 18:45:19 -07001454 if (replExtras != null) {
Nicolas Prevot0e2b73f2014-10-27 10:06:11 +00001455 result = new Intent(defIntent);
Adam Powelle49d9392014-07-17 18:45:19 -07001456 result.putExtras(replExtras);
Adam Powelle49d9392014-07-17 18:45:19 -07001457 }
1458 }
Nicolas Prevot741abfc2015-08-11 12:03:51 +01001459 if (aInfo.name.equals(IntentForwarderActivity.FORWARD_INTENT_TO_PARENT)
Nicolas Prevot0e2b73f2014-10-27 10:06:11 +00001460 || aInfo.name.equals(IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE)) {
1461 result = Intent.createChooser(result,
1462 getIntent().getCharSequenceExtra(Intent.EXTRA_TITLE));
Hakan Seyalioglu7317e8a2016-12-12 16:15:38 -08001463
1464 // Don't auto-launch single intents if the intent is being forwarded. This is done
1465 // because automatically launching a resolving application as a response to the user
1466 // action of switching accounts is pretty unexpected.
1467 result.putExtra(Intent.EXTRA_AUTO_LAUNCH_SINGLE_CHOICE, false);
Nicolas Prevot0e2b73f2014-10-27 10:06:11 +00001468 }
1469 return result;
Adam Powelle49d9392014-07-17 18:45:19 -07001470 }
1471
Adam Powell0b3c1122014-10-09 12:50:14 -07001472 @Override
Adam Powell23882512016-01-29 10:21:00 -08001473 public void onActivityStarted(TargetInfo cti) {
Adam Powell0b3c1122014-10-09 12:50:14 -07001474 if (mChosenComponentSender != null) {
Adam Powell24428412015-04-01 17:19:56 -07001475 final ComponentName target = cti.getResolvedComponentName();
Adam Powell0b3c1122014-10-09 12:50:14 -07001476 if (target != null) {
1477 final Intent fillIn = new Intent().putExtra(Intent.EXTRA_CHOSEN_COMPONENT, target);
1478 try {
1479 mChosenComponentSender.sendIntent(this, Activity.RESULT_OK, fillIn, null, null);
1480 } catch (IntentSender.SendIntentException e) {
1481 Slog.e(TAG, "Unable to launch supplied IntentSender to report "
1482 + "the chosen component: " + e);
1483 }
1484 }
1485 }
1486 }
1487
Adam Powell24428412015-04-01 17:19:56 -07001488 @Override
arangelovcf268642020-01-15 15:09:51 +00001489 public void addUseDifferentAppLabelIfNecessary(ResolverListAdapter adapter) {
Adam Powell52c39212016-04-07 15:14:18 -07001490 if (mCallerChooserTargets != null && mCallerChooserTargets.length > 0) {
arangelova3912cf2019-12-13 14:34:45 +00001491 mChooserMultiProfilePagerAdapter.getActiveListAdapter().addServiceResults(
arangelov38a6fce2019-12-02 18:21:22 +00001492 /* origTarget */ null,
1493 Lists.newArrayList(mCallerChooserTargets),
arangelov5fc9e7d2020-01-07 17:59:14 +00001494 TARGET_TYPE_DEFAULT,
Song Hue2deffd2020-03-09 15:22:29 -07001495 /* directShareShortcutInfoCache */ null, mServiceConnections);
Adam Powell52c39212016-04-07 15:14:18 -07001496 }
arangelovb0802dc2019-10-18 18:03:44 +01001497 }
1498
1499 @Override
Adam Powell23882512016-01-29 10:21:00 -08001500 public int getLayoutResource() {
Adam Powell7d758002015-05-06 17:49:36 -07001501 return R.layout.chooser_grid;
Adam Powell24428412015-04-01 17:19:56 -07001502 }
1503
arangelovb0802dc2019-10-18 18:03:44 +01001504 @Override // ResolverListCommunicator
Adam Powell23882512016-01-29 10:21:00 -08001505 public boolean shouldGetActivityMetadata() {
Adam Powell24428412015-04-01 17:19:56 -07001506 return true;
1507 }
1508
Adam Powell9761ab22015-09-08 17:01:49 -07001509 @Override
Ben Lin145b0ca2016-10-14 14:23:40 -07001510 public boolean shouldAutoLaunchSingleChoice(TargetInfo target) {
Hakan Seyalioglu13405c52017-01-31 19:01:31 -08001511 // Note that this is only safe because the Intent handled by the ChooserActivity is
1512 // guaranteed to contain no extras unknown to the local ClassLoader. That is why this
1513 // method can not be replaced in the ResolverActivity whole hog.
Matt Pietala4b30072019-04-04 13:44:36 -04001514 if (!super.shouldAutoLaunchSingleChoice(target)) {
1515 return false;
1516 }
1517
1518 return getIntent().getBooleanExtra(Intent.EXTRA_AUTO_LAUNCH_SINGLE_CHOICE, true);
Ben Lin145b0ca2016-10-14 14:23:40 -07001519 }
1520
Alison Cichowlas19ee2922019-12-16 19:43:12 -05001521 void showTargetDetails(TargetInfo ti) {
1522 if (ti == null) {
sanryhuang296ca9e2018-03-31 11:17:13 +08001523 return;
1524 }
Alison Cichowlas19ee2922019-12-16 19:43:12 -05001525 ComponentName name = ti.getResolveInfo().activityInfo.getComponentName();
Alison Cichowlas1fd47152019-11-14 19:50:55 -05001526 boolean pinned = mPinnedSharedPrefs.getBoolean(name.flattenToString(), false);
Alison Cichowlas19ee2922019-12-16 19:43:12 -05001527
1528 ResolverTargetActionsDialogFragment f;
1529
1530 // For multiple targets, include info on all targets
1531 if (ti instanceof MultiDisplayResolveInfo) {
1532 MultiDisplayResolveInfo mti = (MultiDisplayResolveInfo) ti;
1533 List<CharSequence> labels = new ArrayList<>();
1534
1535 for (TargetInfo innerInfo : mti.getTargets()) {
1536 labels.add(innerInfo.getResolveInfo().loadLabel(getPackageManager()));
1537 }
Alison Cichowlas4d21ff02019-12-19 18:41:52 -05001538 f = new ResolverTargetActionsDialogFragment(mti.getDisplayLabel(), name,
1539 mti.getTargets(), labels);
Alison Cichowlas19ee2922019-12-16 19:43:12 -05001540 } else {
1541 f = new ResolverTargetActionsDialogFragment(
1542 ti.getResolveInfo().loadLabel(getPackageManager()), name, pinned);
1543 }
1544
Adam Powell23882512016-01-29 10:21:00 -08001545 f.show(getFragmentManager(), TARGET_DETAILS_FRAGMENT_TAG);
1546 }
1547
Adam Powelle49d9392014-07-17 18:45:19 -07001548 private void modifyTargetIntent(Intent in) {
Matt Pietal95574b02019-03-13 08:12:25 -04001549 if (isSendAction(in)) {
Adam Powelle49d9392014-07-17 18:45:19 -07001550 in.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Dianne Hackborn13420f22014-07-18 15:43:56 -07001551 Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
Adam Powelle49d9392014-07-17 18:45:19 -07001552 }
1553 }
Adam Powell24428412015-04-01 17:19:56 -07001554
Adam Powell2ed547e2015-04-29 18:45:04 -07001555 @Override
1556 protected boolean onTargetSelected(TargetInfo target, boolean alwaysCheck) {
1557 if (mRefinementIntentSender != null) {
1558 final Intent fillIn = new Intent();
1559 final List<Intent> sourceIntents = target.getAllSourceIntents();
1560 if (!sourceIntents.isEmpty()) {
1561 fillIn.putExtra(Intent.EXTRA_INTENT, sourceIntents.get(0));
1562 if (sourceIntents.size() > 1) {
1563 final Intent[] alts = new Intent[sourceIntents.size() - 1];
1564 for (int i = 1, N = sourceIntents.size(); i < N; i++) {
1565 alts[i - 1] = sourceIntents.get(i);
1566 }
1567 fillIn.putExtra(Intent.EXTRA_ALTERNATE_INTENTS, alts);
1568 }
1569 if (mRefinementResultReceiver != null) {
1570 mRefinementResultReceiver.destroy();
1571 }
1572 mRefinementResultReceiver = new RefinementResultReceiver(this, target, null);
1573 fillIn.putExtra(Intent.EXTRA_RESULT_RECEIVER,
1574 mRefinementResultReceiver);
1575 try {
1576 mRefinementIntentSender.sendIntent(this, 0, fillIn, null, null);
1577 return false;
1578 } catch (SendIntentException e) {
1579 Log.e(TAG, "Refinement IntentSender failed to send", e);
1580 }
1581 }
1582 }
Kang Li9fa2a2c2017-01-06 13:33:24 -08001583 updateModelAndChooserCounts(target);
Adam Powell2ed547e2015-04-29 18:45:04 -07001584 return super.onTargetSelected(target, alwaysCheck);
1585 }
1586
Adam Powell98b7f892015-06-19 12:38:45 -07001587 @Override
Adam Powell23882512016-01-29 10:21:00 -08001588 public void startSelected(int which, boolean always, boolean filtered) {
arangelov38a6fce2019-12-02 18:21:22 +00001589 ChooserListAdapter currentListAdapter =
arangelova3912cf2019-12-13 14:34:45 +00001590 mChooserMultiProfilePagerAdapter.getActiveListAdapter();
arangelov38a6fce2019-12-02 18:21:22 +00001591 TargetInfo targetInfo = currentListAdapter
1592 .targetInfoForPosition(which, filtered);
Matt Pietala4b30072019-04-04 13:44:36 -04001593 if (targetInfo != null && targetInfo instanceof NotSelectableTargetInfo) {
1594 return;
1595 }
1596
Kang Li9082f5b2016-12-02 10:56:21 -08001597 final long selectionCost = System.currentTimeMillis() - mChooserShownTime;
Alison Cichowlas19ee2922019-12-16 19:43:12 -05001598
Alison Cichowlas19ee2922019-12-16 19:43:12 -05001599 if (targetInfo instanceof MultiDisplayResolveInfo) {
1600 MultiDisplayResolveInfo mti = (MultiDisplayResolveInfo) targetInfo;
Alison Cichowlase12616a2019-12-20 19:05:27 -05001601 if (!mti.hasSelected()) {
1602 // Stacked apps get a disambiguation first
1603 CharSequence[] labels = new CharSequence[mti.getTargets().size()];
1604 int i = 0;
1605 for (TargetInfo ti : mti.getTargets()) {
1606 labels[i++] = ti.getResolveInfo().loadLabel(getPackageManager());
1607 }
1608 ChooserStackedAppDialogFragment f = new ChooserStackedAppDialogFragment(
1609 targetInfo.getDisplayLabel(),
1610 ((MultiDisplayResolveInfo) targetInfo), labels, which);
Alison Cichowlas19ee2922019-12-16 19:43:12 -05001611
Alison Cichowlase12616a2019-12-20 19:05:27 -05001612 f.show(getFragmentManager(), TARGET_DETAILS_FRAGMENT_TAG);
1613 return;
1614 }
Alison Cichowlas19ee2922019-12-16 19:43:12 -05001615 }
1616
Adam Powell98b7f892015-06-19 12:38:45 -07001617 super.startSelected(which, always, filtered);
1618
Alison Cichowlas19ee2922019-12-16 19:43:12 -05001619
arangelov38a6fce2019-12-02 18:21:22 +00001620 if (currentListAdapter.getCount() > 0) {
Adam Powell98b7f892015-06-19 12:38:45 -07001621 // Log the index of which type of target the user picked.
1622 // Lower values mean the ranking was better.
1623 int cat = 0;
1624 int value = which;
Susi Kharraz-Post8c14f772019-04-17 16:33:41 -04001625 int directTargetAlsoRanked = -1;
Susi Kharraz-Post4bcca522019-04-23 15:07:10 -04001626 int numCallerProvided = 0;
Susi Kharraz-Post14cbfcd2019-04-01 11:07:59 -04001627 HashedStringCache.HashResult directTargetHashed = null;
arangelov38a6fce2019-12-02 18:21:22 +00001628 switch (currentListAdapter.getPositionTargetType(which)) {
Adam Powell98b7f892015-06-19 12:38:45 -07001629 case ChooserListAdapter.TARGET_SERVICE:
Chris Wrenf6e9228b2016-01-26 18:04:35 -05001630 cat = MetricsEvent.ACTION_ACTIVITY_CHOOSER_PICKED_SERVICE_TARGET;
Susi Kharraz-Post14cbfcd2019-04-01 11:07:59 -04001631 // Log the package name + target name to answer the question if most users
1632 // share to mostly the same person or to a bunch of different people.
arangelov38a6fce2019-12-02 18:21:22 +00001633 ChooserTarget target = currentListAdapter.getChooserTargetForValue(value);
Susi Kharraz-Post14cbfcd2019-04-01 11:07:59 -04001634 directTargetHashed = HashedStringCache.getInstance().hashString(
1635 this,
1636 TAG,
1637 target.getComponentName().getPackageName()
1638 + target.getTitle().toString(),
1639 mMaxHashSaltDays);
Susi Kharraz-Post8c14f772019-04-17 16:33:41 -04001640 directTargetAlsoRanked = getRankedPosition((SelectableTargetInfo) targetInfo);
Matt Pietal9a6b23d2019-04-19 14:47:14 -04001641
1642 if (mCallerChooserTargets != null) {
Susi Kharraz-Post4bcca522019-04-23 15:07:10 -04001643 numCallerProvided = mCallerChooserTargets.length;
Matt Pietal9a6b23d2019-04-19 14:47:14 -04001644 }
Adam Powell98b7f892015-06-19 12:38:45 -07001645 break;
Susi Kharraz-Post4bcca522019-04-23 15:07:10 -04001646 case ChooserListAdapter.TARGET_CALLER:
Adam Powell98b7f892015-06-19 12:38:45 -07001647 case ChooserListAdapter.TARGET_STANDARD:
Susi Kharraz-Post4bcca522019-04-23 15:07:10 -04001648 cat = MetricsEvent.ACTION_ACTIVITY_CHOOSER_PICKED_APP_TARGET;
arangelov38a6fce2019-12-02 18:21:22 +00001649 value -= currentListAdapter.getSelectableServiceTargetCount();
1650 numCallerProvided = currentListAdapter.getCallerTargetCount();
Adam Powell98b7f892015-06-19 12:38:45 -07001651 break;
Alison Cichowlasd0a075b2019-04-10 20:18:59 -04001652 case ChooserListAdapter.TARGET_STANDARD_AZ:
1653 // A-Z targets are unranked standard targets; we use -1 to mark that they
1654 // are from the alphabetical pool.
1655 value = -1;
1656 cat = MetricsEvent.ACTION_ACTIVITY_CHOOSER_PICKED_STANDARD_TARGET;
1657 break;
Adam Powell98b7f892015-06-19 12:38:45 -07001658 }
1659
1660 if (cat != 0) {
Susi Kharraz-Post14cbfcd2019-04-01 11:07:59 -04001661 LogMaker targetLogMaker = new LogMaker(cat).setSubtype(value);
1662 if (directTargetHashed != null) {
1663 targetLogMaker.addTaggedData(
1664 MetricsEvent.FIELD_HASHED_TARGET_NAME, directTargetHashed.hashedString);
1665 targetLogMaker.addTaggedData(
1666 MetricsEvent.FIELD_HASHED_TARGET_SALT_GEN,
1667 directTargetHashed.saltGeneration);
Susi Kharraz-Post8c14f772019-04-17 16:33:41 -04001668 targetLogMaker.addTaggedData(MetricsEvent.FIELD_RANKED_POSITION,
1669 directTargetAlsoRanked);
Susi Kharraz-Post14cbfcd2019-04-01 11:07:59 -04001670 }
Susi Kharraz-Post4bcca522019-04-23 15:07:10 -04001671 targetLogMaker.addTaggedData(MetricsEvent.FIELD_IS_CATEGORY_USED,
1672 numCallerProvided);
Susi Kharraz-Post14cbfcd2019-04-01 11:07:59 -04001673 getMetricsLogger().write(targetLogMaker);
Adam Powell98b7f892015-06-19 12:38:45 -07001674 }
Kang Li9082f5b2016-12-02 10:56:21 -08001675
1676 if (mIsSuccessfullySelected) {
1677 if (DEBUG) {
1678 Log.d(TAG, "User Selection Time Cost is " + selectionCost);
1679 Log.d(TAG, "position of selected app/service/caller is " +
1680 Integer.toString(value));
1681 }
1682 MetricsLogger.histogram(null, "user_selection_cost_for_smart_sharing",
1683 (int) selectionCost);
1684 MetricsLogger.histogram(null, "app_position_for_smart_sharing", value);
1685 }
Adam Powell98b7f892015-06-19 12:38:45 -07001686 }
1687 }
1688
Susi Kharraz-Post8c14f772019-04-17 16:33:41 -04001689 private int getRankedPosition(SelectableTargetInfo targetInfo) {
1690 String targetPackageName =
1691 targetInfo.getChooserTarget().getComponentName().getPackageName();
arangelov38a6fce2019-12-02 18:21:22 +00001692 ChooserListAdapter currentListAdapter =
arangelova3912cf2019-12-13 14:34:45 +00001693 mChooserMultiProfilePagerAdapter.getActiveListAdapter();
arangelov38a6fce2019-12-02 18:21:22 +00001694 int maxRankedResults = Math.min(currentListAdapter.mDisplayList.size(),
1695 MAX_LOG_RANK_POSITION);
Susi Kharraz-Post8c14f772019-04-17 16:33:41 -04001696
1697 for (int i = 0; i < maxRankedResults; i++) {
arangelov38a6fce2019-12-02 18:21:22 +00001698 if (currentListAdapter.mDisplayList.get(i)
Susi Kharraz-Post8c14f772019-04-17 16:33:41 -04001699 .getResolveInfo().activityInfo.packageName.equals(targetPackageName)) {
1700 return i;
1701 }
1702 }
1703 return -1;
1704 }
1705
Matt Pietal9236adc2019-12-12 09:24:23 -05001706 @Override
1707 protected boolean shouldAddFooterView() {
1708 // To accommodate for window insets
1709 return true;
1710 }
1711
1712 @Override
1713 protected void applyFooterView(int height) {
1714 int count = mChooserMultiProfilePagerAdapter.getItemCount();
1715
1716 for (int i = 0; i < count; i++) {
1717 mChooserMultiProfilePagerAdapter.getAdapterForIndex(i).setFooterHeight(height);
1718 }
1719 }
1720
Adam Powell24428412015-04-01 17:19:56 -07001721 void queryTargetServices(ChooserListAdapter adapter) {
Mehdi Alizadeh97fb3ed2019-04-25 14:52:02 -07001722 mQueriedTargetServicesTimeMs = System.currentTimeMillis();
1723
arangelov5fc9e7d2020-01-07 17:59:14 +00001724 Context selectedProfileContext = createContextAsUser(
1725 adapter.getUserHandle(), 0 /* flags */);
1726 final PackageManager pm = selectedProfileContext.getPackageManager();
1727 ShortcutManager sm = selectedProfileContext.getSystemService(ShortcutManager.class);
Adam Powell24428412015-04-01 17:19:56 -07001728 int targetsToQuery = 0;
Matt Pietalab73a882019-06-05 07:04:55 -04001729
Adam Powell24428412015-04-01 17:19:56 -07001730 for (int i = 0, N = adapter.getDisplayResolveInfoCount(); i < N; i++) {
1731 final DisplayResolveInfo dri = adapter.getDisplayResolveInfo(i);
Adam Powell3a09c522015-10-21 13:21:28 -07001732 if (adapter.getScore(dri) == 0) {
1733 // A score of 0 means the app hasn't been used in some time;
1734 // don't query it as it's not likely to be relevant.
1735 continue;
1736 }
Adam Powell24428412015-04-01 17:19:56 -07001737 final ActivityInfo ai = dri.getResolveInfo().activityInfo;
arangelovb0802dc2019-10-18 18:03:44 +01001738 if (ChooserFlags.USE_SHORTCUT_MANAGER_FOR_DIRECT_TARGETS
Mehdi Alizadeh85fd3d52019-01-23 12:49:53 -08001739 && sm.hasShareTargets(ai.packageName)) {
1740 // Share targets will be queried from ShortcutManager
1741 continue;
1742 }
Adam Powell24428412015-04-01 17:19:56 -07001743 final Bundle md = ai.metaData;
1744 final String serviceName = md != null ? convertServiceName(ai.packageName,
1745 md.getString(ChooserTargetService.META_DATA_NAME)) : null;
1746 if (serviceName != null) {
1747 final ComponentName serviceComponent = new ComponentName(
1748 ai.packageName, serviceName);
Matt Pietalab73a882019-06-05 07:04:55 -04001749
arangelov5fc9e7d2020-01-07 17:59:14 +00001750 UserHandle userHandle = adapter.getUserHandle();
1751 Pair<ComponentName, UserHandle> requestedItem =
1752 new Pair<>(serviceComponent, userHandle);
1753 if (mServicesRequested.contains(requestedItem)) {
Matt Pietalab73a882019-06-05 07:04:55 -04001754 continue;
1755 }
arangelov5fc9e7d2020-01-07 17:59:14 +00001756 mServicesRequested.add(requestedItem);
Matt Pietalab73a882019-06-05 07:04:55 -04001757
Adam Powell24428412015-04-01 17:19:56 -07001758 final Intent serviceIntent = new Intent(ChooserTargetService.SERVICE_INTERFACE)
1759 .setComponent(serviceComponent);
1760
1761 if (DEBUG) {
1762 Log.d(TAG, "queryTargets found target with service " + serviceComponent);
1763 }
1764
1765 try {
1766 final String perm = pm.getServiceInfo(serviceComponent, 0).permission;
1767 if (!ChooserTargetService.BIND_PERMISSION.equals(perm)) {
1768 Log.w(TAG, "ChooserTargetService " + serviceComponent + " does not require"
1769 + " permission " + ChooserTargetService.BIND_PERMISSION
1770 + " - this service will not be queried for ChooserTargets."
1771 + " add android:permission=\""
1772 + ChooserTargetService.BIND_PERMISSION + "\""
1773 + " to the <service> tag for " + serviceComponent
1774 + " in the manifest.");
1775 continue;
1776 }
1777 } catch (NameNotFoundException e) {
Adam Powell52c39212016-04-07 15:14:18 -07001778 Log.e(TAG, "Could not look up service " + serviceComponent
1779 + "; component name not found");
Adam Powell24428412015-04-01 17:19:56 -07001780 continue;
1781 }
1782
Adam Powell9761ab22015-09-08 17:01:49 -07001783 final ChooserTargetServiceConnection conn =
arangelov5fc9e7d2020-01-07 17:59:14 +00001784 new ChooserTargetServiceConnection(this, dri,
1785 adapter.getUserHandle());
Adam Powell52c39212016-04-07 15:14:18 -07001786
arangelov5fc9e7d2020-01-07 17:59:14 +00001787 // Explicitly specify the user handle instead of calling bindService
Adam Powell52c39212016-04-07 15:14:18 -07001788 // to avoid the warning from calling from the system process without an explicit
1789 // user handle
1790 if (bindServiceAsUser(serviceIntent, conn, BIND_AUTO_CREATE | BIND_NOT_FOREGROUND,
arangelov5fc9e7d2020-01-07 17:59:14 +00001791 adapter.getUserHandle())) {
Adam Powell24428412015-04-01 17:19:56 -07001792 if (DEBUG) {
1793 Log.d(TAG, "Binding service connection for target " + dri
1794 + " intent " + serviceIntent);
1795 }
1796 mServiceConnections.add(conn);
1797 targetsToQuery++;
1798 }
1799 }
Adam Powell2ed547e2015-04-29 18:45:04 -07001800 if (targetsToQuery >= QUERY_TARGET_SERVICE_LIMIT) {
Matt Pietal26038402019-01-08 07:29:34 -05001801 if (DEBUG) {
1802 Log.d(TAG, "queryTargets hit query target limit "
1803 + QUERY_TARGET_SERVICE_LIMIT);
1804 }
Adam Powell24428412015-04-01 17:19:56 -07001805 break;
1806 }
1807 }
1808
Matt Pietalab73a882019-06-05 07:04:55 -04001809 mChooserHandler.restartServiceRequestTimer();
Adam Powell24428412015-04-01 17:19:56 -07001810 }
1811
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -08001812 private IntentFilter getTargetIntentFilter() {
1813 try {
1814 final Intent intent = getTargetIntent();
1815 String dataString = intent.getDataString();
Katsiaryna Naliuka66cd0562020-01-16 18:01:30 +01001816 if (!TextUtils.isEmpty(dataString)) {
1817 return new IntentFilter(intent.getAction(), dataString);
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -08001818 }
Katsiaryna Naliukae2c0b5f2020-02-18 19:26:21 +01001819 if (intent.getType() == null) {
1820 Log.e(TAG, "Failed to get target intent filter: intent data and type are null");
1821 return null;
1822 }
Katsiaryna Naliuka66cd0562020-01-16 18:01:30 +01001823 IntentFilter intentFilter = new IntentFilter(intent.getAction(), intent.getType());
1824 List<Uri> contentUris = new ArrayList<>();
1825 if (Intent.ACTION_SEND.equals(intent.getAction())) {
1826 Uri uri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
1827 if (uri != null) {
1828 contentUris.add(uri);
1829 }
1830 } else {
1831 List<Uri> uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
1832 if (uris != null) {
1833 contentUris.addAll(uris);
1834 }
1835 }
1836 for (Uri uri : contentUris) {
1837 intentFilter.addDataScheme(uri.getScheme());
1838 intentFilter.addDataAuthority(uri.getAuthority(), null);
1839 intentFilter.addDataPath(uri.getPath(), PatternMatcher.PATTERN_LITERAL);
1840 }
1841 return intentFilter;
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -08001842 } catch (Exception e) {
Katsiaryna Naliukae2c0b5f2020-02-18 19:26:21 +01001843 Log.e(TAG, "Failed to get target intent filter", e);
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -08001844 return null;
1845 }
1846 }
1847
George Hodulik69d4a082019-01-18 11:27:03 -08001848 private List<DisplayResolveInfo> getDisplayResolveInfos(ChooserListAdapter adapter) {
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -08001849 // Need to keep the original DisplayResolveInfos to be able to reconstruct ServiceResultInfo
1850 // and use the old code path. This Ugliness should go away when Sharesheet is refactored.
George Hodulik69d4a082019-01-18 11:27:03 -08001851 List<DisplayResolveInfo> driList = new ArrayList<>();
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -08001852 int targetsToQuery = 0;
1853 for (int i = 0, n = adapter.getDisplayResolveInfoCount(); i < n; i++) {
1854 final DisplayResolveInfo dri = adapter.getDisplayResolveInfo(i);
1855 if (adapter.getScore(dri) == 0) {
1856 // A score of 0 means the app hasn't been used in some time;
1857 // don't query it as it's not likely to be relevant.
1858 continue;
1859 }
1860 driList.add(dri);
1861 targetsToQuery++;
1862 // TODO(b/121287224): Do we need this here? (similar to queryTargetServices)
1863 if (targetsToQuery >= SHARE_TARGET_QUERY_PACKAGE_LIMIT) {
1864 if (DEBUG) {
1865 Log.d(TAG, "queryTargets hit query target limit "
1866 + SHARE_TARGET_QUERY_PACKAGE_LIMIT);
1867 }
1868 break;
1869 }
1870 }
George Hodulik69d4a082019-01-18 11:27:03 -08001871 return driList;
1872 }
1873
George Hodulik3f399f22019-04-26 16:17:54 -07001874 private void queryDirectShareTargets(
1875 ChooserListAdapter adapter, boolean skipAppPredictionService) {
Mehdi Alizadeh97fb3ed2019-04-25 14:52:02 -07001876 mQueriedSharingShortcutsTimeMs = System.currentTimeMillis();
arangelov5fc9e7d2020-01-07 17:59:14 +00001877 UserHandle userHandle = adapter.getUserHandle();
George Hodulik3f399f22019-04-26 16:17:54 -07001878 if (!skipAppPredictionService) {
arangelov5fc9e7d2020-01-07 17:59:14 +00001879 AppPredictor appPredictor = getAppPredictorForDirectShareIfEnabled(userHandle);
George Hodulik3f399f22019-04-26 16:17:54 -07001880 if (appPredictor != null) {
1881 appPredictor.requestPredictionUpdate();
1882 return;
1883 }
George Hodulik69d4a082019-01-18 11:27:03 -08001884 }
George Hodulik145b3a52019-03-27 11:18:43 -07001885 // Default to just querying ShortcutManager if AppPredictor not present.
arangelov38a6fce2019-12-02 18:21:22 +00001886 //TODO(arangelov) we're using mIntents here, investicate possible implications on work tab
George Hodulik69d4a082019-01-18 11:27:03 -08001887 final IntentFilter filter = getTargetIntentFilter();
1888 if (filter == null) {
1889 return;
1890 }
1891 final List<DisplayResolveInfo> driList = getDisplayResolveInfos(adapter);
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -08001892
1893 AsyncTask.execute(() -> {
arangelov5fc9e7d2020-01-07 17:59:14 +00001894 Context selectedProfileContext = createContextAsUser(userHandle, 0 /* flags */);
1895 ShortcutManager sm = (ShortcutManager) selectedProfileContext
1896 .getSystemService(Context.SHORTCUT_SERVICE);
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -08001897 List<ShortcutManager.ShareShortcutInfo> resultList = sm.getShareTargets(filter);
arangelov5fc9e7d2020-01-07 17:59:14 +00001898 sendShareShortcutInfoList(resultList, driList, null, userHandle);
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -08001899 });
1900 }
1901
George Hodulik69d4a082019-01-18 11:27:03 -08001902 private void sendShareShortcutInfoList(
1903 List<ShortcutManager.ShareShortcutInfo> resultList,
George Hodulikaa5238c2019-04-18 14:17:51 -07001904 List<DisplayResolveInfo> driList,
arangelov5fc9e7d2020-01-07 17:59:14 +00001905 @Nullable List<AppTarget> appTargets, UserHandle userHandle) {
Mehdi Alizadeh3e3216f2019-05-27 17:56:51 -07001906 if (appTargets != null && appTargets.size() != resultList.size()) {
1907 throw new RuntimeException("resultList and appTargets must have the same size."
1908 + " resultList.size()=" + resultList.size()
1909 + " appTargets.size()=" + appTargets.size());
1910 }
1911
1912 for (int i = resultList.size() - 1; i >= 0; i--) {
1913 final String packageName = resultList.get(i).getTargetComponent().getPackageName();
1914 if (!isPackageEnabled(packageName)) {
1915 resultList.remove(i);
1916 if (appTargets != null) {
1917 appTargets.remove(i);
1918 }
1919 }
1920 }
1921
Mehdi Alizadeh06955f62019-09-11 17:23:10 -07001922 // If |appTargets| is not null, results are from AppPredictionService and already sorted.
1923 final int shortcutType = (appTargets == null ? TARGET_TYPE_SHORTCUTS_FROM_SHORTCUT_MANAGER :
1924 TARGET_TYPE_SHORTCUTS_FROM_PREDICTION_SERVICE);
1925
George Hodulik69d4a082019-01-18 11:27:03 -08001926 // Match ShareShortcutInfos with DisplayResolveInfos to be able to use the old code path
1927 // for direct share targets. After ShareSheet is refactored we should use the
1928 // ShareShortcutInfos directly.
1929 boolean resultMessageSent = false;
1930 for (int i = 0; i < driList.size(); i++) {
Mehdi Alizadeh707c0cf2019-09-03 18:11:48 -07001931 List<ShortcutManager.ShareShortcutInfo> matchingShortcuts = new ArrayList<>();
George Hodulik69d4a082019-01-18 11:27:03 -08001932 for (int j = 0; j < resultList.size(); j++) {
1933 if (driList.get(i).getResolvedComponentName().equals(
1934 resultList.get(j).getTargetComponent())) {
Mehdi Alizadeh707c0cf2019-09-03 18:11:48 -07001935 matchingShortcuts.add(resultList.get(j));
George Hodulik69d4a082019-01-18 11:27:03 -08001936 }
1937 }
Mehdi Alizadeh707c0cf2019-09-03 18:11:48 -07001938 if (matchingShortcuts.isEmpty()) {
George Hodulik69d4a082019-01-18 11:27:03 -08001939 continue;
1940 }
Mehdi Alizadeh707c0cf2019-09-03 18:11:48 -07001941 List<ChooserTarget> chooserTargets = convertToChooserTarget(
1942 matchingShortcuts, resultList, appTargets, shortcutType);
1943
arangelov5fc9e7d2020-01-07 17:59:14 +00001944
1945
George Hodulik69d4a082019-01-18 11:27:03 -08001946 final Message msg = Message.obtain();
Matt Pietalab73a882019-06-05 07:04:55 -04001947 msg.what = ChooserHandler.SHORTCUT_MANAGER_SHARE_TARGET_RESULT;
arangelov5fc9e7d2020-01-07 17:59:14 +00001948 msg.obj = new ServiceResultInfo(driList.get(i), chooserTargets, null, userHandle);
Mehdi Alizadeh06955f62019-09-11 17:23:10 -07001949 msg.arg1 = shortcutType;
George Hodulik69d4a082019-01-18 11:27:03 -08001950 mChooserHandler.sendMessage(msg);
1951 resultMessageSent = true;
1952 }
1953
1954 if (resultMessageSent) {
George Hodulik145b3a52019-03-27 11:18:43 -07001955 sendShortcutManagerShareTargetResultCompleted();
George Hodulik69d4a082019-01-18 11:27:03 -08001956 }
1957 }
1958
George Hodulik145b3a52019-03-27 11:18:43 -07001959 private void sendShortcutManagerShareTargetResultCompleted() {
1960 final Message msg = Message.obtain();
Matt Pietalab73a882019-06-05 07:04:55 -04001961 msg.what = ChooserHandler.SHORTCUT_MANAGER_SHARE_TARGET_RESULT_COMPLETED;
George Hodulik145b3a52019-03-27 11:18:43 -07001962 mChooserHandler.sendMessage(msg);
1963 }
1964
Mehdi Alizadeh3e3216f2019-05-27 17:56:51 -07001965 private boolean isPackageEnabled(String packageName) {
1966 if (TextUtils.isEmpty(packageName)) {
1967 return false;
1968 }
1969 ApplicationInfo appInfo;
1970 try {
1971 appInfo = getPackageManager().getApplicationInfo(packageName, 0);
1972 } catch (NameNotFoundException e) {
1973 return false;
1974 }
1975
1976 if (appInfo != null && appInfo.enabled
1977 && (appInfo.flags & ApplicationInfo.FLAG_SUSPENDED) == 0) {
1978 return true;
1979 }
1980 return false;
1981 }
1982
Mehdi Alizadeh707c0cf2019-09-03 18:11:48 -07001983 /**
1984 * Converts a list of ShareShortcutInfos to ChooserTargets.
1985 * @param matchingShortcuts List of shortcuts, all from the same package, that match the current
1986 * share intent filter.
1987 * @param allShortcuts List of all the shortcuts from all the packages on the device that are
1988 * returned for the current sharing action.
1989 * @param allAppTargets List of AppTargets. Null if the results are not from prediction service.
1990 * @param shortcutType One of the values TARGET_TYPE_SHORTCUTS_FROM_SHORTCUT_MANAGER or
1991 * TARGET_TYPE_SHORTCUTS_FROM_PREDICTION_SERVICE
1992 * @return A list of ChooserTargets sorted by score in descending order.
1993 */
1994 @VisibleForTesting
1995 @NonNull
1996 public List<ChooserTarget> convertToChooserTarget(
1997 @NonNull List<ShortcutManager.ShareShortcutInfo> matchingShortcuts,
1998 @NonNull List<ShortcutManager.ShareShortcutInfo> allShortcuts,
1999 @Nullable List<AppTarget> allAppTargets, @ShareTargetType int shortcutType) {
2000 // A set of distinct scores for the matched shortcuts. We use index of a rank in the sorted
2001 // list instead of the actual rank value when converting a rank to a score.
2002 List<Integer> scoreList = new ArrayList<>();
2003 if (shortcutType == TARGET_TYPE_SHORTCUTS_FROM_SHORTCUT_MANAGER) {
2004 for (int i = 0; i < matchingShortcuts.size(); i++) {
2005 int shortcutRank = matchingShortcuts.get(i).getShortcutInfo().getRank();
2006 if (!scoreList.contains(shortcutRank)) {
2007 scoreList.add(shortcutRank);
2008 }
2009 }
2010 Collections.sort(scoreList);
2011 }
2012
2013 List<ChooserTarget> chooserTargetList = new ArrayList<>(matchingShortcuts.size());
2014 for (int i = 0; i < matchingShortcuts.size(); i++) {
2015 ShortcutInfo shortcutInfo = matchingShortcuts.get(i).getShortcutInfo();
2016 int indexInAllShortcuts = allShortcuts.indexOf(matchingShortcuts.get(i));
2017
2018 float score;
2019 if (shortcutType == TARGET_TYPE_SHORTCUTS_FROM_PREDICTION_SERVICE) {
2020 // Incoming results are ordered. Create a score based on index in the original list.
2021 score = Math.max(1.0f - (0.01f * indexInAllShortcuts), 0.0f);
2022 } else {
2023 // Create a score based on the rank of the shortcut.
2024 int rankIndex = scoreList.indexOf(shortcutInfo.getRank());
2025 score = Math.max(1.0f - (0.01f * rankIndex), 0.0f);
2026 }
2027
2028 Bundle extras = new Bundle();
2029 extras.putString(Intent.EXTRA_SHORTCUT_ID, shortcutInfo.getId());
2030 ChooserTarget chooserTarget = new ChooserTarget(shortcutInfo.getShortLabel(),
2031 null, // Icon will be loaded later if this target is selected to be shown.
2032 score, matchingShortcuts.get(i).getTargetComponent().clone(), extras);
2033
2034 chooserTargetList.add(chooserTarget);
2035 if (mDirectShareAppTargetCache != null && allAppTargets != null) {
2036 mDirectShareAppTargetCache.put(chooserTarget,
2037 allAppTargets.get(indexInAllShortcuts));
2038 }
arangelov5fc9e7d2020-01-07 17:59:14 +00002039 if (mDirectShareShortcutInfoCache != null) {
2040 mDirectShareShortcutInfoCache.put(chooserTarget, shortcutInfo);
2041 }
Mehdi Alizadeh707c0cf2019-09-03 18:11:48 -07002042 }
Mehdi Alizadeh707c0cf2019-09-03 18:11:48 -07002043 // Sort ChooserTargets by score in descending order
2044 Comparator<ChooserTarget> byScore =
2045 (ChooserTarget a, ChooserTarget b) -> -Float.compare(a.getScore(), b.getScore());
2046 Collections.sort(chooserTargetList, byScore);
2047 return chooserTargetList;
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -08002048 }
2049
Adam Powell24428412015-04-01 17:19:56 -07002050 private String convertServiceName(String packageName, String serviceName) {
2051 if (TextUtils.isEmpty(serviceName)) {
2052 return null;
2053 }
2054
2055 final String fullName;
2056 if (serviceName.startsWith(".")) {
2057 // Relative to the app package. Prepend the app package name.
2058 fullName = packageName + serviceName;
2059 } else if (serviceName.indexOf('.') >= 0) {
2060 // Fully qualified package name.
2061 fullName = serviceName;
2062 } else {
2063 fullName = null;
2064 }
2065 return fullName;
2066 }
2067
2068 void unbindRemainingServices() {
2069 if (DEBUG) {
2070 Log.d(TAG, "unbindRemainingServices, " + mServiceConnections.size() + " left");
2071 }
2072 for (int i = 0, N = mServiceConnections.size(); i < N; i++) {
2073 final ChooserTargetServiceConnection conn = mServiceConnections.get(i);
2074 if (DEBUG) Log.d(TAG, "unbinding " + conn);
2075 unbindService(conn);
Adam Powell9761ab22015-09-08 17:01:49 -07002076 conn.destroy();
Adam Powell24428412015-04-01 17:19:56 -07002077 }
Matt Pietalab73a882019-06-05 07:04:55 -04002078 mServicesRequested.clear();
Adam Powell24428412015-04-01 17:19:56 -07002079 mServiceConnections.clear();
Adam Powell24428412015-04-01 17:19:56 -07002080 }
2081
Mehdi Alizadeh97fb3ed2019-04-25 14:52:02 -07002082 private void logDirectShareTargetReceived(int logCategory) {
2083 final long queryTime =
2084 logCategory == MetricsEvent.ACTION_DIRECT_SHARE_TARGETS_LOADED_SHORTCUT_MANAGER
2085 ? mQueriedSharingShortcutsTimeMs : mQueriedTargetServicesTimeMs;
2086 final int apiLatency = (int) (System.currentTimeMillis() - queryTime);
2087 getMetricsLogger().write(new LogMaker(logCategory).setSubtype(apiLatency));
2088 }
2089
Kang Li9fa2a2c2017-01-06 13:33:24 -08002090 void updateModelAndChooserCounts(TargetInfo info) {
Kang Li53b43142016-11-14 14:38:25 -08002091 if (info != null) {
George Hodulik145b3a52019-03-27 11:18:43 -07002092 sendClickToAppPredictor(info);
Kang Li53b43142016-11-14 14:38:25 -08002093 final ResolveInfo ri = info.getResolveInfo();
Kang Li64b018e2017-01-05 17:30:06 -08002094 Intent targetIntent = getTargetIntent();
2095 if (ri != null && ri.activityInfo != null && targetIntent != null) {
arangelov38a6fce2019-12-02 18:21:22 +00002096 ChooserListAdapter currentListAdapter =
arangelova3912cf2019-12-13 14:34:45 +00002097 mChooserMultiProfilePagerAdapter.getActiveListAdapter();
arangelov38a6fce2019-12-02 18:21:22 +00002098 if (currentListAdapter != null) {
2099 currentListAdapter.updateModel(info.getResolvedComponentName());
2100 currentListAdapter.updateChooserCounts(ri.activityInfo.packageName, getUserId(),
Kang Li9fa2a2c2017-01-06 13:33:24 -08002101 targetIntent.getAction());
Kang Li0cef910d2017-01-05 09:14:36 -08002102 }
Kang Li53b43142016-11-14 14:38:25 -08002103 if (DEBUG) {
Kang Li64b018e2017-01-05 17:30:06 -08002104 Log.d(TAG, "ResolveInfo Package is " + ri.activityInfo.packageName);
Kang Li64b018e2017-01-05 17:30:06 -08002105 Log.d(TAG, "Action to be updated is " + targetIntent.getAction());
Kang Li53b43142016-11-14 14:38:25 -08002106 }
George Hodulikf2b0d342019-01-25 12:43:54 -08002107 } else if (DEBUG) {
Kang Li53b43142016-11-14 14:38:25 -08002108 Log.d(TAG, "Can not log Chooser Counts of null ResovleInfo");
2109 }
2110 }
Kang Li9082f5b2016-12-02 10:56:21 -08002111 mIsSuccessfullySelected = true;
Kang Li53b43142016-11-14 14:38:25 -08002112 }
2113
George Hodulikf2b0d342019-01-25 12:43:54 -08002114 private void sendClickToAppPredictor(TargetInfo targetInfo) {
arangelov5fc9e7d2020-01-07 17:59:14 +00002115 AppPredictor directShareAppPredictor = getAppPredictorForDirectShareIfEnabled(
2116 mChooserMultiProfilePagerAdapter.getCurrentUserHandle());
George Hodulikaa5238c2019-04-18 14:17:51 -07002117 if (directShareAppPredictor == null) {
George Hodulik145b3a52019-03-27 11:18:43 -07002118 return;
2119 }
George Hodulikf2b0d342019-01-25 12:43:54 -08002120 if (!(targetInfo instanceof ChooserTargetInfo)) {
2121 return;
2122 }
2123 ChooserTarget chooserTarget = ((ChooserTargetInfo) targetInfo).getChooserTarget();
George Hodulikaa5238c2019-04-18 14:17:51 -07002124 AppTarget appTarget = null;
2125 if (mDirectShareAppTargetCache != null) {
2126 appTarget = mDirectShareAppTargetCache.get(chooserTarget);
George Hodulikf2b0d342019-01-25 12:43:54 -08002127 }
George Hodulikaa5238c2019-04-18 14:17:51 -07002128 // This is a direct share click that was provided by the APS
2129 if (appTarget != null) {
2130 directShareAppPredictor.notifyAppTargetEvent(
2131 new AppTargetEvent.Builder(appTarget, AppTargetEvent.ACTION_LAUNCH)
2132 .setLaunchLocation(LAUNCH_LOCATON_DIRECT_SHARE)
2133 .build());
George Hodulikf2b0d342019-01-25 12:43:54 -08002134 }
George Hodulikf2b0d342019-01-25 12:43:54 -08002135 }
2136
George Hodulik145b3a52019-03-27 11:18:43 -07002137 @Nullable
arangelov5fc9e7d2020-01-07 17:59:14 +00002138 private AppPredictor createAppPredictor(UserHandle userHandle) {
Mehdi Alizadeha1c18a82019-08-15 16:31:38 -07002139 if (!mIsAppPredictorComponentAvailable) {
2140 return null;
2141 }
arangelov5fc9e7d2020-01-07 17:59:14 +00002142
arangelove5b369c2020-03-12 17:36:05 +00002143 if (getPersonalProfileUserHandle().equals(userHandle)) {
arangelov5fc9e7d2020-01-07 17:59:14 +00002144 if (mPersonalAppPredictor != null) {
2145 return mPersonalAppPredictor;
2146 }
2147 } else {
2148 if (mWorkAppPredictor != null) {
2149 return mWorkAppPredictor;
2150 }
George Hodulik145b3a52019-03-27 11:18:43 -07002151 }
arangelov5fc9e7d2020-01-07 17:59:14 +00002152
2153 // TODO(b/148230574): Currently AppPredictor fetches only the same-profile app targets.
2154 // Make AppPredictor work cross-profile.
2155 Context contextAsUser = createContextAsUser(userHandle, 0 /* flags */);
2156 final IntentFilter filter = getTargetIntentFilter();
2157 Bundle extras = new Bundle();
2158 extras.putParcelable(APP_PREDICTION_INTENT_FILTER_KEY, filter);
2159 AppPredictionContext appPredictionContext = new AppPredictionContext.Builder(contextAsUser)
2160 .setUiSurface(APP_PREDICTION_SHARE_UI_SURFACE)
2161 .setPredictedTargetCount(APP_PREDICTION_SHARE_TARGET_QUERY_PACKAGE_LIMIT)
2162 .setExtras(extras)
2163 .build();
2164 AppPredictionManager appPredictionManager =
2165 contextAsUser
2166 .getSystemService(AppPredictionManager.class);
2167 AppPredictor appPredictionSession = appPredictionManager.createAppPredictionSession(
2168 appPredictionContext);
arangelove5b369c2020-03-12 17:36:05 +00002169 if (getPersonalProfileUserHandle().equals(userHandle)) {
arangelov5fc9e7d2020-01-07 17:59:14 +00002170 mPersonalAppPredictor = appPredictionSession;
2171 } else {
2172 mWorkAppPredictor = appPredictionSession;
2173 }
2174 return appPredictionSession;
George Hodulik145b3a52019-03-27 11:18:43 -07002175 }
2176
2177 /**
2178 * This will return an app predictor if it is enabled for direct share sorting
2179 * and if one exists. Otherwise, it returns null.
arangelov5fc9e7d2020-01-07 17:59:14 +00002180 * @param userHandle
George Hodulik145b3a52019-03-27 11:18:43 -07002181 */
2182 @Nullable
arangelov5fc9e7d2020-01-07 17:59:14 +00002183 private AppPredictor getAppPredictorForDirectShareIfEnabled(UserHandle userHandle) {
arangelovb0802dc2019-10-18 18:03:44 +01002184 return ChooserFlags.USE_PREDICTION_MANAGER_FOR_DIRECT_TARGETS
arangelov5fc9e7d2020-01-07 17:59:14 +00002185 && !ActivityManager.isLowRamDeviceStatic() ? createAppPredictor(userHandle) : null;
George Hodulik145b3a52019-03-27 11:18:43 -07002186 }
2187
George Hodulikc681ce42019-04-12 17:10:31 -07002188 /**
2189 * This will return an app predictor if it is enabled for share activity sorting
2190 * and if one exists. Otherwise, it returns null.
2191 */
2192 @Nullable
arangelov5fc9e7d2020-01-07 17:59:14 +00002193 private AppPredictor getAppPredictorForShareActivitiesIfEnabled(UserHandle userHandle) {
2194 return USE_PREDICTION_MANAGER_FOR_SHARE_ACTIVITIES ? createAppPredictor(userHandle) : null;
George Hodulikc681ce42019-04-12 17:10:31 -07002195 }
2196
Adam Powell2ed547e2015-04-29 18:45:04 -07002197 void onRefinementResult(TargetInfo selectedTarget, Intent matchingIntent) {
2198 if (mRefinementResultReceiver != null) {
2199 mRefinementResultReceiver.destroy();
2200 mRefinementResultReceiver = null;
2201 }
Adam Powell2ed547e2015-04-29 18:45:04 -07002202 if (selectedTarget == null) {
2203 Log.e(TAG, "Refinement result intent did not match any known targets; canceling");
2204 } else if (!checkTargetSourceIntent(selectedTarget, matchingIntent)) {
2205 Log.e(TAG, "onRefinementResult: Selected target " + selectedTarget
2206 + " cannot match refined source intent " + matchingIntent);
Kang Li53b43142016-11-14 14:38:25 -08002207 } else {
2208 TargetInfo clonedTarget = selectedTarget.cloneFilledIn(matchingIntent, 0);
2209 if (super.onTargetSelected(clonedTarget, false)) {
Kang Li9fa2a2c2017-01-06 13:33:24 -08002210 updateModelAndChooserCounts(clonedTarget);
Kang Li53b43142016-11-14 14:38:25 -08002211 finish();
2212 return;
2213 }
Adam Powell2ed547e2015-04-29 18:45:04 -07002214 }
2215 onRefinementCanceled();
2216 }
2217
2218 void onRefinementCanceled() {
2219 if (mRefinementResultReceiver != null) {
2220 mRefinementResultReceiver.destroy();
2221 mRefinementResultReceiver = null;
2222 }
2223 finish();
2224 }
2225
2226 boolean checkTargetSourceIntent(TargetInfo target, Intent matchingIntent) {
2227 final List<Intent> targetIntents = target.getAllSourceIntents();
2228 for (int i = 0, N = targetIntents.size(); i < N; i++) {
2229 final Intent targetIntent = targetIntents.get(i);
2230 if (targetIntent.filterEquals(matchingIntent)) {
2231 return true;
2232 }
2233 }
2234 return false;
2235 }
2236
arangelov5fc9e7d2020-01-07 17:59:14 +00002237 void filterServiceTargets(Context contextAsUser, String packageName,
2238 List<ChooserTarget> targets) {
Adam Powell666d82a2015-07-15 20:14:57 -07002239 if (targets == null) {
2240 return;
2241 }
2242
arangelov5fc9e7d2020-01-07 17:59:14 +00002243 final PackageManager pm = contextAsUser.getPackageManager();
Adam Powell666d82a2015-07-15 20:14:57 -07002244 for (int i = targets.size() - 1; i >= 0; i--) {
2245 final ChooserTarget target = targets.get(i);
2246 final ComponentName targetName = target.getComponentName();
2247 if (packageName != null && packageName.equals(targetName.getPackageName())) {
2248 // Anything from the original target's package is fine.
2249 continue;
2250 }
2251
2252 boolean remove;
2253 try {
2254 final ActivityInfo ai = pm.getActivityInfo(targetName, 0);
2255 remove = !ai.exported || ai.permission != null;
2256 } catch (NameNotFoundException e) {
2257 Log.e(TAG, "Target " + target + " returned by " + packageName
2258 + " component not found");
2259 remove = true;
2260 }
2261
2262 if (remove) {
2263 targets.remove(i);
2264 }
2265 }
2266 }
2267
Alison Cichowlas1c8816c2019-04-03 17:43:22 -04002268 /**
2269 * Sort intents alphabetically based on display label.
2270 */
arangelovb0802dc2019-10-18 18:03:44 +01002271 static class AzInfoComparator implements Comparator<DisplayResolveInfo> {
Alison Cichowlas1c8816c2019-04-03 17:43:22 -04002272 Collator mCollator;
2273 AzInfoComparator(Context context) {
2274 mCollator = Collator.getInstance(context.getResources().getConfiguration().locale);
2275 }
2276
2277 @Override
arangelovb0802dc2019-10-18 18:03:44 +01002278 public int compare(
2279 DisplayResolveInfo lhsp, DisplayResolveInfo rhsp) {
Alison Cichowlas1c8816c2019-04-03 17:43:22 -04002280 return mCollator.compare(lhsp.getDisplayLabel(), rhsp.getDisplayLabel());
2281 }
2282 }
2283
Susi Kharraz-Post7e2115d2019-02-01 16:51:22 -05002284 protected MetricsLogger getMetricsLogger() {
2285 if (mMetricsLogger == null) {
2286 mMetricsLogger = new MetricsLogger();
2287 }
2288 return mMetricsLogger;
2289 }
2290
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -08002291 public class ChooserListController extends ResolverListController {
2292 public ChooserListController(Context context,
2293 PackageManager pm,
2294 Intent targetIntent,
2295 String referrerPackageName,
George Hodulikc681ce42019-04-12 17:10:31 -07002296 int launchedFromUid,
arangelov38a6fce2019-12-02 18:21:22 +00002297 UserHandle userId,
George Hodulikc681ce42019-04-12 17:10:31 -07002298 AbstractResolverComparator resolverComparator) {
arangelov38a6fce2019-12-02 18:21:22 +00002299 super(context, pm, targetIntent, referrerPackageName, launchedFromUid, userId,
George Hodulikc681ce42019-04-12 17:10:31 -07002300 resolverComparator);
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -08002301 }
2302
2303 @Override
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -08002304 boolean isComponentFiltered(ComponentName name) {
2305 if (mFilteredComponentNames == null) {
2306 return false;
2307 }
2308 for (ComponentName filteredComponentName : mFilteredComponentNames) {
2309 if (name.equals(filteredComponentName)) {
2310 return true;
2311 }
2312 }
2313 return false;
2314 }
Alison Cichowlas1fd47152019-11-14 19:50:55 -05002315
2316 @Override
2317 public boolean isComponentPinned(ComponentName name) {
2318 return mPinnedSharedPrefs.getBoolean(name.flattenToString(), false);
2319 }
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -08002320 }
2321
arangelov38a6fce2019-12-02 18:21:22 +00002322 @VisibleForTesting
2323 public ChooserGridAdapter createChooserGridAdapter(Context context,
2324 List<Intent> payloadIntents, Intent[] initialIntents, List<ResolveInfo> rList,
2325 boolean filterLastUsed, boolean useLayoutForBrowsables, UserHandle userHandle) {
arangelov5fc9e7d2020-01-07 17:59:14 +00002326 ChooserListAdapter chooserListAdapter = new ChooserListAdapter(context, payloadIntents,
2327 initialIntents, rList,
2328 filterLastUsed, createListController(userHandle), useLayoutForBrowsables,
2329 this, this);
2330 AppPredictor.Callback appPredictorCallback = createAppPredictorCallback(chooserListAdapter);
2331 AppPredictor appPredictor = setupAppPredictorForUser(userHandle, appPredictorCallback);
2332 chooserListAdapter.setAppPredictor(appPredictor);
2333 chooserListAdapter.setAppPredictorCallback(appPredictorCallback);
2334 return new ChooserGridAdapter(chooserListAdapter);
Adam Powell24428412015-04-01 17:19:56 -07002335 }
2336
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -08002337 @VisibleForTesting
arangelov38a6fce2019-12-02 18:21:22 +00002338 protected ResolverListController createListController(UserHandle userHandle) {
arangelov5fc9e7d2020-01-07 17:59:14 +00002339 AppPredictor appPredictor = getAppPredictorForShareActivitiesIfEnabled(userHandle);
George Hodulikc681ce42019-04-12 17:10:31 -07002340 AbstractResolverComparator resolverComparator;
2341 if (appPredictor != null) {
2342 resolverComparator = new AppPredictionServiceResolverComparator(this, getTargetIntent(),
arangelov5fc9e7d2020-01-07 17:59:14 +00002343 getReferrerPackageName(), appPredictor, userHandle);
George Hodulikc681ce42019-04-12 17:10:31 -07002344 } else {
2345 resolverComparator =
2346 new ResolverRankerServiceResolverComparator(this, getTargetIntent(),
2347 getReferrerPackageName(), null);
2348 }
2349
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -08002350 return new ChooserListController(
2351 this,
2352 mPm,
2353 getTargetIntent(),
2354 getReferrerPackageName(),
George Hodulikc681ce42019-04-12 17:10:31 -07002355 mLaunchedFromUid,
arangelov38a6fce2019-12-02 18:21:22 +00002356 userHandle,
George Hodulikc681ce42019-04-12 17:10:31 -07002357 resolverComparator);
Hakan Seyalioglue1276bf2016-12-07 16:38:57 -08002358 }
2359
Matt Pietal26038402019-01-08 07:29:34 -05002360 @VisibleForTesting
2361 protected Bitmap loadThumbnail(Uri uri, Size size) {
2362 if (uri == null || size == null) {
2363 return null;
2364 }
2365
2366 try {
Alison Cichowlas07acade2019-12-20 11:26:23 -05002367 return getContentResolver().loadThumbnail(uri, size, null);
Matt Pietal46d828c2019-02-05 08:07:07 -05002368 } catch (IOException | NullPointerException | SecurityException ex) {
Matt Pietal62532e52019-05-07 09:51:37 -04002369 logContentPreviewWarning(uri);
Matt Pietal26038402019-01-08 07:29:34 -05002370 }
2371 return null;
2372 }
2373
arangelovb0802dc2019-10-18 18:03:44 +01002374 static final class PlaceHolderTargetInfo extends NotSelectableTargetInfo {
2375 public Drawable getDisplayIcon(Context context) {
Mike Digmanac1d88c2019-04-18 15:15:55 -07002376 AnimatedVectorDrawable avd = (AnimatedVectorDrawable)
arangelovb0802dc2019-10-18 18:03:44 +01002377 context.getDrawable(R.drawable.chooser_direct_share_icon_placeholder);
Mike Digmanac1d88c2019-04-18 15:15:55 -07002378 avd.start(); // Start animation after generation
2379 return avd;
Matt Pietalcdfcd9a2019-03-05 08:31:47 -05002380 }
2381 }
2382
arangelovb0802dc2019-10-18 18:03:44 +01002383 static final class EmptyTargetInfo extends NotSelectableTargetInfo {
2384 public Drawable getDisplayIcon(Context context) {
Matt Pietalcdfcd9a2019-03-05 08:31:47 -05002385 return null;
2386 }
2387 }
2388
Matt Pietal5b648562019-03-12 07:40:26 -04002389 private void handleScroll(View view, int x, int y, int oldx, int oldy) {
arangelov38a6fce2019-12-02 18:21:22 +00002390 if (mChooserMultiProfilePagerAdapter.getCurrentRootAdapter() != null) {
2391 mChooserMultiProfilePagerAdapter.getCurrentRootAdapter().handleScroll(view, y, oldy);
Matt Pietal5b648562019-03-12 07:40:26 -04002392 }
2393 }
2394
Matt Pietalfe28f9a2019-03-22 07:59:58 -04002395 /*
2396 * Need to dynamically adjust how many icons can fit per row before we add them,
2397 * which also means setting the correct offset to initially show the content
2398 * preview area + 2 rows of targets
2399 */
2400 private void handleLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft,
2401 int oldTop, int oldRight, int oldBottom) {
arangelov38a6fce2019-12-02 18:21:22 +00002402 if (mChooserMultiProfilePagerAdapter == null) {
2403 return;
2404 }
arangelovcf268642020-01-15 15:09:51 +00002405 RecyclerView recyclerView = mChooserMultiProfilePagerAdapter.getActiveAdapterView();
arangelov38a6fce2019-12-02 18:21:22 +00002406 ChooserGridAdapter gridAdapter = mChooserMultiProfilePagerAdapter.getCurrentRootAdapter();
2407 if (gridAdapter == null || recyclerView == null) {
Matt Pietalfe28f9a2019-03-22 07:59:58 -04002408 return;
2409 }
2410
Matt Pietalab73a882019-06-05 07:04:55 -04002411 final int availableWidth = right - left - v.getPaddingLeft() - v.getPaddingRight();
arangelov19e1fea2020-03-10 18:09:39 +00002412 boolean isLayoutUpdated = gridAdapter.consumeLayoutRequest()
arangelov38a6fce2019-12-02 18:21:22 +00002413 || gridAdapter.calculateChooserTargetWidth(availableWidth)
2414 || recyclerView.getAdapter() == null
arangelov19e1fea2020-03-10 18:09:39 +00002415 || availableWidth != mCurrAvailableWidth;
2416 if (isLayoutUpdated
2417 || mLastNumberOfChildren != recyclerView.getChildCount()) {
Matt Pietalab73a882019-06-05 07:04:55 -04002418 mCurrAvailableWidth = availableWidth;
arangelov19e1fea2020-03-10 18:09:39 +00002419 if (isLayoutUpdated
2420 && mChooserMultiProfilePagerAdapter.getCurrentUserHandle() != getUser()) {
2421 // This fixes b/150936654 - empty work tab in share sheet when swiping
2422 mChooserMultiProfilePagerAdapter.getActiveAdapterView()
2423 .setAdapter(mChooserMultiProfilePagerAdapter.getCurrentRootAdapter());
2424 return;
arangelova30787b2020-03-11 18:33:26 +00002425 } else if (mChooserMultiProfilePagerAdapter.getCurrentUserHandle() != getUser()) {
2426 return;
arangelov19e1fea2020-03-10 18:09:39 +00002427 }
Matt Pietalfe28f9a2019-03-22 07:59:58 -04002428
2429 getMainThreadHandler().post(() -> {
arangelov38a6fce2019-12-02 18:21:22 +00002430 if (mResolverDrawerLayout == null || gridAdapter == null) {
Matt Pietalfe28f9a2019-03-22 07:59:58 -04002431 return;
2432 }
2433
Matt Pietal800136a2019-05-08 07:46:39 -04002434 final int bottomInset = mSystemWindowInsets != null
2435 ? mSystemWindowInsets.bottom : 0;
2436 int offset = bottomInset;
arangelovc4dbdbd2020-02-18 20:54:16 +00002437 int rowsToShow = gridAdapter.getContentPreviewRowCount()
2438 + gridAdapter.getProfileRowCount()
arangelov38a6fce2019-12-02 18:21:22 +00002439 + gridAdapter.getServiceTargetRowCount()
2440 + gridAdapter.getCallerAndRankedTargetRowCount();
Matt Pietalfe28f9a2019-03-22 07:59:58 -04002441
2442 // then this is most likely not a SEND_* action, so check
2443 // the app target count
2444 if (rowsToShow == 0) {
arangelov38a6fce2019-12-02 18:21:22 +00002445 rowsToShow = gridAdapter.getRowCount();
Matt Pietalfe28f9a2019-03-22 07:59:58 -04002446 }
2447
2448 // still zero? then use a default height and leave, which
2449 // can happen when there are no targets to show
arangelov590fba32020-02-11 18:05:42 +00002450 if (rowsToShow == 0 && !shouldShowStickyContentPreview()) {
Matt Pietal800136a2019-05-08 07:46:39 -04002451 offset += getResources().getDimensionPixelSize(
Matt Pietalfe28f9a2019-03-22 07:59:58 -04002452 R.dimen.chooser_max_collapsed_height);
2453 mResolverDrawerLayout.setCollapsibleHeightReserved(offset);
2454 return;
2455 }
2456
arangelovc4dbdbd2020-02-18 20:54:16 +00002457 View stickyContentPreview = findViewById(R.id.content_preview_container);
2458 if (shouldShowStickyContentPreview() && isStickyContentPreviewShowing()) {
2459 offset += stickyContentPreview.getHeight();
arangelova3912cf2019-12-13 14:34:45 +00002460 }
2461
arangelovf163a882020-02-18 17:18:47 +00002462 if (shouldShowTabs()) {
arangelova69e6762020-02-05 21:25:15 +00002463 offset += findViewById(R.id.tabs).getHeight();
2464 }
2465
arangelov2a4d0b12020-03-04 18:15:04 +00002466 View tabDivider = findViewById(R.id.resolver_tab_divider);
2467 if (tabDivider.getVisibility() == View.VISIBLE) {
2468 offset += tabDivider.getHeight();
2469 }
2470
arangelova30787b2020-03-11 18:33:26 +00002471 if (recyclerView.getVisibility() == View.VISIBLE) {
2472 int directShareHeight = 0;
2473 rowsToShow = Math.min(4, rowsToShow);
2474 mLastNumberOfChildren = recyclerView.getChildCount();
2475 for (int i = 0, childCount = recyclerView.getChildCount();
2476 i < childCount && rowsToShow > 0; i++) {
2477 View child = recyclerView.getChildAt(i);
2478 if (((GridLayoutManager.LayoutParams)
2479 child.getLayoutParams()).getSpanIndex() != 0) {
2480 continue;
2481 }
2482 int height = child.getHeight();
2483 offset += height;
2484
2485 if (gridAdapter.getTargetType(
2486 recyclerView.getChildAdapterPosition(child))
2487 == ChooserListAdapter.TARGET_SERVICE) {
2488 directShareHeight = height;
2489 }
2490 rowsToShow--;
Zhen Zhangbde7b462019-11-11 11:49:33 -08002491 }
Matt Pietal394ebd02019-05-03 07:36:21 -04002492
arangelova30787b2020-03-11 18:33:26 +00002493 boolean isExpandable = getResources().getConfiguration().orientation
2494 == Configuration.ORIENTATION_PORTRAIT && !isInMultiWindowMode();
2495 if (directShareHeight != 0 && isSendAction(getTargetIntent())
2496 && isExpandable) {
2497 // make sure to leave room for direct share 4->8 expansion
2498 int requiredExpansionHeight =
2499 (int) (directShareHeight / DIRECT_SHARE_EXPANSION_RATE);
2500 int topInset = mSystemWindowInsets != null ? mSystemWindowInsets.top : 0;
2501 int minHeight = bottom - top - mResolverDrawerLayout.getAlwaysShowHeight()
2502 - requiredExpansionHeight - topInset - bottomInset;
2503
2504 offset = Math.min(offset, minHeight);
Matt Pietal394ebd02019-05-03 07:36:21 -04002505 }
arangelova30787b2020-03-11 18:33:26 +00002506 } else {
2507 ViewGroup currentEmptyStateView = getCurrentEmptyStateView();
2508 if (currentEmptyStateView.getVisibility() == View.VISIBLE) {
2509 offset += currentEmptyStateView.getHeight();
2510 }
Matt Pietalfe28f9a2019-03-22 07:59:58 -04002511 }
2512
Matt Pietal399e8c72019-04-04 15:49:48 -04002513 mResolverDrawerLayout.setCollapsibleHeightReserved(Math.min(offset, bottom - top));
Matt Pietalfe28f9a2019-03-22 07:59:58 -04002514 });
2515 }
2516 }
2517
arangelova30787b2020-03-11 18:33:26 +00002518 private ViewGroup getCurrentEmptyStateView() {
2519 int currentPage = mChooserMultiProfilePagerAdapter.getCurrentPage();
2520 return mChooserMultiProfilePagerAdapter.getItem(currentPage).getEmptyStateView();
2521 }
2522
Adam Powella182e452015-07-06 16:57:56 -07002523 static class BaseChooserTargetComparator implements Comparator<ChooserTarget> {
2524 @Override
2525 public int compare(ChooserTarget lhs, ChooserTarget rhs) {
2526 // Descending order
Adam Powell77a533f2015-10-16 10:47:32 -07002527 return (int) Math.signum(rhs.getScore() - lhs.getScore());
Adam Powella182e452015-07-06 16:57:56 -07002528 }
2529 }
2530
arangelovb0802dc2019-10-18 18:03:44 +01002531 @Override // ResolverListCommunicator
arangelov7981b122020-01-16 10:58:27 +00002532 public void onHandlePackagesChanged(ResolverListAdapter listAdapter) {
arangelovb0802dc2019-10-18 18:03:44 +01002533 mServicesRequested.clear();
arangelova3912cf2019-12-13 14:34:45 +00002534 mChooserMultiProfilePagerAdapter.getActiveListAdapter().notifyDataSetChanged();
arangelov7981b122020-01-16 10:58:27 +00002535 super.onHandlePackagesChanged(listAdapter);
arangelovb0802dc2019-10-18 18:03:44 +01002536 }
Alison Cichowlas1c8816c2019-04-03 17:43:22 -04002537
arangelovb0802dc2019-10-18 18:03:44 +01002538 @Override // SelectableTargetInfoCommunicator
2539 public ActivityInfoPresentationGetter makePresentationGetter(ActivityInfo info) {
arangelova3912cf2019-12-13 14:34:45 +00002540 return mChooserMultiProfilePagerAdapter.getActiveListAdapter().makePresentationGetter(info);
arangelovb0802dc2019-10-18 18:03:44 +01002541 }
2542
2543 @Override // SelectableTargetInfoCommunicator
2544 public Intent getReferrerFillInIntent() {
2545 return mReferrerFillInIntent;
2546 }
2547
2548 @Override // ChooserListCommunicator
2549 public int getMaxRankedTargets() {
arangelov38a6fce2019-12-02 18:21:22 +00002550 return mChooserMultiProfilePagerAdapter.getCurrentRootAdapter() == null
Zhen Zhangbde7b462019-11-11 11:49:33 -08002551 ? ChooserGridAdapter.MAX_TARGETS_PER_ROW_PORTRAIT
arangelov38a6fce2019-12-02 18:21:22 +00002552 : mChooserMultiProfilePagerAdapter.getCurrentRootAdapter().getMaxTargetsPerRow();
arangelovb0802dc2019-10-18 18:03:44 +01002553 }
2554
2555 @Override // ChooserListCommunicator
arangelov5fc9e7d2020-01-07 17:59:14 +00002556 public void sendListViewUpdateMessage(UserHandle userHandle) {
2557 Message msg = Message.obtain();
2558 msg.what = ChooserHandler.LIST_VIEW_UPDATE_MESSAGE;
2559 msg.obj = userHandle;
2560 mChooserHandler.sendMessageDelayed(msg, LIST_VIEW_UPDATE_INTERVAL_IN_MILLIS);
arangelovb0802dc2019-10-18 18:03:44 +01002561 }
2562
2563 @Override
arangelova3912cf2019-12-13 14:34:45 +00002564 public void onListRebuilt(ResolverListAdapter listAdapter) {
arangelovcf268642020-01-15 15:09:51 +00002565 setupScrollListener();
2566
arangelova3912cf2019-12-13 14:34:45 +00002567 ChooserListAdapter chooserListAdapter = (ChooserListAdapter) listAdapter;
arangelovc4dbdbd2020-02-18 20:54:16 +00002568 if (chooserListAdapter.getUserHandle()
arangelove5b369c2020-03-12 17:36:05 +00002569 .equals(mChooserMultiProfilePagerAdapter.getCurrentUserHandle())) {
arangelovc4dbdbd2020-02-18 20:54:16 +00002570 mChooserMultiProfilePagerAdapter.getActiveAdapterView()
2571 .setAdapter(mChooserMultiProfilePagerAdapter.getCurrentRootAdapter());
2572 mChooserMultiProfilePagerAdapter
2573 .setupListAdapter(mChooserMultiProfilePagerAdapter.getCurrentPage());
2574 }
2575
arangelova3912cf2019-12-13 14:34:45 +00002576 if (chooserListAdapter.mDisplayList == null
2577 || chooserListAdapter.mDisplayList.isEmpty()) {
2578 chooserListAdapter.notifyDataSetChanged();
arangelovb0802dc2019-10-18 18:03:44 +01002579 } else {
2580 new AsyncTask<Void, Void, Void>() {
2581 @Override
2582 protected Void doInBackground(Void... voids) {
arangelova3912cf2019-12-13 14:34:45 +00002583 chooserListAdapter.updateAlphabeticalList();
arangelovb0802dc2019-10-18 18:03:44 +01002584 return null;
2585 }
2586 @Override
2587 protected void onPostExecute(Void aVoid) {
arangelova3912cf2019-12-13 14:34:45 +00002588 chooserListAdapter.notifyDataSetChanged();
arangelovb0802dc2019-10-18 18:03:44 +01002589 }
2590 }.execute();
2591 }
2592
2593 // don't support direct share on low ram devices
2594 if (ActivityManager.isLowRamDeviceStatic()) {
2595 return;
2596 }
2597
2598 if (ChooserFlags.USE_SHORTCUT_MANAGER_FOR_DIRECT_TARGETS
2599 || ChooserFlags.USE_PREDICTION_MANAGER_FOR_DIRECT_TARGETS) {
2600 if (DEBUG) {
2601 Log.d(TAG, "querying direct share targets from ShortcutManager");
2602 }
2603
arangelova3912cf2019-12-13 14:34:45 +00002604 queryDirectShareTargets(chooserListAdapter, false);
arangelovb0802dc2019-10-18 18:03:44 +01002605 }
2606 if (USE_CHOOSER_TARGET_SERVICE_FOR_DIRECT_TARGETS) {
2607 if (DEBUG) {
2608 Log.d(TAG, "List built querying services");
2609 }
2610
arangelova3912cf2019-12-13 14:34:45 +00002611 queryTargetServices(chooserListAdapter);
arangelovb0802dc2019-10-18 18:03:44 +01002612 }
2613 }
2614
arangelovcf268642020-01-15 15:09:51 +00002615 private void setupScrollListener() {
arangelovf163a882020-02-18 17:18:47 +00002616 if (mResolverDrawerLayout == null || shouldShowTabs()) {
arangelovcf268642020-01-15 15:09:51 +00002617 return;
2618 }
2619 final View chooserHeader = mResolverDrawerLayout.findViewById(R.id.chooser_header);
2620 final float defaultElevation = chooserHeader.getElevation();
2621 final float chooserHeaderScrollElevation =
2622 getResources().getDimensionPixelSize(R.dimen.chooser_header_scroll_elevation);
2623
2624 mChooserMultiProfilePagerAdapter.getActiveAdapterView().addOnScrollListener(
2625 new RecyclerView.OnScrollListener() {
2626 public void onScrollStateChanged(RecyclerView view, int scrollState) {
2627 }
2628
2629 public void onScrolled(RecyclerView view, int dx, int dy) {
2630 if (view.getChildCount() > 0) {
2631 View child = view.getLayoutManager().findViewByPosition(0);
2632 if (child == null || child.getTop() < 0) {
2633 chooserHeader.setElevation(chooserHeaderScrollElevation);
2634 return;
2635 }
2636 }
2637
2638 chooserHeader.setElevation(defaultElevation);
2639 }
2640 });
2641 }
2642
arangelovb0802dc2019-10-18 18:03:44 +01002643 @Override // ChooserListCommunicator
2644 public boolean isSendAction(Intent targetIntent) {
Matt Pietal95574b02019-03-13 08:12:25 -04002645 if (targetIntent == null) {
2646 return false;
2647 }
2648
2649 String action = targetIntent.getAction();
2650 if (action == null) {
2651 return false;
2652 }
2653
2654 if (Intent.ACTION_SEND.equals(action) || Intent.ACTION_SEND_MULTIPLE.equals(action)) {
2655 return true;
2656 }
2657
2658 return false;
2659 }
2660
arangelov590fba32020-02-11 18:05:42 +00002661 /**
2662 * The sticky content preview is shown only when we have a tabbed view. It's shown above
2663 * the tabs so it is not part of the scrollable list. If we are not in tabbed view,
2664 * we instead show the content preview as a regular list item.
2665 */
2666 private boolean shouldShowStickyContentPreview() {
arangelovc4dbdbd2020-02-18 20:54:16 +00002667 return shouldShowStickyContentPreviewNoOrientationCheck()
arangelov590fba32020-02-11 18:05:42 +00002668 && getResources().getBoolean(R.bool.sharesheet_show_content_preview);
arangelova3912cf2019-12-13 14:34:45 +00002669 }
2670
arangelovc4dbdbd2020-02-18 20:54:16 +00002671 private boolean shouldShowStickyContentPreviewNoOrientationCheck() {
2672 return shouldShowTabs()
2673 && mMultiProfilePagerAdapter.getListAdapterForUserHandle(
2674 UserHandle.of(UserHandle.myUserId())).getCount() > 0
2675 && isSendAction(getTargetIntent());
2676 }
2677
arangelov590fba32020-02-11 18:05:42 +00002678 private void updateStickyContentPreview() {
arangelovc4dbdbd2020-02-18 20:54:16 +00002679 if (shouldShowStickyContentPreviewNoOrientationCheck()) {
2680 // The sticky content preview is only shown when we show the work and personal tabs.
2681 // We don't show it in landscape as otherwise there is no room for scrolling.
2682 // If the sticky content preview will be shown at some point with orientation change,
2683 // then always preload it to avoid subsequent resizing of the share sheet.
2684 ViewGroup contentPreviewContainer = findViewById(R.id.content_preview_container);
2685 if (contentPreviewContainer.getChildCount() == 0) {
2686 ViewGroup contentPreviewView = createContentPreviewView(contentPreviewContainer);
2687 contentPreviewContainer.addView(contentPreviewView);
2688 }
2689 }
arangelov590fba32020-02-11 18:05:42 +00002690 if (shouldShowStickyContentPreview()) {
2691 showStickyContentPreview();
arangelova3912cf2019-12-13 14:34:45 +00002692 } else {
arangelov590fba32020-02-11 18:05:42 +00002693 hideStickyContentPreview();
arangelova3912cf2019-12-13 14:34:45 +00002694 }
2695 }
2696
arangelov590fba32020-02-11 18:05:42 +00002697 private void showStickyContentPreview() {
arangelovc4dbdbd2020-02-18 20:54:16 +00002698 if (isStickyContentPreviewShowing()) {
2699 return;
2700 }
arangelova3912cf2019-12-13 14:34:45 +00002701 ViewGroup contentPreviewContainer = findViewById(R.id.content_preview_container);
2702 contentPreviewContainer.setVisibility(View.VISIBLE);
arangelovc4dbdbd2020-02-18 20:54:16 +00002703 }
2704
2705 private boolean isStickyContentPreviewShowing() {
2706 ViewGroup contentPreviewContainer = findViewById(R.id.content_preview_container);
2707 return contentPreviewContainer.getVisibility() == View.VISIBLE;
arangelova3912cf2019-12-13 14:34:45 +00002708 }
2709
arangelov590fba32020-02-11 18:05:42 +00002710 private void hideStickyContentPreview() {
arangelovc4dbdbd2020-02-18 20:54:16 +00002711 if (!isStickyContentPreviewShowing()) {
2712 return;
2713 }
arangelova3912cf2019-12-13 14:34:45 +00002714 ViewGroup contentPreviewContainer = findViewById(R.id.content_preview_container);
arangelova3912cf2019-12-13 14:34:45 +00002715 contentPreviewContainer.setVisibility(View.GONE);
2716 }
2717
2718 private void logActionShareWithPreview() {
2719 Intent targetIntent = getTargetIntent();
2720 int previewType = findPreferredContentPreview(targetIntent, getContentResolver());
2721 getMetricsLogger().write(new LogMaker(MetricsEvent.ACTION_SHARE_WITH_PREVIEW)
2722 .setSubtype(previewType));
2723 }
2724
Zhen Zhangbde7b462019-11-11 11:49:33 -08002725 /**
2726 * Used to bind types of individual item including
2727 * {@link ChooserGridAdapter#VIEW_TYPE_NORMAL},
arangelov590fba32020-02-11 18:05:42 +00002728 * {@link ChooserGridAdapter#VIEW_TYPE_CONTENT_PREVIEW},
Zhen Zhangbde7b462019-11-11 11:49:33 -08002729 * {@link ChooserGridAdapter#VIEW_TYPE_PROFILE},
2730 * and {@link ChooserGridAdapter#VIEW_TYPE_AZ_LABEL}.
2731 */
2732 final class ItemViewHolder extends RecyclerView.ViewHolder {
2733 ResolverListAdapter.ViewHolder mWrappedViewHolder;
2734 int mListPosition = ChooserListAdapter.NO_POSITION;
2735
2736 ItemViewHolder(View itemView, boolean isClickable) {
2737 super(itemView);
2738 mWrappedViewHolder = new ResolverListAdapter.ViewHolder(itemView);
2739 if (isClickable) {
2740 itemView.setOnClickListener(v -> startSelected(mListPosition,
2741 false/* always */, true/* filterd */));
2742 itemView.setOnLongClickListener(v -> {
2743 showTargetDetails(
arangelova3912cf2019-12-13 14:34:45 +00002744 mChooserMultiProfilePagerAdapter.getActiveListAdapter()
Alison Cichowlas19ee2922019-12-16 19:43:12 -05002745 .targetInfoForPosition(mListPosition, /* filtered */ true));
Zhen Zhangbde7b462019-11-11 11:49:33 -08002746 return true;
2747 });
2748 }
2749 }
2750 }
2751
2752 /**
Matt Pietal9236adc2019-12-12 09:24:23 -05002753 * Add a footer to the list, to support scrolling behavior below the navbar.
arangelov38a6fce2019-12-02 18:21:22 +00002754 */
Matt Pietal9236adc2019-12-12 09:24:23 -05002755 final class FooterViewHolder extends RecyclerView.ViewHolder {
2756 FooterViewHolder(View itemView) {
2757 super(itemView);
2758 }
arangelov38a6fce2019-12-02 18:21:22 +00002759 }
2760
2761 /**
2762 * Intentionally override the {@link ResolverActivity} implementation as we only need that
2763 * implementation for the intent resolver case.
2764 */
2765 @Override
2766 public void onButtonClick(View v) {}
2767
2768 /**
2769 * Intentionally override the {@link ResolverActivity} implementation as we only need that
2770 * implementation for the intent resolver case.
2771 */
2772 @Override
2773 protected void resetButtonBar() {}
2774
arangelov4bf17472020-02-17 20:21:46 +00002775 @Override
2776 protected String getMetricsCategory() {
2777 return METRICS_CATEGORY_CHOOSER;
2778 }
2779
arangelov38a6fce2019-12-02 18:21:22 +00002780 /**
Zhen Zhangbde7b462019-11-11 11:49:33 -08002781 * Adapter for all types of items and targets in ShareSheet.
2782 * Note that ranked sections like Direct Share - while appearing grid-like - are handled on the
2783 * row level by this adapter but not on the item level. Individual targets within the row are
2784 * handled by {@link ChooserListAdapter}
2785 */
arangelovcf268642020-01-15 15:09:51 +00002786 @VisibleForTesting
2787 public final class ChooserGridAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Adam Powell7d758002015-05-06 17:49:36 -07002788 private ChooserListAdapter mChooserListAdapter;
2789 private final LayoutInflater mLayoutInflater;
Adam Powell7d758002015-05-06 17:49:36 -07002790
Matt Pietal5b648562019-03-12 07:40:26 -04002791 private DirectShareViewHolder mDirectShareViewHolder;
Matt Pietalab986b52019-04-10 10:14:32 -04002792 private int mChooserTargetWidth = 0;
Mike Digman849a9d12019-04-29 11:20:48 -07002793 private boolean mShowAzLabelIfPoss;
Matt Pietal5b648562019-03-12 07:40:26 -04002794
arangelov590fba32020-02-11 18:05:42 +00002795 private boolean mHideContentPreview = false;
Matt Pietale7cacab2019-05-23 07:21:36 -04002796 private boolean mLayoutRequested = false;
2797
Matt Pietal2025a1b2020-01-07 10:08:07 -05002798 private int mFooterHeight = 0;
Matt Pietal9236adc2019-12-12 09:24:23 -05002799
Matt Pietal5b648562019-03-12 07:40:26 -04002800 private static final int VIEW_TYPE_DIRECT_SHARE = 0;
2801 private static final int VIEW_TYPE_NORMAL = 1;
arangelov590fba32020-02-11 18:05:42 +00002802 private static final int VIEW_TYPE_CONTENT_PREVIEW = 2;
2803 private static final int VIEW_TYPE_PROFILE = 3;
2804 private static final int VIEW_TYPE_AZ_LABEL = 4;
2805 private static final int VIEW_TYPE_CALLER_AND_RANK = 5;
2806 private static final int VIEW_TYPE_FOOTER = 6;
Matt Pietal5b648562019-03-12 07:40:26 -04002807
Matt Pietalfaedea82019-03-21 10:36:54 -04002808 private static final int MAX_TARGETS_PER_ROW_PORTRAIT = 4;
2809 private static final int MAX_TARGETS_PER_ROW_LANDSCAPE = 8;
2810
Mike Digman849a9d12019-04-29 11:20:48 -07002811 private static final int NUM_EXPANSIONS_TO_HIDE_AZ_LABEL = 20;
2812
Zhen Zhangbde7b462019-11-11 11:49:33 -08002813 ChooserGridAdapter(ChooserListAdapter wrappedAdapter) {
2814 super();
Adam Powell7d758002015-05-06 17:49:36 -07002815 mChooserListAdapter = wrappedAdapter;
2816 mLayoutInflater = LayoutInflater.from(ChooserActivity.this);
2817
Mike Digman849a9d12019-04-29 11:20:48 -07002818 mShowAzLabelIfPoss = getNumSheetExpansions() < NUM_EXPANSIONS_TO_HIDE_AZ_LABEL;
2819
Adam Powell7d758002015-05-06 17:49:36 -07002820 wrappedAdapter.registerDataSetObserver(new DataSetObserver() {
2821 @Override
2822 public void onChanged() {
2823 super.onChanged();
2824 notifyDataSetChanged();
2825 }
2826
2827 @Override
2828 public void onInvalidated() {
2829 super.onInvalidated();
Zhen Zhangbde7b462019-11-11 11:49:33 -08002830 notifyDataSetChanged();
Adam Powell7d758002015-05-06 17:49:36 -07002831 }
2832 });
2833 }
2834
Matt Pietal9236adc2019-12-12 09:24:23 -05002835 public void setFooterHeight(int height) {
Matt Pietal2025a1b2020-01-07 10:08:07 -05002836 mFooterHeight = height;
Matt Pietal9236adc2019-12-12 09:24:23 -05002837 }
2838
Matt Pietalfaedea82019-03-21 10:36:54 -04002839 /**
Matt Pietalab986b52019-04-10 10:14:32 -04002840 * Calculate the chooser target width to maximize space per item
Matt Pietalfaedea82019-03-21 10:36:54 -04002841 *
2842 * @param width The new row width to use for recalculation
Matt Pietalab986b52019-04-10 10:14:32 -04002843 * @return true if the view width has changed
Matt Pietalfaedea82019-03-21 10:36:54 -04002844 */
Matt Pietalab986b52019-04-10 10:14:32 -04002845 public boolean calculateChooserTargetWidth(int width) {
Matt Pietalab986b52019-04-10 10:14:32 -04002846 if (width == 0) {
Matt Pietalfaedea82019-03-21 10:36:54 -04002847 return false;
2848 }
2849
Zhen Zhangbde7b462019-11-11 11:49:33 -08002850 int newWidth = width / getMaxTargetsPerRow();
Matt Pietalab986b52019-04-10 10:14:32 -04002851 if (newWidth != mChooserTargetWidth) {
2852 mChooserTargetWidth = newWidth;
Matt Pietalfaedea82019-03-21 10:36:54 -04002853 return true;
2854 }
2855
2856 return false;
2857 }
2858
arangelov38a6fce2019-12-02 18:21:22 +00002859 int getMaxTargetsPerRow() {
Matt Pietalfaedea82019-03-21 10:36:54 -04002860 int maxTargets = MAX_TARGETS_PER_ROW_PORTRAIT;
Matt Pietal3e4b56f2019-05-31 12:06:17 -04002861 if (shouldDisplayLandscape(getResources().getConfiguration().orientation)) {
Matt Pietalfaedea82019-03-21 10:36:54 -04002862 maxTargets = MAX_TARGETS_PER_ROW_LANDSCAPE;
2863 }
Matt Pietalab986b52019-04-10 10:14:32 -04002864 return maxTargets;
Matt Pietal5b648562019-03-12 07:40:26 -04002865 }
2866
arangelov590fba32020-02-11 18:05:42 +00002867 /**
2868 * Hides the list item content preview.
2869 * <p>Not to be confused with the sticky content preview which is above the
2870 * personal and work tabs.
2871 */
2872 public void hideContentPreview() {
2873 mHideContentPreview = true;
2874 mLayoutRequested = true;
2875 notifyDataSetChanged();
2876 }
2877
Matt Pietale7cacab2019-05-23 07:21:36 -04002878 public boolean consumeLayoutRequest() {
2879 boolean oldValue = mLayoutRequested;
2880 mLayoutRequested = false;
2881 return oldValue;
2882 }
2883
Zhen Zhangbde7b462019-11-11 11:49:33 -08002884 public int getRowCount() {
Adam Powell7d758002015-05-06 17:49:36 -07002885 return (int) (
arangelov590fba32020-02-11 18:05:42 +00002886 getContentPreviewRowCount()
2887 + getProfileRowCount()
Matt Pietal26038402019-01-08 07:29:34 -05002888 + getServiceTargetRowCount()
Alison Cichowlasd0a075b2019-04-10 20:18:59 -04002889 + getCallerAndRankedTargetRowCount()
Mike Digmanae730b12019-04-25 11:10:31 -07002890 + getAzLabelRowCount()
Alison Cichowlas1c8816c2019-04-03 17:43:22 -04002891 + Math.ceil(
2892 (float) mChooserListAdapter.getAlphaTargetCount()
2893 / getMaxTargetsPerRow())
Adam Powell7d758002015-05-06 17:49:36 -07002894 );
2895 }
2896
arangelov590fba32020-02-11 18:05:42 +00002897 /**
2898 * Returns either {@code 0} or {@code 1} depending on whether we want to show the list item
2899 * content preview. Not to be confused with the sticky content preview which is above the
2900 * personal and work tabs.
2901 */
2902 public int getContentPreviewRowCount() {
2903 // For the tabbed case we show the sticky content preview above the tabs,
2904 // please refer to shouldShowStickyContentPreview
arangelovf163a882020-02-18 17:18:47 +00002905 if (shouldShowTabs()) {
arangelov590fba32020-02-11 18:05:42 +00002906 return 0;
2907 }
2908 if (!isSendAction(getTargetIntent())) {
2909 return 0;
2910 }
2911
2912 if (mHideContentPreview || mChooserListAdapter == null
2913 || mChooserListAdapter.getCount() == 0) {
2914 return 0;
2915 }
2916
2917 return 1;
2918 }
2919
Matt Pietal74c6ed02019-04-18 13:38:46 -04002920 public int getProfileRowCount() {
arangelovf163a882020-02-18 17:18:47 +00002921 if (shouldShowTabs()) {
arangelov590fba32020-02-11 18:05:42 +00002922 return 0;
2923 }
Matt Pietal74c6ed02019-04-18 13:38:46 -04002924 return mChooserListAdapter.getOtherProfile() == null ? 0 : 1;
2925 }
2926
Matt Pietal9236adc2019-12-12 09:24:23 -05002927 public int getFooterRowCount() {
2928 return 1;
2929 }
2930
Alison Cichowlasd0a075b2019-04-10 20:18:59 -04002931 public int getCallerAndRankedTargetRowCount() {
Adam Powell63b31692015-09-28 10:45:00 -07002932 return (int) Math.ceil(
Alison Cichowlasd0a075b2019-04-10 20:18:59 -04002933 ((float) mChooserListAdapter.getCallerTargetCount()
2934 + mChooserListAdapter.getRankedTargetCount()) / getMaxTargetsPerRow());
Adam Powell63b31692015-09-28 10:45:00 -07002935 }
2936
Matt Pietal5b648562019-03-12 07:40:26 -04002937 // There can be at most one row in the listview, that is internally
2938 // a ViewGroup with 2 rows
Adam Powell63b31692015-09-28 10:45:00 -07002939 public int getServiceTargetRowCount() {
arangelovb0802dc2019-10-18 18:03:44 +01002940 if (isSendAction(getTargetIntent())
2941 && !ActivityManager.isLowRamDeviceStatic()) {
Matt Pietal95574b02019-03-13 08:12:25 -04002942 return 1;
2943 }
2944 return 0;
Adam Powell63b31692015-09-28 10:45:00 -07002945 }
2946
Mike Digmanae730b12019-04-25 11:10:31 -07002947 public int getAzLabelRowCount() {
2948 // Only show a label if the a-z list is showing
Mike Digman849a9d12019-04-29 11:20:48 -07002949 return (mShowAzLabelIfPoss && mChooserListAdapter.getAlphaTargetCount() > 0) ? 1 : 0;
Mike Digmanae730b12019-04-25 11:10:31 -07002950 }
2951
Adam Powell7d758002015-05-06 17:49:36 -07002952 @Override
Zhen Zhangbde7b462019-11-11 11:49:33 -08002953 public int getItemCount() {
2954 return (int) (
arangelov590fba32020-02-11 18:05:42 +00002955 getContentPreviewRowCount()
2956 + getProfileRowCount()
Zhen Zhangbde7b462019-11-11 11:49:33 -08002957 + getServiceTargetRowCount()
2958 + getCallerAndRankedTargetRowCount()
2959 + getAzLabelRowCount()
2960 + mChooserListAdapter.getAlphaTargetCount()
Matt Pietal9236adc2019-12-12 09:24:23 -05002961 + getFooterRowCount()
Zhen Zhangbde7b462019-11-11 11:49:33 -08002962 );
Adam Powell7d758002015-05-06 17:49:36 -07002963 }
2964
2965 @Override
Zhen Zhangbde7b462019-11-11 11:49:33 -08002966 public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
2967 switch (viewType) {
arangelov590fba32020-02-11 18:05:42 +00002968 case VIEW_TYPE_CONTENT_PREVIEW:
2969 return new ItemViewHolder(createContentPreviewView(parent), false);
Zhen Zhangbde7b462019-11-11 11:49:33 -08002970 case VIEW_TYPE_PROFILE:
2971 return new ItemViewHolder(createProfileView(parent), false);
2972 case VIEW_TYPE_AZ_LABEL:
2973 return new ItemViewHolder(createAzLabelView(parent), false);
2974 case VIEW_TYPE_NORMAL:
2975 return new ItemViewHolder(mChooserListAdapter.createView(parent), true);
2976 case VIEW_TYPE_DIRECT_SHARE:
2977 case VIEW_TYPE_CALLER_AND_RANK:
2978 return createItemGroupViewHolder(viewType, parent);
Matt Pietal9236adc2019-12-12 09:24:23 -05002979 case VIEW_TYPE_FOOTER:
Matt Pietal2025a1b2020-01-07 10:08:07 -05002980 Space sp = new Space(parent.getContext());
2981 sp.setLayoutParams(new RecyclerView.LayoutParams(
2982 LayoutParams.MATCH_PARENT, mFooterHeight));
2983 return new FooterViewHolder(sp);
Zhen Zhangbde7b462019-11-11 11:49:33 -08002984 default:
2985 // Since we catch all possible viewTypes above, no chance this is being called.
2986 return null;
2987 }
Adam Powell7d758002015-05-06 17:49:36 -07002988 }
2989
2990 @Override
Zhen Zhangbde7b462019-11-11 11:49:33 -08002991 public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Matt Pietal5b648562019-03-12 07:40:26 -04002992 int viewType = getItemViewType(position);
Zhen Zhangbde7b462019-11-11 11:49:33 -08002993 switch (viewType) {
2994 case VIEW_TYPE_DIRECT_SHARE:
2995 case VIEW_TYPE_CALLER_AND_RANK:
2996 bindItemGroupViewHolder(position, (ItemGroupViewHolder) holder);
2997 break;
2998 case VIEW_TYPE_NORMAL:
2999 bindItemViewHolder(position, (ItemViewHolder) holder);
3000 break;
3001 default:
Matt Pietal1ef88002019-03-13 10:43:18 -04003002 }
Adam Powell7d758002015-05-06 17:49:36 -07003003 }
3004
Matt Pietal5b648562019-03-12 07:40:26 -04003005 @Override
3006 public int getItemViewType(int position) {
Mike Digmanae730b12019-04-25 11:10:31 -07003007 int count;
Matt Pietal1ef88002019-03-13 10:43:18 -04003008
arangelov590fba32020-02-11 18:05:42 +00003009 int countSum = (count = getContentPreviewRowCount());
3010 if (count > 0 && position < countSum) return VIEW_TYPE_CONTENT_PREVIEW;
3011
3012 countSum += (count = getProfileRowCount());
Mike Digmanae730b12019-04-25 11:10:31 -07003013 if (count > 0 && position < countSum) return VIEW_TYPE_PROFILE;
Adam Powell63b31692015-09-28 10:45:00 -07003014
Mike Digmanae730b12019-04-25 11:10:31 -07003015 countSum += (count = getServiceTargetRowCount());
3016 if (count > 0 && position < countSum) return VIEW_TYPE_DIRECT_SHARE;
3017
3018 countSum += (count = getCallerAndRankedTargetRowCount());
Zhen Zhangbde7b462019-11-11 11:49:33 -08003019 if (count > 0 && position < countSum) return VIEW_TYPE_CALLER_AND_RANK;
Mike Digmanae730b12019-04-25 11:10:31 -07003020
3021 countSum += (count = getAzLabelRowCount());
3022 if (count > 0 && position < countSum) return VIEW_TYPE_AZ_LABEL;
Matt Pietal5b648562019-03-12 07:40:26 -04003023
Matt Pietal9236adc2019-12-12 09:24:23 -05003024 if (position == getItemCount() - 1) return VIEW_TYPE_FOOTER;
3025
Matt Pietal5b648562019-03-12 07:40:26 -04003026 return VIEW_TYPE_NORMAL;
3027 }
3028
Zhen Zhangbde7b462019-11-11 11:49:33 -08003029 public int getTargetType(int position) {
3030 return mChooserListAdapter.getPositionTargetType(getListPosition(position));
Matt Pietal1ef88002019-03-13 10:43:18 -04003031 }
3032
Zhen Zhangbde7b462019-11-11 11:49:33 -08003033 private View createProfileView(ViewGroup parent) {
3034 View profileRow = mLayoutInflater.inflate(R.layout.chooser_profile_row, parent, false);
Matt Pietal74c6ed02019-04-18 13:38:46 -04003035 profileRow.setBackground(
3036 getResources().getDrawable(R.drawable.chooser_row_layer_list, null));
3037 mProfileView = profileRow.findViewById(R.id.profile_button);
3038 mProfileView.setOnClickListener(ChooserActivity.this::onProfileClick);
arangelovb0802dc2019-10-18 18:03:44 +01003039 updateProfileViewButton();
Matt Pietal74c6ed02019-04-18 13:38:46 -04003040 return profileRow;
3041 }
3042
Mike Digmanae730b12019-04-25 11:10:31 -07003043 private View createAzLabelView(ViewGroup parent) {
3044 return mLayoutInflater.inflate(R.layout.chooser_az_label_row, parent, false);
3045 }
3046
Zhen Zhangbde7b462019-11-11 11:49:33 -08003047 private ItemGroupViewHolder loadViewsIntoGroup(ItemGroupViewHolder holder) {
Matt Pietal5b648562019-03-12 07:40:26 -04003048 final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
Matt Pietalab986b52019-04-10 10:14:32 -04003049 final int exactSpec = MeasureSpec.makeMeasureSpec(mChooserTargetWidth,
3050 MeasureSpec.EXACTLY);
Matt Pietal5b648562019-03-12 07:40:26 -04003051 int columnCount = holder.getColumnCount();
3052
Mike Digmanba232682019-03-27 14:55:26 -07003053 final boolean isDirectShare = holder instanceof DirectShareViewHolder;
3054
Matt Pietal5b648562019-03-12 07:40:26 -04003055 for (int i = 0; i < columnCount; i++) {
Mike Digmanba232682019-03-27 14:55:26 -07003056 final View v = mChooserListAdapter.createView(holder.getRowByIndex(i));
Adam Powell4eb98712015-10-14 13:10:18 -07003057 final int column = i;
Adam Powell63b31692015-09-28 10:45:00 -07003058 v.setOnClickListener(new OnClickListener() {
3059 @Override
3060 public void onClick(View v) {
Matt Pietal5b648562019-03-12 07:40:26 -04003061 startSelected(holder.getItemIndex(column), false, true);
Adam Powell63b31692015-09-28 10:45:00 -07003062 }
3063 });
3064 v.setOnLongClickListener(new OnLongClickListener() {
3065 @Override
3066 public boolean onLongClick(View v) {
Adam Powell23882512016-01-29 10:21:00 -08003067 showTargetDetails(
Alison Cichowlas19ee2922019-12-16 19:43:12 -05003068 mChooserListAdapter.targetInfoForPosition(
Matt Pietal5b648562019-03-12 07:40:26 -04003069 holder.getItemIndex(column), true));
Adam Powell63b31692015-09-28 10:45:00 -07003070 return true;
3071 }
3072 });
Zhen Zhangbde7b462019-11-11 11:49:33 -08003073 holder.addView(i, v);
Adam Powell63b31692015-09-28 10:45:00 -07003074
Mike Digmanba232682019-03-27 14:55:26 -07003075 // Force Direct Share to be 2 lines and auto-wrap to second line via hoz scroll =
3076 // false. TextView#setHorizontallyScrolling must be reset after #setLines. Must be
3077 // done before measuring.
3078 if (isDirectShare) {
3079 final ViewHolder vh = (ViewHolder) v.getTag();
3080 vh.text.setLines(2);
3081 vh.text.setHorizontallyScrolling(false);
3082 vh.text2.setVisibility(View.GONE);
Adam Powell63b31692015-09-28 10:45:00 -07003083 }
Mike Digmanba232682019-03-27 14:55:26 -07003084
3085 // Force height to be a given so we don't have visual disruption during scaling.
Matt Pietalab986b52019-04-10 10:14:32 -04003086 v.measure(exactSpec, spec);
3087 setViewBounds(v, v.getMeasuredWidth(), v.getMeasuredHeight());
Adam Powell63b31692015-09-28 10:45:00 -07003088 }
3089
Matt Pietal5b648562019-03-12 07:40:26 -04003090 final ViewGroup viewGroup = holder.getViewGroup();
3091
Mike Digmanba232682019-03-27 14:55:26 -07003092 // Pre-measure and fix height so we can scale later.
Adam Powell63b31692015-09-28 10:45:00 -07003093 holder.measure();
Matt Pietalab986b52019-04-10 10:14:32 -04003094 setViewBounds(viewGroup, LayoutParams.MATCH_PARENT, holder.getMeasuredRowHeight());
Mike Digmanba232682019-03-27 14:55:26 -07003095
3096 if (isDirectShare) {
3097 DirectShareViewHolder dsvh = (DirectShareViewHolder) holder;
Matt Pietalab986b52019-04-10 10:14:32 -04003098 setViewBounds(dsvh.getRow(0), LayoutParams.MATCH_PARENT, dsvh.getMinRowHeight());
3099 setViewBounds(dsvh.getRow(1), LayoutParams.MATCH_PARENT, dsvh.getMinRowHeight());
Adam Powell7d758002015-05-06 17:49:36 -07003100 }
Matt Pietal5b648562019-03-12 07:40:26 -04003101
3102 viewGroup.setTag(holder);
3103
Adam Powell7d758002015-05-06 17:49:36 -07003104 return holder;
3105 }
3106
Matt Pietalab986b52019-04-10 10:14:32 -04003107 private void setViewBounds(View view, int widthPx, int heightPx) {
Mike Digmanba232682019-03-27 14:55:26 -07003108 LayoutParams lp = view.getLayoutParams();
3109 if (lp == null) {
Matt Pietalab986b52019-04-10 10:14:32 -04003110 lp = new LayoutParams(widthPx, heightPx);
Mike Digmanba232682019-03-27 14:55:26 -07003111 view.setLayoutParams(lp);
3112 } else {
3113 lp.height = heightPx;
Matt Pietalab986b52019-04-10 10:14:32 -04003114 lp.width = widthPx;
Mike Digmanba232682019-03-27 14:55:26 -07003115 }
3116 }
3117
Zhen Zhangbde7b462019-11-11 11:49:33 -08003118 ItemGroupViewHolder createItemGroupViewHolder(int viewType, ViewGroup parent) {
Matt Pietal5b648562019-03-12 07:40:26 -04003119 if (viewType == VIEW_TYPE_DIRECT_SHARE) {
3120 ViewGroup parentGroup = (ViewGroup) mLayoutInflater.inflate(
3121 R.layout.chooser_row_direct_share, parent, false);
3122 ViewGroup row1 = (ViewGroup) mLayoutInflater.inflate(R.layout.chooser_row,
3123 parentGroup, false);
3124 ViewGroup row2 = (ViewGroup) mLayoutInflater.inflate(R.layout.chooser_row,
3125 parentGroup, false);
3126 parentGroup.addView(row1);
3127 parentGroup.addView(row2);
3128
3129 mDirectShareViewHolder = new DirectShareViewHolder(parentGroup,
3130 Lists.newArrayList(row1, row2), getMaxTargetsPerRow());
Zhen Zhangbde7b462019-11-11 11:49:33 -08003131 loadViewsIntoGroup(mDirectShareViewHolder);
Matt Pietal5b648562019-03-12 07:40:26 -04003132
3133 return mDirectShareViewHolder;
3134 } else {
3135 ViewGroup row = (ViewGroup) mLayoutInflater.inflate(R.layout.chooser_row, parent,
3136 false);
Zhen Zhangbde7b462019-11-11 11:49:33 -08003137 ItemGroupViewHolder holder = new SingleRowViewHolder(row, getMaxTargetsPerRow());
3138 loadViewsIntoGroup(holder);
Matt Pietal5b648562019-03-12 07:40:26 -04003139
3140 return holder;
3141 }
3142 }
3143
Matt Pietaldadc0d12019-04-16 12:53:28 -04003144 /**
Mike Digmanae730b12019-04-25 11:10:31 -07003145 * Need to merge CALLER + ranked STANDARD into a single row and prevent a separator from
3146 * showing on top of the AZ list if the AZ label is visible. All other types are placed into
3147 * their own row as determined by their target type, and dividers are added in the list to
3148 * separate each type.
Matt Pietaldadc0d12019-04-16 12:53:28 -04003149 */
3150 int getRowType(int rowPosition) {
Mike Digmanae730b12019-04-25 11:10:31 -07003151 // Merge caller and ranked standard into a single row
Matt Pietaldadc0d12019-04-16 12:53:28 -04003152 int positionType = mChooserListAdapter.getPositionTargetType(rowPosition);
3153 if (positionType == ChooserListAdapter.TARGET_CALLER) {
3154 return ChooserListAdapter.TARGET_STANDARD;
3155 }
3156
Mike Digmanae730b12019-04-25 11:10:31 -07003157 // If an the A-Z label is shown, prevent a separator from appearing by making the A-Z
3158 // row type the same as the suggestion row type
3159 if (getAzLabelRowCount() > 0 && positionType == ChooserListAdapter.TARGET_STANDARD_AZ) {
3160 return ChooserListAdapter.TARGET_STANDARD;
3161 }
3162
Matt Pietaldadc0d12019-04-16 12:53:28 -04003163 return positionType;
3164 }
3165
Zhen Zhangbde7b462019-11-11 11:49:33 -08003166 void bindItemViewHolder(int position, ItemViewHolder holder) {
3167 View v = holder.itemView;
3168 int listPosition = getListPosition(position);
3169 holder.mListPosition = listPosition;
3170 mChooserListAdapter.bindView(listPosition, v);
3171 }
Matt Pietalcdfcd9a2019-03-05 08:31:47 -05003172
Zhen Zhangbde7b462019-11-11 11:49:33 -08003173 void bindItemGroupViewHolder(int position, ItemGroupViewHolder holder) {
3174 final ViewGroup viewGroup = (ViewGroup) holder.itemView;
3175 int start = getListPosition(position);
3176 int startType = getRowType(start);
arangelov934c64c2020-02-14 13:48:23 +00003177 if (viewGroup.getForeground() == null && position > 0) {
Zhen Zhangbde7b462019-11-11 11:49:33 -08003178 viewGroup.setForeground(
Matt Pietal74c6ed02019-04-18 13:38:46 -04003179 getResources().getDrawable(R.drawable.chooser_row_layer_list, null));
Matt Pietalcdfcd9a2019-03-05 08:31:47 -05003180 }
3181
Matt Pietalfaedea82019-03-21 10:36:54 -04003182 int columnCount = holder.getColumnCount();
Matt Pietal5b648562019-03-12 07:40:26 -04003183 int end = start + columnCount - 1;
Matt Pietaldadc0d12019-04-16 12:53:28 -04003184 while (getRowType(end) != startType && end >= start) {
Adam Powell7d758002015-05-06 17:49:36 -07003185 end--;
3186 }
3187
Matt Pietalcdfcd9a2019-03-05 08:31:47 -05003188 if (end == start && mChooserListAdapter.getItem(start) instanceof EmptyTargetInfo) {
Zhen Zhangbde7b462019-11-11 11:49:33 -08003189 final TextView textView = viewGroup.findViewById(R.id.chooser_row_text_option);
Adam Powell63b31692015-09-28 10:45:00 -07003190
Matt Pietalcdfcd9a2019-03-05 08:31:47 -05003191 if (textView.getVisibility() != View.VISIBLE) {
3192 textView.setAlpha(0.0f);
3193 textView.setVisibility(View.VISIBLE);
3194 textView.setText(R.string.chooser_no_direct_share_targets);
3195
3196 ValueAnimator fadeAnim = ObjectAnimator.ofFloat(textView, "alpha", 0.0f, 1.0f);
3197 fadeAnim.setInterpolator(new DecelerateInterpolator(1.0f));
3198
3199 float translationInPx = getResources().getDimensionPixelSize(
3200 R.dimen.chooser_row_text_option_translate);
3201 textView.setTranslationY(translationInPx);
3202 ValueAnimator translateAnim = ObjectAnimator.ofFloat(textView, "translationY",
3203 0.0f);
3204 translateAnim.setInterpolator(new DecelerateInterpolator(1.0f));
3205
3206 AnimatorSet animSet = new AnimatorSet();
3207 animSet.setDuration(NO_DIRECT_SHARE_ANIM_IN_MILLIS);
3208 animSet.setStartDelay(NO_DIRECT_SHARE_ANIM_IN_MILLIS);
3209 animSet.playTogether(fadeAnim, translateAnim);
3210 animSet.start();
3211 }
Adam Powell7d758002015-05-06 17:49:36 -07003212 }
3213
Matt Pietal5b648562019-03-12 07:40:26 -04003214 for (int i = 0; i < columnCount; i++) {
3215 final View v = holder.getView(i);
arangelov38a6fce2019-12-02 18:21:22 +00003216
Adam Powell7d758002015-05-06 17:49:36 -07003217 if (start + i <= end) {
Matt Pietalfaedea82019-03-21 10:36:54 -04003218 holder.setViewVisibility(i, View.VISIBLE);
Matt Pietal5b648562019-03-12 07:40:26 -04003219 holder.setItemIndex(i, start + i);
3220 mChooserListAdapter.bindView(holder.getItemIndex(i), v);
Adam Powell7d758002015-05-06 17:49:36 -07003221 } else {
Matt Pietalfaedea82019-03-21 10:36:54 -04003222 holder.setViewVisibility(i, View.INVISIBLE);
Adam Powell7d758002015-05-06 17:49:36 -07003223 }
3224 }
3225 }
3226
Zhen Zhangbde7b462019-11-11 11:49:33 -08003227 int getListPosition(int position) {
arangelov590fba32020-02-11 18:05:42 +00003228 position -= getContentPreviewRowCount() + getProfileRowCount();
Matt Pietal1ef88002019-03-13 10:43:18 -04003229
Matt Pietal5b648562019-03-12 07:40:26 -04003230 final int serviceCount = mChooserListAdapter.getServiceTargetCount();
3231 final int serviceRows = (int) Math.ceil((float) serviceCount
3232 / ChooserListAdapter.MAX_SERVICE_TARGETS);
Zhen Zhangbde7b462019-11-11 11:49:33 -08003233 if (position < serviceRows) {
3234 return position * getMaxTargetsPerRow();
Adam Powell7d758002015-05-06 17:49:36 -07003235 }
3236
Zhen Zhangbde7b462019-11-11 11:49:33 -08003237 position -= serviceRows;
3238
Matt Pietaldadc0d12019-04-16 12:53:28 -04003239 final int callerAndRankedCount = mChooserListAdapter.getCallerTargetCount()
3240 + mChooserListAdapter.getRankedTargetCount();
3241 final int callerAndRankedRows = getCallerAndRankedTargetRowCount();
Zhen Zhangbde7b462019-11-11 11:49:33 -08003242 if (position < callerAndRankedRows) {
3243 return serviceCount + position * getMaxTargetsPerRow();
Adam Powell7d758002015-05-06 17:49:36 -07003244 }
3245
Zhen Zhangbde7b462019-11-11 11:49:33 -08003246 position -= getAzLabelRowCount() + callerAndRankedRows;
Mike Digmanae730b12019-04-25 11:10:31 -07003247
Zhen Zhangbde7b462019-11-11 11:49:33 -08003248 return callerAndRankedCount + serviceCount + position;
Matt Pietal5b648562019-03-12 07:40:26 -04003249 }
3250
3251 public void handleScroll(View v, int y, int oldy) {
Matt Pietale54dcc2e2019-05-02 12:59:38 -04003252 // Only expand direct share area if there is a minimum number of shortcuts,
3253 // which will help reduce the amount of visible shuffling due to older-style
3254 // direct share targets.
3255 int orientation = getResources().getConfiguration().orientation;
3256 boolean canExpandDirectShare =
3257 mChooserListAdapter.getNumShortcutResults() > getMaxTargetsPerRow()
Matt Pietal3e4b56f2019-05-31 12:06:17 -04003258 && orientation == Configuration.ORIENTATION_PORTRAIT
3259 && !isInMultiWindowMode();
Matt Pietale54dcc2e2019-05-02 12:59:38 -04003260
3261 if (mDirectShareViewHolder != null && canExpandDirectShare) {
arangelov38a6fce2019-12-02 18:21:22 +00003262 mDirectShareViewHolder.handleScroll(
arangelovcf268642020-01-15 15:09:51 +00003263 mChooserMultiProfilePagerAdapter.getActiveAdapterView(), y, oldy,
arangelov38a6fce2019-12-02 18:21:22 +00003264 getMaxTargetsPerRow());
Matt Pietal5b648562019-03-12 07:40:26 -04003265 }
Adam Powell7d758002015-05-06 17:49:36 -07003266 }
arangelov38a6fce2019-12-02 18:21:22 +00003267
3268 public ChooserListAdapter getListAdapter() {
3269 return mChooserListAdapter;
3270 }
3271
arangelov38a6fce2019-12-02 18:21:22 +00003272 boolean shouldCellSpan(int position) {
3273 return getItemViewType(position) == VIEW_TYPE_NORMAL;
3274 }
Adam Powell7d758002015-05-06 17:49:36 -07003275 }
3276
Zhen Zhangbde7b462019-11-11 11:49:33 -08003277 /**
3278 * Used to bind types for group of items including:
3279 * {@link ChooserGridAdapter#VIEW_TYPE_DIRECT_SHARE},
3280 * and {@link ChooserGridAdapter#VIEW_TYPE_CALLER_AND_RANK}.
3281 */
3282 abstract class ItemGroupViewHolder extends RecyclerView.ViewHolder {
Matt Pietal5b648562019-03-12 07:40:26 -04003283 protected int mMeasuredRowHeight;
3284 private int[] mItemIndices;
3285 protected final View[] mCells;
Matt Pietal5b648562019-03-12 07:40:26 -04003286 private final int mColumnCount;
Adam Powell63b31692015-09-28 10:45:00 -07003287
Zhen Zhangbde7b462019-11-11 11:49:33 -08003288 ItemGroupViewHolder(int cellCount, View itemView) {
3289 super(itemView);
Matt Pietal5b648562019-03-12 07:40:26 -04003290 this.mCells = new View[cellCount];
3291 this.mItemIndices = new int[cellCount];
Matt Pietal5b648562019-03-12 07:40:26 -04003292 this.mColumnCount = cellCount;
3293 }
3294
3295 abstract ViewGroup addView(int index, View v);
3296
3297 abstract ViewGroup getViewGroup();
3298
Mike Digmanba232682019-03-27 14:55:26 -07003299 abstract ViewGroup getRowByIndex(int index);
3300
3301 abstract ViewGroup getRow(int rowNumber);
Matt Pietal5b648562019-03-12 07:40:26 -04003302
Matt Pietalfaedea82019-03-21 10:36:54 -04003303 abstract void setViewVisibility(int i, int visibility);
3304
Matt Pietal5b648562019-03-12 07:40:26 -04003305 public int getColumnCount() {
3306 return mColumnCount;
3307 }
3308
Adam Powell63b31692015-09-28 10:45:00 -07003309 public void measure() {
3310 final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
Matt Pietal5b648562019-03-12 07:40:26 -04003311 getViewGroup().measure(spec, spec);
3312 mMeasuredRowHeight = getViewGroup().getMeasuredHeight();
3313 }
3314
3315 public int getMeasuredRowHeight() {
3316 return mMeasuredRowHeight;
3317 }
3318
Matt Pietal5b648562019-03-12 07:40:26 -04003319 public void setItemIndex(int itemIndex, int listIndex) {
3320 mItemIndices[itemIndex] = listIndex;
3321 }
3322
3323 public int getItemIndex(int itemIndex) {
3324 return mItemIndices[itemIndex];
3325 }
3326
3327 public View getView(int index) {
3328 return mCells[index];
3329 }
3330 }
3331
Zhen Zhangbde7b462019-11-11 11:49:33 -08003332 class SingleRowViewHolder extends ItemGroupViewHolder {
Matt Pietal5b648562019-03-12 07:40:26 -04003333 private final ViewGroup mRow;
3334
3335 SingleRowViewHolder(ViewGroup row, int cellCount) {
Zhen Zhangbde7b462019-11-11 11:49:33 -08003336 super(cellCount, row);
Matt Pietal5b648562019-03-12 07:40:26 -04003337
3338 this.mRow = row;
3339 }
3340
3341 public ViewGroup getViewGroup() {
3342 return mRow;
3343 }
3344
Mike Digmanba232682019-03-27 14:55:26 -07003345 public ViewGroup getRowByIndex(int index) {
Matt Pietal5b648562019-03-12 07:40:26 -04003346 return mRow;
3347 }
3348
Mike Digmanba232682019-03-27 14:55:26 -07003349 public ViewGroup getRow(int rowNumber) {
3350 if (rowNumber == 0) return mRow;
3351 return null;
3352 }
3353
Matt Pietal5b648562019-03-12 07:40:26 -04003354 public ViewGroup addView(int index, View v) {
3355 mRow.addView(v);
3356 mCells[index] = v;
3357
Matt Pietal5b648562019-03-12 07:40:26 -04003358 return mRow;
3359 }
Matt Pietalfaedea82019-03-21 10:36:54 -04003360
3361 public void setViewVisibility(int i, int visibility) {
3362 getView(i).setVisibility(visibility);
3363 }
Matt Pietal5b648562019-03-12 07:40:26 -04003364 }
3365
Zhen Zhangbde7b462019-11-11 11:49:33 -08003366 class DirectShareViewHolder extends ItemGroupViewHolder {
Matt Pietal5b648562019-03-12 07:40:26 -04003367 private final ViewGroup mParent;
3368 private final List<ViewGroup> mRows;
3369 private int mCellCountPerRow;
3370
3371 private boolean mHideDirectShareExpansion = false;
3372 private int mDirectShareMinHeight = 0;
3373 private int mDirectShareCurrHeight = 0;
3374 private int mDirectShareMaxHeight = 0;
3375
Matt Pietalfaedea82019-03-21 10:36:54 -04003376 private final boolean[] mCellVisibility;
3377
Matt Pietal5b648562019-03-12 07:40:26 -04003378 DirectShareViewHolder(ViewGroup parent, List<ViewGroup> rows, int cellCountPerRow) {
Zhen Zhangbde7b462019-11-11 11:49:33 -08003379 super(rows.size() * cellCountPerRow, parent);
Matt Pietal5b648562019-03-12 07:40:26 -04003380
3381 this.mParent = parent;
3382 this.mRows = rows;
3383 this.mCellCountPerRow = cellCountPerRow;
Matt Pietalfaedea82019-03-21 10:36:54 -04003384 this.mCellVisibility = new boolean[rows.size() * cellCountPerRow];
Matt Pietal5b648562019-03-12 07:40:26 -04003385 }
3386
3387 public ViewGroup addView(int index, View v) {
Mike Digmanba232682019-03-27 14:55:26 -07003388 ViewGroup row = getRowByIndex(index);
Matt Pietal5b648562019-03-12 07:40:26 -04003389 row.addView(v);
3390 mCells[index] = v;
3391
Matt Pietal5b648562019-03-12 07:40:26 -04003392 return row;
3393 }
3394
3395 public ViewGroup getViewGroup() {
3396 return mParent;
3397 }
3398
Mike Digmanba232682019-03-27 14:55:26 -07003399 public ViewGroup getRowByIndex(int index) {
Matt Pietal5b648562019-03-12 07:40:26 -04003400 return mRows.get(index / mCellCountPerRow);
3401 }
3402
Mike Digmanba232682019-03-27 14:55:26 -07003403 public ViewGroup getRow(int rowNumber) {
3404 return mRows.get(rowNumber);
3405 }
3406
Matt Pietal5b648562019-03-12 07:40:26 -04003407 public void measure() {
3408 final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
3409 getRow(0).measure(spec, spec);
3410 getRow(1).measure(spec, spec);
3411
Matt Pietal5b648562019-03-12 07:40:26 -04003412 mDirectShareMinHeight = getRow(0).getMeasuredHeight();
3413 mDirectShareCurrHeight = mDirectShareCurrHeight > 0
Zhen Zhangbde7b462019-11-11 11:49:33 -08003414 ? mDirectShareCurrHeight : mDirectShareMinHeight;
Matt Pietal5b648562019-03-12 07:40:26 -04003415 mDirectShareMaxHeight = 2 * mDirectShareMinHeight;
3416 }
3417
3418 public int getMeasuredRowHeight() {
3419 return mDirectShareCurrHeight;
3420 }
3421
Matt Pietala9c8e502019-04-10 14:27:35 -04003422 public int getMinRowHeight() {
3423 return mDirectShareMinHeight;
3424 }
3425
Matt Pietalfaedea82019-03-21 10:36:54 -04003426 public void setViewVisibility(int i, int visibility) {
3427 final View v = getView(i);
3428 if (visibility == View.VISIBLE) {
3429 mCellVisibility[i] = true;
3430 v.setVisibility(visibility);
3431 v.setAlpha(1.0f);
3432 } else if (visibility == View.INVISIBLE && mCellVisibility[i]) {
3433 mCellVisibility[i] = false;
3434
3435 ValueAnimator fadeAnim = ObjectAnimator.ofFloat(v, "alpha", 1.0f, 0f);
3436 fadeAnim.setDuration(NO_DIRECT_SHARE_ANIM_IN_MILLIS);
3437 fadeAnim.setInterpolator(new AccelerateInterpolator(1.0f));
3438 fadeAnim.addListener(new AnimatorListenerAdapter() {
3439 public void onAnimationEnd(Animator animation) {
3440 v.setVisibility(View.INVISIBLE);
3441 }
3442 });
3443 fadeAnim.start();
3444 }
3445 }
3446
Zhen Zhangbde7b462019-11-11 11:49:33 -08003447 public void handleScroll(RecyclerView view, int y, int oldy, int maxTargetsPerRow) {
Matt Pietala9c8e502019-04-10 14:27:35 -04003448 // only exit early if fully collapsed, otherwise onListRebuilt() with shifting
3449 // targets can lock us into an expanded mode
3450 boolean notExpanded = mDirectShareCurrHeight == mDirectShareMinHeight;
3451 if (notExpanded) {
3452 if (mHideDirectShareExpansion) {
3453 return;
3454 }
Matt Pietal5b648562019-03-12 07:40:26 -04003455
Matt Pietala9c8e502019-04-10 14:27:35 -04003456 // only expand if we have more than maxTargetsPerRow, and delay that decision
3457 // until they start to scroll
arangelova3912cf2019-12-13 14:34:45 +00003458 if (mChooserMultiProfilePagerAdapter.getActiveListAdapter()
arangelov38a6fce2019-12-02 18:21:22 +00003459 .getSelectableServiceTargetCount() <= maxTargetsPerRow) {
Matt Pietala9c8e502019-04-10 14:27:35 -04003460 mHideDirectShareExpansion = true;
3461 return;
3462 }
Matt Pietal5b648562019-03-12 07:40:26 -04003463 }
3464
Matt Pietalfe28f9a2019-03-22 07:59:58 -04003465 int yDiff = (int) ((oldy - y) * DIRECT_SHARE_EXPANSION_RATE);
Matt Pietal5b648562019-03-12 07:40:26 -04003466
3467 int prevHeight = mDirectShareCurrHeight;
Matt Pietalc6d3ac22019-04-25 14:38:30 -04003468 int newHeight = Math.min(prevHeight + yDiff, mDirectShareMaxHeight);
3469 newHeight = Math.max(newHeight, mDirectShareMinHeight);
3470 yDiff = newHeight - prevHeight;
Matt Pietal5b648562019-03-12 07:40:26 -04003471
Matt Pietalfe28f9a2019-03-22 07:59:58 -04003472 if (view == null || view.getChildCount() == 0 || yDiff == 0) {
Matt Pietal5b648562019-03-12 07:40:26 -04003473 return;
3474 }
3475
Matt Pietalfe28f9a2019-03-22 07:59:58 -04003476 // locate the item to expand, and offset the rows below that one
3477 boolean foundExpansion = false;
3478 for (int i = 0; i < view.getChildCount(); i++) {
3479 View child = view.getChildAt(i);
Matt Pietal1ef88002019-03-13 10:43:18 -04003480
Matt Pietalfe28f9a2019-03-22 07:59:58 -04003481 if (foundExpansion) {
3482 child.offsetTopAndBottom(yDiff);
3483 } else {
3484 if (child.getTag() != null && child.getTag() instanceof DirectShareViewHolder) {
3485 int widthSpec = MeasureSpec.makeMeasureSpec(child.getWidth(),
3486 MeasureSpec.EXACTLY);
Matt Pietalc6d3ac22019-04-25 14:38:30 -04003487 int heightSpec = MeasureSpec.makeMeasureSpec(newHeight,
Matt Pietalfe28f9a2019-03-22 07:59:58 -04003488 MeasureSpec.EXACTLY);
3489 child.measure(widthSpec, heightSpec);
3490 child.getLayoutParams().height = child.getMeasuredHeight();
3491 child.layout(child.getLeft(), child.getTop(), child.getRight(),
3492 child.getTop() + child.getMeasuredHeight());
Matt Pietal5b648562019-03-12 07:40:26 -04003493
Matt Pietalfe28f9a2019-03-22 07:59:58 -04003494 foundExpansion = true;
3495 }
3496 }
Matt Pietal5b648562019-03-12 07:40:26 -04003497 }
Matt Pietalc6d3ac22019-04-25 14:38:30 -04003498
3499 if (foundExpansion) {
3500 mDirectShareCurrHeight = newHeight;
3501 }
Adam Powell63b31692015-09-28 10:45:00 -07003502 }
3503 }
3504
Adam Powell9761ab22015-09-08 17:01:49 -07003505 static class ChooserTargetServiceConnection implements ServiceConnection {
Adam Powell52c39212016-04-07 15:14:18 -07003506 private DisplayResolveInfo mOriginalTarget;
Adam Powell9761ab22015-09-08 17:01:49 -07003507 private ComponentName mConnectedComponent;
3508 private ChooserActivity mChooserActivity;
arangelov5fc9e7d2020-01-07 17:59:14 +00003509 private final UserHandle mUserHandle;
Adam Powell9761ab22015-09-08 17:01:49 -07003510 private final Object mLock = new Object();
Adam Powell24428412015-04-01 17:19:56 -07003511
3512 private final IChooserTargetResult mChooserTargetResult = new IChooserTargetResult.Stub() {
3513 @Override
3514 public void sendResult(List<ChooserTarget> targets) throws RemoteException {
Adam Powell9761ab22015-09-08 17:01:49 -07003515 synchronized (mLock) {
3516 if (mChooserActivity == null) {
3517 Log.e(TAG, "destroyed ChooserTargetServiceConnection received result from "
3518 + mConnectedComponent + "; ignoring...");
3519 return;
3520 }
arangelov5fc9e7d2020-01-07 17:59:14 +00003521 Context contextAsUser =
3522 mChooserActivity.createContextAsUser(mUserHandle, 0 /* flags */);
3523 mChooserActivity.filterServiceTargets(contextAsUser,
Adam Powell9761ab22015-09-08 17:01:49 -07003524 mOriginalTarget.getResolveInfo().activityInfo.packageName, targets);
3525 final Message msg = Message.obtain();
Matt Pietalab73a882019-06-05 07:04:55 -04003526 msg.what = ChooserHandler.CHOOSER_TARGET_SERVICE_RESULT;
Adam Powell9761ab22015-09-08 17:01:49 -07003527 msg.obj = new ServiceResultInfo(mOriginalTarget, targets,
arangelov5fc9e7d2020-01-07 17:59:14 +00003528 ChooserTargetServiceConnection.this, mUserHandle);
Adam Powell9761ab22015-09-08 17:01:49 -07003529 mChooserActivity.mChooserHandler.sendMessage(msg);
3530 }
Adam Powell24428412015-04-01 17:19:56 -07003531 }
3532 };
3533
Adam Powell9761ab22015-09-08 17:01:49 -07003534 public ChooserTargetServiceConnection(ChooserActivity chooserActivity,
arangelov5fc9e7d2020-01-07 17:59:14 +00003535 DisplayResolveInfo dri, UserHandle userHandle) {
Adam Powell9761ab22015-09-08 17:01:49 -07003536 mChooserActivity = chooserActivity;
Adam Powell24428412015-04-01 17:19:56 -07003537 mOriginalTarget = dri;
arangelov5fc9e7d2020-01-07 17:59:14 +00003538 mUserHandle = userHandle;
Adam Powell24428412015-04-01 17:19:56 -07003539 }
3540
3541 @Override
3542 public void onServiceConnected(ComponentName name, IBinder service) {
3543 if (DEBUG) Log.d(TAG, "onServiceConnected: " + name);
Adam Powell9761ab22015-09-08 17:01:49 -07003544 synchronized (mLock) {
3545 if (mChooserActivity == null) {
3546 Log.e(TAG, "destroyed ChooserTargetServiceConnection got onServiceConnected");
3547 return;
3548 }
3549
3550 final IChooserTargetService icts = IChooserTargetService.Stub.asInterface(service);
3551 try {
3552 icts.getChooserTargets(mOriginalTarget.getResolvedComponentName(),
3553 mOriginalTarget.getResolveInfo().filter, mChooserTargetResult);
3554 } catch (RemoteException e) {
3555 Log.e(TAG, "Querying ChooserTargetService " + name + " failed.", e);
3556 mChooserActivity.unbindService(this);
Adam Powell9761ab22015-09-08 17:01:49 -07003557 mChooserActivity.mServiceConnections.remove(this);
Dan Sandlerfcd7fae2017-09-25 17:40:04 -04003558 destroy();
Adam Powell9761ab22015-09-08 17:01:49 -07003559 }
Adam Powell24428412015-04-01 17:19:56 -07003560 }
3561 }
3562
3563 @Override
3564 public void onServiceDisconnected(ComponentName name) {
3565 if (DEBUG) Log.d(TAG, "onServiceDisconnected: " + name);
Adam Powell9761ab22015-09-08 17:01:49 -07003566 synchronized (mLock) {
3567 if (mChooserActivity == null) {
3568 Log.e(TAG,
3569 "destroyed ChooserTargetServiceConnection got onServiceDisconnected");
3570 return;
3571 }
3572
3573 mChooserActivity.unbindService(this);
Adam Powell9761ab22015-09-08 17:01:49 -07003574 mChooserActivity.mServiceConnections.remove(this);
3575 if (mChooserActivity.mServiceConnections.isEmpty()) {
Adam Powell9761ab22015-09-08 17:01:49 -07003576 mChooserActivity.sendVoiceChoicesIfNeeded();
3577 }
3578 mConnectedComponent = null;
Dan Sandlerfcd7fae2017-09-25 17:40:04 -04003579 destroy();
Adam Powell9761ab22015-09-08 17:01:49 -07003580 }
3581 }
3582
3583 public void destroy() {
3584 synchronized (mLock) {
3585 mChooserActivity = null;
Adam Powell52c39212016-04-07 15:14:18 -07003586 mOriginalTarget = null;
Adam Powell4c470d62015-06-19 17:46:17 -07003587 }
Adam Powell24428412015-04-01 17:19:56 -07003588 }
3589
3590 @Override
3591 public String toString() {
Adam Powell9761ab22015-09-08 17:01:49 -07003592 return "ChooserTargetServiceConnection{service="
3593 + mConnectedComponent + ", activity="
Adam Powell52c39212016-04-07 15:14:18 -07003594 + (mOriginalTarget != null
3595 ? mOriginalTarget.getResolveInfo().activityInfo.toString()
3596 : "<connection destroyed>") + "}";
Adam Powell24428412015-04-01 17:19:56 -07003597 }
Song Hue2deffd2020-03-09 15:22:29 -07003598
3599 public ComponentName getComponentName() {
3600 return mOriginalTarget.getResolveInfo().activityInfo.getComponentName();
3601 }
Adam Powell24428412015-04-01 17:19:56 -07003602 }
3603
3604 static class ServiceResultInfo {
3605 public final DisplayResolveInfo originalTarget;
3606 public final List<ChooserTarget> resultTargets;
3607 public final ChooserTargetServiceConnection connection;
arangelov5fc9e7d2020-01-07 17:59:14 +00003608 public final UserHandle userHandle;
Adam Powell24428412015-04-01 17:19:56 -07003609
3610 public ServiceResultInfo(DisplayResolveInfo ot, List<ChooserTarget> rt,
arangelov5fc9e7d2020-01-07 17:59:14 +00003611 ChooserTargetServiceConnection c, UserHandle userHandle) {
Adam Powell24428412015-04-01 17:19:56 -07003612 originalTarget = ot;
3613 resultTargets = rt;
3614 connection = c;
arangelov5fc9e7d2020-01-07 17:59:14 +00003615 this.userHandle = userHandle;
Adam Powell24428412015-04-01 17:19:56 -07003616 }
3617 }
Adam Powell2ed547e2015-04-29 18:45:04 -07003618
3619 static class RefinementResultReceiver extends ResultReceiver {
3620 private ChooserActivity mChooserActivity;
3621 private TargetInfo mSelectedTarget;
3622
3623 public RefinementResultReceiver(ChooserActivity host, TargetInfo target,
3624 Handler handler) {
3625 super(handler);
3626 mChooserActivity = host;
3627 mSelectedTarget = target;
3628 }
3629
3630 @Override
3631 protected void onReceiveResult(int resultCode, Bundle resultData) {
3632 if (mChooserActivity == null) {
3633 Log.e(TAG, "Destroyed RefinementResultReceiver received a result");
3634 return;
3635 }
3636 if (resultData == null) {
3637 Log.e(TAG, "RefinementResultReceiver received null resultData");
3638 return;
3639 }
3640
3641 switch (resultCode) {
3642 case RESULT_CANCELED:
3643 mChooserActivity.onRefinementCanceled();
3644 break;
3645 case RESULT_OK:
3646 Parcelable intentParcelable = resultData.getParcelable(Intent.EXTRA_INTENT);
3647 if (intentParcelable instanceof Intent) {
3648 mChooserActivity.onRefinementResult(mSelectedTarget,
3649 (Intent) intentParcelable);
3650 } else {
3651 Log.e(TAG, "RefinementResultReceiver received RESULT_OK but no Intent"
3652 + " in resultData with key Intent.EXTRA_INTENT");
3653 }
3654 break;
3655 default:
3656 Log.w(TAG, "Unknown result code " + resultCode
3657 + " sent to RefinementResultReceiver");
3658 break;
3659 }
3660 }
3661
3662 public void destroy() {
3663 mChooserActivity = null;
3664 mSelectedTarget = null;
3665 }
3666 }
Adam Powell63b31692015-09-28 10:45:00 -07003667
Matt Pietal26038402019-01-08 07:29:34 -05003668 /**
3669 * Used internally to round image corners while obeying view padding.
3670 */
3671 public static class RoundedRectImageView extends ImageView {
3672 private int mRadius = 0;
3673 private Path mPath = new Path();
Matt Pietal0ea391b2019-01-30 10:44:15 -05003674 private Paint mOverlayPaint = new Paint(0);
Matt Pietal9aaf00c2019-04-09 10:09:12 -04003675 private Paint mRoundRectPaint = new Paint(0);
Matt Pietal0ea391b2019-01-30 10:44:15 -05003676 private Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
3677 private String mExtraImageCount = null;
Matt Pietal26038402019-01-08 07:29:34 -05003678
3679 public RoundedRectImageView(Context context) {
3680 super(context);
3681 }
3682
3683 public RoundedRectImageView(Context context, AttributeSet attrs) {
3684 this(context, attrs, 0);
3685 }
3686
3687 public RoundedRectImageView(Context context, AttributeSet attrs, int defStyleAttr) {
3688 this(context, attrs, defStyleAttr, 0);
3689 }
3690
3691 public RoundedRectImageView(Context context, AttributeSet attrs, int defStyleAttr,
3692 int defStyleRes) {
3693 super(context, attrs, defStyleAttr, defStyleRes);
3694 mRadius = context.getResources().getDimensionPixelSize(R.dimen.chooser_corner_radius);
Matt Pietal0ea391b2019-01-30 10:44:15 -05003695
3696 mOverlayPaint.setColor(0x99000000);
3697 mOverlayPaint.setStyle(Paint.Style.FILL);
3698
Matt Pietal9aaf00c2019-04-09 10:09:12 -04003699 mRoundRectPaint.setColor(context.getResources().getColor(R.color.chooser_row_divider));
3700 mRoundRectPaint.setStyle(Paint.Style.STROKE);
3701 mRoundRectPaint.setStrokeWidth(context.getResources()
3702 .getDimensionPixelSize(R.dimen.chooser_preview_image_border));
3703
Matt Pietal0ea391b2019-01-30 10:44:15 -05003704 mTextPaint.setColor(Color.WHITE);
3705 mTextPaint.setTextSize(context.getResources()
3706 .getDimensionPixelSize(R.dimen.chooser_preview_image_font_size));
3707 mTextPaint.setTextAlign(Paint.Align.CENTER);
Matt Pietal26038402019-01-08 07:29:34 -05003708 }
3709
3710 private void updatePath(int width, int height) {
3711 mPath.reset();
3712
Matt Pietal9aaf00c2019-04-09 10:09:12 -04003713 int imageWidth = width - getPaddingRight() - getPaddingLeft();
3714 int imageHeight = height - getPaddingBottom() - getPaddingTop();
Matt Pietal26038402019-01-08 07:29:34 -05003715 mPath.addRoundRect(getPaddingLeft(), getPaddingTop(), imageWidth, imageHeight, mRadius,
3716 mRadius, Path.Direction.CW);
3717 }
3718
3719 /**
3720 * Sets the corner radius on all corners
3721 *
3722 * param radius 0 for no radius, &gt; 0 for a visible corner radius
3723 */
3724 public void setRadius(int radius) {
3725 mRadius = radius;
3726 updatePath(getWidth(), getHeight());
3727 }
3728
Matt Pietal0ea391b2019-01-30 10:44:15 -05003729 /**
3730 * Display an overlay with extra image count on 3rd image
3731 */
3732 public void setExtraImageCount(int count) {
3733 if (count > 0) {
3734 this.mExtraImageCount = "+" + count;
3735 } else {
3736 this.mExtraImageCount = null;
3737 }
3738 }
3739
Matt Pietal26038402019-01-08 07:29:34 -05003740 @Override
3741 protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
3742 super.onSizeChanged(width, height, oldWidth, oldHeight);
3743 updatePath(width, height);
3744 }
3745
3746 @Override
3747 protected void onDraw(Canvas canvas) {
3748 if (mRadius != 0) {
3749 canvas.clipPath(mPath);
3750 }
3751
3752 super.onDraw(canvas);
Matt Pietal0ea391b2019-01-30 10:44:15 -05003753
Matt Pietal9aaf00c2019-04-09 10:09:12 -04003754 int x = getPaddingLeft();
3755 int y = getPaddingRight();
3756 int width = getWidth() - getPaddingRight() - getPaddingLeft();
3757 int height = getHeight() - getPaddingBottom() - getPaddingTop();
Matt Pietal0ea391b2019-01-30 10:44:15 -05003758 if (mExtraImageCount != null) {
Matt Pietal9aaf00c2019-04-09 10:09:12 -04003759 canvas.drawRect(x, y, width, height, mOverlayPaint);
Matt Pietal0ea391b2019-01-30 10:44:15 -05003760
3761 int xPos = canvas.getWidth() / 2;
3762 int yPos = (int) ((canvas.getHeight() / 2.0f)
3763 - ((mTextPaint.descent() + mTextPaint.ascent()) / 2.0f));
3764
3765 canvas.drawText(mExtraImageCount, xPos, yPos, mTextPaint);
3766 }
Matt Pietal9aaf00c2019-04-09 10:09:12 -04003767
3768 canvas.drawRoundRect(x, y, width, height, mRadius, mRadius, mRoundRectPaint);
Matt Pietal26038402019-01-08 07:29:34 -05003769 }
3770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003771}