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