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