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