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