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 com.android.internal.R;
20import com.android.internal.content.PackageMonitor;
21
22import android.content.ComponentName;
23import android.content.Context;
24import android.content.DialogInterface;
25import android.content.Intent;
26import android.content.IntentFilter;
27import android.content.pm.ActivityInfo;
28import android.content.pm.LabeledIntent;
29import android.content.pm.PackageManager;
30import android.content.pm.ResolveInfo;
31import android.graphics.drawable.Drawable;
32import android.net.Uri;
33import android.os.Bundle;
34import android.os.PatternMatcher;
35import android.util.Log;
36import android.view.View;
37import android.view.ViewGroup;
38import android.view.LayoutInflater;
39import android.widget.BaseAdapter;
40import android.widget.CheckBox;
41import android.widget.CompoundButton;
42import android.widget.ImageView;
43import android.widget.TextView;
44import java.util.ArrayList;
45import java.util.Collections;
46import java.util.HashSet;
47import java.util.Iterator;
48import java.util.List;
49import java.util.Set;
50
51/**
52 * This activity is displayed when the system attempts to start an Intent for
53 * which there is more than one matching activity, allowing the user to decide
54 * which to go to.  It is not normally used directly by application developers.
55 */
56public class ResolverActivity extends AlertActivity implements
57        DialogInterface.OnClickListener, CheckBox.OnCheckedChangeListener {
58    private ResolveListAdapter mAdapter;
59    private CheckBox mAlwaysCheck;
60    private TextView mClearDefaultHint;
61    private PackageManager mPm;
62
63    private final PackageMonitor mPackageMonitor = new PackageMonitor() {
64        @Override public void onSomePackagesChanged() {
65            mAdapter.handlePackagesChanged();
66        }
67    };
68
69    private Intent makeMyIntent() {
70        Intent intent = new Intent(getIntent());
71        // The resolver activity is set to be hidden from recent tasks.
72        // we don't want this attribute to be propagated to the next activity
73        // being launched.  Note that if the original Intent also had this
74        // flag set, we are now losing it.  That should be a very rare case
75        // and we can live with this.
76        intent.setFlags(intent.getFlags()&~Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
77        return intent;
78    }
79
80    @Override
81    protected void onCreate(Bundle savedInstanceState) {
82        onCreate(savedInstanceState, makeMyIntent(),
83                getResources().getText(com.android.internal.R.string.whichApplication),
84                null, null, true);
85    }
86
87    protected void onCreate(Bundle savedInstanceState, Intent intent,
88            CharSequence title, Intent[] initialIntents, List<ResolveInfo> rList,
89            boolean alwaysUseOption) {
90        super.onCreate(savedInstanceState);
91        mPm = getPackageManager();
92        intent.setComponent(null);
93
94        AlertController.AlertParams ap = mAlertParams;
95
96        ap.mTitle = title;
97        ap.mOnClickListener = this;
98
99        mPackageMonitor.register(this, false);
100
101        if (alwaysUseOption) {
102            LayoutInflater inflater = (LayoutInflater) getSystemService(
103                    Context.LAYOUT_INFLATER_SERVICE);
104            ap.mView = inflater.inflate(R.layout.always_use_checkbox, null);
105            mAlwaysCheck = (CheckBox)ap.mView.findViewById(com.android.internal.R.id.alwaysUse);
106            mAlwaysCheck.setText(R.string.alwaysUse);
107            mAlwaysCheck.setOnCheckedChangeListener(this);
108            mClearDefaultHint = (TextView)ap.mView.findViewById(
109                                                        com.android.internal.R.id.clearDefaultHint);
110            mClearDefaultHint.setVisibility(View.GONE);
111        }
112        mAdapter = new ResolveListAdapter(this, intent, initialIntents, rList);
113        int count = mAdapter.getCount();
114        if (count > 1) {
115            ap.mAdapter = mAdapter;
116        } else if (count == 1) {
117            startActivity(mAdapter.intentForPosition(0));
118            finish();
119            return;
120        } else {
121            ap.mMessage = getResources().getText(com.android.internal.R.string.noApplications);
122        }
123
124        setupAlert();
125    }
126
127    @Override
128    protected void onRestart() {
129        super.onRestart();
130        mPackageMonitor.register(this, false);
131        mAdapter.handlePackagesChanged();
132    }
133
134    @Override
135    protected void onStop() {
136        super.onStop();
137        mPackageMonitor.unregister();
138    }
139
140    public void onClick(DialogInterface dialog, int which) {
141        ResolveInfo ri = mAdapter.resolveInfoForPosition(which);
142        Intent intent = mAdapter.intentForPosition(which);
143        boolean alwaysCheck = (mAlwaysCheck != null && mAlwaysCheck.isChecked());
144        onIntentSelected(ri, intent, alwaysCheck);
145        finish();
146    }
147
148    protected void onIntentSelected(ResolveInfo ri, Intent intent, boolean alwaysCheck) {
149        if (alwaysCheck) {
150            // Build a reasonable intent filter, based on what matched.
151            IntentFilter filter = new IntentFilter();
152
153            if (intent.getAction() != null) {
154                filter.addAction(intent.getAction());
155            }
156            Set<String> categories = intent.getCategories();
157            if (categories != null) {
158                for (String cat : categories) {
159                    filter.addCategory(cat);
160                }
161            }
162            filter.addCategory(Intent.CATEGORY_DEFAULT);
163
164            int cat = ri.match&IntentFilter.MATCH_CATEGORY_MASK;
165            Uri data = intent.getData();
166            if (cat == IntentFilter.MATCH_CATEGORY_TYPE) {
167                String mimeType = intent.resolveType(this);
168                if (mimeType != null) {
169                    try {
170                        filter.addDataType(mimeType);
171                    } catch (IntentFilter.MalformedMimeTypeException e) {
172                        Log.w("ResolverActivity", e);
173                        filter = null;
174                    }
175                }
176            }
177            if (data != null && data.getScheme() != null) {
178                // We need the data specification if there was no type,
179                // OR if the scheme is not one of our magical "file:"
180                // or "content:" schemes (see IntentFilter for the reason).
181                if (cat != IntentFilter.MATCH_CATEGORY_TYPE
182                        || (!"file".equals(data.getScheme())
183                                && !"content".equals(data.getScheme()))) {
184                    filter.addDataScheme(data.getScheme());
185
186                    // Look through the resolved filter to determine which part
187                    // of it matched the original Intent.
188                    Iterator<IntentFilter.AuthorityEntry> aIt = ri.filter.authoritiesIterator();
189                    if (aIt != null) {
190                        while (aIt.hasNext()) {
191                            IntentFilter.AuthorityEntry a = aIt.next();
192                            if (a.match(data) >= 0) {
193                                int port = a.getPort();
194                                filter.addDataAuthority(a.getHost(),
195                                        port >= 0 ? Integer.toString(port) : null);
196                                break;
197                            }
198                        }
199                    }
200                    Iterator<PatternMatcher> pIt = ri.filter.pathsIterator();
201                    if (pIt != null) {
202                        String path = data.getPath();
203                        while (path != null && pIt.hasNext()) {
204                            PatternMatcher p = pIt.next();
205                            if (p.match(path)) {
206                                filter.addDataPath(p.getPath(), p.getType());
207                                break;
208                            }
209                        }
210                    }
211                }
212            }
213
214            if (filter != null) {
215                final int N = mAdapter.mList.size();
216                ComponentName[] set = new ComponentName[N];
217                int bestMatch = 0;
218                for (int i=0; i<N; i++) {
219                    ResolveInfo r = mAdapter.mList.get(i).ri;
220                    set[i] = new ComponentName(r.activityInfo.packageName,
221                            r.activityInfo.name);
222                    if (r.match > bestMatch) bestMatch = r.match;
223                }
224                getPackageManager().addPreferredActivity(filter, bestMatch, set,
225                        intent.getComponent());
226            }
227        }
228
229        if (intent != null) {
230            startActivity(intent);
231        }
232    }
233
234    private final class DisplayResolveInfo {
235        ResolveInfo ri;
236        CharSequence displayLabel;
237        Drawable displayIcon;
238        CharSequence extendedInfo;
239        Intent origIntent;
240
241        DisplayResolveInfo(ResolveInfo pri, CharSequence pLabel,
242                CharSequence pInfo, Intent pOrigIntent) {
243            ri = pri;
244            displayLabel = pLabel;
245            extendedInfo = pInfo;
246            origIntent = pOrigIntent;
247        }
248    }
249
250    private final class ResolveListAdapter extends BaseAdapter {
251        private final Intent[] mInitialIntents;
252        private final List<ResolveInfo> mBaseResolveList;
253        private final Intent mIntent;
254        private final LayoutInflater mInflater;
255
256        private List<ResolveInfo> mCurrentResolveList;
257        private List<DisplayResolveInfo> mList;
258
259        public ResolveListAdapter(Context context, Intent intent,
260                Intent[] initialIntents, List<ResolveInfo> rList) {
261            mIntent = new Intent(intent);
262            mIntent.setComponent(null);
263            mInitialIntents = initialIntents;
264            mBaseResolveList = rList;
265            mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
266            rebuildList();
267        }
268
269        public void handlePackagesChanged() {
270            rebuildList();
271            notifyDataSetChanged();
272            if (mList.size() <= 0) {
273                // We no longer have any items...  just finish the activity.
274                finish();
275            }
276        }
277
278        private void rebuildList() {
279            if (mBaseResolveList != null) {
280                mCurrentResolveList = mBaseResolveList;
281            } else {
282                mCurrentResolveList = mPm.queryIntentActivities(
283                        mIntent, PackageManager.MATCH_DEFAULT_ONLY
284                        | (mAlwaysCheck != null ? PackageManager.GET_RESOLVED_FILTER : 0));
285            }
286            int N;
287            if ((mCurrentResolveList != null) && ((N = mCurrentResolveList.size()) > 0)) {
288                // Only display the first matches that are either of equal
289                // priority or have asked to be default options.
290                ResolveInfo r0 = mCurrentResolveList.get(0);
291                for (int i=1; i<N; i++) {
292                    ResolveInfo ri = mCurrentResolveList.get(i);
293                    if (false) Log.v(
294                        "ResolveListActivity",
295                        r0.activityInfo.name + "=" +
296                        r0.priority + "/" + r0.isDefault + " vs " +
297                        ri.activityInfo.name + "=" +
298                        ri.priority + "/" + ri.isDefault);
299                   if (r0.priority != ri.priority ||
300                        r0.isDefault != ri.isDefault) {
301                        while (i < N) {
302                            mCurrentResolveList.remove(i);
303                            N--;
304                        }
305                    }
306                }
307                if (N > 1) {
308                    ResolveInfo.DisplayNameComparator rComparator =
309                            new ResolveInfo.DisplayNameComparator(mPm);
310                    Collections.sort(mCurrentResolveList, rComparator);
311                }
312
313                mList = new ArrayList<DisplayResolveInfo>();
314
315                // First put the initial items at the top.
316                if (mInitialIntents != null) {
317                    for (int i=0; i<mInitialIntents.length; i++) {
318                        Intent ii = mInitialIntents[i];
319                        if (ii == null) {
320                            continue;
321                        }
322                        ActivityInfo ai = ii.resolveActivityInfo(
323                                getPackageManager(), 0);
324                        if (ai == null) {
325                            Log.w("ResolverActivity", "No activity found for "
326                                    + ii);
327                            continue;
328                        }
329                        ResolveInfo ri = new ResolveInfo();
330                        ri.activityInfo = ai;
331                        if (ii instanceof LabeledIntent) {
332                            LabeledIntent li = (LabeledIntent)ii;
333                            ri.resolvePackageName = li.getSourcePackage();
334                            ri.labelRes = li.getLabelResource();
335                            ri.nonLocalizedLabel = li.getNonLocalizedLabel();
336                            ri.icon = li.getIconResource();
337                        }
338                        mList.add(new DisplayResolveInfo(ri,
339                                ri.loadLabel(getPackageManager()), null, ii));
340                    }
341                }
342
343                // Check for applications with same name and use application name or
344                // package name if necessary
345                r0 = mCurrentResolveList.get(0);
346                int start = 0;
347                CharSequence r0Label =  r0.loadLabel(mPm);
348                for (int i = 1; i < N; i++) {
349                    if (r0Label == null) {
350                        r0Label = r0.activityInfo.packageName;
351                    }
352                    ResolveInfo ri = mCurrentResolveList.get(i);
353                    CharSequence riLabel = ri.loadLabel(mPm);
354                    if (riLabel == null) {
355                        riLabel = ri.activityInfo.packageName;
356                    }
357                    if (riLabel.equals(r0Label)) {
358                        continue;
359                    }
360                    processGroup(mCurrentResolveList, start, (i-1), r0, r0Label);
361                    r0 = ri;
362                    r0Label = riLabel;
363                    start = i;
364                }
365                // Process last group
366                processGroup(mCurrentResolveList, start, (N-1), r0, r0Label);
367            }
368        }
369
370        private void processGroup(List<ResolveInfo> rList, int start, int end, ResolveInfo ro,
371                CharSequence roLabel) {
372            // Process labels from start to i
373            int num = end - start+1;
374            if (num == 1) {
375                // No duplicate labels. Use label for entry at start
376                mList.add(new DisplayResolveInfo(ro, roLabel, null, null));
377            } else {
378                boolean usePkg = false;
379                CharSequence startApp = ro.activityInfo.applicationInfo.loadLabel(mPm);
380                if (startApp == null) {
381                    usePkg = true;
382                }
383                if (!usePkg) {
384                    // Use HashSet to track duplicates
385                    HashSet<CharSequence> duplicates =
386                        new HashSet<CharSequence>();
387                    duplicates.add(startApp);
388                    for (int j = start+1; j <= end ; j++) {
389                        ResolveInfo jRi = rList.get(j);
390                        CharSequence jApp = jRi.activityInfo.applicationInfo.loadLabel(mPm);
391                        if ( (jApp == null) || (duplicates.contains(jApp))) {
392                            usePkg = true;
393                            break;
394                        } else {
395                            duplicates.add(jApp);
396                        }
397                    }
398                    // Clear HashSet for later use
399                    duplicates.clear();
400                }
401                for (int k = start; k <= end; k++) {
402                    ResolveInfo add = rList.get(k);
403                    if (usePkg) {
404                        // Use application name for all entries from start to end-1
405                        mList.add(new DisplayResolveInfo(add, roLabel,
406                                add.activityInfo.packageName, null));
407                    } else {
408                        // Use package name for all entries from start to end-1
409                        mList.add(new DisplayResolveInfo(add, roLabel,
410                                add.activityInfo.applicationInfo.loadLabel(mPm), null));
411                    }
412                }
413            }
414        }
415
416        public ResolveInfo resolveInfoForPosition(int position) {
417            if (mList == null) {
418                return null;
419            }
420
421            return mList.get(position).ri;
422        }
423
424        public Intent intentForPosition(int position) {
425            if (mList == null) {
426                return null;
427            }
428
429            DisplayResolveInfo dri = mList.get(position);
430
431            Intent intent = new Intent(dri.origIntent != null
432                    ? dri.origIntent : mIntent);
433            intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT
434                    |Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
435            ActivityInfo ai = dri.ri.activityInfo;
436            intent.setComponent(new ComponentName(
437                    ai.applicationInfo.packageName, ai.name));
438            return intent;
439        }
440
441        public int getCount() {
442            return mList != null ? mList.size() : 0;
443        }
444
445        public Object getItem(int position) {
446            return position;
447        }
448
449        public long getItemId(int position) {
450            return position;
451        }
452
453        public View getView(int position, View convertView, ViewGroup parent) {
454            View view;
455            if (convertView == null) {
456                view = mInflater.inflate(
457                        com.android.internal.R.layout.resolve_list_item, parent, false);
458            } else {
459                view = convertView;
460            }
461            bindView(view, mList.get(position));
462            return view;
463        }
464
465        private final void bindView(View view, DisplayResolveInfo info) {
466            TextView text = (TextView)view.findViewById(com.android.internal.R.id.text1);
467            TextView text2 = (TextView)view.findViewById(com.android.internal.R.id.text2);
468            ImageView icon = (ImageView)view.findViewById(R.id.icon);
469            text.setText(info.displayLabel);
470            if (info.extendedInfo != null) {
471                text2.setVisibility(View.VISIBLE);
472                text2.setText(info.extendedInfo);
473            } else {
474                text2.setVisibility(View.GONE);
475            }
476            if (info.displayIcon == null) {
477                info.displayIcon = info.ri.loadIcon(mPm);
478            }
479            icon.setImageDrawable(info.displayIcon);
480        }
481    }
482
483    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
484        if (mClearDefaultHint == null) return;
485
486        if(isChecked) {
487            mClearDefaultHint.setVisibility(View.VISIBLE);
488        } else {
489            mClearDefaultHint.setVisibility(View.GONE);
490        }
491    }
492}
493
494