ChooserActivity.java revision a5e50e2612fefd0c50595445dd4f2a68cfa33377
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.internal.app;
18
19import android.animation.ObjectAnimator;
20import android.annotation.NonNull;
21import android.app.Activity;
22import android.app.usage.UsageStatsManager;
23import android.content.ComponentName;
24import android.content.Context;
25import android.content.Intent;
26import android.content.IntentSender;
27import android.content.IntentSender.SendIntentException;
28import android.content.ServiceConnection;
29import android.content.SharedPreferences;
30import android.content.pm.ActivityInfo;
31import android.content.pm.LabeledIntent;
32import android.content.pm.PackageManager;
33import android.content.pm.PackageManager.NameNotFoundException;
34import android.content.pm.ResolveInfo;
35import android.database.DataSetObserver;
36import android.graphics.Color;
37import android.graphics.drawable.Drawable;
38import android.graphics.drawable.Icon;
39import android.os.Bundle;
40import android.os.Environment;
41import android.os.Handler;
42import android.os.IBinder;
43import android.os.Message;
44import android.os.Parcelable;
45import android.os.Process;
46import android.os.RemoteException;
47import android.os.ResultReceiver;
48import android.os.UserHandle;
49import android.os.UserManager;
50import android.os.storage.StorageManager;
51import android.service.chooser.ChooserTarget;
52import android.service.chooser.ChooserTargetService;
53import android.service.chooser.IChooserTargetResult;
54import android.service.chooser.IChooserTargetService;
55import android.text.TextUtils;
56import android.util.FloatProperty;
57import android.util.Log;
58import android.util.Slog;
59import android.view.LayoutInflater;
60import android.view.View;
61import android.view.View.MeasureSpec;
62import android.view.View.OnClickListener;
63import android.view.View.OnLongClickListener;
64import android.view.ViewGroup;
65import android.view.ViewGroup.LayoutParams;
66import android.view.animation.AnimationUtils;
67import android.view.animation.Interpolator;
68import android.widget.AbsListView;
69import android.widget.BaseAdapter;
70import android.widget.ListView;
71import com.android.internal.R;
72import com.android.internal.annotations.VisibleForTesting;
73import com.android.internal.app.ResolverActivity.TargetInfo;
74import com.android.internal.logging.MetricsLogger;
75import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
76import com.google.android.collect.Lists;
77
78import java.io.File;
79import java.util.ArrayList;
80import java.util.Collections;
81import java.util.Comparator;
82import java.util.List;
83
84public class ChooserActivity extends ResolverActivity {
85    private static final String TAG = "ChooserActivity";
86
87    private static final boolean DEBUG = false;
88
89    private static final int QUERY_TARGET_SERVICE_LIMIT = 5;
90    private static final int WATCHDOG_TIMEOUT_MILLIS = 5000;
91
92    private Bundle mReplacementExtras;
93    private IntentSender mChosenComponentSender;
94    private IntentSender mRefinementIntentSender;
95    private RefinementResultReceiver mRefinementResultReceiver;
96    private ChooserTarget[] mCallerChooserTargets;
97    private ComponentName[] mFilteredComponentNames;
98
99    private Intent mReferrerFillInIntent;
100
101    private long mChooserShownTime;
102    private boolean mIsSuccessfullySelected;
103
104    private ChooserListAdapter mChooserListAdapter;
105    private ChooserRowAdapter mChooserRowAdapter;
106
107    private SharedPreferences mPinnedSharedPrefs;
108    private static final float PINNED_TARGET_SCORE_BOOST = 1000.f;
109    private static final float CALLER_TARGET_SCORE_BOOST = 900.f;
110    private static final String PINNED_SHARED_PREFS_NAME = "chooser_pin_settings";
111    private static final String TARGET_DETAILS_FRAGMENT_TAG = "targetDetailsFragment";
112
113    private final List<ChooserTargetServiceConnection> mServiceConnections = new ArrayList<>();
114
115    private static final int CHOOSER_TARGET_SERVICE_RESULT = 1;
116    private static final int CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT = 2;
117
118    private final Handler mChooserHandler = new Handler() {
119        @Override
120        public void handleMessage(Message msg) {
121            switch (msg.what) {
122                case CHOOSER_TARGET_SERVICE_RESULT:
123                    if (DEBUG) Log.d(TAG, "CHOOSER_TARGET_SERVICE_RESULT");
124                    if (isDestroyed()) break;
125                    final ServiceResultInfo sri = (ServiceResultInfo) msg.obj;
126                    if (!mServiceConnections.contains(sri.connection)) {
127                        Log.w(TAG, "ChooserTargetServiceConnection " + sri.connection
128                                + " returned after being removed from active connections."
129                                + " Have you considered returning results faster?");
130                        break;
131                    }
132                    if (sri.resultTargets != null) {
133                        mChooserListAdapter.addServiceResults(sri.originalTarget,
134                                sri.resultTargets);
135                    }
136                    unbindService(sri.connection);
137                    sri.connection.destroy();
138                    mServiceConnections.remove(sri.connection);
139                    if (mServiceConnections.isEmpty()) {
140                        mChooserHandler.removeMessages(CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT);
141                        sendVoiceChoicesIfNeeded();
142                        mChooserListAdapter.setShowServiceTargets(true);
143                    }
144                    break;
145
146                case CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT:
147                    if (DEBUG) {
148                        Log.d(TAG, "CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT; unbinding services");
149                    }
150                    unbindRemainingServices();
151                    sendVoiceChoicesIfNeeded();
152                    mChooserListAdapter.setShowServiceTargets(true);
153                    break;
154
155                default:
156                    super.handleMessage(msg);
157            }
158        }
159    };
160
161    @Override
162    protected void onCreate(Bundle savedInstanceState) {
163        final long intentReceivedTime = System.currentTimeMillis();
164        mIsSuccessfullySelected = false;
165        Intent intent = getIntent();
166        Parcelable targetParcelable = intent.getParcelableExtra(Intent.EXTRA_INTENT);
167        if (!(targetParcelable instanceof Intent)) {
168            Log.w("ChooserActivity", "Target is not an intent: " + targetParcelable);
169            finish();
170            super.onCreate(null);
171            return;
172        }
173        Intent target = (Intent) targetParcelable;
174        if (target != null) {
175            modifyTargetIntent(target);
176        }
177        Parcelable[] targetsParcelable
178                = intent.getParcelableArrayExtra(Intent.EXTRA_ALTERNATE_INTENTS);
179        if (targetsParcelable != null) {
180            final boolean offset = target == null;
181            Intent[] additionalTargets =
182                    new Intent[offset ? targetsParcelable.length - 1 : targetsParcelable.length];
183            for (int i = 0; i < targetsParcelable.length; i++) {
184                if (!(targetsParcelable[i] instanceof Intent)) {
185                    Log.w(TAG, "EXTRA_ALTERNATE_INTENTS array entry #" + i + " is not an Intent: "
186                            + targetsParcelable[i]);
187                    finish();
188                    super.onCreate(null);
189                    return;
190                }
191                final Intent additionalTarget = (Intent) targetsParcelable[i];
192                if (i == 0 && target == null) {
193                    target = additionalTarget;
194                    modifyTargetIntent(target);
195                } else {
196                    additionalTargets[offset ? i - 1 : i] = additionalTarget;
197                    modifyTargetIntent(additionalTarget);
198                }
199            }
200            setAdditionalTargets(additionalTargets);
201        }
202
203        mReplacementExtras = intent.getBundleExtra(Intent.EXTRA_REPLACEMENT_EXTRAS);
204        CharSequence title = intent.getCharSequenceExtra(Intent.EXTRA_TITLE);
205        int defaultTitleRes = 0;
206        if (title == null) {
207            defaultTitleRes = com.android.internal.R.string.chooseActivity;
208        }
209        Parcelable[] pa = intent.getParcelableArrayExtra(Intent.EXTRA_INITIAL_INTENTS);
210        Intent[] initialIntents = null;
211        if (pa != null) {
212            initialIntents = new Intent[pa.length];
213            for (int i=0; i<pa.length; i++) {
214                if (!(pa[i] instanceof Intent)) {
215                    Log.w(TAG, "Initial intent #" + i + " not an Intent: " + pa[i]);
216                    finish();
217                    super.onCreate(null);
218                    return;
219                }
220                final Intent in = (Intent) pa[i];
221                modifyTargetIntent(in);
222                initialIntents[i] = in;
223            }
224        }
225
226        mReferrerFillInIntent = new Intent().putExtra(Intent.EXTRA_REFERRER, getReferrer());
227
228        mChosenComponentSender = intent.getParcelableExtra(
229                Intent.EXTRA_CHOSEN_COMPONENT_INTENT_SENDER);
230        mRefinementIntentSender = intent.getParcelableExtra(
231                Intent.EXTRA_CHOOSER_REFINEMENT_INTENT_SENDER);
232        setSafeForwardingMode(true);
233
234        pa = intent.getParcelableArrayExtra(Intent.EXTRA_EXCLUDE_COMPONENTS);
235        if (pa != null) {
236            ComponentName[] names = new ComponentName[pa.length];
237            for (int i = 0; i < pa.length; i++) {
238                if (!(pa[i] instanceof ComponentName)) {
239                    Log.w(TAG, "Filtered component #" + i + " not a ComponentName: " + pa[i]);
240                    names = null;
241                    break;
242                }
243                names[i] = (ComponentName) pa[i];
244            }
245            mFilteredComponentNames = names;
246        }
247
248        pa = intent.getParcelableArrayExtra(Intent.EXTRA_CHOOSER_TARGETS);
249        if (pa != null) {
250            ChooserTarget[] targets = new ChooserTarget[pa.length];
251            for (int i = 0; i < pa.length; i++) {
252                if (!(pa[i] instanceof ChooserTarget)) {
253                    Log.w(TAG, "Chooser target #" + i + " not a ChooserTarget: " + pa[i]);
254                    targets = null;
255                    break;
256                }
257                targets[i] = (ChooserTarget) pa[i];
258            }
259            mCallerChooserTargets = targets;
260        }
261
262        mPinnedSharedPrefs = getPinnedSharedPrefs(this);
263        super.onCreate(savedInstanceState, target, title, defaultTitleRes, initialIntents,
264                null, false);
265
266        MetricsLogger.action(this, MetricsEvent.ACTION_ACTIVITY_CHOOSER_SHOWN);
267
268        mChooserShownTime = System.currentTimeMillis();
269        final long systemCost = mChooserShownTime - intentReceivedTime;
270        MetricsLogger.histogram(null, "system_cost_for_smart_sharing", (int) systemCost);
271        if (DEBUG) {
272            Log.d(TAG, "System Time Cost is " + systemCost);
273        }
274    }
275
276    static SharedPreferences getPinnedSharedPrefs(Context context) {
277        // The code below is because in the android:ui process, no one can hear you scream.
278        // The package info in the context isn't initialized in the way it is for normal apps,
279        // so the standard, name-based context.getSharedPreferences doesn't work. Instead, we
280        // build the path manually below using the same policy that appears in ContextImpl.
281        // This fails silently under the hood if there's a problem, so if we find ourselves in
282        // the case where we don't have access to credential encrypted storage we just won't
283        // have our pinned target info.
284        final File prefsFile = new File(new File(
285                Environment.getDataUserCePackageDirectory(StorageManager.UUID_PRIVATE_INTERNAL,
286                        context.getUserId(), context.getPackageName()),
287                "shared_prefs"),
288                PINNED_SHARED_PREFS_NAME + ".xml");
289        return context.getSharedPreferences(prefsFile, MODE_PRIVATE);
290    }
291
292    @Override
293    protected void onDestroy() {
294        super.onDestroy();
295        if (mRefinementResultReceiver != null) {
296            mRefinementResultReceiver.destroy();
297            mRefinementResultReceiver = null;
298        }
299        unbindRemainingServices();
300        mChooserHandler.removeMessages(CHOOSER_TARGET_SERVICE_RESULT);
301    }
302
303    @Override
304    public Intent getReplacementIntent(ActivityInfo aInfo, Intent defIntent) {
305        Intent result = defIntent;
306        if (mReplacementExtras != null) {
307            final Bundle replExtras = mReplacementExtras.getBundle(aInfo.packageName);
308            if (replExtras != null) {
309                result = new Intent(defIntent);
310                result.putExtras(replExtras);
311            }
312        }
313        if (aInfo.name.equals(IntentForwarderActivity.FORWARD_INTENT_TO_PARENT)
314                || aInfo.name.equals(IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE)) {
315            result = Intent.createChooser(result,
316                    getIntent().getCharSequenceExtra(Intent.EXTRA_TITLE));
317
318            // Don't auto-launch single intents if the intent is being forwarded. This is done
319            // because automatically launching a resolving application as a response to the user
320            // action of switching accounts is pretty unexpected.
321            result.putExtra(Intent.EXTRA_AUTO_LAUNCH_SINGLE_CHOICE, false);
322        }
323        return result;
324    }
325
326    @Override
327    public void onActivityStarted(TargetInfo cti) {
328        if (mChosenComponentSender != null) {
329            final ComponentName target = cti.getResolvedComponentName();
330            if (target != null) {
331                final Intent fillIn = new Intent().putExtra(Intent.EXTRA_CHOSEN_COMPONENT, target);
332                try {
333                    mChosenComponentSender.sendIntent(this, Activity.RESULT_OK, fillIn, null, null);
334                } catch (IntentSender.SendIntentException e) {
335                    Slog.e(TAG, "Unable to launch supplied IntentSender to report "
336                            + "the chosen component: " + e);
337                }
338            }
339        }
340    }
341
342    @Override
343    public void onPrepareAdapterView(AbsListView adapterView, ResolveListAdapter adapter,
344            boolean alwaysUseOption) {
345        final ListView listView = adapterView instanceof ListView ? (ListView) adapterView : null;
346        mChooserListAdapter = (ChooserListAdapter) adapter;
347        if (mCallerChooserTargets != null && mCallerChooserTargets.length > 0) {
348            mChooserListAdapter.addServiceResults(null, Lists.newArrayList(mCallerChooserTargets));
349        }
350        mChooserRowAdapter = new ChooserRowAdapter(mChooserListAdapter);
351        mChooserRowAdapter.registerDataSetObserver(new OffsetDataSetObserver(adapterView));
352        adapterView.setAdapter(mChooserRowAdapter);
353        if (listView != null) {
354            listView.setItemsCanFocus(true);
355        }
356    }
357
358    @Override
359    public int getLayoutResource() {
360        return R.layout.chooser_grid;
361    }
362
363    @Override
364    public boolean shouldGetActivityMetadata() {
365        return true;
366    }
367
368    @Override
369    public boolean shouldAutoLaunchSingleChoice(TargetInfo target) {
370        return getIntent().getBooleanExtra(Intent.EXTRA_AUTO_LAUNCH_SINGLE_CHOICE,
371                super.shouldAutoLaunchSingleChoice(target));
372    }
373
374    @Override
375    public void showTargetDetails(ResolveInfo ri) {
376        ComponentName name = ri.activityInfo.getComponentName();
377        boolean pinned = mPinnedSharedPrefs.getBoolean(name.flattenToString(), false);
378        ResolverTargetActionsDialogFragment f =
379                new ResolverTargetActionsDialogFragment(ri.loadLabel(getPackageManager()),
380                        name, pinned);
381        f.show(getFragmentManager(), TARGET_DETAILS_FRAGMENT_TAG);
382    }
383
384    private void modifyTargetIntent(Intent in) {
385        final String action = in.getAction();
386        if (Intent.ACTION_SEND.equals(action) ||
387                Intent.ACTION_SEND_MULTIPLE.equals(action)) {
388            in.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
389                    Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
390        }
391    }
392
393    @Override
394    protected boolean onTargetSelected(TargetInfo target, boolean alwaysCheck) {
395        if (mRefinementIntentSender != null) {
396            final Intent fillIn = new Intent();
397            final List<Intent> sourceIntents = target.getAllSourceIntents();
398            if (!sourceIntents.isEmpty()) {
399                fillIn.putExtra(Intent.EXTRA_INTENT, sourceIntents.get(0));
400                if (sourceIntents.size() > 1) {
401                    final Intent[] alts = new Intent[sourceIntents.size() - 1];
402                    for (int i = 1, N = sourceIntents.size(); i < N; i++) {
403                        alts[i - 1] = sourceIntents.get(i);
404                    }
405                    fillIn.putExtra(Intent.EXTRA_ALTERNATE_INTENTS, alts);
406                }
407                if (mRefinementResultReceiver != null) {
408                    mRefinementResultReceiver.destroy();
409                }
410                mRefinementResultReceiver = new RefinementResultReceiver(this, target, null);
411                fillIn.putExtra(Intent.EXTRA_RESULT_RECEIVER,
412                        mRefinementResultReceiver);
413                try {
414                    mRefinementIntentSender.sendIntent(this, 0, fillIn, null, null);
415                    return false;
416                } catch (SendIntentException e) {
417                    Log.e(TAG, "Refinement IntentSender failed to send", e);
418                }
419            }
420        }
421        updateChooserCounts(target, mContentType);
422        return super.onTargetSelected(target, alwaysCheck);
423    }
424
425    @Override
426    public void startSelected(int which, boolean always, boolean filtered) {
427        final long selectionCost = System.currentTimeMillis() - mChooserShownTime;
428        super.startSelected(which, always, filtered);
429
430        if (mChooserListAdapter != null) {
431            // Log the index of which type of target the user picked.
432            // Lower values mean the ranking was better.
433            int cat = 0;
434            int value = which;
435            switch (mChooserListAdapter.getPositionTargetType(which)) {
436                case ChooserListAdapter.TARGET_CALLER:
437                    cat = MetricsEvent.ACTION_ACTIVITY_CHOOSER_PICKED_APP_TARGET;
438                    break;
439                case ChooserListAdapter.TARGET_SERVICE:
440                    cat = MetricsEvent.ACTION_ACTIVITY_CHOOSER_PICKED_SERVICE_TARGET;
441                    value -= mChooserListAdapter.getCallerTargetCount();
442                    break;
443                case ChooserListAdapter.TARGET_STANDARD:
444                    cat = MetricsEvent.ACTION_ACTIVITY_CHOOSER_PICKED_STANDARD_TARGET;
445                    value -= mChooserListAdapter.getCallerTargetCount()
446                            + mChooserListAdapter.getServiceTargetCount();
447                    break;
448            }
449
450            if (cat != 0) {
451                MetricsLogger.action(this, cat, value);
452            }
453
454            if (mIsSuccessfullySelected) {
455                if (DEBUG) {
456                    Log.d(TAG, "User Selection Time Cost is " + selectionCost);
457                    Log.d(TAG, "position of selected app/service/caller is " +
458                            Integer.toString(value));
459                }
460                MetricsLogger.histogram(null, "user_selection_cost_for_smart_sharing",
461                        (int) selectionCost);
462                MetricsLogger.histogram(null, "app_position_for_smart_sharing", value);
463            }
464        }
465    }
466
467    void queryTargetServices(ChooserListAdapter adapter) {
468        final PackageManager pm = getPackageManager();
469        int targetsToQuery = 0;
470        for (int i = 0, N = adapter.getDisplayResolveInfoCount(); i < N; i++) {
471            final DisplayResolveInfo dri = adapter.getDisplayResolveInfo(i);
472            if (adapter.getScore(dri) == 0) {
473                // A score of 0 means the app hasn't been used in some time;
474                // don't query it as it's not likely to be relevant.
475                continue;
476            }
477            final ActivityInfo ai = dri.getResolveInfo().activityInfo;
478            final Bundle md = ai.metaData;
479            final String serviceName = md != null ? convertServiceName(ai.packageName,
480                    md.getString(ChooserTargetService.META_DATA_NAME)) : null;
481            if (serviceName != null) {
482                final ComponentName serviceComponent = new ComponentName(
483                        ai.packageName, serviceName);
484                final Intent serviceIntent = new Intent(ChooserTargetService.SERVICE_INTERFACE)
485                        .setComponent(serviceComponent);
486
487                if (DEBUG) {
488                    Log.d(TAG, "queryTargets found target with service " + serviceComponent);
489                }
490
491                try {
492                    final String perm = pm.getServiceInfo(serviceComponent, 0).permission;
493                    if (!ChooserTargetService.BIND_PERMISSION.equals(perm)) {
494                        Log.w(TAG, "ChooserTargetService " + serviceComponent + " does not require"
495                                + " permission " + ChooserTargetService.BIND_PERMISSION
496                                + " - this service will not be queried for ChooserTargets."
497                                + " add android:permission=\""
498                                + ChooserTargetService.BIND_PERMISSION + "\""
499                                + " to the <service> tag for " + serviceComponent
500                                + " in the manifest.");
501                        continue;
502                    }
503                } catch (NameNotFoundException e) {
504                    Log.e(TAG, "Could not look up service " + serviceComponent
505                            + "; component name not found");
506                    continue;
507                }
508
509                final ChooserTargetServiceConnection conn =
510                        new ChooserTargetServiceConnection(this, dri);
511
512                // Explicitly specify Process.myUserHandle instead of calling bindService
513                // to avoid the warning from calling from the system process without an explicit
514                // user handle
515                if (bindServiceAsUser(serviceIntent, conn, BIND_AUTO_CREATE | BIND_NOT_FOREGROUND,
516                        Process.myUserHandle())) {
517                    if (DEBUG) {
518                        Log.d(TAG, "Binding service connection for target " + dri
519                                + " intent " + serviceIntent);
520                    }
521                    mServiceConnections.add(conn);
522                    targetsToQuery++;
523                }
524            }
525            if (targetsToQuery >= QUERY_TARGET_SERVICE_LIMIT) {
526                if (DEBUG) Log.d(TAG, "queryTargets hit query target limit "
527                        + QUERY_TARGET_SERVICE_LIMIT);
528                break;
529            }
530        }
531
532        if (!mServiceConnections.isEmpty()) {
533            if (DEBUG) Log.d(TAG, "queryTargets setting watchdog timer for "
534                    + WATCHDOG_TIMEOUT_MILLIS + "ms");
535            mChooserHandler.sendEmptyMessageDelayed(CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT,
536                    WATCHDOG_TIMEOUT_MILLIS);
537        } else {
538            sendVoiceChoicesIfNeeded();
539        }
540    }
541
542    private String convertServiceName(String packageName, String serviceName) {
543        if (TextUtils.isEmpty(serviceName)) {
544            return null;
545        }
546
547        final String fullName;
548        if (serviceName.startsWith(".")) {
549            // Relative to the app package. Prepend the app package name.
550            fullName = packageName + serviceName;
551        } else if (serviceName.indexOf('.') >= 0) {
552            // Fully qualified package name.
553            fullName = serviceName;
554        } else {
555            fullName = null;
556        }
557        return fullName;
558    }
559
560    void unbindRemainingServices() {
561        if (DEBUG) {
562            Log.d(TAG, "unbindRemainingServices, " + mServiceConnections.size() + " left");
563        }
564        for (int i = 0, N = mServiceConnections.size(); i < N; i++) {
565            final ChooserTargetServiceConnection conn = mServiceConnections.get(i);
566            if (DEBUG) Log.d(TAG, "unbinding " + conn);
567            unbindService(conn);
568            conn.destroy();
569        }
570        mServiceConnections.clear();
571        mChooserHandler.removeMessages(CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT);
572    }
573
574    public void onSetupVoiceInteraction() {
575        // Do nothing. We'll send the voice stuff ourselves.
576    }
577
578    void updateChooserCounts(TargetInfo info, String annotation) {
579        if (info != null) {
580            UsageStatsManager usageStatsManager =
581                    (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
582            if (usageStatsManager == null) {
583                if (DEBUG) {
584                    Log.d(TAG, "Can not start UsageStatsManager");
585                }
586                return;
587            }
588            final ResolveInfo ri = info.getResolveInfo();
589            if (ri != null && ri.activityInfo != null) {
590                usageStatsManager.reportChooserSelection(ri.activityInfo.packageName, getUserId(),
591                        annotation, null, info.getResolvedIntent().getAction());
592                mResolverComparator.updateModel(info.getResolvedComponentName());
593                if (DEBUG) {
594                    Log.d(TAG, "ResolveInfo Package is" + ri.activityInfo.packageName);
595                }
596            } else if(DEBUG) {
597                Log.d(TAG, "Can not log Chooser Counts of null ResovleInfo");
598            }
599        }
600        mIsSuccessfullySelected = true;
601    }
602
603    void onRefinementResult(TargetInfo selectedTarget, Intent matchingIntent) {
604        if (mRefinementResultReceiver != null) {
605            mRefinementResultReceiver.destroy();
606            mRefinementResultReceiver = null;
607        }
608        if (selectedTarget == null) {
609            Log.e(TAG, "Refinement result intent did not match any known targets; canceling");
610        } else if (!checkTargetSourceIntent(selectedTarget, matchingIntent)) {
611            Log.e(TAG, "onRefinementResult: Selected target " + selectedTarget
612                    + " cannot match refined source intent " + matchingIntent);
613        } else {
614            TargetInfo clonedTarget = selectedTarget.cloneFilledIn(matchingIntent, 0);
615            if (super.onTargetSelected(clonedTarget, false)) {
616                updateChooserCounts(clonedTarget, mContentType);
617                finish();
618                return;
619            }
620        }
621        onRefinementCanceled();
622    }
623
624    void onRefinementCanceled() {
625        if (mRefinementResultReceiver != null) {
626            mRefinementResultReceiver.destroy();
627            mRefinementResultReceiver = null;
628        }
629        finish();
630    }
631
632    boolean checkTargetSourceIntent(TargetInfo target, Intent matchingIntent) {
633        final List<Intent> targetIntents = target.getAllSourceIntents();
634        for (int i = 0, N = targetIntents.size(); i < N; i++) {
635            final Intent targetIntent = targetIntents.get(i);
636            if (targetIntent.filterEquals(matchingIntent)) {
637                return true;
638            }
639        }
640        return false;
641    }
642
643    void filterServiceTargets(String packageName, List<ChooserTarget> targets) {
644        if (targets == null) {
645            return;
646        }
647
648        final PackageManager pm = getPackageManager();
649        for (int i = targets.size() - 1; i >= 0; i--) {
650            final ChooserTarget target = targets.get(i);
651            final ComponentName targetName = target.getComponentName();
652            if (packageName != null && packageName.equals(targetName.getPackageName())) {
653                // Anything from the original target's package is fine.
654                continue;
655            }
656
657            boolean remove;
658            try {
659                final ActivityInfo ai = pm.getActivityInfo(targetName, 0);
660                remove = !ai.exported || ai.permission != null;
661            } catch (NameNotFoundException e) {
662                Log.e(TAG, "Target " + target + " returned by " + packageName
663                        + " component not found");
664                remove = true;
665            }
666
667            if (remove) {
668                targets.remove(i);
669            }
670        }
671    }
672
673    public class ChooserListController extends ResolverListController {
674        public ChooserListController(Context context,
675                PackageManager pm,
676                Intent targetIntent,
677                String referrerPackageName,
678                int launchedFromUid) {
679            super(context, pm, targetIntent, referrerPackageName, launchedFromUid);
680        }
681
682        @Override
683        boolean isComponentPinned(ComponentName name) {
684            return mPinnedSharedPrefs.getBoolean(name.flattenToString(), false);
685        }
686
687        @Override
688        boolean isComponentFiltered(ComponentName name) {
689            if (mFilteredComponentNames == null) {
690                return false;
691            }
692            for (ComponentName filteredComponentName : mFilteredComponentNames) {
693                if (name.equals(filteredComponentName)) {
694                    return true;
695                }
696            }
697            return false;
698        }
699
700        @Override
701        public float getScore(DisplayResolveInfo target) {
702            if (target == null) {
703                return CALLER_TARGET_SCORE_BOOST;
704            }
705            float score = super.getScore(target);
706            if (target.isPinned()) {
707                score += PINNED_TARGET_SCORE_BOOST;
708            }
709            return score;
710        }
711    }
712
713    @Override
714    public ResolveListAdapter createAdapter(Context context, List<Intent> payloadIntents,
715            Intent[] initialIntents, List<ResolveInfo> rList, int launchedFromUid,
716            boolean filterLastUsed) {
717        final ChooserListAdapter adapter = new ChooserListAdapter(context, payloadIntents,
718                initialIntents, rList, launchedFromUid, filterLastUsed, createListController());
719        return adapter;
720    }
721
722    @VisibleForTesting
723    protected ResolverListController createListController() {
724        return new ChooserListController(
725                this,
726                mPm,
727                getTargetIntent(),
728                getReferrerPackageName(),
729                mLaunchedFromUid);
730    }
731
732    final class ChooserTargetInfo implements TargetInfo {
733        private final DisplayResolveInfo mSourceInfo;
734        private final ResolveInfo mBackupResolveInfo;
735        private final ChooserTarget mChooserTarget;
736        private Drawable mBadgeIcon = null;
737        private CharSequence mBadgeContentDescription;
738        private Drawable mDisplayIcon;
739        private final Intent mFillInIntent;
740        private final int mFillInFlags;
741        private final float mModifiedScore;
742
743        public ChooserTargetInfo(DisplayResolveInfo sourceInfo, ChooserTarget chooserTarget,
744                float modifiedScore) {
745            mSourceInfo = sourceInfo;
746            mChooserTarget = chooserTarget;
747            mModifiedScore = modifiedScore;
748            if (sourceInfo != null) {
749                final ResolveInfo ri = sourceInfo.getResolveInfo();
750                if (ri != null) {
751                    final ActivityInfo ai = ri.activityInfo;
752                    if (ai != null && ai.applicationInfo != null) {
753                        final PackageManager pm = getPackageManager();
754                        mBadgeIcon = pm.getApplicationIcon(ai.applicationInfo);
755                        mBadgeContentDescription = pm.getApplicationLabel(ai.applicationInfo);
756                    }
757                }
758            }
759            final Icon icon = chooserTarget.getIcon();
760            // TODO do this in the background
761            mDisplayIcon = icon != null ? icon.loadDrawable(ChooserActivity.this) : null;
762
763            if (sourceInfo != null) {
764                mBackupResolveInfo = null;
765            } else {
766                mBackupResolveInfo = getPackageManager().resolveActivity(getResolvedIntent(), 0);
767            }
768
769            mFillInIntent = null;
770            mFillInFlags = 0;
771        }
772
773        private ChooserTargetInfo(ChooserTargetInfo other, Intent fillInIntent, int flags) {
774            mSourceInfo = other.mSourceInfo;
775            mBackupResolveInfo = other.mBackupResolveInfo;
776            mChooserTarget = other.mChooserTarget;
777            mBadgeIcon = other.mBadgeIcon;
778            mBadgeContentDescription = other.mBadgeContentDescription;
779            mDisplayIcon = other.mDisplayIcon;
780            mFillInIntent = fillInIntent;
781            mFillInFlags = flags;
782            mModifiedScore = other.mModifiedScore;
783        }
784
785        public float getModifiedScore() {
786            return mModifiedScore;
787        }
788
789        @Override
790        public Intent getResolvedIntent() {
791            if (mSourceInfo != null) {
792                return mSourceInfo.getResolvedIntent();
793            }
794
795            final Intent targetIntent = new Intent(getTargetIntent());
796            targetIntent.setComponent(mChooserTarget.getComponentName());
797            targetIntent.putExtras(mChooserTarget.getIntentExtras());
798            return targetIntent;
799        }
800
801        @Override
802        public ComponentName getResolvedComponentName() {
803            if (mSourceInfo != null) {
804                return mSourceInfo.getResolvedComponentName();
805            } else if (mBackupResolveInfo != null) {
806                return new ComponentName(mBackupResolveInfo.activityInfo.packageName,
807                        mBackupResolveInfo.activityInfo.name);
808            }
809            return null;
810        }
811
812        private Intent getBaseIntentToSend() {
813            Intent result = getResolvedIntent();
814            if (result == null) {
815                Log.e(TAG, "ChooserTargetInfo: no base intent available to send");
816            } else {
817                result = new Intent(result);
818                if (mFillInIntent != null) {
819                    result.fillIn(mFillInIntent, mFillInFlags);
820                }
821                result.fillIn(mReferrerFillInIntent, 0);
822            }
823            return result;
824        }
825
826        @Override
827        public boolean start(Activity activity, Bundle options) {
828            throw new RuntimeException("ChooserTargets should be started as caller.");
829        }
830
831        @Override
832        public boolean startAsCaller(Activity activity, Bundle options, int userId) {
833            final Intent intent = getBaseIntentToSend();
834            if (intent == null) {
835                return false;
836            }
837            intent.setComponent(mChooserTarget.getComponentName());
838            intent.putExtras(mChooserTarget.getIntentExtras());
839
840            // Important: we will ignore the target security checks in ActivityManager
841            // if and only if the ChooserTarget's target package is the same package
842            // where we got the ChooserTargetService that provided it. This lets a
843            // ChooserTargetService provide a non-exported or permission-guarded target
844            // to the chooser for the user to pick.
845            //
846            // If mSourceInfo is null, we got this ChooserTarget from the caller or elsewhere
847            // so we'll obey the caller's normal security checks.
848            final boolean ignoreTargetSecurity = mSourceInfo != null
849                    && mSourceInfo.getResolvedComponentName().getPackageName()
850                    .equals(mChooserTarget.getComponentName().getPackageName());
851            activity.startActivityAsCaller(intent, options, ignoreTargetSecurity, userId);
852            return true;
853        }
854
855        @Override
856        public boolean startAsUser(Activity activity, Bundle options, UserHandle user) {
857            throw new RuntimeException("ChooserTargets should be started as caller.");
858        }
859
860        @Override
861        public ResolveInfo getResolveInfo() {
862            return mSourceInfo != null ? mSourceInfo.getResolveInfo() : mBackupResolveInfo;
863        }
864
865        @Override
866        public CharSequence getDisplayLabel() {
867            return mChooserTarget.getTitle();
868        }
869
870        @Override
871        public CharSequence getExtendedInfo() {
872            // ChooserTargets have badge icons, so we won't show the extended info to disambiguate.
873            return null;
874        }
875
876        @Override
877        public Drawable getDisplayIcon() {
878            return mDisplayIcon;
879        }
880
881        @Override
882        public Drawable getBadgeIcon() {
883            return mBadgeIcon;
884        }
885
886        @Override
887        public CharSequence getBadgeContentDescription() {
888            return mBadgeContentDescription;
889        }
890
891        @Override
892        public TargetInfo cloneFilledIn(Intent fillInIntent, int flags) {
893            return new ChooserTargetInfo(this, fillInIntent, flags);
894        }
895
896        @Override
897        public List<Intent> getAllSourceIntents() {
898            final List<Intent> results = new ArrayList<>();
899            if (mSourceInfo != null) {
900                // We only queried the service for the first one in our sourceinfo.
901                results.add(mSourceInfo.getAllSourceIntents().get(0));
902            }
903            return results;
904        }
905
906        @Override
907        public boolean isPinned() {
908            return mSourceInfo != null ? mSourceInfo.isPinned() : false;
909        }
910    }
911
912    public class ChooserListAdapter extends ResolveListAdapter {
913        public static final int TARGET_BAD = -1;
914        public static final int TARGET_CALLER = 0;
915        public static final int TARGET_SERVICE = 1;
916        public static final int TARGET_STANDARD = 2;
917
918        private static final int MAX_SERVICE_TARGETS = 8;
919        private static final int MAX_TARGETS_PER_SERVICE = 4;
920
921        private final List<ChooserTargetInfo> mServiceTargets = new ArrayList<>();
922        private final List<TargetInfo> mCallerTargets = new ArrayList<>();
923        private boolean mShowServiceTargets;
924
925        private float mLateFee = 1.f;
926
927        private final BaseChooserTargetComparator mBaseTargetComparator
928                = new BaseChooserTargetComparator();
929
930        public ChooserListAdapter(Context context, List<Intent> payloadIntents,
931                Intent[] initialIntents, List<ResolveInfo> rList, int launchedFromUid,
932                boolean filterLastUsed, ResolverListController resolverListController) {
933            // Don't send the initial intents through the shared ResolverActivity path,
934            // we want to separate them into a different section.
935            super(context, payloadIntents, null, rList, launchedFromUid, filterLastUsed,
936                    resolverListController);
937
938            if (initialIntents != null) {
939                final PackageManager pm = getPackageManager();
940                for (int i = 0; i < initialIntents.length; i++) {
941                    final Intent ii = initialIntents[i];
942                    if (ii == null) {
943                        continue;
944                    }
945
946                    // We reimplement Intent#resolveActivityInfo here because if we have an
947                    // implicit intent, we want the ResolveInfo returned by PackageManager
948                    // instead of one we reconstruct ourselves. The ResolveInfo returned might
949                    // have extra metadata and resolvePackageName set and we want to respect that.
950                    ResolveInfo ri = null;
951                    ActivityInfo ai = null;
952                    final ComponentName cn = ii.getComponent();
953                    if (cn != null) {
954                        try {
955                            ai = pm.getActivityInfo(ii.getComponent(), 0);
956                            ri = new ResolveInfo();
957                            ri.activityInfo = ai;
958                        } catch (PackageManager.NameNotFoundException ignored) {
959                            // ai will == null below
960                        }
961                    }
962                    if (ai == null) {
963                        ri = pm.resolveActivity(ii, PackageManager.MATCH_DEFAULT_ONLY);
964                        ai = ri != null ? ri.activityInfo : null;
965                    }
966                    if (ai == null) {
967                        Log.w(TAG, "No activity found for " + ii);
968                        continue;
969                    }
970                    UserManager userManager =
971                            (UserManager) getSystemService(Context.USER_SERVICE);
972                    if (ii instanceof LabeledIntent) {
973                        LabeledIntent li = (LabeledIntent)ii;
974                        ri.resolvePackageName = li.getSourcePackage();
975                        ri.labelRes = li.getLabelResource();
976                        ri.nonLocalizedLabel = li.getNonLocalizedLabel();
977                        ri.icon = li.getIconResource();
978                        ri.iconResourceId = ri.icon;
979                    }
980                    if (userManager.isManagedProfile()) {
981                        ri.noResourceId = true;
982                        ri.icon = 0;
983                    }
984                    mCallerTargets.add(new DisplayResolveInfo(ii, ri,
985                            ri.loadLabel(pm), null, ii));
986                }
987            }
988        }
989
990        @Override
991        public boolean showsExtendedInfo(TargetInfo info) {
992            // We have badges so we don't need this text shown.
993            return false;
994        }
995
996        @Override
997        public boolean isComponentPinned(ComponentName name) {
998            return mPinnedSharedPrefs.getBoolean(name.flattenToString(), false);
999        }
1000
1001        @Override
1002        public View onCreateView(ViewGroup parent) {
1003            return mInflater.inflate(
1004                    com.android.internal.R.layout.resolve_grid_item, parent, false);
1005        }
1006
1007        @Override
1008        public void onListRebuilt() {
1009            if (mServiceTargets != null) {
1010                pruneServiceTargets();
1011            }
1012            if (DEBUG) Log.d(TAG, "List built querying services");
1013            queryTargetServices(this);
1014        }
1015
1016        @Override
1017        public boolean shouldGetResolvedFilter() {
1018            return true;
1019        }
1020
1021        @Override
1022        public int getCount() {
1023            return super.getCount() + getServiceTargetCount() + getCallerTargetCount();
1024        }
1025
1026        @Override
1027        public int getUnfilteredCount() {
1028            return super.getUnfilteredCount() + getServiceTargetCount() + getCallerTargetCount();
1029        }
1030
1031        public int getCallerTargetCount() {
1032            return mCallerTargets.size();
1033        }
1034
1035        public int getServiceTargetCount() {
1036            if (!mShowServiceTargets) {
1037                return 0;
1038            }
1039            return Math.min(mServiceTargets.size(), MAX_SERVICE_TARGETS);
1040        }
1041
1042        public int getStandardTargetCount() {
1043            return super.getCount();
1044        }
1045
1046        public int getPositionTargetType(int position) {
1047            int offset = 0;
1048
1049            final int callerTargetCount = getCallerTargetCount();
1050            if (position < callerTargetCount) {
1051                return TARGET_CALLER;
1052            }
1053            offset += callerTargetCount;
1054
1055            final int serviceTargetCount = getServiceTargetCount();
1056            if (position - offset < serviceTargetCount) {
1057                return TARGET_SERVICE;
1058            }
1059            offset += serviceTargetCount;
1060
1061            final int standardTargetCount = super.getCount();
1062            if (position - offset < standardTargetCount) {
1063                return TARGET_STANDARD;
1064            }
1065
1066            return TARGET_BAD;
1067        }
1068
1069        @Override
1070        public TargetInfo getItem(int position) {
1071            return targetInfoForPosition(position, true);
1072        }
1073
1074        @Override
1075        public TargetInfo targetInfoForPosition(int position, boolean filtered) {
1076            int offset = 0;
1077
1078            final int callerTargetCount = getCallerTargetCount();
1079            if (position < callerTargetCount) {
1080                return mCallerTargets.get(position);
1081            }
1082            offset += callerTargetCount;
1083
1084            final int serviceTargetCount = getServiceTargetCount();
1085            if (position - offset < serviceTargetCount) {
1086                return mServiceTargets.get(position - offset);
1087            }
1088            offset += serviceTargetCount;
1089
1090            return filtered ? super.getItem(position - offset)
1091                    : getDisplayInfoAt(position - offset);
1092        }
1093
1094        public void addServiceResults(DisplayResolveInfo origTarget, List<ChooserTarget> targets) {
1095            if (DEBUG) Log.d(TAG, "addServiceResults " + origTarget + ", " + targets.size()
1096                    + " targets");
1097            final float parentScore = getScore(origTarget);
1098            Collections.sort(targets, mBaseTargetComparator);
1099            float lastScore = 0;
1100            for (int i = 0, N = Math.min(targets.size(), MAX_TARGETS_PER_SERVICE); i < N; i++) {
1101                final ChooserTarget target = targets.get(i);
1102                float targetScore = target.getScore();
1103                targetScore *= parentScore;
1104                targetScore *= mLateFee;
1105                if (i > 0 && targetScore >= lastScore) {
1106                    // Apply a decay so that the top app can't crowd out everything else.
1107                    // This incents ChooserTargetServices to define what's truly better.
1108                    targetScore = lastScore * 0.95f;
1109                }
1110                insertServiceTarget(new ChooserTargetInfo(origTarget, target, targetScore));
1111
1112                if (DEBUG) {
1113                    Log.d(TAG, " => " + target.toString() + " score=" + targetScore
1114                            + " base=" + target.getScore()
1115                            + " lastScore=" + lastScore
1116                            + " parentScore=" + parentScore
1117                            + " lateFee=" + mLateFee);
1118                }
1119
1120                lastScore = targetScore;
1121            }
1122
1123            mLateFee *= 0.95f;
1124
1125            notifyDataSetChanged();
1126        }
1127
1128        /**
1129         * Set to true to reveal all service targets at once.
1130         */
1131        public void setShowServiceTargets(boolean show) {
1132            mShowServiceTargets = show;
1133            notifyDataSetChanged();
1134        }
1135
1136        private void insertServiceTarget(ChooserTargetInfo chooserTargetInfo) {
1137            final float newScore = chooserTargetInfo.getModifiedScore();
1138            for (int i = 0, N = mServiceTargets.size(); i < N; i++) {
1139                final ChooserTargetInfo serviceTarget = mServiceTargets.get(i);
1140                if (newScore > serviceTarget.getModifiedScore()) {
1141                    mServiceTargets.add(i, chooserTargetInfo);
1142                    return;
1143                }
1144            }
1145            mServiceTargets.add(chooserTargetInfo);
1146        }
1147
1148        private void pruneServiceTargets() {
1149            if (DEBUG) Log.d(TAG, "pruneServiceTargets");
1150            for (int i = mServiceTargets.size() - 1; i >= 0; i--) {
1151                final ChooserTargetInfo cti = mServiceTargets.get(i);
1152                if (!hasResolvedTarget(cti.getResolveInfo())) {
1153                    if (DEBUG) Log.d(TAG, " => " + i + " " + cti);
1154                    mServiceTargets.remove(i);
1155                }
1156            }
1157        }
1158    }
1159
1160    static class BaseChooserTargetComparator implements Comparator<ChooserTarget> {
1161        @Override
1162        public int compare(ChooserTarget lhs, ChooserTarget rhs) {
1163            // Descending order
1164            return (int) Math.signum(rhs.getScore() - lhs.getScore());
1165        }
1166    }
1167
1168    static class RowScale {
1169        private static final int DURATION = 400;
1170
1171        float mScale;
1172        ChooserRowAdapter mAdapter;
1173        private final ObjectAnimator mAnimator;
1174
1175        public static final FloatProperty<RowScale> PROPERTY =
1176                new FloatProperty<RowScale>("scale") {
1177            @Override
1178            public void setValue(RowScale object, float value) {
1179                object.mScale = value;
1180                object.mAdapter.notifyDataSetChanged();
1181            }
1182
1183            @Override
1184            public Float get(RowScale object) {
1185                return object.mScale;
1186            }
1187        };
1188
1189        public RowScale(@NonNull ChooserRowAdapter adapter, float from, float to) {
1190            mAdapter = adapter;
1191            mScale = from;
1192            if (from == to) {
1193                mAnimator = null;
1194                return;
1195            }
1196
1197            mAnimator = ObjectAnimator.ofFloat(this, PROPERTY, from, to).setDuration(DURATION);
1198        }
1199
1200        public RowScale setInterpolator(Interpolator interpolator) {
1201            if (mAnimator != null) {
1202                mAnimator.setInterpolator(interpolator);
1203            }
1204            return this;
1205        }
1206
1207        public float get() {
1208            return mScale;
1209        }
1210
1211        public void startAnimation() {
1212            if (mAnimator != null) {
1213                mAnimator.start();
1214            }
1215        }
1216
1217        public void cancelAnimation() {
1218            if (mAnimator != null) {
1219                mAnimator.cancel();
1220            }
1221        }
1222    }
1223
1224    class ChooserRowAdapter extends BaseAdapter {
1225        private ChooserListAdapter mChooserListAdapter;
1226        private final LayoutInflater mLayoutInflater;
1227        private final int mColumnCount = 4;
1228        private RowScale[] mServiceTargetScale;
1229        private final Interpolator mInterpolator;
1230
1231        public ChooserRowAdapter(ChooserListAdapter wrappedAdapter) {
1232            mChooserListAdapter = wrappedAdapter;
1233            mLayoutInflater = LayoutInflater.from(ChooserActivity.this);
1234
1235            mInterpolator = AnimationUtils.loadInterpolator(ChooserActivity.this,
1236                    android.R.interpolator.decelerate_quint);
1237
1238            wrappedAdapter.registerDataSetObserver(new DataSetObserver() {
1239                @Override
1240                public void onChanged() {
1241                    super.onChanged();
1242                    final int rcount = getServiceTargetRowCount();
1243                    if (mServiceTargetScale == null
1244                            || mServiceTargetScale.length != rcount) {
1245                        RowScale[] old = mServiceTargetScale;
1246                        int oldRCount = old != null ? old.length : 0;
1247                        mServiceTargetScale = new RowScale[rcount];
1248                        if (old != null && rcount > 0) {
1249                            System.arraycopy(old, 0, mServiceTargetScale, 0,
1250                                    Math.min(old.length, rcount));
1251                        }
1252
1253                        for (int i = rcount; i < oldRCount; i++) {
1254                            old[i].cancelAnimation();
1255                        }
1256
1257                        for (int i = oldRCount; i < rcount; i++) {
1258                            final RowScale rs = new RowScale(ChooserRowAdapter.this, 0.f, 1.f)
1259                                    .setInterpolator(mInterpolator);
1260                            mServiceTargetScale[i] = rs;
1261                        }
1262
1263                        // Start the animations in a separate loop.
1264                        // The process of starting animations will result in
1265                        // binding views to set up initial values, and we must
1266                        // have ALL of the new RowScale objects created above before
1267                        // we get started.
1268                        for (int i = oldRCount; i < rcount; i++) {
1269                            mServiceTargetScale[i].startAnimation();
1270                        }
1271                    }
1272
1273                    notifyDataSetChanged();
1274                }
1275
1276                @Override
1277                public void onInvalidated() {
1278                    super.onInvalidated();
1279                    notifyDataSetInvalidated();
1280                    if (mServiceTargetScale != null) {
1281                        for (RowScale rs : mServiceTargetScale) {
1282                            rs.cancelAnimation();
1283                        }
1284                    }
1285                }
1286            });
1287        }
1288
1289        private float getRowScale(int rowPosition) {
1290            final int start = getCallerTargetRowCount();
1291            final int end = start + getServiceTargetRowCount();
1292            if (rowPosition >= start && rowPosition < end) {
1293                return mServiceTargetScale[rowPosition - start].get();
1294            }
1295            return 1.f;
1296        }
1297
1298        @Override
1299        public int getCount() {
1300            return (int) (
1301                    getCallerTargetRowCount()
1302                    + getServiceTargetRowCount()
1303                    + Math.ceil((float) mChooserListAdapter.getStandardTargetCount() / mColumnCount)
1304            );
1305        }
1306
1307        public int getCallerTargetRowCount() {
1308            return (int) Math.ceil(
1309                    (float) mChooserListAdapter.getCallerTargetCount() / mColumnCount);
1310        }
1311
1312        public int getServiceTargetRowCount() {
1313            return (int) Math.ceil(
1314                    (float) mChooserListAdapter.getServiceTargetCount() / mColumnCount);
1315        }
1316
1317        @Override
1318        public Object getItem(int position) {
1319            // We have nothing useful to return here.
1320            return position;
1321        }
1322
1323        @Override
1324        public long getItemId(int position) {
1325            return position;
1326        }
1327
1328        @Override
1329        public View getView(int position, View convertView, ViewGroup parent) {
1330            final RowViewHolder holder;
1331            if (convertView == null) {
1332                holder = createViewHolder(parent);
1333            } else {
1334                holder = (RowViewHolder) convertView.getTag();
1335            }
1336            bindViewHolder(position, holder);
1337
1338            return holder.row;
1339        }
1340
1341        RowViewHolder createViewHolder(ViewGroup parent) {
1342            final ViewGroup row = (ViewGroup) mLayoutInflater.inflate(R.layout.chooser_row,
1343                    parent, false);
1344            final RowViewHolder holder = new RowViewHolder(row, mColumnCount);
1345            final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
1346
1347            for (int i = 0; i < mColumnCount; i++) {
1348                final View v = mChooserListAdapter.createView(row);
1349                final int column = i;
1350                v.setOnClickListener(new OnClickListener() {
1351                    @Override
1352                    public void onClick(View v) {
1353                        startSelected(holder.itemIndices[column], false, true);
1354                    }
1355                });
1356                v.setOnLongClickListener(new OnLongClickListener() {
1357                    @Override
1358                    public boolean onLongClick(View v) {
1359                        showTargetDetails(
1360                                mChooserListAdapter.resolveInfoForPosition(
1361                                        holder.itemIndices[column], true));
1362                        return true;
1363                    }
1364                });
1365                row.addView(v);
1366                holder.cells[i] = v;
1367
1368                // Force height to be a given so we don't have visual disruption during scaling.
1369                LayoutParams lp = v.getLayoutParams();
1370                v.measure(spec, spec);
1371                if (lp == null) {
1372                    lp = new LayoutParams(LayoutParams.MATCH_PARENT, v.getMeasuredHeight());
1373                    row.setLayoutParams(lp);
1374                } else {
1375                    lp.height = v.getMeasuredHeight();
1376                }
1377            }
1378
1379            // Pre-measure so we can scale later.
1380            holder.measure();
1381            LayoutParams lp = row.getLayoutParams();
1382            if (lp == null) {
1383                lp = new LayoutParams(LayoutParams.MATCH_PARENT, holder.measuredRowHeight);
1384                row.setLayoutParams(lp);
1385            } else {
1386                lp.height = holder.measuredRowHeight;
1387            }
1388            row.setTag(holder);
1389            return holder;
1390        }
1391
1392        void bindViewHolder(int rowPosition, RowViewHolder holder) {
1393            final int start = getFirstRowPosition(rowPosition);
1394            final int startType = mChooserListAdapter.getPositionTargetType(start);
1395
1396            int end = start + mColumnCount - 1;
1397            while (mChooserListAdapter.getPositionTargetType(end) != startType && end >= start) {
1398                end--;
1399            }
1400
1401            if (startType == ChooserListAdapter.TARGET_SERVICE) {
1402                holder.row.setBackgroundColor(
1403                        getColor(R.color.chooser_service_row_background_color));
1404            } else {
1405                holder.row.setBackgroundColor(Color.TRANSPARENT);
1406            }
1407
1408            final int oldHeight = holder.row.getLayoutParams().height;
1409            holder.row.getLayoutParams().height = Math.max(1,
1410                    (int) (holder.measuredRowHeight * getRowScale(rowPosition)));
1411            if (holder.row.getLayoutParams().height != oldHeight) {
1412                holder.row.requestLayout();
1413            }
1414
1415            for (int i = 0; i < mColumnCount; i++) {
1416                final View v = holder.cells[i];
1417                if (start + i <= end) {
1418                    v.setVisibility(View.VISIBLE);
1419                    holder.itemIndices[i] = start + i;
1420                    mChooserListAdapter.bindView(holder.itemIndices[i], v);
1421                } else {
1422                    v.setVisibility(View.GONE);
1423                }
1424            }
1425        }
1426
1427        int getFirstRowPosition(int row) {
1428            final int callerCount = mChooserListAdapter.getCallerTargetCount();
1429            final int callerRows = (int) Math.ceil((float) callerCount / mColumnCount);
1430
1431            if (row < callerRows) {
1432                return row * mColumnCount;
1433            }
1434
1435            final int serviceCount = mChooserListAdapter.getServiceTargetCount();
1436            final int serviceRows = (int) Math.ceil((float) serviceCount / mColumnCount);
1437
1438            if (row < callerRows + serviceRows) {
1439                return callerCount + (row - callerRows) * mColumnCount;
1440            }
1441
1442            return callerCount + serviceCount
1443                    + (row - callerRows - serviceRows) * mColumnCount;
1444        }
1445    }
1446
1447    static class RowViewHolder {
1448        final View[] cells;
1449        final ViewGroup row;
1450        int measuredRowHeight;
1451        int[] itemIndices;
1452
1453        public RowViewHolder(ViewGroup row, int cellCount) {
1454            this.row = row;
1455            this.cells = new View[cellCount];
1456            this.itemIndices = new int[cellCount];
1457        }
1458
1459        public void measure() {
1460            final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
1461            row.measure(spec, spec);
1462            measuredRowHeight = row.getMeasuredHeight();
1463        }
1464    }
1465
1466    static class ChooserTargetServiceConnection implements ServiceConnection {
1467        private DisplayResolveInfo mOriginalTarget;
1468        private ComponentName mConnectedComponent;
1469        private ChooserActivity mChooserActivity;
1470        private final Object mLock = new Object();
1471
1472        private final IChooserTargetResult mChooserTargetResult = new IChooserTargetResult.Stub() {
1473            @Override
1474            public void sendResult(List<ChooserTarget> targets) throws RemoteException {
1475                synchronized (mLock) {
1476                    if (mChooserActivity == null) {
1477                        Log.e(TAG, "destroyed ChooserTargetServiceConnection received result from "
1478                                + mConnectedComponent + "; ignoring...");
1479                        return;
1480                    }
1481                    mChooserActivity.filterServiceTargets(
1482                            mOriginalTarget.getResolveInfo().activityInfo.packageName, targets);
1483                    final Message msg = Message.obtain();
1484                    msg.what = CHOOSER_TARGET_SERVICE_RESULT;
1485                    msg.obj = new ServiceResultInfo(mOriginalTarget, targets,
1486                            ChooserTargetServiceConnection.this);
1487                    mChooserActivity.mChooserHandler.sendMessage(msg);
1488                }
1489            }
1490        };
1491
1492        public ChooserTargetServiceConnection(ChooserActivity chooserActivity,
1493                DisplayResolveInfo dri) {
1494            mChooserActivity = chooserActivity;
1495            mOriginalTarget = dri;
1496        }
1497
1498        @Override
1499        public void onServiceConnected(ComponentName name, IBinder service) {
1500            if (DEBUG) Log.d(TAG, "onServiceConnected: " + name);
1501            synchronized (mLock) {
1502                if (mChooserActivity == null) {
1503                    Log.e(TAG, "destroyed ChooserTargetServiceConnection got onServiceConnected");
1504                    return;
1505                }
1506
1507                final IChooserTargetService icts = IChooserTargetService.Stub.asInterface(service);
1508                try {
1509                    icts.getChooserTargets(mOriginalTarget.getResolvedComponentName(),
1510                            mOriginalTarget.getResolveInfo().filter, mChooserTargetResult);
1511                } catch (RemoteException e) {
1512                    Log.e(TAG, "Querying ChooserTargetService " + name + " failed.", e);
1513                    mChooserActivity.unbindService(this);
1514                    destroy();
1515                    mChooserActivity.mServiceConnections.remove(this);
1516                }
1517            }
1518        }
1519
1520        @Override
1521        public void onServiceDisconnected(ComponentName name) {
1522            if (DEBUG) Log.d(TAG, "onServiceDisconnected: " + name);
1523            synchronized (mLock) {
1524                if (mChooserActivity == null) {
1525                    Log.e(TAG,
1526                            "destroyed ChooserTargetServiceConnection got onServiceDisconnected");
1527                    return;
1528                }
1529
1530                mChooserActivity.unbindService(this);
1531                destroy();
1532                mChooserActivity.mServiceConnections.remove(this);
1533                if (mChooserActivity.mServiceConnections.isEmpty()) {
1534                    mChooserActivity.mChooserHandler.removeMessages(
1535                            CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT);
1536                    mChooserActivity.sendVoiceChoicesIfNeeded();
1537                }
1538                mConnectedComponent = null;
1539            }
1540        }
1541
1542        public void destroy() {
1543            synchronized (mLock) {
1544                mChooserActivity = null;
1545                mOriginalTarget = null;
1546            }
1547        }
1548
1549        @Override
1550        public String toString() {
1551            return "ChooserTargetServiceConnection{service="
1552                    + mConnectedComponent + ", activity="
1553                    + (mOriginalTarget != null
1554                    ? mOriginalTarget.getResolveInfo().activityInfo.toString()
1555                    : "<connection destroyed>") + "}";
1556        }
1557    }
1558
1559    static class ServiceResultInfo {
1560        public final DisplayResolveInfo originalTarget;
1561        public final List<ChooserTarget> resultTargets;
1562        public final ChooserTargetServiceConnection connection;
1563
1564        public ServiceResultInfo(DisplayResolveInfo ot, List<ChooserTarget> rt,
1565                ChooserTargetServiceConnection c) {
1566            originalTarget = ot;
1567            resultTargets = rt;
1568            connection = c;
1569        }
1570    }
1571
1572    static class RefinementResultReceiver extends ResultReceiver {
1573        private ChooserActivity mChooserActivity;
1574        private TargetInfo mSelectedTarget;
1575
1576        public RefinementResultReceiver(ChooserActivity host, TargetInfo target,
1577                Handler handler) {
1578            super(handler);
1579            mChooserActivity = host;
1580            mSelectedTarget = target;
1581        }
1582
1583        @Override
1584        protected void onReceiveResult(int resultCode, Bundle resultData) {
1585            if (mChooserActivity == null) {
1586                Log.e(TAG, "Destroyed RefinementResultReceiver received a result");
1587                return;
1588            }
1589            if (resultData == null) {
1590                Log.e(TAG, "RefinementResultReceiver received null resultData");
1591                return;
1592            }
1593
1594            switch (resultCode) {
1595                case RESULT_CANCELED:
1596                    mChooserActivity.onRefinementCanceled();
1597                    break;
1598                case RESULT_OK:
1599                    Parcelable intentParcelable = resultData.getParcelable(Intent.EXTRA_INTENT);
1600                    if (intentParcelable instanceof Intent) {
1601                        mChooserActivity.onRefinementResult(mSelectedTarget,
1602                                (Intent) intentParcelable);
1603                    } else {
1604                        Log.e(TAG, "RefinementResultReceiver received RESULT_OK but no Intent"
1605                                + " in resultData with key Intent.EXTRA_INTENT");
1606                    }
1607                    break;
1608                default:
1609                    Log.w(TAG, "Unknown result code " + resultCode
1610                            + " sent to RefinementResultReceiver");
1611                    break;
1612            }
1613        }
1614
1615        public void destroy() {
1616            mChooserActivity = null;
1617            mSelectedTarget = null;
1618        }
1619    }
1620
1621    class OffsetDataSetObserver extends DataSetObserver {
1622        private final AbsListView mListView;
1623        private int mCachedViewType = -1;
1624        private View mCachedView;
1625
1626        public OffsetDataSetObserver(AbsListView listView) {
1627            mListView = listView;
1628        }
1629
1630        @Override
1631        public void onChanged() {
1632            if (mResolverDrawerLayout == null) {
1633                return;
1634            }
1635
1636            final int chooserTargetRows = mChooserRowAdapter.getServiceTargetRowCount();
1637            int offset = 0;
1638            for (int i = 0; i < chooserTargetRows; i++)  {
1639                final int pos = mChooserRowAdapter.getCallerTargetRowCount() + i;
1640                final int vt = mChooserRowAdapter.getItemViewType(pos);
1641                if (vt != mCachedViewType) {
1642                    mCachedView = null;
1643                }
1644                final View v = mChooserRowAdapter.getView(pos, mCachedView, mListView);
1645                int height = ((RowViewHolder) (v.getTag())).measuredRowHeight;
1646
1647                offset += (int) (height * mChooserRowAdapter.getRowScale(pos));
1648
1649                if (vt >= 0) {
1650                    mCachedViewType = vt;
1651                    mCachedView = v;
1652                } else {
1653                    mCachedViewType = -1;
1654                }
1655            }
1656
1657            mResolverDrawerLayout.setCollapsibleHeightReserved(offset);
1658        }
1659    }
1660}
1661