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 android.app.Activity;
21import android.app.SearchManager;
22import android.content.ContentResolver;
23import android.content.Context;
24import android.content.Intent;
25import android.net.Uri;
26import android.nfc.NfcAdapter;
27import android.os.AsyncTask;
28import android.os.Bundle;
29import android.provider.Browser;
30import android.provider.MediaStore;
31import android.text.TextUtils;
32import android.util.Patterns;
33
34import com.android.browser.UI.ComboViews;
35import com.android.browser.search.SearchEngine;
36import com.android.common.Search;
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(ComboViews.Bookmarks);
88            return;
89        }
90
91        // In case the SearchDialog is open.
92        ((SearchManager) mActivity.getSystemService(Context.SEARCH_SERVICE))
93                .stopSearch();
94        if (Intent.ACTION_VIEW.equals(action)
95                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)
96                || Intent.ACTION_SEARCH.equals(action)
97                || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
98                || Intent.ACTION_WEB_SEARCH.equals(action)) {
99            // If this was a search request (e.g. search query directly typed into the address bar),
100            // pass it on to the default web search provider.
101            if (handleWebSearchIntent(mActivity, mController, intent)) {
102                return;
103            }
104
105            UrlData urlData = getUrlDataFromIntent(intent);
106            if (urlData.isEmpty()) {
107                urlData = new UrlData(mSettings.getHomePage());
108            }
109
110            if (intent.getBooleanExtra(Browser.EXTRA_CREATE_NEW_TAB, false)
111                  || urlData.isPreloaded()) {
112                Tab t = mController.openTab(urlData);
113                return;
114            }
115            /*
116             * TODO: Don't allow javascript URIs
117             * 0) If this is a javascript: URI, *always* open a new tab
118             * 1) If the URL is already opened, switch to that tab
119             * 2-phone) Reuse tab with same appId
120             * 2-tablet) Open new tab
121             */
122            final String appId = intent
123                    .getStringExtra(Browser.EXTRA_APPLICATION_ID);
124            if (!TextUtils.isEmpty(urlData.mUrl) &&
125                    urlData.mUrl.startsWith("javascript:")) {
126                // Always open javascript: URIs in new tabs
127                mController.openTab(urlData);
128                return;
129            }
130            if (Intent.ACTION_VIEW.equals(action)
131                    && (appId != null)
132                    && appId.startsWith(mActivity.getPackageName())) {
133                Tab appTab = mTabControl.getTabFromAppId(appId);
134                if ((appTab != null) && (appTab == mController.getCurrentTab())) {
135                    mController.switchToTab(appTab);
136                    mController.loadUrlDataIn(appTab, urlData);
137                    return;
138                }
139            }
140            if (Intent.ACTION_VIEW.equals(action)
141                     && !mActivity.getPackageName().equals(appId)) {
142                if (!BrowserActivity.isTablet(mActivity)
143                        && !mSettings.allowAppTabs()) {
144                    Tab appTab = mTabControl.getTabFromAppId(appId);
145                    if (appTab != null) {
146                        mController.reuseTab(appTab, urlData);
147                        return;
148                    }
149                }
150                // No matching application tab, try to find a regular tab
151                // with a matching url.
152                Tab appTab = mTabControl.findTabWithUrl(urlData.mUrl);
153                if (appTab != null) {
154                    // Transfer ownership
155                    appTab.setAppId(appId);
156                    if (current != appTab) {
157                        mController.switchToTab(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                    Tab tab = mController.openTab(urlData);
167                    if (tab != null) {
168                        tab.setAppId(appId);
169                        if ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
170                            tab.setCloseOnBack(true);
171                        }
172                    }
173                }
174            } else {
175                // Get rid of the subwindow if it exists
176                mController.dismissSubWindow(current);
177                // If the current Tab is being used as an application tab,
178                // remove the association, since the new Intent means that it is
179                // no longer associated with that application.
180                current.setAppId(null);
181                mController.loadUrlDataIn(current, urlData);
182            }
183        }
184    }
185
186    protected static UrlData getUrlDataFromIntent(Intent intent) {
187        String url = "";
188        Map<String, String> headers = null;
189        PreloadedTabControl preloaded = null;
190        String preloadedSearchBoxQuery = null;
191        if (intent != null
192                && (intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) {
193            final String action = intent.getAction();
194            if (Intent.ACTION_VIEW.equals(action) ||
195                    NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
196                url = UrlUtils.smartUrlFilter(intent.getData());
197                if (url != null && url.startsWith("http")) {
198                    final Bundle pairs = intent
199                            .getBundleExtra(Browser.EXTRA_HEADERS);
200                    if (pairs != null && !pairs.isEmpty()) {
201                        Iterator<String> iter = pairs.keySet().iterator();
202                        headers = new HashMap<String, String>();
203                        while (iter.hasNext()) {
204                            String key = iter.next();
205                            headers.put(key, pairs.getString(key));
206                        }
207                    }
208                }
209                if (intent.hasExtra(PreloadRequestReceiver.EXTRA_PRELOAD_ID)) {
210                    String id = intent.getStringExtra(PreloadRequestReceiver.EXTRA_PRELOAD_ID);
211                    preloadedSearchBoxQuery = intent.getStringExtra(
212                            PreloadRequestReceiver.EXTRA_SEARCHBOX_SETQUERY);
213                    preloaded = Preloader.getInstance().getPreloadedTab(id);
214                }
215            } else if (Intent.ACTION_SEARCH.equals(action)
216                    || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
217                    || Intent.ACTION_WEB_SEARCH.equals(action)) {
218                url = intent.getStringExtra(SearchManager.QUERY);
219                if (url != null) {
220                    // In general, we shouldn't modify URL from Intent.
221                    // But currently, we get the user-typed URL from search box as well.
222                    url = UrlUtils.fixUrl(url);
223                    url = UrlUtils.smartUrlFilter(url);
224                    String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
225                    if (url.contains(searchSource)) {
226                        String source = null;
227                        final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
228                        if (appData != null) {
229                            source = appData.getString(Search.SOURCE);
230                        }
231                        if (TextUtils.isEmpty(source)) {
232                            source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
233                        }
234                        url = url.replace(searchSource, "&source=android-"+source+"&");
235                    }
236                }
237            }
238        }
239        return new UrlData(url, headers, intent, preloaded, preloadedSearchBoxQuery);
240    }
241
242    /**
243     * Launches the default web search activity with the query parameters if the given intent's data
244     * are identified as plain search terms and not URLs/shortcuts.
245     * @return true if the intent was handled and web search activity was launched, false if not.
246     */
247    static boolean handleWebSearchIntent(Activity activity,
248            Controller controller, Intent intent) {
249        if (intent == null) return false;
250
251        String url = null;
252        final String action = intent.getAction();
253        if (Intent.ACTION_VIEW.equals(action)) {
254            Uri data = intent.getData();
255            if (data != null) url = data.toString();
256        } else if (Intent.ACTION_SEARCH.equals(action)
257                || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
258                || Intent.ACTION_WEB_SEARCH.equals(action)) {
259            url = intent.getStringExtra(SearchManager.QUERY);
260        }
261        return handleWebSearchRequest(activity, controller, url,
262                intent.getBundleExtra(SearchManager.APP_DATA),
263                intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
264    }
265
266    /**
267     * Launches the default web search activity with the query parameters if the given url string
268     * was identified as plain search terms and not URL/shortcut.
269     * @return true if the request was handled and web search activity was launched, false if not.
270     */
271    private static boolean handleWebSearchRequest(Activity activity,
272            Controller controller, String inUrl, Bundle appData,
273            String extraData) {
274        if (inUrl == null) return false;
275
276        // In general, we shouldn't modify URL from Intent.
277        // But currently, we get the user-typed URL from search box as well.
278        String url = UrlUtils.fixUrl(inUrl).trim();
279        if (TextUtils.isEmpty(url)) return false;
280
281        // URLs are handled by the regular flow of control, so
282        // return early.
283        if (Patterns.WEB_URL.matcher(url).matches()
284                || UrlUtils.ACCEPTED_URI_SCHEMA.matcher(url).matches()) {
285            return false;
286        }
287
288        final ContentResolver cr = activity.getContentResolver();
289        final String newUrl = url;
290        if (controller == null || controller.getTabControl() == null
291                || controller.getTabControl().getCurrentWebView() == null
292                || !controller.getTabControl().getCurrentWebView()
293                .isPrivateBrowsingEnabled()) {
294            new AsyncTask<Void, Void, Void>() {
295                @Override
296                protected Void doInBackground(Void... unused) {
297                        Browser.addSearchUrl(cr, newUrl);
298                    return null;
299                }
300            }.execute();
301        }
302
303        SearchEngine searchEngine = BrowserSettings.getInstance().getSearchEngine();
304        if (searchEngine == null) return false;
305        searchEngine.startSearch(activity, url, appData, extraData);
306
307        return true;
308    }
309
310    /**
311     * A UrlData class to abstract how the content will be set to WebView.
312     * This base class uses loadUrl to show the content.
313     */
314    static class UrlData {
315        final String mUrl;
316        final Map<String, String> mHeaders;
317        final PreloadedTabControl mPreloadedTab;
318        final String mSearchBoxQueryToSubmit;
319        final boolean mDisableUrlOverride;
320
321        UrlData(String url) {
322            this.mUrl = url;
323            this.mHeaders = null;
324            this.mPreloadedTab = null;
325            this.mSearchBoxQueryToSubmit = null;
326            this.mDisableUrlOverride = false;
327        }
328
329        UrlData(String url, Map<String, String> headers, Intent intent) {
330            this(url, headers, intent, null, null);
331        }
332
333        UrlData(String url, Map<String, String> headers, Intent intent,
334                PreloadedTabControl preloaded, String searchBoxQueryToSubmit) {
335            this.mUrl = url;
336            this.mHeaders = headers;
337            this.mPreloadedTab = preloaded;
338            this.mSearchBoxQueryToSubmit = searchBoxQueryToSubmit;
339            if (intent != null) {
340                mDisableUrlOverride = intent.getBooleanExtra(
341                        BrowserActivity.EXTRA_DISABLE_URL_OVERRIDE, false);
342            } else {
343                mDisableUrlOverride = false;
344            }
345        }
346
347        boolean isEmpty() {
348            return (mUrl == null || mUrl.length() == 0);
349        }
350
351        boolean isPreloaded() {
352            return mPreloadedTab != null;
353        }
354
355        PreloadedTabControl getPreloadedTab() {
356            return mPreloadedTab;
357        }
358
359        String getSearchBoxQueryToSubmit() {
360            return mSearchBoxQueryToSubmit;
361        }
362    }
363
364}
365