IntentHandler.java revision 7fa9bb35acad5b02baf7d4f8401a318735191203
1/*
2 * Copyright (C) 2010 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
17
18package com.android.browser;
19
20import com.android.browser.search.SearchEngine;
21import com.android.common.Search;
22import com.android.common.speech.LoggingEvents;
23
24import android.app.Activity;
25import android.app.SearchManager;
26import android.content.ContentResolver;
27import android.content.Context;
28import android.content.Intent;
29import android.net.Uri;
30import android.os.AsyncTask;
31import android.os.Bundle;
32import android.provider.Browser;
33import android.provider.MediaStore;
34import android.speech.RecognizerResultsIntent;
35import android.text.TextUtils;
36import android.util.Patterns;
37
38import java.util.HashMap;
39import java.util.Iterator;
40import java.util.Map;
41
42/**
43 * Handle all browser related intents
44 */
45public class IntentHandler {
46
47    // "source" parameter for Google search suggested by the browser
48    final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
49    // "source" parameter for Google search from unknown source
50    final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
51
52    /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
53
54    private Activity mActivity;
55    private Controller mController;
56    private TabControl mTabControl;
57    private BrowserSettings mSettings;
58
59    public IntentHandler(Activity browser, Controller controller) {
60        mActivity = browser;
61        mController = controller;
62        mTabControl = mController.getTabControl();
63        mSettings = controller.getSettings();
64    }
65
66    void onNewIntent(Intent intent) {
67        Tab current = mTabControl.getCurrentTab();
68        // When a tab is closed on exit, the current tab index is set to -1.
69        // Reset before proceed as Browser requires the current tab to be set.
70        if (current == null) {
71            // Try to reset the tab in case the index was incorrect.
72            current = mTabControl.getTab(0);
73            if (current == null) {
74                // No tabs at all so just ignore this intent.
75                return;
76            }
77            mController.setActiveTab(current);
78            mController.resetTitleAndIcon(current);
79        }
80        final String action = intent.getAction();
81        final int flags = intent.getFlags();
82        if (Intent.ACTION_MAIN.equals(action) ||
83                (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
84            // just resume the browser
85            return;
86        }
87        // In case the SearchDialog is open.
88        ((SearchManager) mActivity.getSystemService(Context.SEARCH_SERVICE))
89                .stopSearch();
90        boolean activateVoiceSearch = RecognizerResultsIntent
91                .ACTION_VOICE_SEARCH_RESULTS.equals(action);
92        if (Intent.ACTION_VIEW.equals(action)
93                || Intent.ACTION_SEARCH.equals(action)
94                || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
95                || Intent.ACTION_WEB_SEARCH.equals(action)
96                || activateVoiceSearch) {
97            if (current.isInVoiceSearchMode()) {
98                String title = current.getVoiceDisplayTitle();
99                if (title != null && title.equals(intent.getStringExtra(
100                        SearchManager.QUERY))) {
101                    // The user submitted the same search as the last voice
102                    // search, so do nothing.
103                    return;
104                }
105                if (Intent.ACTION_SEARCH.equals(action)
106                        && current.voiceSearchSourceIsGoogle()) {
107                    Intent logIntent = new Intent(
108                            LoggingEvents.ACTION_LOG_EVENT);
109                    logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
110                            LoggingEvents.VoiceSearch.QUERY_UPDATED);
111                    logIntent.putExtra(
112                            LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
113                            intent.getDataString());
114                    mActivity.sendBroadcast(logIntent);
115                    // Note, onPageStarted will revert the voice title bar
116                    // When http://b/issue?id=2379215 is fixed, we should update
117                    // the title bar here.
118                }
119            }
120            // If this was a search request (e.g. search query directly typed into the address bar),
121            // pass it on to the default web search provider.
122            if (handleWebSearchIntent(mActivity, mController, intent)) {
123                return;
124            }
125
126            UrlData urlData = getUrlDataFromIntent(intent);
127            if (urlData.isEmpty()) {
128                urlData = new UrlData(mSettings.getHomePage());
129            }
130
131            final String appId = intent
132                    .getStringExtra(Browser.EXTRA_APPLICATION_ID);
133            if ((Intent.ACTION_VIEW.equals(action)
134                    // If a voice search has no appId, it means that it came
135                    // from the browser.  In that case, reuse the current tab.
136                    || (activateVoiceSearch && appId != null))
137                    && !mActivity.getPackageName().equals(appId)
138                    && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
139                Tab appTab = mTabControl.getTabFromId(appId);
140                if (appTab != null) {
141                    mController.reuseTab(appTab, appId, urlData);
142                    return;
143                } else {
144                    // No matching application tab, try to find a regular tab
145                    // with a matching url.
146                    appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
147                    if (appTab != null) {
148                        if (current != appTab) {
149                            mController.switchToTab(mTabControl.getTabIndex(appTab));
150                        }
151                        // Otherwise, we are already viewing the correct tab.
152                    } else {
153                        // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
154                        // will be opened in a new tab unless we have reached
155                        // MAX_TABS. Then the url will be opened in the current
156                        // tab. If a new tab is created, it will have "true" for
157                        // exit on close.
158                        mController.openTabAndShow(urlData, true, appId);
159                    }
160                }
161            } else {
162                if (!urlData.isEmpty()
163                        && urlData.mUrl.startsWith("about:debug")) {
164                    if ("about:debug.dom".equals(urlData.mUrl)) {
165                        current.getWebView().dumpDomTree(false);
166                    } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
167                        current.getWebView().dumpDomTree(true);
168                    } else if ("about:debug.render".equals(urlData.mUrl)) {
169                        current.getWebView().dumpRenderTree(false);
170                    } else if ("about:debug.render.file".equals(urlData.mUrl)) {
171                        current.getWebView().dumpRenderTree(true);
172                    } else if ("about:debug.display".equals(urlData.mUrl)) {
173                        current.getWebView().dumpDisplayTree();
174                    } else {
175                        mSettings.toggleDebugSettings();
176                    }
177                    return;
178                }
179                // Get rid of the subwindow if it exists
180                mController.dismissSubWindow(current);
181                // If the current Tab is being used as an application tab,
182                // remove the association, since the new Intent means that it is
183                // no longer associated with that application.
184                current.setAppId(null);
185                mController.loadUrlDataIn(current, urlData);
186            }
187        }
188    }
189
190    protected UrlData getUrlDataFromIntent(Intent intent) {
191        String url = "";
192        Map<String, String> headers = null;
193        if (intent != null) {
194            final String action = intent.getAction();
195            if (Intent.ACTION_VIEW.equals(action)) {
196                url = UrlUtils.smartUrlFilter(intent.getData());
197                if (url != null && url.startsWith("content:")) {
198                    /* Append mimetype so webview knows how to display */
199                    String mimeType = intent.resolveType(mActivity.getContentResolver());
200                    if (mimeType != null) {
201                        url += "?" + mimeType;
202                    }
203                }
204                if (url != null && url.startsWith("http")) {
205                    final Bundle pairs = intent
206                            .getBundleExtra(Browser.EXTRA_HEADERS);
207                    if (pairs != null && !pairs.isEmpty()) {
208                        Iterator<String> iter = pairs.keySet().iterator();
209                        headers = new HashMap<String, String>();
210                        while (iter.hasNext()) {
211                            String key = iter.next();
212                            headers.put(key, pairs.getString(key));
213                        }
214                    }
215                }
216            } else if (Intent.ACTION_SEARCH.equals(action)
217                    || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
218                    || Intent.ACTION_WEB_SEARCH.equals(action)) {
219                url = intent.getStringExtra(SearchManager.QUERY);
220                if (url != null) {
221                    // In general, we shouldn't modify URL from Intent.
222                    // But currently, we get the user-typed URL from search box as well.
223                    url = UrlUtils.fixUrl(url);
224                    url = UrlUtils.smartUrlFilter(url);
225                    String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
226                    if (url.contains(searchSource)) {
227                        String source = null;
228                        final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
229                        if (appData != null) {
230                            source = appData.getString(Search.SOURCE);
231                        }
232                        if (TextUtils.isEmpty(source)) {
233                            source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
234                        }
235                        url = url.replace(searchSource, "&source=android-"+source+"&");
236                    }
237                }
238            }
239        }
240        return new UrlData(url, headers, intent);
241    }
242
243    /**
244     * Launches the default web search activity with the query parameters if the given intent's data
245     * are identified as plain search terms and not URLs/shortcuts.
246     * @return true if the intent was handled and web search activity was launched, false if not.
247     */
248    static boolean handleWebSearchIntent(Activity activity,
249            Controller controller, Intent intent) {
250        if (intent == null) return false;
251
252        String url = null;
253        final String action = intent.getAction();
254        if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
255                action)) {
256            return false;
257        }
258        if (Intent.ACTION_VIEW.equals(action)) {
259            Uri data = intent.getData();
260            if (data != null) url = data.toString();
261        } else if (Intent.ACTION_SEARCH.equals(action)
262                || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
263                || Intent.ACTION_WEB_SEARCH.equals(action)) {
264            url = intent.getStringExtra(SearchManager.QUERY);
265        }
266        return handleWebSearchRequest(activity, controller, url,
267                intent.getBundleExtra(SearchManager.APP_DATA),
268                intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
269    }
270
271    /**
272     * Launches the default web search activity with the query parameters if the given url string
273     * was identified as plain search terms and not URL/shortcut.
274     * @return true if the request was handled and web search activity was launched, false if not.
275     */
276    private static boolean handleWebSearchRequest(Activity activity,
277            Controller controller, String inUrl, Bundle appData,
278            String extraData) {
279        if (inUrl == null) return false;
280
281        // In general, we shouldn't modify URL from Intent.
282        // But currently, we get the user-typed URL from search box as well.
283        String url = UrlUtils.fixUrl(inUrl).trim();
284
285        // URLs are handled by the regular flow of control, so
286        // return early.
287        if (Patterns.WEB_URL.matcher(url).matches()
288                || UrlUtils.ACCEPTED_URI_SCHEMA.matcher(url).matches()) {
289            return false;
290        }
291
292        final ContentResolver cr = activity.getContentResolver();
293        final String newUrl = url;
294        if (controller == null || controller.getTabControl() == null
295                || controller.getTabControl().getCurrentWebView() == null
296                || !controller.getTabControl().getCurrentWebView()
297                .isPrivateBrowsingEnabled()) {
298            new AsyncTask<Void, Void, Void>() {
299                @Override
300                protected Void doInBackground(Void... unused) {
301                        Browser.addSearchUrl(cr, newUrl);
302                    return null;
303                }
304            }.execute();
305        }
306
307        SearchEngine searchEngine = BrowserSettings.getInstance().getSearchEngine();
308        if (searchEngine == null) return false;
309        searchEngine.startSearch(activity, url, appData, extraData);
310
311        return true;
312    }
313
314    /**
315     * A UrlData class to abstract how the content will be set to WebView.
316     * This base class uses loadUrl to show the content.
317     */
318    static class UrlData {
319        final String mUrl;
320        final Map<String, String> mHeaders;
321        final Intent mVoiceIntent;
322
323        UrlData(String url) {
324            this.mUrl = url;
325            this.mHeaders = null;
326            this.mVoiceIntent = null;
327        }
328
329        UrlData(String url, Map<String, String> headers, Intent intent) {
330            this.mUrl = url;
331            this.mHeaders = headers;
332            if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
333                    .equals(intent.getAction())) {
334                this.mVoiceIntent = intent;
335            } else {
336                this.mVoiceIntent = null;
337            }
338        }
339
340        boolean isEmpty() {
341            return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
342        }
343
344        /**
345         * Load this UrlData into the given Tab.  Use loadUrlDataIn to update
346         * the title bar as well.
347         */
348        public void loadIn(Tab t) {
349            if (mVoiceIntent != null) {
350                t.activateVoiceSearchMode(mVoiceIntent);
351            } else {
352                t.getWebView().loadUrl(mUrl, mHeaders);
353            }
354        }
355    }
356
357}
358