1/*
2 * Copyright (C) 2006 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 android.content;
18
19import android.net.Uri;
20import android.os.Parcel;
21import android.os.Parcelable;
22import android.os.PatternMatcher;
23import android.text.TextUtils;
24import android.util.AndroidException;
25import android.util.Log;
26import android.util.Printer;
27
28import com.android.internal.util.XmlUtils;
29
30import org.xmlpull.v1.XmlPullParser;
31import org.xmlpull.v1.XmlPullParserException;
32import org.xmlpull.v1.XmlSerializer;
33
34import java.io.IOException;
35import java.util.ArrayList;
36import java.util.Iterator;
37import java.util.Set;
38
39/**
40 * Structured description of Intent values to be matched.  An IntentFilter can
41 * match against actions, categories, and data (either via its type, scheme,
42 * and/or path) in an Intent.  It also includes a "priority" value which is
43 * used to order multiple matching filters.
44 *
45 * <p>IntentFilter objects are often created in XML as part of a package's
46 * {@link android.R.styleable#AndroidManifest AndroidManifest.xml} file,
47 * using {@link android.R.styleable#AndroidManifestIntentFilter intent-filter}
48 * tags.
49 *
50 * <p>There are three Intent characteristics you can filter on: the
51 * <em>action</em>, <em>data</em>, and <em>categories</em>.  For each of these
52 * characteristics you can provide
53 * multiple possible matching values (via {@link #addAction},
54 * {@link #addDataType}, {@link #addDataScheme}, {@link #addDataSchemeSpecificPart},
55 * {@link #addDataAuthority}, {@link #addDataPath}, and {@link #addCategory}, respectively).
56 * For actions, the field
57 * will not be tested if no values have been given (treating it as a wildcard);
58 * if no data characteristics are specified, however, then the filter will
59 * only match intents that contain no data.
60 *
61 * <p>The data characteristic is
62 * itself divided into three attributes: type, scheme, authority, and path.
63 * Any that are
64 * specified must match the contents of the Intent.  If you specify a scheme
65 * but no type, only Intent that does not have a type (such as mailto:) will
66 * match; a content: URI will never match because they always have a MIME type
67 * that is supplied by their content provider.  Specifying a type with no scheme
68 * has somewhat special meaning: it will match either an Intent with no URI
69 * field, or an Intent with a content: or file: URI.  If you specify neither,
70 * then only an Intent with no data or type will match.  To specify an authority,
71 * you must also specify one or more schemes that it is associated with.
72 * To specify a path, you also must specify both one or more authorities and
73 * one or more schemes it is associated with.
74 *
75 * <div class="special reference">
76 * <h3>Developer Guides</h3>
77 * <p>For information about how to create and resolve intents, read the
78 * <a href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and Intent Filters</a>
79 * developer guide.</p>
80 * </div>
81 *
82 * <h3>Filter Rules</h3>
83 * <p>A match is based on the following rules.  Note that
84 * for an IntentFilter to match an Intent, three conditions must hold:
85 * the <strong>action</strong> and <strong>category</strong> must match, and
86 * the data (both the <strong>data type</strong> and
87 * <strong>data scheme+authority+path</strong> if specified) must match
88 * (see {@link #match(ContentResolver, Intent, boolean, String)} for more details
89 * on how the data fields match).
90 *
91 * <p><strong>Action</strong> matches if any of the given values match the
92 * Intent action; if the filter specifies no actions, then it will only match
93 * Intents that do not contain an action.
94 *
95 * <p><strong>Data Type</strong> matches if any of the given values match the
96 * Intent type.  The Intent
97 * type is determined by calling {@link Intent#resolveType}.  A wildcard can be
98 * used for the MIME sub-type, in both the Intent and IntentFilter, so that the
99 * type "audio/*" will match "audio/mpeg", "audio/aiff", "audio/*", etc.
100 * <em>Note that MIME type matching here is <b>case sensitive</b>, unlike
101 * formal RFC MIME types!</em>  You should thus always use lower case letters
102 * for your MIME types.
103 *
104 * <p><strong>Data Scheme</strong> matches if any of the given values match the
105 * Intent data's scheme.
106 * The Intent scheme is determined by calling {@link Intent#getData}
107 * and {@link android.net.Uri#getScheme} on that URI.
108 * <em>Note that scheme matching here is <b>case sensitive</b>, unlike
109 * formal RFC schemes!</em>  You should thus always use lower case letters
110 * for your schemes.
111 *
112 * <p><strong>Data Scheme Specific Part</strong> matches if any of the given values match
113 * the Intent's data scheme specific part <em>and</em> one of the data schemes in the filter
114 * has matched the Intent, <em>or</em> no scheme specific parts were supplied in the filter.
115 * The Intent scheme specific part is determined by calling
116 * {@link Intent#getData} and {@link android.net.Uri#getSchemeSpecificPart} on that URI.
117 * <em>Note that scheme specific part matching is <b>case sensitive</b>.</em>
118 *
119 * <p><strong>Data Authority</strong> matches if any of the given values match
120 * the Intent's data authority <em>and</em> one of the data schemes in the filter
121 * has matched the Intent, <em>or</em> no authories were supplied in the filter.
122 * The Intent authority is determined by calling
123 * {@link Intent#getData} and {@link android.net.Uri#getAuthority} on that URI.
124 * <em>Note that authority matching here is <b>case sensitive</b>, unlike
125 * formal RFC host names!</em>  You should thus always use lower case letters
126 * for your authority.
127 *
128 * <p><strong>Data Path</strong> matches if any of the given values match the
129 * Intent's data path <em>and</em> both a scheme and authority in the filter
130 * has matched against the Intent, <em>or</em> no paths were supplied in the
131 * filter.  The Intent authority is determined by calling
132 * {@link Intent#getData} and {@link android.net.Uri#getPath} on that URI.
133 *
134 * <p><strong>Categories</strong> match if <em>all</em> of the categories in
135 * the Intent match categories given in the filter.  Extra categories in the
136 * filter that are not in the Intent will not cause the match to fail.  Note
137 * that unlike the action, an IntentFilter with no categories
138 * will only match an Intent that does not have any categories.
139 */
140public class IntentFilter implements Parcelable {
141    private static final String SGLOB_STR = "sglob";
142    private static final String PREFIX_STR = "prefix";
143    private static final String LITERAL_STR = "literal";
144    private static final String PATH_STR = "path";
145    private static final String PORT_STR = "port";
146    private static final String HOST_STR = "host";
147    private static final String AUTH_STR = "auth";
148    private static final String SSP_STR = "ssp";
149    private static final String SCHEME_STR = "scheme";
150    private static final String TYPE_STR = "type";
151    private static final String CAT_STR = "cat";
152    private static final String NAME_STR = "name";
153    private static final String ACTION_STR = "action";
154    private static final String AUTO_VERIFY_STR = "autoVerify";
155
156    /**
157     * The filter {@link #setPriority} value at which system high-priority
158     * receivers are placed; that is, receivers that should execute before
159     * application code. Applications should never use filters with this or
160     * higher priorities.
161     *
162     * @see #setPriority
163     */
164    public static final int SYSTEM_HIGH_PRIORITY = 1000;
165
166    /**
167     * The filter {@link #setPriority} value at which system low-priority
168     * receivers are placed; that is, receivers that should execute after
169     * application code. Applications should never use filters with this or
170     * lower priorities.
171     *
172     * @see #setPriority
173     */
174    public static final int SYSTEM_LOW_PRIORITY = -1000;
175
176    /**
177     * The part of a match constant that describes the category of match
178     * that occurred.  May be either {@link #MATCH_CATEGORY_EMPTY},
179     * {@link #MATCH_CATEGORY_SCHEME}, {@link #MATCH_CATEGORY_SCHEME_SPECIFIC_PART},
180     * {@link #MATCH_CATEGORY_HOST}, {@link #MATCH_CATEGORY_PORT},
181     * {@link #MATCH_CATEGORY_PATH}, or {@link #MATCH_CATEGORY_TYPE}.  Higher
182     * values indicate a better match.
183     */
184    public static final int MATCH_CATEGORY_MASK = 0xfff0000;
185
186    /**
187     * The part of a match constant that applies a quality adjustment to the
188     * basic category of match.  The value {@link #MATCH_ADJUSTMENT_NORMAL}
189     * is no adjustment; higher numbers than that improve the quality, while
190     * lower numbers reduce it.
191     */
192    public static final int MATCH_ADJUSTMENT_MASK = 0x000ffff;
193
194    /**
195     * Quality adjustment applied to the category of match that signifies
196     * the default, base value; higher numbers improve the quality while
197     * lower numbers reduce it.
198     */
199    public static final int MATCH_ADJUSTMENT_NORMAL = 0x8000;
200
201    /**
202     * The filter matched an intent that had no data specified.
203     */
204    public static final int MATCH_CATEGORY_EMPTY = 0x0100000;
205    /**
206     * The filter matched an intent with the same data URI scheme.
207     */
208    public static final int MATCH_CATEGORY_SCHEME = 0x0200000;
209    /**
210     * The filter matched an intent with the same data URI scheme and
211     * authority host.
212     */
213    public static final int MATCH_CATEGORY_HOST = 0x0300000;
214    /**
215     * The filter matched an intent with the same data URI scheme and
216     * authority host and port.
217     */
218    public static final int MATCH_CATEGORY_PORT = 0x0400000;
219    /**
220     * The filter matched an intent with the same data URI scheme,
221     * authority, and path.
222     */
223    public static final int MATCH_CATEGORY_PATH = 0x0500000;
224    /**
225     * The filter matched an intent with the same data URI scheme and
226     * scheme specific part.
227     */
228    public static final int MATCH_CATEGORY_SCHEME_SPECIFIC_PART = 0x0580000;
229    /**
230     * The filter matched an intent with the same data MIME type.
231     */
232    public static final int MATCH_CATEGORY_TYPE = 0x0600000;
233
234    /**
235     * The filter didn't match due to different MIME types.
236     */
237    public static final int NO_MATCH_TYPE = -1;
238    /**
239     * The filter didn't match due to different data URIs.
240     */
241    public static final int NO_MATCH_DATA = -2;
242    /**
243     * The filter didn't match due to different actions.
244     */
245    public static final int NO_MATCH_ACTION = -3;
246    /**
247     * The filter didn't match because it required one or more categories
248     * that were not in the Intent.
249     */
250    public static final int NO_MATCH_CATEGORY = -4;
251
252    /**
253     * HTTP scheme.
254     *
255     * @see #addDataScheme(String)
256     * @hide
257     */
258    public static final String SCHEME_HTTP = "http";
259    /**
260     * HTTPS scheme.
261     *
262     * @see #addDataScheme(String)
263     * @hide
264     */
265    public static final String SCHEME_HTTPS = "https";
266
267    private int mPriority;
268    private final ArrayList<String> mActions;
269    private ArrayList<String> mCategories = null;
270    private ArrayList<String> mDataSchemes = null;
271    private ArrayList<PatternMatcher> mDataSchemeSpecificParts = null;
272    private ArrayList<AuthorityEntry> mDataAuthorities = null;
273    private ArrayList<PatternMatcher> mDataPaths = null;
274    private ArrayList<String> mDataTypes = null;
275    private boolean mHasPartialTypes = false;
276
277    private static final int STATE_VERIFY_AUTO         = 0x00000001;
278    private static final int STATE_NEED_VERIFY         = 0x00000010;
279    private static final int STATE_NEED_VERIFY_CHECKED = 0x00000100;
280    private static final int STATE_VERIFIED            = 0x00001000;
281
282    private int mVerifyState;
283
284    // These functions are the start of more optimized code for managing
285    // the string sets...  not yet implemented.
286
287    private static int findStringInSet(String[] set, String string,
288            int[] lengths, int lenPos) {
289        if (set == null) return -1;
290        final int N = lengths[lenPos];
291        for (int i=0; i<N; i++) {
292            if (set[i].equals(string)) return i;
293        }
294        return -1;
295    }
296
297    private static String[] addStringToSet(String[] set, String string,
298            int[] lengths, int lenPos) {
299        if (findStringInSet(set, string, lengths, lenPos) >= 0) return set;
300        if (set == null) {
301            set = new String[2];
302            set[0] = string;
303            lengths[lenPos] = 1;
304            return set;
305        }
306        final int N = lengths[lenPos];
307        if (N < set.length) {
308            set[N] = string;
309            lengths[lenPos] = N+1;
310            return set;
311        }
312
313        String[] newSet = new String[(N*3)/2 + 2];
314        System.arraycopy(set, 0, newSet, 0, N);
315        set = newSet;
316        set[N] = string;
317        lengths[lenPos] = N+1;
318        return set;
319    }
320
321    private static String[] removeStringFromSet(String[] set, String string,
322            int[] lengths, int lenPos) {
323        int pos = findStringInSet(set, string, lengths, lenPos);
324        if (pos < 0) return set;
325        final int N = lengths[lenPos];
326        if (N > (set.length/4)) {
327            int copyLen = N-(pos+1);
328            if (copyLen > 0) {
329                System.arraycopy(set, pos+1, set, pos, copyLen);
330            }
331            set[N-1] = null;
332            lengths[lenPos] = N-1;
333            return set;
334        }
335
336        String[] newSet = new String[set.length/3];
337        if (pos > 0) System.arraycopy(set, 0, newSet, 0, pos);
338        if ((pos+1) < N) System.arraycopy(set, pos+1, newSet, pos, N-(pos+1));
339        return newSet;
340    }
341
342    /**
343     * This exception is thrown when a given MIME type does not have a valid
344     * syntax.
345     */
346    public static class MalformedMimeTypeException extends AndroidException {
347        public MalformedMimeTypeException() {
348        }
349
350        public MalformedMimeTypeException(String name) {
351            super(name);
352        }
353    }
354
355    /**
356     * Create a new IntentFilter instance with a specified action and MIME
357     * type, where you know the MIME type is correctly formatted.  This catches
358     * the {@link MalformedMimeTypeException} exception that the constructor
359     * can call and turns it into a runtime exception.
360     *
361     * @param action The action to match, i.e. Intent.ACTION_VIEW.
362     * @param dataType The type to match, i.e. "vnd.android.cursor.dir/person".
363     *
364     * @return A new IntentFilter for the given action and type.
365     *
366     * @see #IntentFilter(String, String)
367     */
368    public static IntentFilter create(String action, String dataType) {
369        try {
370            return new IntentFilter(action, dataType);
371        } catch (MalformedMimeTypeException e) {
372            throw new RuntimeException("Bad MIME type", e);
373        }
374    }
375
376    /**
377     * New empty IntentFilter.
378     */
379    public IntentFilter() {
380        mPriority = 0;
381        mActions = new ArrayList<String>();
382    }
383
384    /**
385     * New IntentFilter that matches a single action with no data.  If
386     * no data characteristics are subsequently specified, then the
387     * filter will only match intents that contain no data.
388     *
389     * @param action The action to match, i.e. Intent.ACTION_MAIN.
390     */
391    public IntentFilter(String action) {
392        mPriority = 0;
393        mActions = new ArrayList<String>();
394        addAction(action);
395    }
396
397    /**
398     * New IntentFilter that matches a single action and data type.
399     *
400     * <p><em>Note: MIME type matching in the Android framework is
401     * case-sensitive, unlike formal RFC MIME types.  As a result,
402     * you should always write your MIME types with lower case letters,
403     * and any MIME types you receive from outside of Android should be
404     * converted to lower case before supplying them here.</em></p>
405     *
406     * <p>Throws {@link MalformedMimeTypeException} if the given MIME type is
407     * not syntactically correct.
408     *
409     * @param action The action to match, i.e. Intent.ACTION_VIEW.
410     * @param dataType The type to match, i.e. "vnd.android.cursor.dir/person".
411     *
412     */
413    public IntentFilter(String action, String dataType)
414        throws MalformedMimeTypeException {
415        mPriority = 0;
416        mActions = new ArrayList<String>();
417        addAction(action);
418        addDataType(dataType);
419    }
420
421    /**
422     * New IntentFilter containing a copy of an existing filter.
423     *
424     * @param o The original filter to copy.
425     */
426    public IntentFilter(IntentFilter o) {
427        mPriority = o.mPriority;
428        mActions = new ArrayList<String>(o.mActions);
429        if (o.mCategories != null) {
430            mCategories = new ArrayList<String>(o.mCategories);
431        }
432        if (o.mDataTypes != null) {
433            mDataTypes = new ArrayList<String>(o.mDataTypes);
434        }
435        if (o.mDataSchemes != null) {
436            mDataSchemes = new ArrayList<String>(o.mDataSchemes);
437        }
438        if (o.mDataSchemeSpecificParts != null) {
439            mDataSchemeSpecificParts = new ArrayList<PatternMatcher>(o.mDataSchemeSpecificParts);
440        }
441        if (o.mDataAuthorities != null) {
442            mDataAuthorities = new ArrayList<AuthorityEntry>(o.mDataAuthorities);
443        }
444        if (o.mDataPaths != null) {
445            mDataPaths = new ArrayList<PatternMatcher>(o.mDataPaths);
446        }
447        mHasPartialTypes = o.mHasPartialTypes;
448        mVerifyState = o.mVerifyState;
449    }
450
451    /**
452     * Modify priority of this filter.  The default priority is 0. Positive
453     * values will be before the default, lower values will be after it.
454     * Applications must use a value that is larger than
455     * {@link #SYSTEM_LOW_PRIORITY} and smaller than
456     * {@link #SYSTEM_HIGH_PRIORITY} .
457     *
458     * @param priority The new priority value.
459     *
460     * @see #getPriority
461     * @see #SYSTEM_LOW_PRIORITY
462     * @see #SYSTEM_HIGH_PRIORITY
463     */
464    public final void setPriority(int priority) {
465        mPriority = priority;
466    }
467
468    /**
469     * Return the priority of this filter.
470     *
471     * @return The priority of the filter.
472     *
473     * @see #setPriority
474     */
475    public final int getPriority() {
476        return mPriority;
477    }
478
479    /**
480     * Set whether this filter will needs to be automatically verified against its data URIs or not.
481     * The default is false.
482     *
483     * The verification would need to happen only and only if the Intent action is
484     * {@link android.content.Intent#ACTION_VIEW} and the Intent category is
485     * {@link android.content.Intent#CATEGORY_BROWSABLE} and the Intent data scheme
486     * is "http" or "https".
487     *
488     * True means that the filter will need to use its data URIs to be verified.
489     *
490     * @param autoVerify The new autoVerify value.
491     *
492     * @see #getAutoVerify()
493     * @see #addAction(String)
494     * @see #getAction(int)
495     * @see #addCategory(String)
496     * @see #getCategory(int)
497     * @see #addDataScheme(String)
498     * @see #getDataScheme(int)
499     *
500     * @hide
501     */
502    public final void setAutoVerify(boolean autoVerify) {
503        mVerifyState &= ~STATE_VERIFY_AUTO;
504        if (autoVerify) mVerifyState |= STATE_VERIFY_AUTO;
505    }
506
507    /**
508     * Return if this filter will needs to be automatically verified again its data URIs or not.
509     *
510     * @return True if the filter will needs to be automatically verified. False otherwise.
511     *
512     * @see #setAutoVerify(boolean)
513     *
514     * @hide
515     */
516    public final boolean getAutoVerify() {
517        return ((mVerifyState & STATE_VERIFY_AUTO) == 1);
518    }
519
520    /**
521     * Return if this filter handle all HTTP or HTTPS data URI or not.  This is the
522     * core check for whether a given activity qualifies as a "browser".
523     *
524     * @return True if the filter handle all HTTP or HTTPS data URI. False otherwise.
525     *
526     * This will check if:
527     *
528     * - either the Intent category is {@link android.content.Intent#CATEGORY_APP_BROWSER}
529     * - either the Intent action is {@link android.content.Intent#ACTION_VIEW} and
530     * the Intent category is {@link android.content.Intent#CATEGORY_BROWSABLE} and the Intent
531     * data scheme is "http" or "https" and that there is no specific host defined.
532     *
533     * @hide
534     */
535    public final boolean handleAllWebDataURI() {
536        return hasCategory(Intent.CATEGORY_APP_BROWSER) ||
537                (handlesWebUris(false) && countDataAuthorities() == 0);
538    }
539
540    /**
541     * Return if this filter handles HTTP or HTTPS data URIs.
542     *
543     * @return True if the filter handles ACTION_VIEW/CATEGORY_BROWSABLE,
544     * has at least one HTTP or HTTPS data URI pattern defined, and optionally
545     * does not define any non-http/https data URI patterns.
546     *
547     * This will check if if the Intent action is {@link android.content.Intent#ACTION_VIEW} and
548     * the Intent category is {@link android.content.Intent#CATEGORY_BROWSABLE} and the Intent
549     * data scheme is "http" or "https".
550     *
551     * @param onlyWebSchemes When true, requires that the intent filter declare
552     *     that it handles *only* http: or https: schemes.  This is a requirement for
553     *     the intent filter's domain linkage being verifiable.
554     * @hide
555     */
556    public final boolean handlesWebUris(boolean onlyWebSchemes) {
557        // Require ACTION_VIEW, CATEGORY_BROWSEABLE, and at least one scheme
558        if (!hasAction(Intent.ACTION_VIEW)
559            || !hasCategory(Intent.CATEGORY_BROWSABLE)
560            || mDataSchemes == null
561            || mDataSchemes.size() == 0) {
562            return false;
563        }
564
565        // Now allow only the schemes "http" and "https"
566        final int N = mDataSchemes.size();
567        for (int i = 0; i < N; i++) {
568            final String scheme = mDataSchemes.get(i);
569            final boolean isWebScheme =
570                    SCHEME_HTTP.equals(scheme) || SCHEME_HTTPS.equals(scheme);
571            if (onlyWebSchemes) {
572                // If we're specifically trying to ensure that there are no non-web schemes
573                // declared in this filter, then if we ever see a non-http/https scheme then
574                // we know it's a failure.
575                if (!isWebScheme) {
576                    return false;
577                }
578            } else {
579                // If we see any http/https scheme declaration in this case then the
580                // filter matches what we're looking for.
581                if (isWebScheme) {
582                    return true;
583                }
584            }
585        }
586
587        // We get here if:
588        //   1) onlyWebSchemes and no non-web schemes were found, i.e success; or
589        //   2) !onlyWebSchemes and no http/https schemes were found, i.e. failure.
590        return onlyWebSchemes;
591    }
592
593    /**
594     * Return if this filter needs to be automatically verified again its data URIs or not.
595     *
596     * @return True if the filter needs to be automatically verified. False otherwise.
597     *
598     * This will check if if the Intent action is {@link android.content.Intent#ACTION_VIEW} and
599     * the Intent category is {@link android.content.Intent#CATEGORY_BROWSABLE} and the Intent
600     * data scheme is "http" or "https".
601     *
602     * @see #setAutoVerify(boolean)
603     *
604     * @hide
605     */
606    public final boolean needsVerification() {
607        return getAutoVerify() && handlesWebUris(true);
608    }
609
610    /**
611     * Return if this filter has been verified
612     *
613     * @return true if the filter has been verified or if autoVerify is false.
614     *
615     * @hide
616     */
617    public final boolean isVerified() {
618        if ((mVerifyState & STATE_NEED_VERIFY_CHECKED) == STATE_NEED_VERIFY_CHECKED) {
619            return ((mVerifyState & STATE_NEED_VERIFY) == STATE_NEED_VERIFY);
620        }
621        return false;
622    }
623
624    /**
625     * Set if this filter has been verified
626     *
627     * @param verified true if this filter has been verified. False otherwise.
628     *
629     * @hide
630     */
631    public void setVerified(boolean verified) {
632        mVerifyState |= STATE_NEED_VERIFY_CHECKED;
633        mVerifyState &= ~STATE_VERIFIED;
634        if (verified) mVerifyState |= STATE_VERIFIED;
635    }
636
637    /**
638     * Add a new Intent action to match against.  If any actions are included
639     * in the filter, then an Intent's action must be one of those values for
640     * it to match.  If no actions are included, the Intent action is ignored.
641     *
642     * @param action Name of the action to match, i.e. Intent.ACTION_VIEW.
643     */
644    public final void addAction(String action) {
645        if (!mActions.contains(action)) {
646            mActions.add(action.intern());
647        }
648    }
649
650    /**
651     * Return the number of actions in the filter.
652     */
653    public final int countActions() {
654        return mActions.size();
655    }
656
657    /**
658     * Return an action in the filter.
659     */
660    public final String getAction(int index) {
661        return mActions.get(index);
662    }
663
664    /**
665     * Is the given action included in the filter?  Note that if the filter
666     * does not include any actions, false will <em>always</em> be returned.
667     *
668     * @param action The action to look for.
669     *
670     * @return True if the action is explicitly mentioned in the filter.
671     */
672    public final boolean hasAction(String action) {
673        return action != null && mActions.contains(action);
674    }
675
676    /**
677     * Match this filter against an Intent's action.  If the filter does not
678     * specify any actions, the match will always fail.
679     *
680     * @param action The desired action to look for.
681     *
682     * @return True if the action is listed in the filter.
683     */
684    public final boolean matchAction(String action) {
685        return hasAction(action);
686    }
687
688    /**
689     * Return an iterator over the filter's actions.  If there are no actions,
690     * returns null.
691     */
692    public final Iterator<String> actionsIterator() {
693        return mActions != null ? mActions.iterator() : null;
694    }
695
696    /**
697     * Add a new Intent data type to match against.  If any types are
698     * included in the filter, then an Intent's data must be <em>either</em>
699     * one of these types <em>or</em> a matching scheme.  If no data types
700     * are included, then an Intent will only match if it specifies no data.
701     *
702     * <p><em>Note: MIME type matching in the Android framework is
703     * case-sensitive, unlike formal RFC MIME types.  As a result,
704     * you should always write your MIME types with lower case letters,
705     * and any MIME types you receive from outside of Android should be
706     * converted to lower case before supplying them here.</em></p>
707     *
708     * <p>Throws {@link MalformedMimeTypeException} if the given MIME type is
709     * not syntactically correct.
710     *
711     * @param type Name of the data type to match, i.e. "vnd.android.cursor.dir/person".
712     *
713     * @see #matchData
714     */
715    public final void addDataType(String type)
716        throws MalformedMimeTypeException {
717        final int slashpos = type.indexOf('/');
718        final int typelen = type.length();
719        if (slashpos > 0 && typelen >= slashpos+2) {
720            if (mDataTypes == null) mDataTypes = new ArrayList<String>();
721            if (typelen == slashpos+2 && type.charAt(slashpos+1) == '*') {
722                String str = type.substring(0, slashpos);
723                if (!mDataTypes.contains(str)) {
724                    mDataTypes.add(str.intern());
725                }
726                mHasPartialTypes = true;
727            } else {
728                if (!mDataTypes.contains(type)) {
729                    mDataTypes.add(type.intern());
730                }
731            }
732            return;
733        }
734
735        throw new MalformedMimeTypeException(type);
736    }
737
738    /**
739     * Is the given data type included in the filter?  Note that if the filter
740     * does not include any type, false will <em>always</em> be returned.
741     *
742     * @param type The data type to look for.
743     *
744     * @return True if the type is explicitly mentioned in the filter.
745     */
746    public final boolean hasDataType(String type) {
747        return mDataTypes != null && findMimeType(type);
748    }
749
750    /** @hide */
751    public final boolean hasExactDataType(String type) {
752        return mDataTypes != null && mDataTypes.contains(type);
753    }
754
755    /**
756     * Return the number of data types in the filter.
757     */
758    public final int countDataTypes() {
759        return mDataTypes != null ? mDataTypes.size() : 0;
760    }
761
762    /**
763     * Return a data type in the filter.
764     */
765    public final String getDataType(int index) {
766        return mDataTypes.get(index);
767    }
768
769    /**
770     * Return an iterator over the filter's data types.
771     */
772    public final Iterator<String> typesIterator() {
773        return mDataTypes != null ? mDataTypes.iterator() : null;
774    }
775
776    /**
777     * Add a new Intent data scheme to match against.  If any schemes are
778     * included in the filter, then an Intent's data must be <em>either</em>
779     * one of these schemes <em>or</em> a matching data type.  If no schemes
780     * are included, then an Intent will match only if it includes no data.
781     *
782     * <p><em>Note: scheme matching in the Android framework is
783     * case-sensitive, unlike formal RFC schemes.  As a result,
784     * you should always write your schemes with lower case letters,
785     * and any schemes you receive from outside of Android should be
786     * converted to lower case before supplying them here.</em></p>
787     *
788     * @param scheme Name of the scheme to match, i.e. "http".
789     *
790     * @see #matchData
791     */
792    public final void addDataScheme(String scheme) {
793        if (mDataSchemes == null) mDataSchemes = new ArrayList<String>();
794        if (!mDataSchemes.contains(scheme)) {
795            mDataSchemes.add(scheme.intern());
796        }
797    }
798
799    /**
800     * Return the number of data schemes in the filter.
801     */
802    public final int countDataSchemes() {
803        return mDataSchemes != null ? mDataSchemes.size() : 0;
804    }
805
806    /**
807     * Return a data scheme in the filter.
808     */
809    public final String getDataScheme(int index) {
810        return mDataSchemes.get(index);
811    }
812
813    /**
814     * Is the given data scheme included in the filter?  Note that if the
815     * filter does not include any scheme, false will <em>always</em> be
816     * returned.
817     *
818     * @param scheme The data scheme to look for.
819     *
820     * @return True if the scheme is explicitly mentioned in the filter.
821     */
822    public final boolean hasDataScheme(String scheme) {
823        return mDataSchemes != null && mDataSchemes.contains(scheme);
824    }
825
826    /**
827     * Return an iterator over the filter's data schemes.
828     */
829    public final Iterator<String> schemesIterator() {
830        return mDataSchemes != null ? mDataSchemes.iterator() : null;
831    }
832
833    /**
834     * This is an entry for a single authority in the Iterator returned by
835     * {@link #authoritiesIterator()}.
836     */
837    public final static class AuthorityEntry {
838        private final String mOrigHost;
839        private final String mHost;
840        private final boolean mWild;
841        private final int mPort;
842
843        public AuthorityEntry(String host, String port) {
844            mOrigHost = host;
845            mWild = host.length() > 0 && host.charAt(0) == '*';
846            mHost = mWild ? host.substring(1).intern() : host;
847            mPort = port != null ? Integer.parseInt(port) : -1;
848        }
849
850        AuthorityEntry(Parcel src) {
851            mOrigHost = src.readString();
852            mHost = src.readString();
853            mWild = src.readInt() != 0;
854            mPort = src.readInt();
855        }
856
857        void writeToParcel(Parcel dest) {
858            dest.writeString(mOrigHost);
859            dest.writeString(mHost);
860            dest.writeInt(mWild ? 1 : 0);
861            dest.writeInt(mPort);
862        }
863
864        public String getHost() {
865            return mOrigHost;
866        }
867
868        public int getPort() {
869            return mPort;
870        }
871
872        /** @hide */
873        public boolean match(AuthorityEntry other) {
874            if (mWild != other.mWild) {
875                return false;
876            }
877            if (!mHost.equals(other.mHost)) {
878                return false;
879            }
880            if (mPort != other.mPort) {
881                return false;
882            }
883            return true;
884        }
885
886        /**
887         * Determine whether this AuthorityEntry matches the given data Uri.
888         * <em>Note that this comparison is case-sensitive, unlike formal
889         * RFC host names.  You thus should always normalize to lower-case.</em>
890         *
891         * @param data The Uri to match.
892         * @return Returns either {@link IntentFilter#NO_MATCH_DATA},
893         * {@link IntentFilter#MATCH_CATEGORY_PORT}, or
894         * {@link IntentFilter#MATCH_CATEGORY_HOST}.
895         */
896        public int match(Uri data) {
897            String host = data.getHost();
898            if (host == null) {
899                return NO_MATCH_DATA;
900            }
901            if (false) Log.v("IntentFilter",
902                    "Match host " + host + ": " + mHost);
903            if (mWild) {
904                if (host.length() < mHost.length()) {
905                    return NO_MATCH_DATA;
906                }
907                host = host.substring(host.length()-mHost.length());
908            }
909            if (host.compareToIgnoreCase(mHost) != 0) {
910                return NO_MATCH_DATA;
911            }
912            if (mPort >= 0) {
913                if (mPort != data.getPort()) {
914                    return NO_MATCH_DATA;
915                }
916                return MATCH_CATEGORY_PORT;
917            }
918            return MATCH_CATEGORY_HOST;
919        }
920    };
921
922    /**
923     * Add a new Intent data "scheme specific part" to match against.  The filter must
924     * include one or more schemes (via {@link #addDataScheme}) for the
925     * scheme specific part to be considered.  If any scheme specific parts are
926     * included in the filter, then an Intent's data must match one of
927     * them.  If no scheme specific parts are included, then only the scheme must match.
928     *
929     * <p>The "scheme specific part" that this matches against is the string returned
930     * by {@link android.net.Uri#getSchemeSpecificPart() Uri.getSchemeSpecificPart}.
931     * For Uris that contain a path, this kind of matching is not generally of interest,
932     * since {@link #addDataAuthority(String, String)} and
933     * {@link #addDataPath(String, int)} can provide a better mechanism for matching
934     * them.  However, for Uris that do not contain a path, the authority and path
935     * are empty, so this is the only way to match against the non-scheme part.</p>
936     *
937     * @param ssp Either a raw string that must exactly match the scheme specific part
938     * path, or a simple pattern, depending on <var>type</var>.
939     * @param type Determines how <var>ssp</var> will be compared to
940     * determine a match: either {@link PatternMatcher#PATTERN_LITERAL},
941     * {@link PatternMatcher#PATTERN_PREFIX}, or
942     * {@link PatternMatcher#PATTERN_SIMPLE_GLOB}.
943     *
944     * @see #matchData
945     * @see #addDataScheme
946     */
947    public final void addDataSchemeSpecificPart(String ssp, int type) {
948        addDataSchemeSpecificPart(new PatternMatcher(ssp, type));
949    }
950
951    /** @hide */
952    public final void addDataSchemeSpecificPart(PatternMatcher ssp) {
953        if (mDataSchemeSpecificParts == null) {
954            mDataSchemeSpecificParts = new ArrayList<PatternMatcher>();
955        }
956        mDataSchemeSpecificParts.add(ssp);
957    }
958
959    /**
960     * Return the number of data scheme specific parts in the filter.
961     */
962    public final int countDataSchemeSpecificParts() {
963        return mDataSchemeSpecificParts != null ? mDataSchemeSpecificParts.size() : 0;
964    }
965
966    /**
967     * Return a data scheme specific part in the filter.
968     */
969    public final PatternMatcher getDataSchemeSpecificPart(int index) {
970        return mDataSchemeSpecificParts.get(index);
971    }
972
973    /**
974     * Is the given data scheme specific part included in the filter?  Note that if the
975     * filter does not include any scheme specific parts, false will <em>always</em> be
976     * returned.
977     *
978     * @param data The scheme specific part that is being looked for.
979     *
980     * @return Returns true if the data string matches a scheme specific part listed in the
981     *         filter.
982     */
983    public final boolean hasDataSchemeSpecificPart(String data) {
984        if (mDataSchemeSpecificParts == null) {
985            return false;
986        }
987        final int numDataSchemeSpecificParts = mDataSchemeSpecificParts.size();
988        for (int i = 0; i < numDataSchemeSpecificParts; i++) {
989            final PatternMatcher pe = mDataSchemeSpecificParts.get(i);
990            if (pe.match(data)) {
991                return true;
992            }
993        }
994        return false;
995    }
996
997    /** @hide */
998    public final boolean hasDataSchemeSpecificPart(PatternMatcher ssp) {
999        if (mDataSchemeSpecificParts == null) {
1000            return false;
1001        }
1002        final int numDataSchemeSpecificParts = mDataSchemeSpecificParts.size();
1003        for (int i = 0; i < numDataSchemeSpecificParts; i++) {
1004            final PatternMatcher pe = mDataSchemeSpecificParts.get(i);
1005            if (pe.getType() == ssp.getType() && pe.getPath().equals(ssp.getPath())) {
1006                return true;
1007            }
1008        }
1009        return false;
1010    }
1011
1012    /**
1013     * Return an iterator over the filter's data scheme specific parts.
1014     */
1015    public final Iterator<PatternMatcher> schemeSpecificPartsIterator() {
1016        return mDataSchemeSpecificParts != null ? mDataSchemeSpecificParts.iterator() : null;
1017    }
1018
1019    /**
1020     * Add a new Intent data authority to match against.  The filter must
1021     * include one or more schemes (via {@link #addDataScheme}) for the
1022     * authority to be considered.  If any authorities are
1023     * included in the filter, then an Intent's data must match one of
1024     * them.  If no authorities are included, then only the scheme must match.
1025     *
1026     * <p><em>Note: host name in the Android framework is
1027     * case-sensitive, unlike formal RFC host names.  As a result,
1028     * you should always write your host names with lower case letters,
1029     * and any host names you receive from outside of Android should be
1030     * converted to lower case before supplying them here.</em></p>
1031     *
1032     * @param host The host part of the authority to match.  May start with a
1033     *             single '*' to wildcard the front of the host name.
1034     * @param port Optional port part of the authority to match.  If null, any
1035     *             port is allowed.
1036     *
1037     * @see #matchData
1038     * @see #addDataScheme
1039     */
1040    public final void addDataAuthority(String host, String port) {
1041        if (port != null) port = port.intern();
1042        addDataAuthority(new AuthorityEntry(host.intern(), port));
1043    }
1044
1045    /** @hide */
1046    public final void addDataAuthority(AuthorityEntry ent) {
1047        if (mDataAuthorities == null) mDataAuthorities =
1048                new ArrayList<AuthorityEntry>();
1049        mDataAuthorities.add(ent);
1050    }
1051
1052    /**
1053     * Return the number of data authorities in the filter.
1054     */
1055    public final int countDataAuthorities() {
1056        return mDataAuthorities != null ? mDataAuthorities.size() : 0;
1057    }
1058
1059    /**
1060     * Return a data authority in the filter.
1061     */
1062    public final AuthorityEntry getDataAuthority(int index) {
1063        return mDataAuthorities.get(index);
1064    }
1065
1066    /**
1067     * Is the given data authority included in the filter?  Note that if the
1068     * filter does not include any authorities, false will <em>always</em> be
1069     * returned.
1070     *
1071     * @param data The data whose authority is being looked for.
1072     *
1073     * @return Returns true if the data string matches an authority listed in the
1074     *         filter.
1075     */
1076    public final boolean hasDataAuthority(Uri data) {
1077        return matchDataAuthority(data) >= 0;
1078    }
1079
1080    /** @hide */
1081    public final boolean hasDataAuthority(AuthorityEntry auth) {
1082        if (mDataAuthorities == null) {
1083            return false;
1084        }
1085        final int numDataAuthorities = mDataAuthorities.size();
1086        for (int i = 0; i < numDataAuthorities; i++) {
1087            if (mDataAuthorities.get(i).match(auth)) {
1088                return true;
1089            }
1090        }
1091        return false;
1092    }
1093
1094    /**
1095     * Return an iterator over the filter's data authorities.
1096     */
1097    public final Iterator<AuthorityEntry> authoritiesIterator() {
1098        return mDataAuthorities != null ? mDataAuthorities.iterator() : null;
1099    }
1100
1101    /**
1102     * Add a new Intent data path to match against.  The filter must
1103     * include one or more schemes (via {@link #addDataScheme}) <em>and</em>
1104     * one or more authorities (via {@link #addDataAuthority}) for the
1105     * path to be considered.  If any paths are
1106     * included in the filter, then an Intent's data must match one of
1107     * them.  If no paths are included, then only the scheme/authority must
1108     * match.
1109     *
1110     * <p>The path given here can either be a literal that must directly
1111     * match or match against a prefix, or it can be a simple globbing pattern.
1112     * If the latter, you can use '*' anywhere in the pattern to match zero
1113     * or more instances of the previous character, '.' as a wildcard to match
1114     * any character, and '\' to escape the next character.
1115     *
1116     * @param path Either a raw string that must exactly match the file
1117     * path, or a simple pattern, depending on <var>type</var>.
1118     * @param type Determines how <var>path</var> will be compared to
1119     * determine a match: either {@link PatternMatcher#PATTERN_LITERAL},
1120     * {@link PatternMatcher#PATTERN_PREFIX}, or
1121     * {@link PatternMatcher#PATTERN_SIMPLE_GLOB}.
1122     *
1123     * @see #matchData
1124     * @see #addDataScheme
1125     * @see #addDataAuthority
1126     */
1127    public final void addDataPath(String path, int type) {
1128        addDataPath(new PatternMatcher(path.intern(), type));
1129    }
1130
1131    /** @hide */
1132    public final void addDataPath(PatternMatcher path) {
1133        if (mDataPaths == null) mDataPaths = new ArrayList<PatternMatcher>();
1134        mDataPaths.add(path);
1135    }
1136
1137    /**
1138     * Return the number of data paths in the filter.
1139     */
1140    public final int countDataPaths() {
1141        return mDataPaths != null ? mDataPaths.size() : 0;
1142    }
1143
1144    /**
1145     * Return a data path in the filter.
1146     */
1147    public final PatternMatcher getDataPath(int index) {
1148        return mDataPaths.get(index);
1149    }
1150
1151    /**
1152     * Is the given data path included in the filter?  Note that if the
1153     * filter does not include any paths, false will <em>always</em> be
1154     * returned.
1155     *
1156     * @param data The data path to look for.  This is without the scheme
1157     *             prefix.
1158     *
1159     * @return True if the data string matches a path listed in the
1160     *         filter.
1161     */
1162    public final boolean hasDataPath(String data) {
1163        if (mDataPaths == null) {
1164            return false;
1165        }
1166        final int numDataPaths = mDataPaths.size();
1167        for (int i = 0; i < numDataPaths; i++) {
1168            final PatternMatcher pe = mDataPaths.get(i);
1169            if (pe.match(data)) {
1170                return true;
1171            }
1172        }
1173        return false;
1174    }
1175
1176    /** @hide */
1177    public final boolean hasDataPath(PatternMatcher path) {
1178        if (mDataPaths == null) {
1179            return false;
1180        }
1181        final int numDataPaths = mDataPaths.size();
1182        for (int i = 0; i < numDataPaths; i++) {
1183            final PatternMatcher pe = mDataPaths.get(i);
1184            if (pe.getType() == path.getType() && pe.getPath().equals(path.getPath())) {
1185                return true;
1186            }
1187        }
1188        return false;
1189    }
1190
1191    /**
1192     * Return an iterator over the filter's data paths.
1193     */
1194    public final Iterator<PatternMatcher> pathsIterator() {
1195        return mDataPaths != null ? mDataPaths.iterator() : null;
1196    }
1197
1198    /**
1199     * Match this intent filter against the given Intent data.  This ignores
1200     * the data scheme -- unlike {@link #matchData}, the authority will match
1201     * regardless of whether there is a matching scheme.
1202     *
1203     * @param data The data whose authority is being looked for.
1204     *
1205     * @return Returns either {@link #MATCH_CATEGORY_HOST},
1206     * {@link #MATCH_CATEGORY_PORT}, {@link #NO_MATCH_DATA}.
1207     */
1208    public final int matchDataAuthority(Uri data) {
1209        if (mDataAuthorities == null || data == null) {
1210            return NO_MATCH_DATA;
1211        }
1212        final int numDataAuthorities = mDataAuthorities.size();
1213        for (int i = 0; i < numDataAuthorities; i++) {
1214            final AuthorityEntry ae = mDataAuthorities.get(i);
1215            int match = ae.match(data);
1216            if (match >= 0) {
1217                return match;
1218            }
1219        }
1220        return NO_MATCH_DATA;
1221    }
1222
1223    /**
1224     * Match this filter against an Intent's data (type, scheme and path). If
1225     * the filter does not specify any types and does not specify any
1226     * schemes/paths, the match will only succeed if the intent does not
1227     * also specify a type or data.  If the filter does not specify any schemes,
1228     * it will implicitly match intents with no scheme, or the schemes "content:"
1229     * or "file:" (basically performing a MIME-type only match).  If the filter
1230     * does not specify any MIME types, the Intent also must not specify a MIME
1231     * type.
1232     *
1233     * <p>Be aware that to match against an authority, you must also specify a base
1234     * scheme the authority is in.  To match against a data path, both a scheme
1235     * and authority must be specified.  If the filter does not specify any
1236     * types or schemes that it matches against, it is considered to be empty
1237     * (any authority or data path given is ignored, as if it were empty as
1238     * well).
1239     *
1240     * <p><em>Note: MIME type, Uri scheme, and host name matching in the
1241     * Android framework is case-sensitive, unlike the formal RFC definitions.
1242     * As a result, you should always write these elements with lower case letters,
1243     * and normalize any MIME types or Uris you receive from
1244     * outside of Android to ensure these elements are lower case before
1245     * supplying them here.</em></p>
1246     *
1247     * @param type The desired data type to look for, as returned by
1248     *             Intent.resolveType().
1249     * @param scheme The desired data scheme to look for, as returned by
1250     *               Intent.getScheme().
1251     * @param data The full data string to match against, as supplied in
1252     *             Intent.data.
1253     *
1254     * @return Returns either a valid match constant (a combination of
1255     * {@link #MATCH_CATEGORY_MASK} and {@link #MATCH_ADJUSTMENT_MASK}),
1256     * or one of the error codes {@link #NO_MATCH_TYPE} if the type didn't match
1257     * or {@link #NO_MATCH_DATA} if the scheme/path didn't match.
1258     *
1259     * @see #match
1260     */
1261    public final int matchData(String type, String scheme, Uri data) {
1262        final ArrayList<String> types = mDataTypes;
1263        final ArrayList<String> schemes = mDataSchemes;
1264
1265        int match = MATCH_CATEGORY_EMPTY;
1266
1267        if (types == null && schemes == null) {
1268            return ((type == null && data == null)
1269                ? (MATCH_CATEGORY_EMPTY+MATCH_ADJUSTMENT_NORMAL) : NO_MATCH_DATA);
1270        }
1271
1272        if (schemes != null) {
1273            if (schemes.contains(scheme != null ? scheme : "")) {
1274                match = MATCH_CATEGORY_SCHEME;
1275            } else {
1276                return NO_MATCH_DATA;
1277            }
1278
1279            final ArrayList<PatternMatcher> schemeSpecificParts = mDataSchemeSpecificParts;
1280            if (schemeSpecificParts != null && data != null) {
1281                match = hasDataSchemeSpecificPart(data.getSchemeSpecificPart())
1282                        ? MATCH_CATEGORY_SCHEME_SPECIFIC_PART : NO_MATCH_DATA;
1283            }
1284            if (match != MATCH_CATEGORY_SCHEME_SPECIFIC_PART) {
1285                // If there isn't any matching ssp, we need to match an authority.
1286                final ArrayList<AuthorityEntry> authorities = mDataAuthorities;
1287                if (authorities != null) {
1288                    int authMatch = matchDataAuthority(data);
1289                    if (authMatch >= 0) {
1290                        final ArrayList<PatternMatcher> paths = mDataPaths;
1291                        if (paths == null) {
1292                            match = authMatch;
1293                        } else if (hasDataPath(data.getPath())) {
1294                            match = MATCH_CATEGORY_PATH;
1295                        } else {
1296                            return NO_MATCH_DATA;
1297                        }
1298                    } else {
1299                        return NO_MATCH_DATA;
1300                    }
1301                }
1302            }
1303            // If neither an ssp nor an authority matched, we're done.
1304            if (match == NO_MATCH_DATA) {
1305                return NO_MATCH_DATA;
1306            }
1307        } else {
1308            // Special case: match either an Intent with no data URI,
1309            // or with a scheme: URI.  This is to give a convenience for
1310            // the common case where you want to deal with data in a
1311            // content provider, which is done by type, and we don't want
1312            // to force everyone to say they handle content: or file: URIs.
1313            if (scheme != null && !"".equals(scheme)
1314                    && !"content".equals(scheme)
1315                    && !"file".equals(scheme)) {
1316                return NO_MATCH_DATA;
1317            }
1318        }
1319
1320        if (types != null) {
1321            if (findMimeType(type)) {
1322                match = MATCH_CATEGORY_TYPE;
1323            } else {
1324                return NO_MATCH_TYPE;
1325            }
1326        } else {
1327            // If no MIME types are specified, then we will only match against
1328            // an Intent that does not have a MIME type.
1329            if (type != null) {
1330                return NO_MATCH_TYPE;
1331            }
1332        }
1333
1334        return match + MATCH_ADJUSTMENT_NORMAL;
1335    }
1336
1337    /**
1338     * Add a new Intent category to match against.  The semantics of
1339     * categories is the opposite of actions -- an Intent includes the
1340     * categories that it requires, all of which must be included in the
1341     * filter in order to match.  In other words, adding a category to the
1342     * filter has no impact on matching unless that category is specified in
1343     * the intent.
1344     *
1345     * @param category Name of category to match, i.e. Intent.CATEGORY_EMBED.
1346     */
1347    public final void addCategory(String category) {
1348        if (mCategories == null) mCategories = new ArrayList<String>();
1349        if (!mCategories.contains(category)) {
1350            mCategories.add(category.intern());
1351        }
1352    }
1353
1354    /**
1355     * Return the number of categories in the filter.
1356     */
1357    public final int countCategories() {
1358        return mCategories != null ? mCategories.size() : 0;
1359    }
1360
1361    /**
1362     * Return a category in the filter.
1363     */
1364    public final String getCategory(int index) {
1365        return mCategories.get(index);
1366    }
1367
1368    /**
1369     * Is the given category included in the filter?
1370     *
1371     * @param category The category that the filter supports.
1372     *
1373     * @return True if the category is explicitly mentioned in the filter.
1374     */
1375    public final boolean hasCategory(String category) {
1376        return mCategories != null && mCategories.contains(category);
1377    }
1378
1379    /**
1380     * Return an iterator over the filter's categories.
1381     *
1382     * @return Iterator if this filter has categories or {@code null} if none.
1383     */
1384    public final Iterator<String> categoriesIterator() {
1385        return mCategories != null ? mCategories.iterator() : null;
1386    }
1387
1388    /**
1389     * Match this filter against an Intent's categories.  Each category in
1390     * the Intent must be specified by the filter; if any are not in the
1391     * filter, the match fails.
1392     *
1393     * @param categories The categories included in the intent, as returned by
1394     *                   Intent.getCategories().
1395     *
1396     * @return If all categories match (success), null; else the name of the
1397     *         first category that didn't match.
1398     */
1399    public final String matchCategories(Set<String> categories) {
1400        if (categories == null) {
1401            return null;
1402        }
1403
1404        Iterator<String> it = categories.iterator();
1405
1406        if (mCategories == null) {
1407            return it.hasNext() ? it.next() : null;
1408        }
1409
1410        while (it.hasNext()) {
1411            final String category = it.next();
1412            if (!mCategories.contains(category)) {
1413                return category;
1414            }
1415        }
1416
1417        return null;
1418    }
1419
1420    /**
1421     * Test whether this filter matches the given <var>intent</var>.
1422     *
1423     * @param intent The Intent to compare against.
1424     * @param resolve If true, the intent's type will be resolved by calling
1425     *                Intent.resolveType(); otherwise a simple match against
1426     *                Intent.type will be performed.
1427     * @param logTag Tag to use in debugging messages.
1428     *
1429     * @return Returns either a valid match constant (a combination of
1430     * {@link #MATCH_CATEGORY_MASK} and {@link #MATCH_ADJUSTMENT_MASK}),
1431     * or one of the error codes {@link #NO_MATCH_TYPE} if the type didn't match,
1432     * {@link #NO_MATCH_DATA} if the scheme/path didn't match,
1433     * {@link #NO_MATCH_ACTION} if the action didn't match, or
1434     * {@link #NO_MATCH_CATEGORY} if one or more categories didn't match.
1435     *
1436     * @see #match(String, String, String, android.net.Uri , Set, String)
1437     */
1438    public final int match(ContentResolver resolver, Intent intent,
1439            boolean resolve, String logTag) {
1440        String type = resolve ? intent.resolveType(resolver) : intent.getType();
1441        return match(intent.getAction(), type, intent.getScheme(),
1442                     intent.getData(), intent.getCategories(), logTag);
1443    }
1444
1445    /**
1446     * Test whether this filter matches the given intent data.  A match is
1447     * only successful if the actions and categories in the Intent match
1448     * against the filter, as described in {@link IntentFilter}; in that case,
1449     * the match result returned will be as per {@link #matchData}.
1450     *
1451     * @param action The intent action to match against (Intent.getAction).
1452     * @param type The intent type to match against (Intent.resolveType()).
1453     * @param scheme The data scheme to match against (Intent.getScheme()).
1454     * @param data The data URI to match against (Intent.getData()).
1455     * @param categories The categories to match against
1456     *                   (Intent.getCategories()).
1457     * @param logTag Tag to use in debugging messages.
1458     *
1459     * @return Returns either a valid match constant (a combination of
1460     * {@link #MATCH_CATEGORY_MASK} and {@link #MATCH_ADJUSTMENT_MASK}),
1461     * or one of the error codes {@link #NO_MATCH_TYPE} if the type didn't match,
1462     * {@link #NO_MATCH_DATA} if the scheme/path didn't match,
1463     * {@link #NO_MATCH_ACTION} if the action didn't match, or
1464     * {@link #NO_MATCH_CATEGORY} if one or more categories didn't match.
1465     *
1466     * @see #matchData
1467     * @see Intent#getAction
1468     * @see Intent#resolveType
1469     * @see Intent#getScheme
1470     * @see Intent#getData
1471     * @see Intent#getCategories
1472     */
1473    public final int match(String action, String type, String scheme,
1474            Uri data, Set<String> categories, String logTag) {
1475        if (action != null && !matchAction(action)) {
1476            if (false) Log.v(
1477                logTag, "No matching action " + action + " for " + this);
1478            return NO_MATCH_ACTION;
1479        }
1480
1481        int dataMatch = matchData(type, scheme, data);
1482        if (dataMatch < 0) {
1483            if (false) {
1484                if (dataMatch == NO_MATCH_TYPE) {
1485                    Log.v(logTag, "No matching type " + type
1486                          + " for " + this);
1487                }
1488                if (dataMatch == NO_MATCH_DATA) {
1489                    Log.v(logTag, "No matching scheme/path " + data
1490                          + " for " + this);
1491                }
1492            }
1493            return dataMatch;
1494        }
1495
1496        String categoryMismatch = matchCategories(categories);
1497        if (categoryMismatch != null) {
1498            if (false) {
1499                Log.v(logTag, "No matching category " + categoryMismatch + " for " + this);
1500            }
1501            return NO_MATCH_CATEGORY;
1502        }
1503
1504        // It would be nice to treat container activities as more
1505        // important than ones that can be embedded, but this is not the way...
1506        if (false) {
1507            if (categories != null) {
1508                dataMatch -= mCategories.size() - categories.size();
1509            }
1510        }
1511
1512        return dataMatch;
1513    }
1514
1515    /**
1516     * Write the contents of the IntentFilter as an XML stream.
1517     */
1518    public void writeToXml(XmlSerializer serializer) throws IOException {
1519
1520        if (getAutoVerify()) {
1521            serializer.attribute(null, AUTO_VERIFY_STR, Boolean.toString(true));
1522        }
1523
1524        int N = countActions();
1525        for (int i=0; i<N; i++) {
1526            serializer.startTag(null, ACTION_STR);
1527            serializer.attribute(null, NAME_STR, mActions.get(i));
1528            serializer.endTag(null, ACTION_STR);
1529        }
1530        N = countCategories();
1531        for (int i=0; i<N; i++) {
1532            serializer.startTag(null, CAT_STR);
1533            serializer.attribute(null, NAME_STR, mCategories.get(i));
1534            serializer.endTag(null, CAT_STR);
1535        }
1536        N = countDataTypes();
1537        for (int i=0; i<N; i++) {
1538            serializer.startTag(null, TYPE_STR);
1539            String type = mDataTypes.get(i);
1540            if (type.indexOf('/') < 0) type = type + "/*";
1541            serializer.attribute(null, NAME_STR, type);
1542            serializer.endTag(null, TYPE_STR);
1543        }
1544        N = countDataSchemes();
1545        for (int i=0; i<N; i++) {
1546            serializer.startTag(null, SCHEME_STR);
1547            serializer.attribute(null, NAME_STR, mDataSchemes.get(i));
1548            serializer.endTag(null, SCHEME_STR);
1549        }
1550        N = countDataSchemeSpecificParts();
1551        for (int i=0; i<N; i++) {
1552            serializer.startTag(null, SSP_STR);
1553            PatternMatcher pe = mDataSchemeSpecificParts.get(i);
1554            switch (pe.getType()) {
1555                case PatternMatcher.PATTERN_LITERAL:
1556                    serializer.attribute(null, LITERAL_STR, pe.getPath());
1557                    break;
1558                case PatternMatcher.PATTERN_PREFIX:
1559                    serializer.attribute(null, PREFIX_STR, pe.getPath());
1560                    break;
1561                case PatternMatcher.PATTERN_SIMPLE_GLOB:
1562                    serializer.attribute(null, SGLOB_STR, pe.getPath());
1563                    break;
1564            }
1565            serializer.endTag(null, SSP_STR);
1566        }
1567        N = countDataAuthorities();
1568        for (int i=0; i<N; i++) {
1569            serializer.startTag(null, AUTH_STR);
1570            AuthorityEntry ae = mDataAuthorities.get(i);
1571            serializer.attribute(null, HOST_STR, ae.getHost());
1572            if (ae.getPort() >= 0) {
1573                serializer.attribute(null, PORT_STR, Integer.toString(ae.getPort()));
1574            }
1575            serializer.endTag(null, AUTH_STR);
1576        }
1577        N = countDataPaths();
1578        for (int i=0; i<N; i++) {
1579            serializer.startTag(null, PATH_STR);
1580            PatternMatcher pe = mDataPaths.get(i);
1581            switch (pe.getType()) {
1582                case PatternMatcher.PATTERN_LITERAL:
1583                    serializer.attribute(null, LITERAL_STR, pe.getPath());
1584                    break;
1585                case PatternMatcher.PATTERN_PREFIX:
1586                    serializer.attribute(null, PREFIX_STR, pe.getPath());
1587                    break;
1588                case PatternMatcher.PATTERN_SIMPLE_GLOB:
1589                    serializer.attribute(null, SGLOB_STR, pe.getPath());
1590                    break;
1591            }
1592            serializer.endTag(null, PATH_STR);
1593        }
1594    }
1595
1596    public void readFromXml(XmlPullParser parser) throws XmlPullParserException,
1597            IOException {
1598        String autoVerify = parser.getAttributeValue(null, AUTO_VERIFY_STR);
1599        setAutoVerify(TextUtils.isEmpty(autoVerify) ? false : Boolean.getBoolean(autoVerify));
1600
1601        int outerDepth = parser.getDepth();
1602        int type;
1603        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1604               && (type != XmlPullParser.END_TAG
1605                       || parser.getDepth() > outerDepth)) {
1606            if (type == XmlPullParser.END_TAG
1607                    || type == XmlPullParser.TEXT) {
1608                continue;
1609            }
1610
1611            String tagName = parser.getName();
1612            if (tagName.equals(ACTION_STR)) {
1613                String name = parser.getAttributeValue(null, NAME_STR);
1614                if (name != null) {
1615                    addAction(name);
1616                }
1617            } else if (tagName.equals(CAT_STR)) {
1618                String name = parser.getAttributeValue(null, NAME_STR);
1619                if (name != null) {
1620                    addCategory(name);
1621                }
1622            } else if (tagName.equals(TYPE_STR)) {
1623                String name = parser.getAttributeValue(null, NAME_STR);
1624                if (name != null) {
1625                    try {
1626                        addDataType(name);
1627                    } catch (MalformedMimeTypeException e) {
1628                    }
1629                }
1630            } else if (tagName.equals(SCHEME_STR)) {
1631                String name = parser.getAttributeValue(null, NAME_STR);
1632                if (name != null) {
1633                    addDataScheme(name);
1634                }
1635            } else if (tagName.equals(SSP_STR)) {
1636                String ssp = parser.getAttributeValue(null, LITERAL_STR);
1637                if (ssp != null) {
1638                    addDataSchemeSpecificPart(ssp, PatternMatcher.PATTERN_LITERAL);
1639                } else if ((ssp=parser.getAttributeValue(null, PREFIX_STR)) != null) {
1640                    addDataSchemeSpecificPart(ssp, PatternMatcher.PATTERN_PREFIX);
1641                } else if ((ssp=parser.getAttributeValue(null, SGLOB_STR)) != null) {
1642                    addDataSchemeSpecificPart(ssp, PatternMatcher.PATTERN_SIMPLE_GLOB);
1643                }
1644            } else if (tagName.equals(AUTH_STR)) {
1645                String host = parser.getAttributeValue(null, HOST_STR);
1646                String port = parser.getAttributeValue(null, PORT_STR);
1647                if (host != null) {
1648                    addDataAuthority(host, port);
1649                }
1650            } else if (tagName.equals(PATH_STR)) {
1651                String path = parser.getAttributeValue(null, LITERAL_STR);
1652                if (path != null) {
1653                    addDataPath(path, PatternMatcher.PATTERN_LITERAL);
1654                } else if ((path=parser.getAttributeValue(null, PREFIX_STR)) != null) {
1655                    addDataPath(path, PatternMatcher.PATTERN_PREFIX);
1656                } else if ((path=parser.getAttributeValue(null, SGLOB_STR)) != null) {
1657                    addDataPath(path, PatternMatcher.PATTERN_SIMPLE_GLOB);
1658                }
1659            } else {
1660                Log.w("IntentFilter", "Unknown tag parsing IntentFilter: " + tagName);
1661            }
1662            XmlUtils.skipCurrentTag(parser);
1663        }
1664    }
1665
1666    public void dump(Printer du, String prefix) {
1667        StringBuilder sb = new StringBuilder(256);
1668        if (mActions.size() > 0) {
1669            Iterator<String> it = mActions.iterator();
1670            while (it.hasNext()) {
1671                sb.setLength(0);
1672                sb.append(prefix); sb.append("Action: \"");
1673                        sb.append(it.next()); sb.append("\"");
1674                du.println(sb.toString());
1675            }
1676        }
1677        if (mCategories != null) {
1678            Iterator<String> it = mCategories.iterator();
1679            while (it.hasNext()) {
1680                sb.setLength(0);
1681                sb.append(prefix); sb.append("Category: \"");
1682                        sb.append(it.next()); sb.append("\"");
1683                du.println(sb.toString());
1684            }
1685        }
1686        if (mDataSchemes != null) {
1687            Iterator<String> it = mDataSchemes.iterator();
1688            while (it.hasNext()) {
1689                sb.setLength(0);
1690                sb.append(prefix); sb.append("Scheme: \"");
1691                        sb.append(it.next()); sb.append("\"");
1692                du.println(sb.toString());
1693            }
1694        }
1695        if (mDataSchemeSpecificParts != null) {
1696            Iterator<PatternMatcher> it = mDataSchemeSpecificParts.iterator();
1697            while (it.hasNext()) {
1698                PatternMatcher pe = it.next();
1699                sb.setLength(0);
1700                sb.append(prefix); sb.append("Ssp: \"");
1701                        sb.append(pe); sb.append("\"");
1702                du.println(sb.toString());
1703            }
1704        }
1705        if (mDataAuthorities != null) {
1706            Iterator<AuthorityEntry> it = mDataAuthorities.iterator();
1707            while (it.hasNext()) {
1708                AuthorityEntry ae = it.next();
1709                sb.setLength(0);
1710                sb.append(prefix); sb.append("Authority: \"");
1711                        sb.append(ae.mHost); sb.append("\": ");
1712                        sb.append(ae.mPort);
1713                if (ae.mWild) sb.append(" WILD");
1714                du.println(sb.toString());
1715            }
1716        }
1717        if (mDataPaths != null) {
1718            Iterator<PatternMatcher> it = mDataPaths.iterator();
1719            while (it.hasNext()) {
1720                PatternMatcher pe = it.next();
1721                sb.setLength(0);
1722                sb.append(prefix); sb.append("Path: \"");
1723                        sb.append(pe); sb.append("\"");
1724                du.println(sb.toString());
1725            }
1726        }
1727        if (mDataTypes != null) {
1728            Iterator<String> it = mDataTypes.iterator();
1729            while (it.hasNext()) {
1730                sb.setLength(0);
1731                sb.append(prefix); sb.append("Type: \"");
1732                        sb.append(it.next()); sb.append("\"");
1733                du.println(sb.toString());
1734            }
1735        }
1736        if (mPriority != 0 || mHasPartialTypes) {
1737            sb.setLength(0);
1738            sb.append(prefix); sb.append("mPriority="); sb.append(mPriority);
1739                    sb.append(", mHasPartialTypes="); sb.append(mHasPartialTypes);
1740            du.println(sb.toString());
1741        }
1742        {
1743            sb.setLength(0);
1744            sb.append(prefix); sb.append("AutoVerify="); sb.append(getAutoVerify());
1745            du.println(sb.toString());
1746        }
1747    }
1748
1749    public static final Parcelable.Creator<IntentFilter> CREATOR
1750            = new Parcelable.Creator<IntentFilter>() {
1751        public IntentFilter createFromParcel(Parcel source) {
1752            return new IntentFilter(source);
1753        }
1754
1755        public IntentFilter[] newArray(int size) {
1756            return new IntentFilter[size];
1757        }
1758    };
1759
1760    public final int describeContents() {
1761        return 0;
1762    }
1763
1764    public final void writeToParcel(Parcel dest, int flags) {
1765        dest.writeStringList(mActions);
1766        if (mCategories != null) {
1767            dest.writeInt(1);
1768            dest.writeStringList(mCategories);
1769        } else {
1770            dest.writeInt(0);
1771        }
1772        if (mDataSchemes != null) {
1773            dest.writeInt(1);
1774            dest.writeStringList(mDataSchemes);
1775        } else {
1776            dest.writeInt(0);
1777        }
1778        if (mDataTypes != null) {
1779            dest.writeInt(1);
1780            dest.writeStringList(mDataTypes);
1781        } else {
1782            dest.writeInt(0);
1783        }
1784        if (mDataSchemeSpecificParts != null) {
1785            final int N = mDataSchemeSpecificParts.size();
1786            dest.writeInt(N);
1787            for (int i=0; i<N; i++) {
1788                mDataSchemeSpecificParts.get(i).writeToParcel(dest, flags);
1789            }
1790        } else {
1791            dest.writeInt(0);
1792        }
1793        if (mDataAuthorities != null) {
1794            final int N = mDataAuthorities.size();
1795            dest.writeInt(N);
1796            for (int i=0; i<N; i++) {
1797                mDataAuthorities.get(i).writeToParcel(dest);
1798            }
1799        } else {
1800            dest.writeInt(0);
1801        }
1802        if (mDataPaths != null) {
1803            final int N = mDataPaths.size();
1804            dest.writeInt(N);
1805            for (int i=0; i<N; i++) {
1806                mDataPaths.get(i).writeToParcel(dest, flags);
1807            }
1808        } else {
1809            dest.writeInt(0);
1810        }
1811        dest.writeInt(mPriority);
1812        dest.writeInt(mHasPartialTypes ? 1 : 0);
1813        dest.writeInt(getAutoVerify() ? 1 : 0);
1814    }
1815
1816    /**
1817     * For debugging -- perform a check on the filter, return true if it passed
1818     * or false if it failed.
1819     *
1820     * {@hide}
1821     */
1822    public boolean debugCheck() {
1823        return true;
1824
1825        // This code looks for intent filters that do not specify data.
1826        /*
1827        if (mActions != null && mActions.size() == 1
1828                && mActions.contains(Intent.ACTION_MAIN)) {
1829            return true;
1830        }
1831
1832        if (mDataTypes == null && mDataSchemes == null) {
1833            Log.w("IntentFilter", "QUESTIONABLE INTENT FILTER:");
1834            dump(Log.WARN, "IntentFilter", "  ");
1835            return false;
1836        }
1837
1838        return true;
1839        */
1840    }
1841
1842    private IntentFilter(Parcel source) {
1843        mActions = new ArrayList<String>();
1844        source.readStringList(mActions);
1845        if (source.readInt() != 0) {
1846            mCategories = new ArrayList<String>();
1847            source.readStringList(mCategories);
1848        }
1849        if (source.readInt() != 0) {
1850            mDataSchemes = new ArrayList<String>();
1851            source.readStringList(mDataSchemes);
1852        }
1853        if (source.readInt() != 0) {
1854            mDataTypes = new ArrayList<String>();
1855            source.readStringList(mDataTypes);
1856        }
1857        int N = source.readInt();
1858        if (N > 0) {
1859            mDataSchemeSpecificParts = new ArrayList<PatternMatcher>(N);
1860            for (int i=0; i<N; i++) {
1861                mDataSchemeSpecificParts.add(new PatternMatcher(source));
1862            }
1863        }
1864        N = source.readInt();
1865        if (N > 0) {
1866            mDataAuthorities = new ArrayList<AuthorityEntry>(N);
1867            for (int i=0; i<N; i++) {
1868                mDataAuthorities.add(new AuthorityEntry(source));
1869            }
1870        }
1871        N = source.readInt();
1872        if (N > 0) {
1873            mDataPaths = new ArrayList<PatternMatcher>(N);
1874            for (int i=0; i<N; i++) {
1875                mDataPaths.add(new PatternMatcher(source));
1876            }
1877        }
1878        mPriority = source.readInt();
1879        mHasPartialTypes = source.readInt() > 0;
1880        setAutoVerify(source.readInt() > 0);
1881    }
1882
1883    private final boolean findMimeType(String type) {
1884        final ArrayList<String> t = mDataTypes;
1885
1886        if (type == null) {
1887            return false;
1888        }
1889
1890        if (t.contains(type)) {
1891            return true;
1892        }
1893
1894        // Deal with an Intent wanting to match every type in the IntentFilter.
1895        final int typeLength = type.length();
1896        if (typeLength == 3 && type.equals("*/*")) {
1897            return !t.isEmpty();
1898        }
1899
1900        // Deal with this IntentFilter wanting to match every Intent type.
1901        if (mHasPartialTypes && t.contains("*")) {
1902            return true;
1903        }
1904
1905        final int slashpos = type.indexOf('/');
1906        if (slashpos > 0) {
1907            if (mHasPartialTypes && t.contains(type.substring(0, slashpos))) {
1908                return true;
1909            }
1910            if (typeLength == slashpos+2 && type.charAt(slashpos+1) == '*') {
1911                // Need to look through all types for one that matches
1912                // our base...
1913                final int numTypes = t.size();
1914                for (int i = 0; i < numTypes; i++) {
1915                    final String v = t.get(i);
1916                    if (type.regionMatches(0, v, 0, slashpos+1)) {
1917                        return true;
1918                    }
1919                }
1920            }
1921        }
1922
1923        return false;
1924    }
1925
1926    /**
1927     * @hide
1928     */
1929    public ArrayList<String> getHostsList() {
1930        ArrayList<String> result = new ArrayList<>();
1931        Iterator<IntentFilter.AuthorityEntry> it = authoritiesIterator();
1932        if (it != null) {
1933            while (it.hasNext()) {
1934                IntentFilter.AuthorityEntry entry = it.next();
1935                result.add(entry.getHost());
1936            }
1937        }
1938        return result;
1939    }
1940
1941    /**
1942     * @hide
1943     */
1944    public String[] getHosts() {
1945        ArrayList<String> list = getHostsList();
1946        return list.toArray(new String[list.size()]);
1947    }
1948}
1949