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