blob: 06e07105ee200e6ca03d4c5e8d651c3638d02f8e [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 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
17package com.android.browser;
18
Michael Kolb3f65c382010-08-20 15:31:16 -070019import com.android.browser.ScrollWebView.ScrollListener;
20import com.android.common.Search;
21import com.android.common.speech.LoggingEvents;
22
Michael Kolbed217742010-08-10 17:52:34 -070023import android.app.ActionBar;
The Android Open Source Project0c908882009-03-03 19:32:16 -080024import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080025import android.app.AlertDialog;
26import android.app.ProgressDialog;
27import android.app.SearchManager;
28import android.content.ActivityNotFoundException;
29import android.content.BroadcastReceiver;
Dianne Hackborn80f32622010-08-05 14:17:53 -070030import android.content.ClipboardManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080031import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050032import android.content.ContentProvider;
33import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080034import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040035import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080036import android.content.ContentValues;
37import android.content.Context;
38import android.content.DialogInterface;
39import android.content.Intent;
40import android.content.IntentFilter;
The Android Open Source Project0c908882009-03-03 19:32:16 -080041import android.content.pm.PackageManager;
42import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.content.res.Configuration;
44import android.content.res.Resources;
45import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080046import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010047import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040050import android.graphics.PixelFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080052import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000053import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080054import android.net.Uri;
55import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080056import android.net.http.SslCertificate;
57import android.net.http.SslError;
58import android.os.AsyncTask;
59import android.os.Bundle;
60import android.os.Debug;
61import android.os.Environment;
62import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080063import android.os.Message;
64import android.os.PowerManager;
65import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080066import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080067import android.provider.Browser;
Jeff Hamilton8ce956c2010-08-17 11:13:53 -050068import android.provider.BrowserContract;
Cary Clark5e335a32009-09-22 14:53:11 -040069import android.provider.ContactsContract;
Michael Kolba2b2ba82010-08-04 17:54:03 -070070import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080071import android.provider.Downloads;
72import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050073import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080074import android.text.TextUtils;
75import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080076import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080077import android.util.Patterns;
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -040078import android.view.ActionMode;
The Android Open Source Project0c908882009-03-03 19:32:16 -080079import android.view.ContextMenu;
Michael Kolba2b2ba82010-08-04 17:54:03 -070080import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080081import android.view.Gravity;
82import android.view.KeyEvent;
83import android.view.LayoutInflater;
84import android.view.Menu;
85import android.view.MenuInflater;
86import android.view.MenuItem;
Michael Kolba2b2ba82010-08-04 17:54:03 -070087import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolb3f65c382010-08-20 15:31:16 -070088import android.view.MotionEvent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080089import android.view.View;
90import android.view.ViewGroup;
91import android.view.Window;
92import android.view.WindowManager;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070093import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080094import android.webkit.CookieManager;
95import android.webkit.CookieSyncManager;
96import android.webkit.DownloadListener;
97import android.webkit.HttpAuthHandler;
98import android.webkit.SslErrorHandler;
99import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +0100100import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800101import android.webkit.WebChromeClient;
102import android.webkit.WebHistoryItem;
103import android.webkit.WebIconDatabase;
104import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800105import android.widget.EditText;
106import android.widget.FrameLayout;
107import android.widget.LinearLayout;
108import android.widget.TextView;
109import android.widget.Toast;
110
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400111import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800112import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000113import java.io.IOException;
114import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800115import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700116import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import java.net.URL;
118import java.net.URLEncoder;
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700119import java.util.Calendar;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.util.HashMap;
Grace Kloba00f54c52010-01-27 14:53:51 -0800122import java.util.Iterator;
Grace Kloba068e48b2010-01-26 18:11:27 -0800123import java.util.Map;
Michael Kolbfe251992010-07-08 15:41:55 -0700124import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800125import java.util.regex.Matcher;
126import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800127
128public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700129 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130
Dave Bort31a6d1c2009-04-13 15:56:49 -0700131 /* Define some aliases to make these debugging flags easier to refer to.
132 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
133 */
134 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
135 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
136 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
137
Satish Sampath565505b2009-05-29 15:37:27 +0100138 // These are single-character shortcuts for searching popular sources.
139 private static final int SHORTCUT_INVALID = 0;
140 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
141 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
142 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
143 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
144
Cary Clarka9771242009-08-11 16:42:26 -0400145 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800146 @Override
147 public Void doInBackground(File... files) {
148 if (files != null) {
149 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400150 if (!f.delete()) {
151 Log.e(LOGTAG, f.getPath() + " was not deleted");
152 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800153 }
154 }
155 return null;
156 }
157 }
158
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400159 /**
160 * This layout holds everything you see below the status bar, including the
161 * error console, the custom view container, and the webviews.
162 */
163 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400164
Leon Scrogginsd746a942010-05-19 13:21:44 -0400165 private boolean mXLargeScreenSize;
166
Jeff Davidson43610292010-07-16 16:03:58 -0700167 private Boolean mIsProviderPresent = null;
168 private Uri mRlzUri = null;
169
Grace Kloba22ac16e2009-10-07 18:00:23 -0700170 @Override
171 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700172 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800173 Log.v(LOGTAG, this + " onStart");
174 }
175 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800176 // test the browser in OpenGL
177 // requestWindowFeature(Window.FEATURE_OPENGL);
178
Mike Reedd334bf52010-01-26 15:21:44 -0500179 // enable this to test the browser in 32bit
180 if (false) {
181 getWindow().setFormat(PixelFormat.RGBX_8888);
182 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
183 }
184
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700185 if (AccessibilityManager.getInstance(this).isEnabled()) {
186 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
187 } else {
188 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
189 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800190
191 mResolver = getContentResolver();
192
Grace Kloba0923d692009-09-23 21:37:25 -0700193 // If this was a web search request, pass it on to the default web
194 // search provider and finish this activity.
195 if (handleWebSearchIntent(getIntent())) {
196 finish();
197 return;
198 }
199
The Android Open Source Project0c908882009-03-03 19:32:16 -0800200 mSecLockIcon = Resources.getSystem().getDrawable(
201 android.R.drawable.ic_secure);
202 mMixLockIcon = Resources.getSystem().getDrawable(
203 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204
Michael Kolbed217742010-08-10 17:52:34 -0700205 // Create the tab control and our initial tab
206 mTabControl = new TabControl(this);
207
208 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
209 & Configuration.SCREENLAYOUT_SIZE_MASK)
210 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
211
Leon Scroggins81db3662009-06-04 17:45:11 -0400212 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
213 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400214 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
215 .inflate(R.layout.custom_screen, null);
216 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
217 R.id.main_content);
218 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
219 .findViewById(R.id.error_console);
220 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
221 .findViewById(R.id.fullscreen_custom_content);
222 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Michael Kolbe0a36662010-06-29 10:37:12 -0700223
Leon Scrogginsd746a942010-05-19 13:21:44 -0400224 if (mXLargeScreenSize) {
Michael Kolba2b2ba82010-08-04 17:54:03 -0700225 mTitleBar = new TitleBarXLarge(this);
226 mTitleBar.setProgress(100);
227 mFakeTitleBar = new TitleBarXLarge(this);
Michael Kolbed217742010-08-10 17:52:34 -0700228 ActionBar actionBar = getActionBar();
Michael Kolba2b2ba82010-08-04 17:54:03 -0700229 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Michael Kolbed217742010-08-10 17:52:34 -0700230 actionBar.setCustomNavigationMode(mTabBar);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400231 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400232 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400233 // mTitleBar will be always be shown in the fully loaded mode on
234 // phone
235 mTitleBar.setProgress(100);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400236 mFakeTitleBar = new TitleBar(this);
237 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800238
The Android Open Source Project0c908882009-03-03 19:32:16 -0800239 // Open the icon database and retain all the bookmark urls for favicons
240 retainIconsOnStartup();
241
242 // Keep a settings instance handy.
243 mSettings = BrowserSettings.getInstance();
244 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800245
246 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
247 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
248
Patrick Scott6adacc92010-03-05 08:24:51 -0500249 // Find out if the network is currently up.
250 ConnectivityManager cm = (ConnectivityManager) getSystemService(
251 Context.CONNECTIVITY_SERVICE);
252 NetworkInfo info = cm.getActiveNetworkInfo();
253 if (info != null) {
254 mIsNetworkUp = info.isAvailable();
255 }
256
Grace Klobaa34f6862009-07-31 16:28:17 -0700257 /* enables registration for changes in network status from
258 http stack */
259 mNetworkStateChangedFilter = new IntentFilter();
260 mNetworkStateChangedFilter.addAction(
261 ConnectivityManager.CONNECTIVITY_ACTION);
262 mNetworkStateIntentReceiver = new BroadcastReceiver() {
263 @Override
264 public void onReceive(Context context, Intent intent) {
265 if (intent.getAction().equals(
266 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000267
268 NetworkInfo info = intent.getParcelableExtra(
269 ConnectivityManager.EXTRA_NETWORK_INFO);
270 String typeName = info.getTypeName();
271 String subtypeName = info.getSubtypeName();
272 sendNetworkType(typeName.toLowerCase(),
273 (subtypeName != null ? subtypeName.toLowerCase() : ""));
274
275 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700276 }
277 }
278 };
279
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700280 // Unless the last browser usage was within 24 hours, destroy any
281 // remaining incognito tabs.
282
283 Calendar lastActiveDate = icicle != null ? (Calendar) icicle.getSerializable("lastActiveDate") : null;
284 Calendar today = Calendar.getInstance();
285 Calendar yesterday = Calendar.getInstance();
286 yesterday.add(Calendar.DATE, -1);
287
288 boolean dontRestoreIncognitoTabs = lastActiveDate == null
289 || lastActiveDate.before(yesterday)
290 || lastActiveDate.after(today);
291
292 if (!mTabControl.restoreState(icicle, dontRestoreIncognitoTabs)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800293 // clear up the thumbnail directory if we can't restore the state as
294 // none of the files in the directory are referenced any more.
295 new ClearThumbnails().execute(
296 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700297 // there is no quit on Android. But if we can't restore the state,
298 // we can treat it as a new Browser, remove the old session cookies.
299 CookieManager.getInstance().removeSessionCookie();
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700300 // remove any incognito files
301 WebView.cleanupPrivateBrowsingFiles(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800302 final Intent intent = getIntent();
303 final Bundle extra = intent.getExtras();
304 // Create an initial tab.
305 // If the intent is ACTION_VIEW and data is not null, the Browser is
306 // invoked to view the content by another application. In this case,
307 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700308 UrlData urlData = getUrlDataFromIntent(intent);
309
Leon Scroggins58d56c62010-01-28 15:12:40 -0500310 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700311 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500312 (Intent.ACTION_VIEW.equals(action) &&
313 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500314 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
315 .equals(action),
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700316 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
317 urlData.mUrl, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800318 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800319 attachTabToContentView(t);
320 WebView webView = t.getWebView();
321 if (extra != null) {
322 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
323 if (scale > 0 && scale <= 1000) {
324 webView.setInitialScale(scale);
325 }
326 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800327
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700328 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700329 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800330 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500331 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800332 }
333 } else {
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700334 if (dontRestoreIncognitoTabs) {
335 WebView.cleanupPrivateBrowsingFiles(this);
336 }
337
The Android Open Source Project0c908882009-03-03 19:32:16 -0800338 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400339 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800340 attachTabToContentView(mTabControl.getCurrentTab());
341 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700342
Cary Clarkb4b83182010-07-01 12:36:56 -0400343 // Delete old thumbnails to save space
344 File dir = mTabControl.getThumbnailDir();
345 if (dir.exists()) {
346 for (String child : dir.list()) {
347 File f = new File(dir, child);
348 f.delete();
349 }
350 }
351
Feng Qianb3c02da2009-06-29 15:58:08 -0700352 // Read JavaScript flags if it exists.
353 String jsFlags = mSettings.getJsFlags();
354 if (jsFlags.trim().length() != 0) {
355 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
356 }
Bjorn Bringerta7611812010-03-24 11:12:02 +0000357
358 // Start watching the default geolocation permissions
359 mSystemAllowGeolocationOrigins
360 = new SystemAllowGeolocationOrigins(getApplicationContext());
361 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800362 }
363
Michael Kolba2b2ba82010-08-04 17:54:03 -0700364 ScrollListener getScrollListener() {
365 return mTabBar;
366 }
367
Leon Scroggins58d56c62010-01-28 15:12:40 -0500368 /**
369 * Feed the previously stored results strings to the BrowserProvider so that
370 * the SearchDialog will show them instead of the standard searches.
371 * @param result String to show on the editable line of the SearchDialog.
372 */
373 /* package */ void showVoiceSearchResults(String result) {
374 ContentProviderClient client = mResolver.acquireContentProviderClient(
375 Browser.BOOKMARKS_URI);
376 ContentProvider prov = client.getLocalContentProvider();
377 BrowserProvider bp = (BrowserProvider) prov;
378 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
379 client.release();
380
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500381 Bundle bundle = createGoogleSearchSourceBundle(
382 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
383 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
384 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500385 }
386
The Android Open Source Project0c908882009-03-03 19:32:16 -0800387 @Override
388 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700389 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800390 // When a tab is closed on exit, the current tab index is set to -1.
391 // Reset before proceed as Browser requires the current tab to be set.
392 if (current == null) {
393 // Try to reset the tab in case the index was incorrect.
394 current = mTabControl.getTab(0);
395 if (current == null) {
396 // No tabs at all so just ignore this intent.
397 return;
398 }
399 mTabControl.setCurrentTab(current);
400 attachTabToContentView(current);
401 resetTitleAndIcon(current.getWebView());
402 }
403 final String action = intent.getAction();
404 final int flags = intent.getFlags();
405 if (Intent.ACTION_MAIN.equals(action) ||
406 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
407 // just resume the browser
408 return;
409 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400410 // In case the SearchDialog is open.
411 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
412 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500413 boolean activateVoiceSearch = RecognizerResultsIntent
414 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800415 if (Intent.ACTION_VIEW.equals(action)
416 || Intent.ACTION_SEARCH.equals(action)
417 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500418 || Intent.ACTION_WEB_SEARCH.equals(action)
419 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500420 if (current.isInVoiceSearchMode()) {
421 String title = current.getVoiceDisplayTitle();
422 if (title != null && title.equals(intent.getStringExtra(
423 SearchManager.QUERY))) {
424 // The user submitted the same search as the last voice
425 // search, so do nothing.
426 return;
427 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500428 if (Intent.ACTION_SEARCH.equals(action)
429 && current.voiceSearchSourceIsGoogle()) {
430 Intent logIntent = new Intent(
431 LoggingEvents.ACTION_LOG_EVENT);
432 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
433 LoggingEvents.VoiceSearch.QUERY_UPDATED);
434 logIntent.putExtra(
435 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
436 intent.getDataString());
437 sendBroadcast(logIntent);
438 // Note, onPageStarted will revert the voice title bar
439 // When http://b/issue?id=2379215 is fixed, we should update
440 // the title bar here.
441 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500442 }
Satish Sampath565505b2009-05-29 15:37:27 +0100443 // If this was a search request (e.g. search query directly typed into the address bar),
444 // pass it on to the default web search provider.
445 if (handleWebSearchIntent(intent)) {
446 return;
447 }
448
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700449 UrlData urlData = getUrlDataFromIntent(intent);
450 if (urlData.isEmpty()) {
451 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800452 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700453
Grace Klobacc634032009-07-28 15:58:19 -0700454 final String appId = intent
455 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400456 if ((Intent.ACTION_VIEW.equals(action)
457 // If a voice search has no appId, it means that it came
458 // from the browser. In that case, reuse the current tab.
459 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700460 && !getPackageName().equals(appId)
461 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700462 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700463 if (appTab != null) {
464 Log.i(LOGTAG, "Reusing tab for " + appId);
465 // Dismiss the subwindow if applicable.
466 dismissSubWindow(appTab);
467 // Since we might kill the WebView, remove it from the
468 // content view first.
469 removeTabFromContentView(appTab);
470 // Recreate the main WebView after destroying the old one.
471 // If the WebView has the same original url and is on that
472 // page, it can be reused.
473 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400474 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100475
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700476 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400477 switchToTab(mTabControl.getTabIndex(appTab));
478 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500479 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400480 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700481 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400482 // If the tab was the current tab, we have to attach
483 // it to the view system again.
484 attachTabToContentView(appTab);
485 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500486 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700487 }
488 }
489 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400490 } else {
491 // No matching application tab, try to find a regular tab
492 // with a matching url.
493 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400494 if (appTab != null) {
495 if (current != appTab) {
496 switchToTab(mTabControl.getTabIndex(appTab));
497 }
498 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400499 } else {
500 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
501 // will be opened in a new tab unless we have reached
502 // MAX_TABS. Then the url will be opened in the current
503 // tab. If a new tab is created, it will have "true" for
504 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400505 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400506 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700507 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800508 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800509 if (!urlData.isEmpty()
510 && urlData.mUrl.startsWith("about:debug")) {
511 if ("about:debug.dom".equals(urlData.mUrl)) {
512 current.getWebView().dumpDomTree(false);
513 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
514 current.getWebView().dumpDomTree(true);
515 } else if ("about:debug.render".equals(urlData.mUrl)) {
516 current.getWebView().dumpRenderTree(false);
517 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
518 current.getWebView().dumpRenderTree(true);
519 } else if ("about:debug.display".equals(urlData.mUrl)) {
520 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800521 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
522 int index = urlData.mUrl.codePointAt(16) - '0';
523 if (index <= 0 || index > 9) {
524 current.getWebView().setDragTracker(null);
525 } else {
526 current.getWebView().setDragTracker(new MeshTracker(index));
527 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800528 } else {
529 mSettings.toggleDebugSettings();
530 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800531 return;
532 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400533 // Get rid of the subwindow if it exists
534 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400535 // If the current Tab is being used as an application tab,
536 // remove the association, since the new Intent means that it is
537 // no longer associated with that application.
538 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500539 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800540 }
541 }
542 }
543
Satish Sampath565505b2009-05-29 15:37:27 +0100544 private int parseUrlShortcut(String url) {
545 if (url == null) return SHORTCUT_INVALID;
546
547 // FIXME: quick search, need to be customized by setting
548 if (url.length() > 2 && url.charAt(1) == ' ') {
549 switch (url.charAt(0)) {
550 case 'g': return SHORTCUT_GOOGLE_SEARCH;
551 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
552 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
553 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
554 }
555 }
556 return SHORTCUT_INVALID;
557 }
558
559 /**
560 * Launches the default web search activity with the query parameters if the given intent's data
561 * are identified as plain search terms and not URLs/shortcuts.
562 * @return true if the intent was handled and web search activity was launched, false if not.
563 */
564 private boolean handleWebSearchIntent(Intent intent) {
565 if (intent == null) return false;
566
567 String url = null;
568 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500569 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
570 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500571 return false;
572 }
Satish Sampath565505b2009-05-29 15:37:27 +0100573 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700574 Uri data = intent.getData();
575 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100576 } else if (Intent.ACTION_SEARCH.equals(action)
577 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
578 || Intent.ACTION_WEB_SEARCH.equals(action)) {
579 url = intent.getStringExtra(SearchManager.QUERY);
580 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100581 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
582 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100583 }
584
585 /**
586 * Launches the default web search activity with the query parameters if the given url string
587 * was identified as plain search terms and not URL/shortcut.
588 * @return true if the request was handled and web search activity was launched, false if not.
589 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100590 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100591 if (inUrl == null) return false;
592
593 // In general, we shouldn't modify URL from Intent.
594 // But currently, we get the user-typed URL from search box as well.
595 String url = fixUrl(inUrl).trim();
596
597 // URLs and site specific search shortcuts are handled by the regular flow of control, so
598 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800599 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100600 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100601 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
602 return false;
603 }
604
Leon Scroggins8d06e362010-03-24 14:45:57 -0400605 final ContentResolver cr = mResolver;
606 final String newUrl = url;
Elliott Slaughter627d96f2010-08-18 16:35:30 -0700607 if (mTabControl == null || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700608 new AsyncTask<Void, Void, Void>() {
609 @Override
610 protected Void doInBackground(Void... unused) {
611 Browser.updateVisitedHistory(cr, newUrl, false);
612 Browser.addSearchUrl(cr, newUrl);
613 return null;
614 }
615 }.execute();
616 }
Satish Sampath565505b2009-05-29 15:37:27 +0100617
618 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
619 intent.addCategory(Intent.CATEGORY_DEFAULT);
620 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100621 if (appData != null) {
622 intent.putExtra(SearchManager.APP_DATA, appData);
623 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100624 if (extraData != null) {
625 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
626 }
Grace Klobacc634032009-07-28 15:58:19 -0700627 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Mattias Falk552751e2010-08-23 12:03:57 +0200628
629 // can't be sure there is an activity for the Intent
630 try {
631 startActivity(intent);
632 } catch (ActivityNotFoundException ex) {
633 return false;
634 }
Satish Sampath565505b2009-05-29 15:37:27 +0100635
636 return true;
637 }
638
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700639 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500640 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800641 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800642 if (intent != null) {
643 final String action = intent.getAction();
644 if (Intent.ACTION_VIEW.equals(action)) {
645 url = smartUrlFilter(intent.getData());
646 if (url != null && url.startsWith("content:")) {
647 /* Append mimetype so webview knows how to display */
648 String mimeType = intent.resolveType(getContentResolver());
649 if (mimeType != null) {
650 url += "?" + mimeType;
651 }
652 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800653 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800654 final Bundle pairs = intent
655 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800656 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800657 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800658 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800659 while (iter.hasNext()) {
660 String key = iter.next();
661 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800662 }
663 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700664 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800665 } else if (Intent.ACTION_SEARCH.equals(action)
666 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
667 || Intent.ACTION_WEB_SEARCH.equals(action)) {
668 url = intent.getStringExtra(SearchManager.QUERY);
669 if (url != null) {
670 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800671 // In general, we shouldn't modify URL from Intent.
672 // But currently, we get the user-typed URL from search box as well.
673 url = fixUrl(url);
674 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400675 final ContentResolver cr = mResolver;
676 final String newUrl = url;
Elliott Slaughter8389e992010-08-20 15:44:08 -0700677 if (mTabControl == null
678 || mTabControl.getCurrentWebView() == null
679 || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
680 new AsyncTask<Void, Void, Void>() {
681 @Override
682 protected Void doInBackground(Void... unused) {
683 Browser.updateVisitedHistory(cr, newUrl, false);
684 return null;
685 }
686 }.execute();
687 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800688 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
689 if (url.contains(searchSource)) {
690 String source = null;
691 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
692 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000693 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800694 }
695 if (TextUtils.isEmpty(source)) {
696 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
697 }
698 url = url.replace(searchSource, "&source=android-"+source+"&");
699 }
700 }
701 }
702 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500703 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800704 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500705 /* package */ void showVoiceTitleBar(String title) {
706 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500707 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700708 mFakeTitleBar.setInVoiceMode(true);
709 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500710 }
711 /* package */ void revertVoiceTitleBar() {
712 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500713 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700714 mFakeTitleBar.setInVoiceMode(false);
715 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500716 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800717 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400718 // FIXME: Converting the url to lower case
719 // duplicates functionality in smartUrlFilter().
720 // However, changing all current callers of fixUrl to
721 // call smartUrlFilter in addition may have unwanted
722 // consequences, and is deferred for now.
723 int colon = inUrl.indexOf(':');
724 boolean allLower = true;
725 for (int index = 0; index < colon; index++) {
726 char ch = inUrl.charAt(index);
727 if (!Character.isLetter(ch)) {
728 break;
729 }
730 allLower &= Character.isLowerCase(ch);
731 if (index == colon - 1 && !allLower) {
732 inUrl = inUrl.substring(0, colon).toLowerCase()
733 + inUrl.substring(colon);
734 }
735 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800736 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
737 return inUrl;
738 if (inUrl.startsWith("http:") ||
739 inUrl.startsWith("https:")) {
740 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
741 inUrl = inUrl.replaceFirst("/", "//");
742 } else inUrl = inUrl.replaceFirst(":", "://");
743 }
744 return inUrl;
745 }
746
Grace Kloba22ac16e2009-10-07 18:00:23 -0700747 @Override
748 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800749 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700750 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800751 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
752 }
753
754 if (!mActivityInPause) {
755 Log.e(LOGTAG, "BrowserActivity is already resumed.");
756 return;
757 }
758
Mike Reed7bfa63b2009-05-28 11:08:32 -0400759 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800760 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400761 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800762
763 if (mWakeLock.isHeld()) {
764 mHandler.removeMessages(RELEASE_WAKELOCK);
765 mWakeLock.release();
766 }
767
The Android Open Source Project0c908882009-03-03 19:32:16 -0800768 registerReceiver(mNetworkStateIntentReceiver,
769 mNetworkStateChangedFilter);
770 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800771 }
772
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400773 /**
774 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400775 * would change its appearance, use a different TitleBar to show overlayed
776 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400777 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700778 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400779
780 /**
781 * Keeps track of whether the options menu is open. This is important in
782 * determining whether to show or hide the title bar overlay.
783 */
784 private boolean mOptionsMenuOpen;
785
786 /**
787 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
788 * of whether the configuration has changed. The first onMenuOpened call
789 * after a configuration change is simply a reopening of the same menu
790 * (i.e. mIconView did not change).
791 */
792 private boolean mConfigChanged;
793
794 /**
795 * Whether or not the options menu is in its smaller, icon menu form. When
796 * true, we want the title bar overlay to be up. When false, we do not.
797 * Only meaningful if mOptionsMenuOpen is true.
798 */
799 private boolean mIconView;
800
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400801 @Override
802 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400803 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
804 if (mOptionsMenuOpen) {
805 if (mConfigChanged) {
806 // We do not need to make any changes to the state of the
807 // title bar, since the only thing that happened was a
808 // change in orientation
809 mConfigChanged = false;
810 } else {
811 if (mIconView) {
812 // Switching the menu to expanded view, so hide the
813 // title bar.
814 hideFakeTitleBar();
815 mIconView = false;
816 } else {
817 // Switching the menu back to icon view, so show the
818 // title bar once again.
819 showFakeTitleBar();
820 mIconView = true;
821 }
822 }
823 } else {
824 // The options menu is closed, so open it, and show the title
825 showFakeTitleBar();
826 mOptionsMenuOpen = true;
827 mConfigChanged = false;
828 mIconView = true;
829 }
830 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400831 return true;
832 }
833
Michael Kolba2b2ba82010-08-04 17:54:03 -0700834 void showFakeTitleBar() {
835 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700836 WebView mainView = mTabControl.getCurrentWebView();
837 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700838 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400839 return;
840 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100841 // Do not need to check for null, since the current tab will have
842 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400843 if (isInCustomActionMode()) {
844 // Do not show the fake title bar, while a custom ActionMode
845 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100846 return;
847 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700848 if (mXLargeScreenSize) {
849 mContentView.addView(mFakeTitleBar);
850 mTabBar.onShowTitleBar();
851 } else {
852 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400853
Michael Kolba2b2ba82010-08-04 17:54:03 -0700854 // Add the title bar to the window manager so it can receive
855 // touches
856 // while the menu is up
857 WindowManager.LayoutParams params =
858 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
859 ViewGroup.LayoutParams.WRAP_CONTENT,
860 WindowManager.LayoutParams.TYPE_APPLICATION,
861 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
862 PixelFormat.TRANSLUCENT);
863 params.gravity = Gravity.TOP;
864 boolean atTop = mainView.getScrollY() == 0;
865 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
866 manager.addView(mFakeTitleBar, params);
867 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400868 }
869 }
870
871 @Override
872 public void onOptionsMenuClosed(Menu menu) {
873 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400874 if (!mInLoad) {
875 hideFakeTitleBar();
876 } else if (!mIconView) {
877 // The page is currently loading, and we are in expanded mode, so
878 // we were not showing the menu. Show it once again. It will be
879 // removed when the page finishes.
880 showFakeTitleBar();
881 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400882 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700883
Michael Kolba2b2ba82010-08-04 17:54:03 -0700884 void stopScrolling() {
885 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
886 }
887
888 void hideFakeTitleBar() {
889 if (!isFakeTitleBarShowing()) return;
890 if (mXLargeScreenSize) {
891 mContentView.removeView(mFakeTitleBar);
892 mTabBar.onHideTitleBar();
893 } else {
894 WindowManager.LayoutParams params =
895 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
896 WebView mainView = mTabControl.getCurrentWebView();
897 // Although we decided whether or not to animate based on the
898 // current
899 // scroll position, the scroll position may have changed since the
900 // fake title bar was displayed. Make sure it has the appropriate
901 // animation/lack thereof before removing.
902 params.windowAnimations =
903 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
904 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
905 manager.updateViewLayout(mFakeTitleBar, params);
906 manager.removeView(mFakeTitleBar);
907 }
908 }
909
910 boolean isFakeTitleBarShowing() {
911 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400912 }
913
The Android Open Source Project0c908882009-03-03 19:32:16 -0800914 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400915 * Special method for the fake title bar to call when displaying its context
916 * menu, since it is in its own Window, and its parent does not show a
917 * context menu.
918 */
919 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400920 if (null == mTitleBar.getParent()) {
921 return;
922 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400923 openContextMenu(mTitleBar);
924 }
925
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400926 @Override
927 public void onContextMenuClosed(Menu menu) {
928 super.onContextMenuClosed(menu);
929 if (mInLoad) {
930 showFakeTitleBar();
931 }
932 }
933
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400934 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800935 * onSaveInstanceState(Bundle map)
936 * onSaveInstanceState is called right before onStop(). The map contains
937 * the saved state.
938 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700939 @Override
940 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700941 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800942 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
943 }
944 // the default implementation requires each view to have an id. As the
945 // browser handles the state itself and it doesn't use id for the views,
946 // don't call the default implementation. Otherwise it will trigger the
947 // warning like this, "couldn't save which view has focus because the
948 // focused view XXX has no id".
949
950 // Save all the tabs
951 mTabControl.saveState(outState);
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700952
953 // Save time so that we know how old incognito tabs (if any) are.
954 outState.putSerializable("lastActiveDate", Calendar.getInstance());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800955 }
956
Grace Kloba22ac16e2009-10-07 18:00:23 -0700957 @Override
958 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800959 super.onPause();
960
961 if (mActivityInPause) {
962 Log.e(LOGTAG, "BrowserActivity is already paused.");
963 return;
964 }
965
Mike Reed7bfa63b2009-05-28 11:08:32 -0400966 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800967 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400968 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800969 mWakeLock.acquire();
970 mHandler.sendMessageDelayed(mHandler
971 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
972 }
973
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400974 // FIXME: This removes the active tabs page and resets the menu to
975 // MAIN_MENU. A better solution might be to do this work in onNewIntent
976 // but then we would need to save it in onSaveInstanceState and restore
977 // it in onCreate/onRestoreInstanceState
978 if (mActiveTabsPage != null) {
979 removeActiveTabPage(true);
980 }
981
The Android Open Source Project0c908882009-03-03 19:32:16 -0800982 cancelStopToast();
983
984 // unregister network state listener
985 unregisterReceiver(mNetworkStateIntentReceiver);
986 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800987 }
988
Grace Kloba22ac16e2009-10-07 18:00:23 -0700989 @Override
990 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700991 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800992 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
993 }
994 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700995
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400996 if (mUploadMessage != null) {
997 mUploadMessage.onReceiveValue(null);
998 mUploadMessage = null;
999 }
1000
Grace Kloba0923d692009-09-23 21:37:25 -07001001 if (mTabControl == null) return;
1002
Grace Kloba1fc98a32009-10-21 13:23:08 -07001003 // Remove the fake title bar if it is there
1004 hideFakeTitleBar();
1005
The Android Open Source Project0c908882009-03-03 19:32:16 -08001006 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001007 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001008 if (t != null) {
1009 dismissSubWindow(t);
1010 removeTabFromContentView(t);
1011 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001012 // Destroy all the tabs
1013 mTabControl.destroy();
1014 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001015
Bjorn Bringerta7611812010-03-24 11:12:02 +00001016 // Stop watching the default geolocation permissions
1017 mSystemAllowGeolocationOrigins.stop();
1018 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001019 }
1020
1021 @Override
1022 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001023 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001024 super.onConfigurationChanged(newConfig);
1025
1026 if (mPageInfoDialog != null) {
1027 mPageInfoDialog.dismiss();
1028 showPageInfo(
1029 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001030 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001031 }
1032 if (mSSLCertificateDialog != null) {
1033 mSSLCertificateDialog.dismiss();
1034 showSSLCertificate(
1035 mSSLCertificateView);
1036 }
1037 if (mSSLCertificateOnErrorDialog != null) {
1038 mSSLCertificateOnErrorDialog.dismiss();
1039 showSSLCertificateOnError(
1040 mSSLCertificateOnErrorView,
1041 mSSLCertificateOnErrorHandler,
1042 mSSLCertificateOnErrorError);
1043 }
1044 if (mHttpAuthenticationDialog != null) {
1045 String title = ((TextView) mHttpAuthenticationDialog
1046 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1047 .toString();
1048 String name = ((TextView) mHttpAuthenticationDialog
1049 .findViewById(R.id.username_edit)).getText().toString();
1050 String password = ((TextView) mHttpAuthenticationDialog
1051 .findViewById(R.id.password_edit)).getText().toString();
1052 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1053 .getId();
1054 mHttpAuthenticationDialog.dismiss();
1055 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1056 name, password, focusId);
1057 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001058 }
1059
Grace Kloba22ac16e2009-10-07 18:00:23 -07001060 @Override
1061 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001062 super.onLowMemory();
1063 mTabControl.freeMemory();
1064 }
1065
Cary Clarkff4d92c2010-03-25 11:17:03 -04001066 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001067 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001068 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001069 boolean inLoad = tab.inLoad();
1070 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001071 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001072 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001073 if (w != null) {
1074 w.resumeTimers();
1075 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001076 }
1077 }
1078
Mike Reed7bfa63b2009-05-28 11:08:32 -04001079 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001080 Tab tab = mTabControl.getCurrentTab();
1081 boolean inLoad = tab.inLoad();
1082 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001083 CookieSyncManager.getInstance().stopSync();
1084 WebView w = mTabControl.getCurrentWebView();
1085 if (w != null) {
1086 w.pauseTimers();
1087 }
1088 return true;
1089 } else {
1090 return false;
1091 }
1092 }
1093
The Android Open Source Project0c908882009-03-03 19:32:16 -08001094 // Open the icon database and retain all the icons for visited sites.
1095 private void retainIconsOnStartup() {
1096 final WebIconDatabase db = WebIconDatabase.getInstance();
1097 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001098 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001099 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001100 c = Browser.getAllBookmarks(mResolver);
1101 if (c.moveToFirst()) {
1102 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1103 do {
1104 String url = c.getString(urlIndex);
1105 db.retainIconForPageUrl(url);
1106 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001107 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001108 } catch (IllegalStateException e) {
1109 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001110 } finally {
1111 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001112 }
1113 }
1114
1115 // Helper method for getting the top window.
1116 WebView getTopWindow() {
1117 return mTabControl.getCurrentTopWebView();
1118 }
1119
Grace Kloba22ac16e2009-10-07 18:00:23 -07001120 TabControl getTabControl() {
1121 return mTabControl;
1122 }
1123
The Android Open Source Project0c908882009-03-03 19:32:16 -08001124 @Override
1125 public boolean onCreateOptionsMenu(Menu menu) {
1126 super.onCreateOptionsMenu(menu);
1127
1128 MenuInflater inflater = getMenuInflater();
1129 inflater.inflate(R.menu.browser, menu);
1130 mMenu = menu;
1131 updateInLoadMenuItems();
1132 return true;
1133 }
1134
1135 /**
1136 * As the menu can be open when loading state changes
1137 * we must manually update the state of the stop/reload menu
1138 * item
1139 */
1140 private void updateInLoadMenuItems() {
1141 if (mMenu == null) {
1142 return;
1143 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001144 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001145 MenuItem src = mInLoad ?
1146 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001147 mMenu.findItem(R.id.reload_menu_id);
1148 if (src != null) {
1149 dest.setIcon(src.getIcon());
1150 dest.setTitle(src.getTitle());
1151 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001152 }
1153
1154 @Override
1155 public boolean onContextItemSelected(MenuItem item) {
1156 // chording is not an issue with context menus, but we use the same
1157 // options selector, so set mCanChord to true so we can access them.
1158 mCanChord = true;
1159 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001160 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001161 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001162 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001163 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001164 Tab currentTab = mTabControl.getCurrentTab();
1165 if (null == currentTab) {
1166 result = false;
1167 break;
1168 }
1169 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001170 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001171 result = false;
1172 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001173 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001174 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001175 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001176 // -- Browser context menu
1177 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001178 case R.id.bookmark_context_menu_id:
1179 case R.id.save_link_context_menu_id:
1180 case R.id.share_link_context_menu_id:
1181 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001182 final WebView webView = getTopWindow();
1183 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001184 result = false;
1185 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001186 }
1187 final HashMap hrefMap = new HashMap();
1188 hrefMap.put("webview", webView);
1189 final Message msg = mHandler.obtainMessage(
1190 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001191 webView.requestFocusNodeHref(msg);
1192 break;
1193
1194 default:
1195 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001196 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001197 }
1198 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001199 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001200 }
1201
1202 private Bundle createGoogleSearchSourceBundle(String source) {
1203 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001204 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001205 return bundle;
1206 }
1207
Leon Scroggins8ad29922010-02-16 12:33:55 -05001208 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001209 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001210 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001211 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001212 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001213 }
1214
Leon Scroggins8ad29922010-02-16 12:33:55 -05001215 /**
1216 * Overriding this to insert a local information bundle
1217 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001218 @Override
1219 public void startSearch(String initialQuery, boolean selectInitialQuery,
1220 Bundle appSearchData, boolean globalSearch) {
1221 if (appSearchData == null) {
1222 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1223 }
1224 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1225 }
1226
Leon Scroggins1f005d32009-08-10 17:36:42 -04001227 /**
1228 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1229 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001230 * @param index Index of the tab to change to, as defined by
1231 * mTabControl.getTabIndex(Tab t).
1232 * @return boolean True if we successfully switched to a different tab. If
1233 * the indexth tab is null, or if that tab is the same as
1234 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001235 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001236 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001237 Tab tab = mTabControl.getTab(index);
1238 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001239 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001240 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001241 }
1242 if (currentTab != null) {
1243 // currentTab may be null if it was just removed. In that case,
1244 // we do not need to remove it
1245 removeTabFromContentView(currentTab);
1246 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001247 mTabControl.setCurrentTab(tab);
1248 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001249 resetTitleIconAndProgress();
1250 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001251 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001252 }
1253
Grace Kloba22ac16e2009-10-07 18:00:23 -07001254 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001255 return openTabAndShow(mSettings.getHomePage(), false, null);
1256 }
1257
Leon Scroggins1f005d32009-08-10 17:36:42 -04001258 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001259 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001260 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001261 // This is the last tab. Open a new one, with the home
1262 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001263 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001264 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001265 return;
1266 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001267 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001268 int indexToShow = -1;
1269 if (parent != null) {
1270 indexToShow = mTabControl.getTabIndex(parent);
1271 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001272 final int currentIndex = mTabControl.getCurrentIndex();
1273 // Try to move to the tab to the right
1274 indexToShow = currentIndex + 1;
1275 if (indexToShow > mTabControl.getTabCount() - 1) {
1276 // Try to move to the tab to the left
1277 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001278 }
1279 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001280 if (switchToTab(indexToShow)) {
1281 // Close window
1282 closeTab(current);
1283 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001284 }
1285
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001286 private ActiveTabsPage mActiveTabsPage;
1287
1288 /**
1289 * Remove the active tabs page.
1290 * @param needToAttach If true, the active tabs page did not attach a tab
1291 * to the content view, so we need to do that here.
1292 */
1293 /* package */ void removeActiveTabPage(boolean needToAttach) {
1294 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001295 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001296 mActiveTabsPage = null;
1297 mMenuState = R.id.MAIN_MENU;
1298 if (needToAttach) {
1299 attachTabToContentView(mTabControl.getCurrentTab());
1300 }
1301 getTopWindow().requestFocus();
1302 }
1303
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001304 @Override
1305 public ActionMode onStartActionMode(ActionMode.Callback callback) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001306 mActionMode = super.onStartActionMode(callback);
1307 hideFakeTitleBar();
1308 // Would like to change the MENU, but onEndActionMode may not be called
1309 return mActionMode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001310 }
1311
The Android Open Source Project0c908882009-03-03 19:32:16 -08001312 @Override
1313 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolbed217742010-08-10 17:52:34 -07001314 // check the action bar button before mCanChord check, as the prepare call
1315 // doesn't come for action bar buttons
1316 if (item.getItemId() == R.id.newtab) {
Michael Kolb300b7f02010-08-25 13:47:24 -07001317 openTabToHomePage();
1318 mHandler.sendMessage(mHandler.obtainMessage(OPEN_BOOKMARKS));
Michael Kolbed217742010-08-10 17:52:34 -07001319 return true;
1320 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001321 if (!mCanChord) {
1322 // The user has already fired a shortcut with this hold down of the
1323 // menu key.
1324 return false;
1325 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001326 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001327 return false;
1328 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001329 if (mMenuIsDown) {
1330 // The shortcut action consumes the MENU. Even if it is still down,
1331 // it won't trigger the next shortcut action. In the case of the
1332 // shortcut action triggering a new activity, like Bookmarks, we
1333 // won't get onKeyUp for MENU. So it is important to reset it here.
1334 mMenuIsDown = false;
1335 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001336 switch (item.getItemId()) {
1337 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001338 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001339 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001340 break;
1341
Michael Kolbae62fd42010-08-18 16:33:28 -07001342 case R.id.incognito_menu_id:
1343 openIncognitoTab();
1344 break;
1345
Leon Scroggins64b80f32009-08-07 12:03:34 -04001346 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001347 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001348 break;
1349
1350 case R.id.bookmarks_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001351 bookmarksOrHistoryPicker(false, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001352 break;
1353
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001354 case R.id.active_tabs_menu_id:
1355 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1356 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001357 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001358 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001359 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1360 mActiveTabsPage.requestFocus();
1361 mMenuState = EMPTY_MENU;
1362 break;
1363
Leon Scroggins1f005d32009-08-10 17:36:42 -04001364 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001365 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001366 break;
1367
1368 case R.id.stop_reload_menu_id:
1369 if (mInLoad) {
1370 stopLoading();
1371 } else {
1372 getTopWindow().reload();
1373 }
1374 break;
1375
1376 case R.id.back_menu_id:
1377 getTopWindow().goBack();
1378 break;
1379
1380 case R.id.forward_menu_id:
1381 getTopWindow().goForward();
1382 break;
1383
1384 case R.id.close_menu_id:
1385 // Close the subwindow if it exists.
1386 if (mTabControl.getCurrentSubWindow() != null) {
1387 dismissSubWindow(mTabControl.getCurrentTab());
1388 break;
1389 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001390 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001391 break;
1392
1393 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001394 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001395 if (current != null) {
1396 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001397 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001398 }
1399 break;
1400
1401 case R.id.preferences_menu_id:
1402 Intent intent = new Intent(this,
1403 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001404 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1405 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001406 startActivityForResult(intent, PREFERENCES_PAGE);
1407 break;
1408
1409 case R.id.find_menu_id:
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001410 getTopWindow().showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001411 break;
1412
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001413 case R.id.save_webarchive_menu_id:
1414 if (LOGD_ENABLED) {
1415 Log.d(LOGTAG, "Save as Web Archive");
1416 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001417 String state = Environment.getExternalStorageState();
1418 if (Environment.MEDIA_MOUNTED.equals(state)) {
1419 String directory = Environment.getExternalStoragePublicDirectory(
1420 Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator;
1421 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1422 @Override
1423 public void onReceiveValue(String value) {
1424 if (value != null) {
1425 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved,
1426 Toast.LENGTH_SHORT).show();
1427 } else {
1428 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1429 Toast.LENGTH_SHORT).show();
1430 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001431 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001432 });
1433 } else {
1434 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1435 Toast.LENGTH_SHORT).show();
1436 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001437 break;
1438
The Android Open Source Project0c908882009-03-03 19:32:16 -08001439 case R.id.page_info_menu_id:
1440 showPageInfo(mTabControl.getCurrentTab(), false);
1441 break;
1442
1443 case R.id.classic_history_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001444 bookmarksOrHistoryPicker(true, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001445 break;
1446
Leon Scroggins96afcb12009-12-10 12:35:56 -05001447 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001448 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001449 Tab currentTab = mTabControl.getCurrentTab();
1450 if (null == currentTab) {
1451 mCanChord = false;
1452 return false;
1453 }
1454 currentTab.populatePickerData();
1455 sharePage(this, currentTab.getTitle(),
1456 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001457 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1458 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001459 break;
1460
1461 case R.id.dump_nav_menu_id:
1462 getTopWindow().debugDump();
1463 break;
1464
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001465 case R.id.dump_counters_menu_id:
1466 getTopWindow().dumpV8Counters();
1467 break;
1468
The Android Open Source Project0c908882009-03-03 19:32:16 -08001469 case R.id.zoom_in_menu_id:
1470 getTopWindow().zoomIn();
1471 break;
1472
1473 case R.id.zoom_out_menu_id:
1474 getTopWindow().zoomOut();
1475 break;
1476
1477 case R.id.view_downloads_menu_id:
1478 viewDownloads(null);
1479 break;
1480
The Android Open Source Project0c908882009-03-03 19:32:16 -08001481 case R.id.window_one_menu_id:
1482 case R.id.window_two_menu_id:
1483 case R.id.window_three_menu_id:
1484 case R.id.window_four_menu_id:
1485 case R.id.window_five_menu_id:
1486 case R.id.window_six_menu_id:
1487 case R.id.window_seven_menu_id:
1488 case R.id.window_eight_menu_id:
1489 {
1490 int menuid = item.getItemId();
1491 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1492 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001493 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001494 if (desiredTab != null &&
1495 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001496 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001497 }
1498 break;
1499 }
1500 }
1501 }
1502 break;
1503
1504 default:
1505 if (!super.onOptionsItemSelected(item)) {
1506 return false;
1507 }
1508 // Otherwise fall through.
1509 }
1510 mCanChord = false;
1511 return true;
1512 }
1513
Leon Scroggins571b3762010-05-26 10:25:01 -04001514 /* package */ void bookmarkCurrentPage() {
1515 Intent i = new Intent(BrowserActivity.this,
1516 AddBookmarkPage.class);
1517 WebView w = getTopWindow();
1518 i.putExtra("url", w.getUrl());
1519 i.putExtra("title", w.getTitle());
1520 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001521 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1522 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001523 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001524 startActivity(i);
1525 }
1526
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001527 /*
1528 * True if a custom ActionMode (i.e. find or select) is in use.
1529 */
1530 private boolean isInCustomActionMode() {
1531 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001532 }
1533
1534 /*
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001535 * End the current ActionMode.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001536 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001537 void endActionMode() {
1538 if (mActionMode != null) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001539 ActionMode mode = mActionMode;
1540 onEndActionMode();
1541 mode.finish();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001542 }
1543 }
1544
1545 /*
1546 * Called by find and select when they are finished. Replace title bars
1547 * as necessary.
1548 */
1549 public void onEndActionMode() {
1550 if (!isInCustomActionMode()) return;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001551 if (mInLoad) {
1552 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001553 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001554 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001555 showFakeTitleBar();
1556 }
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001557 // Would like to return the menu state to normal, but this does not
1558 // necessarily get called.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001559 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001560 }
1561
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001562 // For select and find, we keep track of the ActionMode so that
1563 // finish() can be called as desired.
1564 private ActionMode mActionMode;
1565
Grace Kloba22ac16e2009-10-07 18:00:23 -07001566 @Override
1567 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001568 // This happens when the user begins to hold down the menu key, so
1569 // allow them to chord to get a shortcut.
1570 mCanChord = true;
1571 // Note: setVisible will decide whether an item is visible; while
1572 // setEnabled() will decide whether an item is enabled, which also means
1573 // whether the matching shortcut key will function.
1574 super.onPrepareOptionsMenu(menu);
1575 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001576 case EMPTY_MENU:
1577 if (mCurrentMenuState != mMenuState) {
1578 menu.setGroupVisible(R.id.MAIN_MENU, false);
1579 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1580 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001581 }
1582 break;
1583 default:
1584 if (mCurrentMenuState != mMenuState) {
1585 menu.setGroupVisible(R.id.MAIN_MENU, true);
1586 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1587 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001588 }
1589 final WebView w = getTopWindow();
1590 boolean canGoBack = false;
1591 boolean canGoForward = false;
1592 boolean isHome = false;
1593 if (w != null) {
1594 canGoBack = w.canGoBack();
1595 canGoForward = w.canGoForward();
1596 isHome = mSettings.getHomePage().equals(w.getUrl());
1597 }
1598 final MenuItem back = menu.findItem(R.id.back_menu_id);
1599 back.setEnabled(canGoBack);
1600
1601 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1602 home.setEnabled(!isHome);
1603
Michael Kolbe0a36662010-06-29 10:37:12 -07001604 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1605 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001606
Michael Kolbed217742010-08-10 17:52:34 -07001607 if (!mXLargeScreenSize) {
1608 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1609 newtab.setEnabled(mTabControl.canCreateNewTab());
1610 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001611
The Android Open Source Project0c908882009-03-03 19:32:16 -08001612 // decide whether to show the share link option
1613 PackageManager pm = getPackageManager();
1614 Intent send = new Intent(Intent.ACTION_SEND);
1615 send.setType("text/plain");
1616 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1617 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1618
The Android Open Source Project0c908882009-03-03 19:32:16 -08001619 boolean isNavDump = mSettings.isNavDump();
1620 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1621 nav.setVisible(isNavDump);
1622 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001623
1624 boolean showDebugSettings = mSettings.showDebugSettings();
1625 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1626 counter.setVisible(showDebugSettings);
1627 counter.setEnabled(showDebugSettings);
1628
The Android Open Source Project0c908882009-03-03 19:32:16 -08001629 break;
1630 }
1631 mCurrentMenuState = mMenuState;
1632 return true;
1633 }
1634
1635 @Override
1636 public void onCreateContextMenu(ContextMenu menu, View v,
1637 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001638 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001639 return;
1640 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001641 WebView webview = (WebView) v;
1642 WebView.HitTestResult result = webview.getHitTestResult();
1643 if (result == null) {
1644 return;
1645 }
1646
1647 int type = result.getType();
1648 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1649 Log.w(LOGTAG,
1650 "We should not show context menu when nothing is touched");
1651 return;
1652 }
1653 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1654 // let TextView handles context menu
1655 return;
1656 }
1657
1658 // Note, http://b/issue?id=1106666 is requesting that
1659 // an inflated menu can be used again. This is not available
1660 // yet, so inflate each time (yuk!)
1661 MenuInflater inflater = getMenuInflater();
1662 inflater.inflate(R.menu.browsercontext, menu);
1663
1664 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001665 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001666 menu.setGroupVisible(R.id.PHONE_MENU,
1667 type == WebView.HitTestResult.PHONE_TYPE);
1668 menu.setGroupVisible(R.id.EMAIL_MENU,
1669 type == WebView.HitTestResult.EMAIL_TYPE);
1670 menu.setGroupVisible(R.id.GEO_MENU,
1671 type == WebView.HitTestResult.GEO_TYPE);
1672 menu.setGroupVisible(R.id.IMAGE_MENU,
1673 type == WebView.HitTestResult.IMAGE_TYPE
1674 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1675 menu.setGroupVisible(R.id.ANCHOR_MENU,
1676 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1677 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1678
1679 // Setup custom handling depending on the type
1680 switch (type) {
1681 case WebView.HitTestResult.PHONE_TYPE:
1682 menu.setHeaderTitle(Uri.decode(extra));
1683 menu.findItem(R.id.dial_context_menu_id).setIntent(
1684 new Intent(Intent.ACTION_VIEW, Uri
1685 .parse(WebView.SCHEME_TEL + extra)));
1686 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1687 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001688 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001689 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1690 addIntent);
1691 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1692 new Copy(extra));
1693 break;
1694
1695 case WebView.HitTestResult.EMAIL_TYPE:
1696 menu.setHeaderTitle(extra);
1697 menu.findItem(R.id.email_context_menu_id).setIntent(
1698 new Intent(Intent.ACTION_VIEW, Uri
1699 .parse(WebView.SCHEME_MAILTO + extra)));
1700 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1701 new Copy(extra));
1702 break;
1703
1704 case WebView.HitTestResult.GEO_TYPE:
1705 menu.setHeaderTitle(extra);
1706 menu.findItem(R.id.map_context_menu_id).setIntent(
1707 new Intent(Intent.ACTION_VIEW, Uri
1708 .parse(WebView.SCHEME_GEO
1709 + URLEncoder.encode(extra))));
1710 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1711 new Copy(extra));
1712 break;
1713
1714 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1715 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1716 TextView titleView = (TextView) LayoutInflater.from(this)
1717 .inflate(android.R.layout.browser_link_context_header,
1718 null);
1719 titleView.setText(extra);
1720 menu.setHeaderView(titleView);
1721 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001722 boolean showNewTab = mTabControl.canCreateNewTab();
1723 MenuItem newTabItem
1724 = menu.findItem(R.id.open_newtab_context_menu_id);
1725 newTabItem.setVisible(showNewTab);
1726 if (showNewTab) {
1727 newTabItem.setOnMenuItemClickListener(
1728 new MenuItem.OnMenuItemClickListener() {
1729 public boolean onMenuItemClick(MenuItem item) {
1730 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001731 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001732 if (newTab != parent) {
1733 parent.addChildTab(newTab);
1734 }
1735 return true;
1736 }
1737 });
1738 }
Ben Murdochde353622009-10-12 10:29:00 +01001739 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1740 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001741 PackageManager pm = getPackageManager();
1742 Intent send = new Intent(Intent.ACTION_SEND);
1743 send.setType("text/plain");
1744 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1745 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1746 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1747 break;
1748 }
1749 // otherwise fall through to handle image part
1750 case WebView.HitTestResult.IMAGE_TYPE:
1751 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1752 menu.setHeaderTitle(extra);
1753 }
1754 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1755 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1756 menu.findItem(R.id.download_context_menu_id).
1757 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001758 menu.findItem(R.id.set_wallpaper_context_menu_id).
1759 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001760 break;
1761
1762 default:
1763 Log.w(LOGTAG, "We should not get here.");
1764 break;
1765 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001766 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001767 }
1768
The Android Open Source Project0c908882009-03-03 19:32:16 -08001769 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001770 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001771 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001772 // Attach the container that contains the main WebView and any other UI
1773 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001774 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001775
1776 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001777 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001778 if (errorConsole.numberOfErrors() == 0) {
1779 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1780 } else {
1781 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1782 }
1783
1784 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001785 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001786 ViewGroup.LayoutParams.WRAP_CONTENT));
1787 }
1788
Michael Kolba2b2ba82010-08-04 17:54:03 -07001789 WebView view = t.getWebView();
1790 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001791 if (t.isInVoiceSearchMode()) {
1792 showVoiceTitleBar(t.getVoiceDisplayTitle());
1793 } else {
1794 revertVoiceTitleBar();
1795 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001796 // Request focus on the top window.
1797 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001798 if (mTabControl.getTabChangeListener() != null) {
1799 mTabControl.getTabChangeListener().onCurrentTab(t);
1800 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001801 }
1802
1803 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001804 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001805 t.attachSubWindow(mContentView);
1806 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001807 }
1808
1809 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001810 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001811 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001812 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001813
Grace Kloba22ac16e2009-10-07 18:00:23 -07001814 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1815 if (errorConsole != null) {
1816 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001817 }
1818
Michael Kolba2b2ba82010-08-04 17:54:03 -07001819 WebView view = t.getWebView();
1820 if (view != null) {
1821 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001822 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001823 }
1824
1825 // Remove the sub window if it exists. Also called by TabControl when the
1826 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001827 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001828 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001829 // dismiss the subwindow. This will destroy the WebView.
1830 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001831 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001832 }
1833
Leon Scroggins1f005d32009-08-10 17:36:42 -04001834 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001835 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001836 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001837 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001838 }
1839
1840 // This method does a ton of stuff. It will attempt to create a new tab
1841 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001842 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001843 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1844 String appId) {
1845 final Tab currentTab = mTabControl.getCurrentTab();
1846 if (mTabControl.canCreateNewTab()) {
1847 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001848 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001849 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001850 // If the last tab was removed from the active tabs page, currentTab
1851 // will be null.
1852 if (currentTab != null) {
1853 removeTabFromContentView(currentTab);
1854 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001855 // We must set the new tab as the current tab to reflect the old
1856 // animation behavior.
1857 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001858 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001859 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001860 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001861 }
1862 return tab;
1863 } else {
1864 // Get rid of the subwindow if it exists
1865 dismissSubWindow(currentTab);
1866 if (!urlData.isEmpty()) {
1867 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001868 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001869 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001870 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001871 }
1872 }
1873
Michael Kolb68792c82010-08-09 16:39:18 -07001874 private Tab openTab(String url, boolean forceForeground) {
1875 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001876 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001877 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001878 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001879 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001880 }
Grace Klobac9181842009-04-14 08:53:22 -07001881 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001882 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001883 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001884 }
1885 }
1886
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001887 /* package */ Tab openIncognitoTab() {
1888 if (mTabControl.canCreateNewTab()) {
1889 Tab currentTab = mTabControl.getCurrentTab();
1890 Tab tab = mTabControl.createNewTab(false, null, null, true);
1891 if (currentTab != null) {
1892 removeTabFromContentView(currentTab);
1893 }
1894 mTabControl.setCurrentTab(tab);
1895 attachTabToContentView(tab);
1896 return tab;
1897 }
1898 return null;
1899 }
1900
The Android Open Source Project0c908882009-03-03 19:32:16 -08001901 private class Copy implements OnMenuItemClickListener {
1902 private CharSequence mText;
1903
1904 public boolean onMenuItemClick(MenuItem item) {
1905 copy(mText);
1906 return true;
1907 }
1908
1909 public Copy(CharSequence toCopy) {
1910 mText = toCopy;
1911 }
1912 }
1913
1914 private class Download implements OnMenuItemClickListener {
1915 private String mText;
1916
1917 public boolean onMenuItemClick(MenuItem item) {
1918 onDownloadStartNoStream(mText, null, null, null, -1);
1919 return true;
1920 }
1921
1922 public Download(String toDownload) {
1923 mText = toDownload;
1924 }
1925 }
1926
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001927 private class SetAsWallpaper extends Thread implements
1928 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1929 private URL mUrl;
1930 private ProgressDialog mWallpaperProgress;
1931 private boolean mCanceled = false;
1932
1933 public SetAsWallpaper(String url) {
1934 try {
1935 mUrl = new URL(url);
1936 } catch (MalformedURLException e) {
1937 mUrl = null;
1938 }
1939 }
1940
1941 public void onCancel(DialogInterface dialog) {
1942 mCanceled = true;
1943 }
1944
1945 public boolean onMenuItemClick(MenuItem item) {
1946 if (mUrl != null) {
1947 // The user may have tried to set a image with a large file size as their
1948 // background so it may take a few moments to perform the operation. Display
1949 // a progress spinner while it is working.
1950 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1951 mWallpaperProgress.setIndeterminate(true);
1952 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1953 mWallpaperProgress.setCancelable(true);
1954 mWallpaperProgress.setOnCancelListener(this);
1955 mWallpaperProgress.show();
1956 start();
1957 }
1958 return true;
1959 }
1960
Michael Kolbe0a36662010-06-29 10:37:12 -07001961 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001962 public void run() {
1963 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1964 try {
1965 // TODO: This will cause the resource to be downloaded again, when we
1966 // should in most cases be able to grab it from the cache. To fix this
1967 // we should query WebCore to see if we can access a cached version and
1968 // instead open an input stream on that. This pattern could also be used
1969 // in the download manager where the same problem exists.
1970 InputStream inputstream = mUrl.openStream();
1971 if (inputstream != null) {
1972 setWallpaper(inputstream);
1973 }
1974 } catch (IOException e) {
1975 Log.e(LOGTAG, "Unable to set new wallpaper");
1976 // Act as though the user canceled the operation so we try to
1977 // restore the old wallpaper.
1978 mCanceled = true;
1979 }
1980
1981 if (mCanceled) {
1982 // Restore the old wallpaper if the user cancelled whilst we were setting
1983 // the new wallpaper.
1984 int width = oldWallpaper.getIntrinsicWidth();
1985 int height = oldWallpaper.getIntrinsicHeight();
1986 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1987 Canvas canvas = new Canvas(bm);
1988 oldWallpaper.setBounds(0, 0, width, height);
1989 oldWallpaper.draw(canvas);
1990 try {
1991 setWallpaper(bm);
1992 } catch (IOException e) {
1993 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1994 }
1995 mCanceled = false;
1996 }
1997
1998 if (mWallpaperProgress.isShowing()) {
1999 mWallpaperProgress.dismiss();
2000 }
2001 }
2002 }
2003
The Android Open Source Project0c908882009-03-03 19:32:16 -08002004 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07002005 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
2006 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002007 }
2008
2009 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002010 * Resets the browser title-view to whatever it must be
2011 * (for example, if we had a loading error)
2012 * When we have a new page, we call resetTitle, when we
2013 * have to reset the titlebar to whatever it used to be
2014 * (for example, if the user chose to stop loading), we
2015 * call resetTitleAndRevertLockIcon.
2016 */
2017 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002018 mTabControl.getCurrentTab().revertLockIcon();
2019 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002020 resetTitleIconAndProgress();
2021 }
2022
2023 /**
2024 * Reset the title, favicon, and progress.
2025 */
2026 private void resetTitleIconAndProgress() {
2027 WebView current = mTabControl.getCurrentWebView();
2028 if (current == null) {
2029 return;
2030 }
2031 resetTitleAndIcon(current);
2032 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002033 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002034 }
2035
2036 // Reset the title and the icon based on the given item.
2037 private void resetTitleAndIcon(WebView view) {
2038 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2039 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002040 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002041 setFavicon(item.getFavicon());
2042 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002043 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002044 setFavicon(null);
2045 }
2046 }
2047
2048 /**
2049 * Sets a title composed of the URL and the title string.
2050 * @param url The URL of the site being loaded.
2051 * @param title The title of the site being loaded.
2052 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002053 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002054 mUrl = url;
2055 mTitle = title;
2056
Leon Scroggins58d56c62010-01-28 15:12:40 -05002057 // If we are in voice search mode, the title has already been set.
2058 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2059 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002060 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002061 }
2062
2063 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002064 * @param url The URL to build a title version of the URL from.
2065 * @return The title version of the URL or null if fails.
2066 * The title version of the URL can be either the URL hostname,
2067 * or the hostname with an "https://" prefix (for secure URLs),
2068 * or an empty string if, for example, the URL in question is a
2069 * file:// URL with no hostname.
2070 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002071 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002072 String titleUrl = null;
2073
2074 if (url != null) {
2075 try {
2076 // parse the url string
2077 URL urlObj = new URL(url);
2078 if (urlObj != null) {
2079 titleUrl = "";
2080
2081 String protocol = urlObj.getProtocol();
2082 String host = urlObj.getHost();
2083
2084 if (host != null && 0 < host.length()) {
2085 titleUrl = host;
2086 if (protocol != null) {
2087 // if a secure site, add an "https://" prefix!
2088 if (protocol.equalsIgnoreCase("https")) {
2089 titleUrl = protocol + "://" + host;
2090 }
2091 }
2092 }
2093 }
2094 } catch (MalformedURLException e) {}
2095 }
2096
2097 return titleUrl;
2098 }
2099
2100 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002101 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002102 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002103 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002104 }
2105
2106 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002107 * Close the tab, remove its associated title bar, and adjust mTabControl's
2108 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002109 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002110 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002111 int currentIndex = mTabControl.getCurrentIndex();
2112 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002113 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002114 if (currentIndex >= removeIndex && currentIndex != 0) {
2115 currentIndex--;
2116 }
2117 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002118 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002119 updateLockIconToLatest();
Elliott Slaughtere440a882010-08-20 13:54:45 -07002120
2121 if (!mTabControl.hasAnyOpenIncognitoTabs()) {
2122 WebView.cleanupPrivateBrowsingFiles(this);
2123 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002124 }
2125
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002126 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002127 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002128 if (current == null) {
2129 /*
2130 * Instead of finishing the activity, simply push this to the back
2131 * of the stack and let ActivityManager to choose the foreground
2132 * activity. As BrowserActivity is singleTask, it will be always the
2133 * root of the task. So we can use either true or false for
2134 * moveTaskToBack().
2135 */
2136 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002137 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002138 }
2139 WebView w = current.getWebView();
2140 if (w.canGoBack()) {
2141 w.goBack();
2142 } else {
2143 // Check to see if we are closing a window that was created by
2144 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002145 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002146 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002147 switchToTab(mTabControl.getTabIndex(parent));
2148 // Now we close the other tab
2149 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002150 } else {
2151 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002152 // force the tab's inLoad() to be false as we are going to
2153 // either finish the activity or remove the tab. This will
2154 // ensure pauseWebViewTimers() taking action.
2155 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002156 if (mTabControl.getTabCount() == 1) {
2157 finish();
2158 return;
2159 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002160 // call pauseWebViewTimers() now, we won't be able to call
2161 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002162 // Temporarily change mActivityInPause to be true as
2163 // pauseWebViewTimers() will do nothing if mActivityInPause
2164 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002165 boolean savedState = mActivityInPause;
2166 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002167 Log.e(LOGTAG, "BrowserActivity is already paused "
2168 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002169 }
2170 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002171 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002172 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002173 removeTabFromContentView(current);
2174 mTabControl.removeTab(current);
2175 }
2176 /*
2177 * Instead of finishing the activity, simply push this to the back
2178 * of the stack and let ActivityManager to choose the foreground
2179 * activity. As BrowserActivity is singleTask, it will be always the
2180 * root of the task. So we can use either true or false for
2181 * moveTaskToBack().
2182 */
2183 moveTaskToBack(true);
2184 }
2185 }
2186 }
2187
Grace Kloba22ac16e2009-10-07 18:00:23 -07002188 boolean isMenuDown() {
2189 return mMenuIsDown;
2190 }
2191
Grace Kloba5942df02009-09-18 11:48:29 -07002192 @Override
2193 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002194 // Even if MENU is already held down, we need to call to super to open
2195 // the IME on long press.
2196 if (KeyEvent.KEYCODE_MENU == keyCode) {
2197 mMenuIsDown = true;
2198 return super.onKeyDown(keyCode, event);
2199 }
Grace Kloba5942df02009-09-18 11:48:29 -07002200 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2201 // still down, we don't want to trigger the search. Pretend to consume
2202 // the key and do nothing.
2203 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002204
Grace Kloba5942df02009-09-18 11:48:29 -07002205 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002206 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002207 // WebView/WebTextView handle the keys in the KeyDown. As
2208 // the Activity's shortcut keys are only handled when WebView
2209 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2210 if (event.isShiftPressed()) {
2211 getTopWindow().pageUp(false);
2212 } else {
2213 getTopWindow().pageDown(false);
2214 }
Grace Kloba5942df02009-09-18 11:48:29 -07002215 return true;
2216 case KeyEvent.KEYCODE_BACK:
2217 if (event.getRepeatCount() == 0) {
2218 event.startTracking();
2219 return true;
2220 } else if (mCustomView == null && mActiveTabsPage == null
2221 && event.isLongPress()) {
Michael Kolb68792c82010-08-09 16:39:18 -07002222 bookmarksOrHistoryPicker(true, false);
Grace Kloba5942df02009-09-18 11:48:29 -07002223 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002224 }
Grace Kloba5942df02009-09-18 11:48:29 -07002225 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002226 }
Grace Kloba5942df02009-09-18 11:48:29 -07002227 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002228 }
2229
Grace Kloba5942df02009-09-18 11:48:29 -07002230 @Override
2231 public boolean onKeyUp(int keyCode, KeyEvent event) {
2232 switch(keyCode) {
2233 case KeyEvent.KEYCODE_MENU:
2234 mMenuIsDown = false;
2235 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002236 case KeyEvent.KEYCODE_BACK:
2237 if (event.isTracking() && !event.isCanceled()) {
2238 if (mCustomView != null) {
2239 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002240 mTabControl.getCurrentWebView().getWebChromeClient()
2241 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002242 } else if (mActiveTabsPage != null) {
2243 // if tab page is showing, hide it
2244 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002245 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002246 WebView subwindow = mTabControl.getCurrentSubWindow();
2247 if (subwindow != null) {
2248 if (subwindow.canGoBack()) {
2249 subwindow.goBack();
2250 } else {
2251 dismissSubWindow(mTabControl.getCurrentTab());
2252 }
2253 } else {
2254 goBackOnePageOrQuit();
2255 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002256 }
Grace Kloba5942df02009-09-18 11:48:29 -07002257 return true;
2258 }
2259 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002260 }
Grace Kloba5942df02009-09-18 11:48:29 -07002261 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002262 }
2263
Leon Scroggins68579392009-09-15 15:31:54 -04002264 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002265 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002266 resetTitleAndRevertLockIcon();
2267 WebView w = getTopWindow();
2268 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002269 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2270 // same logic here. But for subwindow case, should we call into the main
2271 // WebView's onPageFinished as we never call its onPageStarted and if
2272 // the page finishes itself, we don't call onPageFinished.
2273 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2274 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002275
2276 cancelStopToast();
2277 mStopToast = Toast
2278 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2279 mStopToast.show();
2280 }
2281
Grace Kloba22ac16e2009-10-07 18:00:23 -07002282 boolean didUserStopLoading() {
2283 return mDidStopLoad;
2284 }
2285
The Android Open Source Project0c908882009-03-03 19:32:16 -08002286 private void cancelStopToast() {
2287 if (mStopToast != null) {
2288 mStopToast.cancel();
2289 mStopToast = null;
2290 }
2291 }
2292
Grace Kloba22ac16e2009-10-07 18:00:23 -07002293 // called by a UI or non-UI thread to post the message
2294 public void postMessage(int what, int arg1, int arg2, Object obj,
2295 long delayMillis) {
2296 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2297 obj), delayMillis);
2298 }
2299
2300 // called by a UI or non-UI thread to remove the message
2301 void removeMessages(int what, Object object) {
2302 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002303 }
2304
2305 // public message ids
2306 public final static int LOAD_URL = 1001;
2307 public final static int STOP_LOAD = 1002;
2308
2309 // Message Ids
2310 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002311 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002312
Grace Kloba22ac16e2009-10-07 18:00:23 -07002313 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002314
Ben Murdocheecb4e62010-07-06 16:30:38 +01002315 private static final int TOUCH_ICON_DOWNLOADED = 109;
2316
Michael Kolb300b7f02010-08-25 13:47:24 -07002317 private static final int OPEN_BOOKMARKS = 201;
2318
The Android Open Source Project0c908882009-03-03 19:32:16 -08002319 // Private handler for handling javascript and saving passwords
2320 private Handler mHandler = new Handler() {
2321
Michael Kolbe0a36662010-06-29 10:37:12 -07002322 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002323 public void handleMessage(Message msg) {
2324 switch (msg.what) {
Michael Kolb300b7f02010-08-25 13:47:24 -07002325 case OPEN_BOOKMARKS:
2326 bookmarksOrHistoryPicker(false, false);
2327 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002328 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002329 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002330 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002331 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002332 if (url == null || url.length() == 0) {
2333 break;
2334 }
2335 HashMap focusNodeMap = (HashMap) msg.obj;
2336 WebView view = (WebView) focusNodeMap.get("webview");
2337 // Only apply the action if the top window did not change.
2338 if (getTopWindow() != view) {
2339 break;
2340 }
2341 switch (msg.arg1) {
2342 case R.id.open_context_menu_id:
2343 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002344 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002345 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002346 case R.id.bookmark_context_menu_id:
2347 Intent intent = new Intent(BrowserActivity.this,
2348 AddBookmarkPage.class);
2349 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002350 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002351 startActivity(intent);
2352 break;
2353 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002354 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002355 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002356 break;
2357 case R.id.copy_link_context_menu_id:
2358 copy(url);
2359 break;
2360 case R.id.save_link_context_menu_id:
2361 case R.id.download_context_menu_id:
2362 onDownloadStartNoStream(url, null, null, null, -1);
2363 break;
2364 }
2365 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002366 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002367
2368 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002369 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002370 break;
2371
2372 case STOP_LOAD:
2373 stopLoading();
2374 break;
2375
The Android Open Source Project0c908882009-03-03 19:32:16 -08002376 case RELEASE_WAKELOCK:
2377 if (mWakeLock.isHeld()) {
2378 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002379 // if we reach here, Browser should be still in the
2380 // background loading after WAKELOCK_TIMEOUT (5-min).
2381 // To avoid burning the battery, stop loading.
2382 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002383 }
2384 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002385
2386 case UPDATE_BOOKMARK_THUMBNAIL:
2387 WebView view = (WebView) msg.obj;
2388 if (view != null) {
2389 updateScreenshot(view);
2390 }
2391 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002392
2393 case TOUCH_ICON_DOWNLOADED:
2394 Bundle b = msg.getData();
2395 showSaveToHomescreenDialog(b.getString("url"),
2396 b.getString("title"),
2397 (Bitmap) b.getParcelable("touchIcon"),
2398 (Bitmap) b.getParcelable("favicon"));
2399 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002400 }
2401 }
2402 };
2403
Leon Scroggins96afcb12009-12-10 12:35:56 -05002404 /**
2405 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2406 * an {@link Intent} to launch the Activity chooser.
2407 * @param c Context used to launch a new Activity.
2408 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002409 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002410 * @param url URL of the page. Stored in the Intent with
2411 * {@link Intent#EXTRA_TEXT}
2412 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2413 * with {@link Browser#EXTRA_SHARE_FAVICON}
2414 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2415 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2416 */
2417 public static final void sharePage(Context c, String title, String url,
2418 Bitmap favicon, Bitmap screenshot) {
2419 Intent send = new Intent(Intent.ACTION_SEND);
2420 send.setType("text/plain");
2421 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002422 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002423 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2424 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2425 try {
2426 c.startActivity(Intent.createChooser(send, c.getString(
2427 R.string.choosertitle_sharevia)));
2428 } catch(android.content.ActivityNotFoundException ex) {
2429 // if no app handles it, do nothing
2430 }
2431 }
2432
Leon Scroggins89c6d362009-07-15 16:54:37 -04002433 private void updateScreenshot(WebView view) {
2434 // If this is a bookmarked site, add a screenshot to the database.
2435 // FIXME: When should we update? Every time?
2436 // FIXME: Would like to make sure there is actually something to
2437 // draw, but the API for that (WebViewCore.pictureReady()) is not
2438 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002439
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002440 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2441 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002442 if (bm == null) {
2443 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002444 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002445
2446 final ContentResolver cr = getContentResolver();
2447 final String url = view.getUrl();
2448 final String originalUrl = view.getOriginalUrl();
2449
2450 new AsyncTask<Void, Void, Void>() {
2451 @Override
2452 protected Void doInBackground(Void... unused) {
2453 Cursor c = null;
2454 try {
Jeff Hamilton84029622010-08-05 14:29:28 -05002455 c = Bookmarks.queryBookmarksForUrl(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002456 cr, originalUrl, url);
Patrick Scottcb192b52010-04-14 14:38:55 -04002457 if (c != null) {
2458 if (c.moveToFirst()) {
2459 ContentValues values = new ContentValues();
2460 final ByteArrayOutputStream os
2461 = new ByteArrayOutputStream();
2462 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002463 values.put(BrowserContract.Bookmarks.THUMBNAIL,
Patrick Scottcb192b52010-04-14 14:38:55 -04002464 os.toByteArray());
2465 do {
2466 cr.update(ContentUris.withAppendedId(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002467 BrowserContract.Bookmarks.CONTENT_URI, c.getLong(0)),
Patrick Scottcb192b52010-04-14 14:38:55 -04002468 values, null, null);
2469 } while (c.moveToNext());
2470 }
2471 }
2472 } catch (IllegalStateException e) {
2473 // Ignore
2474 } finally {
2475 if (c != null) c.close();
2476 }
2477 return null;
2478 }
2479 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002480 }
2481
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002482 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002483 * Return the desired width for thumbnail screenshots, which are stored in
2484 * the database, and used on the bookmarks screen.
2485 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002486 * @return desired width for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002487 */
2488 /* package */ static int getDesiredThumbnailWidth(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002489 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailWidth);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002490 }
2491
2492 /**
2493 * Return the desired height for thumbnail screenshots, which are stored in
2494 * the database, and used on the bookmarks screen.
2495 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002496 * @return desired height for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002497 */
2498 /* package */ static int getDesiredThumbnailHeight(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002499 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailHeight);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002500 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002501
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002502 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002503 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002504 if (thumbnail == null) {
2505 return null;
2506 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002507 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002508 Canvas canvas = new Canvas(bm);
2509 // May need to tweak these values to determine what is the
2510 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002511 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002512 int thumbnailHeight = thumbnail.getHeight();
2513 float scaleFactorX = 1.0f;
2514 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002515 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002516 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002517 } else {
2518 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002519 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002520
2521 if (view.getWidth() > view.getHeight() &&
2522 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2523 // If the device is in landscape and the page is shorter
2524 // than the height of the view, stretch the thumbnail to fill the
2525 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002526 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002527 } else {
2528 // In the portrait case, this looks nice.
2529 scaleFactorY = scaleFactorX;
2530 }
2531
2532 canvas.scale(scaleFactorX, scaleFactorY);
2533
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002534 thumbnail.draw(canvas);
2535 return bm;
2536 }
2537
The Android Open Source Project0c908882009-03-03 19:32:16 -08002538 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002539 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002540 //-------------------------------------------------------------------------
2541
2542 // Use in overrideUrlLoading
2543 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2544 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2545 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2546 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2547
Leon Scroggins92472e82010-02-17 16:32:28 -05002548 // Keep this initial progress in sync with initialProgressValue (* 100)
2549 // in ProgressTracker.cpp
2550 private final static int INITIAL_PROGRESS = 10;
2551
Grace Kloba22ac16e2009-10-07 18:00:23 -07002552 void onPageStarted(WebView view, String url, Bitmap favicon) {
2553 // when BrowserActivity just starts, onPageStarted may be called before
2554 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2555 // to start the timer. As we won't switch tabs while an activity is in
2556 // pause state, we can ensure calling resume and pause in pair.
2557 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002558
Grace Kloba22ac16e2009-10-07 18:00:23 -07002559 resetLockIcon(url);
2560 setUrlTitle(url, null);
2561 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002562 // Show some progress so that the user knows the page is beginning to
2563 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002564 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002565 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002566 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002567 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002568 if (mSettings.isTracing()) {
2569 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002570 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002571 WebAddress uri = new WebAddress(url);
2572 host = uri.mHost;
2573 } catch (android.net.ParseException ex) {
2574 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002575 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002576 host = host.replace('.', '_');
2577 host += ".trace";
2578 mInTrace = true;
2579 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2580 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002581
Grace Kloba22ac16e2009-10-07 18:00:23 -07002582 // Performance probe
2583 if (false) {
2584 mStart = SystemClock.uptimeMillis();
2585 mProcessStart = Process.getElapsedCpuTime();
2586 long[] sysCpu = new long[7];
2587 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2588 sysCpu, null)) {
2589 mUserStart = sysCpu[0] + sysCpu[1];
2590 mSystemStart = sysCpu[2];
2591 mIdleStart = sysCpu[3];
2592 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2593 }
2594 mUiStart = SystemClock.currentThreadTimeMillis();
2595 }
2596 }
2597
2598 void onPageFinished(WebView view, String url) {
2599 // Reset the title and icon in case we stopped a provisional load.
2600 resetTitleAndIcon(view);
2601 // Update the lock icon image only once we are done loading
2602 updateLockIconToLatest();
2603 // pause the WebView timer and release the wake lock if it is finished
2604 // while BrowserActivity is in pause state.
2605 if (mActivityInPause && pauseWebViewTimers()) {
2606 if (mWakeLock.isHeld()) {
2607 mHandler.removeMessages(RELEASE_WAKELOCK);
2608 mWakeLock.release();
2609 }
2610 }
2611
2612 // Performance probe
2613 if (false) {
2614 long[] sysCpu = new long[7];
2615 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2616 sysCpu, null)) {
2617 String uiInfo = "UI thread used "
2618 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2619 + " ms";
2620 if (LOGD_ENABLED) {
2621 Log.d(LOGTAG, uiInfo);
2622 }
2623 //The string that gets written to the log
2624 String performanceString = "It took total "
2625 + (SystemClock.uptimeMillis() - mStart)
2626 + " ms clock time to load the page."
2627 + "\nbrowser process used "
2628 + (Process.getElapsedCpuTime() - mProcessStart)
2629 + " ms, user processes used "
2630 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2631 + " ms, kernel used "
2632 + (sysCpu[2] - mSystemStart) * 10
2633 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2634 + " ms and irq took "
2635 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2636 * 10 + " ms, " + uiInfo;
2637 if (LOGD_ENABLED) {
2638 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2639 }
2640 if (url != null) {
2641 // strip the url to maintain consistency
2642 String newUrl = new String(url);
2643 if (newUrl.startsWith("http://www.")) {
2644 newUrl = newUrl.substring(11);
2645 } else if (newUrl.startsWith("http://")) {
2646 newUrl = newUrl.substring(7);
2647 } else if (newUrl.startsWith("https://www.")) {
2648 newUrl = newUrl.substring(12);
2649 } else if (newUrl.startsWith("https://")) {
2650 newUrl = newUrl.substring(8);
2651 }
2652 if (LOGD_ENABLED) {
2653 Log.d(LOGTAG, newUrl + " loaded");
2654 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002655 }
2656 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002657 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002658
Grace Kloba22ac16e2009-10-07 18:00:23 -07002659 if (mInTrace) {
2660 mInTrace = false;
2661 Debug.stopMethodTracing();
2662 }
2663 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002664
Grace Klobae7fe26b2010-06-28 16:23:33 -07002665 private void closeEmptyChildTab() {
2666 Tab current = mTabControl.getCurrentTab();
2667 if (current != null
2668 && current.getWebView().copyBackForwardList().getSize() == 0) {
2669 Tab parent = current.getParentTab();
2670 if (parent != null) {
2671 switchToTab(mTabControl.getTabIndex(parent));
2672 closeTab(current);
2673 }
2674 }
2675 }
2676
Grace Kloba22ac16e2009-10-07 18:00:23 -07002677 boolean shouldOverrideUrlLoading(WebView view, String url) {
2678 if (url.startsWith(SCHEME_WTAI)) {
2679 // wtai://wp/mc;number
2680 // number=string(phone-number)
2681 if (url.startsWith(SCHEME_WTAI_MC)) {
2682 Intent intent = new Intent(Intent.ACTION_VIEW,
2683 Uri.parse(WebView.SCHEME_TEL +
2684 url.substring(SCHEME_WTAI_MC.length())));
2685 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002686 // before leaving BrowserActivity, close the empty child tab.
2687 // If a new tab is created through JavaScript open to load this
2688 // url, we would like to close it as we will load this url in a
2689 // different Activity.
2690 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002691 return true;
2692 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002693 // wtai://wp/sd;dtmf
2694 // dtmf=string(dialstring)
2695 if (url.startsWith(SCHEME_WTAI_SD)) {
2696 // TODO: only send when there is active voice connection
2697 return false;
2698 }
2699 // wtai://wp/ap;number;name
2700 // number=string(phone-number)
2701 // name=string
2702 if (url.startsWith(SCHEME_WTAI_AP)) {
2703 // TODO
2704 return false;
2705 }
2706 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002707
Grace Kloba22ac16e2009-10-07 18:00:23 -07002708 // The "about:" schemes are internal to the browser; don't want these to
2709 // be dispatched to other apps.
2710 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002711 return false;
2712 }
2713
Jeff Davidson43610292010-07-16 16:03:58 -07002714 // If this is a Google search, attempt to add an RLZ string (if one isn't already present).
2715 if (rlzProviderPresent()) {
2716 Uri siteUri = Uri.parse(url);
2717 if (needsRlzString(siteUri)) {
2718 String rlz = null;
2719 Cursor cur = null;
2720 try {
2721 cur = getContentResolver().query(getRlzUri(), null, null, null, null);
2722 if (cur != null && cur.moveToFirst() && !cur.isNull(0)) {
2723 url = siteUri.buildUpon()
2724 .appendQueryParameter("rlz", cur.getString(0))
2725 .build().toString();
2726 }
2727 } finally {
2728 if (cur != null) {
2729 cur.close();
2730 }
2731 }
2732 loadUrl(view, url);
2733 return true;
2734 }
2735 }
2736
Grace Kloba22ac16e2009-10-07 18:00:23 -07002737 Intent intent;
2738 // perform generic parsing of the URI to turn it into an Intent.
2739 try {
2740 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2741 } catch (URISyntaxException ex) {
2742 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2743 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002744 }
2745
Grace Kloba22ac16e2009-10-07 18:00:23 -07002746 // check whether the intent can be resolved. If not, we will see
2747 // whether we can download it from the Market.
2748 if (getPackageManager().resolveActivity(intent, 0) == null) {
2749 String packagename = intent.getPackage();
2750 if (packagename != null) {
2751 intent = new Intent(Intent.ACTION_VIEW, Uri
2752 .parse("market://search?q=pname:" + packagename));
2753 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2754 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002755 // before leaving BrowserActivity, close the empty child tab.
2756 // If a new tab is created through JavaScript open to load this
2757 // url, we would like to close it as we will load this url in a
2758 // different Activity.
2759 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002760 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002761 } else {
2762 return false;
2763 }
2764 }
2765
Grace Kloba22ac16e2009-10-07 18:00:23 -07002766 // sanitize the Intent, ensuring web pages can not bypass browser
2767 // security (only access to BROWSABLE activities).
2768 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2769 intent.setComponent(null);
2770 try {
2771 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002772 // before leaving BrowserActivity, close the empty child tab.
2773 // If a new tab is created through JavaScript open to load this
2774 // url, we would like to close it as we will load this url in a
2775 // different Activity.
2776 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002777 return true;
2778 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002779 } catch (ActivityNotFoundException ex) {
2780 // ignore the error. If no application can handle the URL,
2781 // eg about:blank, assume the browser can handle it.
2782 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002783
Grace Kloba22ac16e2009-10-07 18:00:23 -07002784 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002785 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002786 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002787 return true;
2788 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002789 return false;
2790 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002791
Jeff Davidson43610292010-07-16 16:03:58 -07002792 // Determine whether the RLZ provider is present on the system.
2793 private boolean rlzProviderPresent() {
2794 if (mIsProviderPresent == null) {
2795 PackageManager pm = getPackageManager();
2796 mIsProviderPresent = pm.resolveContentProvider(BrowserSettings.RLZ_PROVIDER, 0) != null;
2797 }
2798 return mIsProviderPresent;
2799 }
2800
2801 // Retrieve the RLZ access point string and cache the URI used to retrieve RLZ values.
2802 private Uri getRlzUri() {
2803 if (mRlzUri == null) {
2804 String ap = getResources().getString(R.string.rlz_access_point);
2805 mRlzUri = Uri.withAppendedPath(BrowserSettings.RLZ_PROVIDER_URI, ap);
2806 }
2807 return mRlzUri;
2808 }
2809
2810 // Determine if this URI appears to be for a Google search and does not have an RLZ parameter.
2811 // Taken largely from Chrome source, src/chrome/browser/google_url_tracker.cc
2812 private static boolean needsRlzString(Uri uri) {
Bill Napierc50e71a2010-08-27 14:03:03 -07002813 String scheme = uri.getScheme();
2814 if (("http".equals(scheme) || "https".equals(scheme)) &&
2815 (uri.getQueryParameter("q") != null) && (uri.getQueryParameter("rlz") == null)) {
Jeff Davidson43610292010-07-16 16:03:58 -07002816 String host = uri.getHost();
2817 if (host == null) {
2818 return false;
2819 }
2820 String[] hostComponents = host.split("\\.");
2821
2822 if (hostComponents.length < 2) {
2823 return false;
2824 }
2825 int googleComponent = hostComponents.length - 2;
2826 String component = hostComponents[googleComponent];
2827 if (!"google".equals(component)) {
2828 if (hostComponents.length < 3 ||
2829 (!"co".equals(component) && !"com".equals(component))) {
2830 return false;
2831 }
2832 googleComponent = hostComponents.length - 3;
2833 if (!"google".equals(hostComponents[googleComponent])) {
2834 return false;
2835 }
2836 }
2837
2838 // Google corp network handling.
2839 if (googleComponent > 0 && "corp".equals(hostComponents[googleComponent - 1])) {
2840 return false;
2841 }
2842
2843 return true;
2844 }
2845 return false;
2846 }
2847
Grace Kloba22ac16e2009-10-07 18:00:23 -07002848 // -------------------------------------------------------------------------
2849 // Helper function for WebChromeClient
2850 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002851
Grace Kloba22ac16e2009-10-07 18:00:23 -07002852 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002853
2854 // On the phone, the fake title bar will always cover up the
2855 // regular title bar (or the regular one is offscreen), so only the
2856 // fake title bar needs to change its progress
2857 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002858
Grace Kloba22ac16e2009-10-07 18:00:23 -07002859 if (newProgress == 100) {
2860 // onProgressChanged() may continue to be called after the main
2861 // frame has finished loading, as any remaining sub frames continue
2862 // to load. We'll only get called once though with newProgress as
2863 // 100 when everything is loaded. (onPageFinished is called once
2864 // when the main frame completes loading regardless of the state of
2865 // any sub frames so calls to onProgressChanges may continue after
2866 // onPageFinished has executed)
2867 if (mInLoad) {
2868 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002869 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002870 // If the options menu is open, leave the title bar
2871 if (!mOptionsMenuOpen || !mIconView) {
2872 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002873 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002874 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002875 } else {
2876 if (!mInLoad) {
2877 // onPageFinished may have already been called but a subframe is
2878 // still loading and updating the progress. Reset mInLoad and
2879 // update the menu items.
2880 mInLoad = true;
2881 updateInLoadMenuItems();
2882 }
2883 // When the page first begins to load, the Activity may still be
2884 // paused, in which case showFakeTitleBar will do nothing. Call
2885 // again as the page continues to load so that it will be shown.
2886 // (Calling it will the fake title bar is already showing will also
2887 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002888 if (!mOptionsMenuOpen || mIconView) {
2889 // This page has begun to load, so show the title bar
2890 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002891 }
2892 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002893 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002894
Grace Kloba22ac16e2009-10-07 18:00:23 -07002895 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002896 // if a view already exists then immediately terminate the new one
2897 if (mCustomView != null) {
2898 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002899 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002900 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002901
2902 // Add the custom view to its container.
2903 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2904 mCustomView = view;
2905 mCustomViewCallback = callback;
2906 // Save the menu state and set it to empty while the custom
2907 // view is showing.
2908 mOldMenuState = mMenuState;
2909 mMenuState = EMPTY_MENU;
2910 // Hide the content view.
2911 mContentView.setVisibility(View.GONE);
2912 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002913 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002914 mCustomViewContainer.setVisibility(View.VISIBLE);
2915 mCustomViewContainer.bringToFront();
2916 }
2917
2918 void onHideCustomView() {
2919 if (mCustomView == null)
2920 return;
2921
2922 // Hide the custom view.
2923 mCustomView.setVisibility(View.GONE);
2924 // Remove the custom view from its container.
2925 mCustomViewContainer.removeView(mCustomView);
2926 mCustomView = null;
2927 // Reset the old menu state.
2928 mMenuState = mOldMenuState;
2929 mOldMenuState = EMPTY_MENU;
2930 mCustomViewContainer.setVisibility(View.GONE);
2931 mCustomViewCallback.onCustomViewHidden();
2932 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002933 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002934 mContentView.setVisibility(View.VISIBLE);
2935 }
2936
2937 Bitmap getDefaultVideoPoster() {
2938 if (mDefaultVideoPoster == null) {
2939 mDefaultVideoPoster = BitmapFactory.decodeResource(
2940 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002941 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002942 return mDefaultVideoPoster;
2943 }
Patrick Scott3918d442009-08-04 13:22:29 -04002944
Grace Kloba22ac16e2009-10-07 18:00:23 -07002945 View getVideoLoadingProgressView() {
2946 if (mVideoProgressView == null) {
2947 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2948 mVideoProgressView = inflater.inflate(
2949 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002950 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002951 return mVideoProgressView;
2952 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002953
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002954 /*
2955 * The Object used to inform the WebView of the file to upload.
2956 */
2957 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002958 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002959
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002960 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2961
2962 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002963 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002964 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002965 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002966 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002967 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002968 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002969 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002970
Ben Murdoch039bd472010-07-21 21:26:57 +01002971 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002972 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002973
Ben Murdoch6af492a2010-06-15 12:38:17 +01002974 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002975 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002976 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2977 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002978
Ben Murdoch6af492a2010-06-15 12:38:17 +01002979 if (mUploadMessage != null) {
2980 // Already a file picker operation in progress.
2981 return;
2982 }
2983
Grace Kloba22ac16e2009-10-07 18:00:23 -07002984 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002985
2986 // Parse the accept type.
2987 String params[] = acceptType.split(";");
2988 String mimeType = params[0];
2989
2990 for (String p : params) {
2991 String[] keyValue = p.split("=");
2992 if (keyValue.length == 2) {
2993 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002994 if (mediaSourceKey.equals(keyValue[0])) {
2995 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002996 }
2997 }
2998 }
2999
3000 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07003001 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
3002 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003003
3004 // Create an intent to add to the standard file picker that will
3005 // capture an image from the camera. We'll combine this intent with
3006 // the standard OPENABLE picker unless the web developer specifically
3007 // requested the camera or gallery be opened by passing a parameter
3008 // in the accept type.
3009 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
3010 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3011 Environment.DIRECTORY_DCIM);
3012 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3013 File.separator + "browser-photos");
3014 cameraDataDir.mkdirs();
3015 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3016 System.currentTimeMillis() + ".jpg";
3017 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3018
Ben Murdoch6af492a2010-06-15 12:38:17 +01003019 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3020
Ben Murdoch039bd472010-07-21 21:26:57 +01003021 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3022
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003023 if (mimeType.equals(imageMimeType)) {
3024 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003025 addCamcorderIntent = false;
3026 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003027 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3028 // directly.
3029 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3030 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003031 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3032 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003033 addCameraIntent = false;
3034 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003035 } else if (mimeType.equals(videoMimeType)) {
3036 i.setType(videoMimeType);
3037 addCameraIntent = false;
3038 // The camcorder saves it's own file and returns it to us in the intent, so
3039 // we don't need to generate one here.
3040 mCameraFilePath = null;
3041
3042 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003043 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3044 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003045 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3046 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003047 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3048 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003049 addCamcorderIntent = false;
3050 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003051 } else if (mimeType.equals(audioMimeType)) {
3052 i.setType(audioMimeType);
3053 addCameraIntent = false;
3054 addCamcorderIntent = false;
3055 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3056 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3057 // recorder.
3058 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3059 return;
3060 }
3061 // On a default system, there is no single option to open an audio "gallery". Both the
3062 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3063 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3064 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003065 } else {
3066 i.setType("*/*");
3067 }
3068
Ben Murdoch6af492a2010-06-15 12:38:17 +01003069 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003070 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3071 chooser.putExtra(Intent.EXTRA_INTENT, i);
3072
Ben Murdoch6af492a2010-06-15 12:38:17 +01003073 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3074
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003075 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003076 extraInitialIntents.add(cameraIntent);
3077 }
3078
3079 if (addCamcorderIntent) {
3080 extraInitialIntents.add(camcorderIntent);
3081 }
3082
3083 if (extraInitialIntents.size() > 0) {
3084 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3085 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003086 }
3087
3088 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3089 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003090 }
3091
3092 // -------------------------------------------------------------------------
3093 // Implement functions for DownloadListener
3094 // -------------------------------------------------------------------------
3095
The Android Open Source Project0c908882009-03-03 19:32:16 -08003096 /**
3097 * Notify the host application a download should be done, or that
3098 * the data should be streamed if a streaming viewer is available.
3099 * @param url The full url to the content that should be downloaded
3100 * @param contentDisposition Content-disposition http header, if
3101 * present.
3102 * @param mimetype The mimetype of the content reported by the server
3103 * @param contentLength The file size reported by the server
3104 */
3105 public void onDownloadStart(String url, String userAgent,
3106 String contentDisposition, String mimetype, long contentLength) {
3107 // if we're dealing wih A/V content that's not explicitly marked
3108 // for download, check if it's streamable.
3109 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003110 || !contentDisposition.regionMatches(
3111 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003112 // query the package manager to see if there's a registered handler
3113 // that matches.
3114 Intent intent = new Intent(Intent.ACTION_VIEW);
3115 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003116 ResolveInfo info = getPackageManager().resolveActivity(intent,
3117 PackageManager.MATCH_DEFAULT_ONLY);
3118 if (info != null) {
3119 ComponentName myName = getComponentName();
3120 // If we resolved to ourselves, we don't want to attempt to
3121 // load the url only to try and download it again.
3122 if (!myName.getPackageName().equals(
3123 info.activityInfo.packageName)
3124 || !myName.getClassName().equals(
3125 info.activityInfo.name)) {
3126 // someone (other than us) knows how to handle this mime
3127 // type with this scheme, don't download.
3128 try {
3129 startActivity(intent);
3130 return;
3131 } catch (ActivityNotFoundException ex) {
3132 if (LOGD_ENABLED) {
3133 Log.d(LOGTAG, "activity not found for " + mimetype
3134 + " over " + Uri.parse(url).getScheme(),
3135 ex);
3136 }
3137 // Best behavior is to fall back to a download in this
3138 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003139 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003140 }
3141 }
3142 }
3143 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3144 }
3145
Kristian Monsenfa52d172010-03-25 18:29:21 +00003146 // This is to work around the fact that java.net.URI throws Exceptions
3147 // instead of just encoding URL's properly
3148 // Helper method for onDownloadStartNoStream
3149 private static String encodePath(String path) {
3150 char[] chars = path.toCharArray();
3151
3152 boolean needed = false;
3153 for (char c : chars) {
3154 if (c == '[' || c == ']') {
3155 needed = true;
3156 break;
3157 }
3158 }
3159 if (needed == false) {
3160 return path;
3161 }
3162
3163 StringBuilder sb = new StringBuilder("");
3164 for (char c : chars) {
3165 if (c == '[' || c == ']') {
3166 sb.append('%');
3167 sb.append(Integer.toHexString(c));
3168 } else {
3169 sb.append(c);
3170 }
3171 }
3172
3173 return sb.toString();
3174 }
3175
The Android Open Source Project0c908882009-03-03 19:32:16 -08003176 /**
3177 * Notify the host application a download should be done, even if there
3178 * is a streaming viewer available for thise type.
3179 * @param url The full url to the content that should be downloaded
3180 * @param contentDisposition Content-disposition http header, if
3181 * present.
3182 * @param mimetype The mimetype of the content reported by the server
3183 * @param contentLength The file size reported by the server
3184 */
3185 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3186 String contentDisposition, String mimetype, long contentLength) {
3187
3188 String filename = URLUtil.guessFileName(url,
3189 contentDisposition, mimetype);
3190
3191 // Check to see if we have an SDCard
3192 String status = Environment.getExternalStorageState();
3193 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3194 int title;
3195 String msg;
3196
3197 // Check to see if the SDCard is busy, same as the music app
3198 if (status.equals(Environment.MEDIA_SHARED)) {
3199 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3200 title = R.string.download_sdcard_busy_dlg_title;
3201 } else {
3202 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3203 title = R.string.download_no_sdcard_dlg_title;
3204 }
3205
3206 new AlertDialog.Builder(this)
3207 .setTitle(title)
3208 .setIcon(android.R.drawable.ic_dialog_alert)
3209 .setMessage(msg)
3210 .setPositiveButton(R.string.ok, null)
3211 .show();
3212 return;
3213 }
3214
Kristian Monsenfa52d172010-03-25 18:29:21 +00003215 // java.net.URI is a lot stricter than KURL so we have to encode some
3216 // extra characters. Fix for b 2538060 and b 1634719
3217 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003218 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003219 webAddress = new WebAddress(url);
3220 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003221 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003222 // This only happens for very bad urls, we want to chatch the
3223 // exception here
3224 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003225 return;
3226 }
3227
3228 // XXX: Have to use the old url since the cookies were stored using the
3229 // old percent-encoded url.
3230 String cookies = CookieManager.getInstance().getCookie(url);
3231
3232 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003233 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003234 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3235 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3236 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003237 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003238 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003239 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003240 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3241 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3242 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3243 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003244 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003245 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003246 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003247 }
3248 if (mimetype == null) {
3249 // We must have long pressed on a link or image to download it. We
3250 // are not sure of the mimetype in this case, so do a head request
3251 new FetchUrlMimeType(this).execute(values);
3252 } else {
3253 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003254 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003255 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003256 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3257 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003258 }
3259
Grace Kloba22ac16e2009-10-07 18:00:23 -07003260 // -------------------------------------------------------------------------
3261
The Android Open Source Project0c908882009-03-03 19:32:16 -08003262 /**
3263 * Resets the lock icon. This method is called when we start a new load and
3264 * know the url to be loaded.
3265 */
3266 private void resetLockIcon(String url) {
3267 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003268 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003269 updateLockIconImage(LOCK_ICON_UNSECURE);
3270 }
3271
The Android Open Source Project0c908882009-03-03 19:32:16 -08003272 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003273 * Update the lock icon to correspond to our latest state.
3274 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003275 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003276 Tab t = mTabControl.getCurrentTab();
3277 if (t != null) {
3278 updateLockIconImage(t.getLockIconType());
3279 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003280 }
3281
3282 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003283 * Updates the lock-icon image in the title-bar.
3284 */
3285 private void updateLockIconImage(int lockIconType) {
3286 Drawable d = null;
3287 if (lockIconType == LOCK_ICON_SECURE) {
3288 d = mSecLockIcon;
3289 } else if (lockIconType == LOCK_ICON_MIXED) {
3290 d = mMixLockIcon;
3291 }
Leon Scroggins68579392009-09-15 15:31:54 -04003292 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003293 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003294 }
3295
3296 /**
3297 * Displays a page-info dialog.
3298 * @param tab The tab to show info about
3299 * @param fromShowSSLCertificateOnError The flag that indicates whether
3300 * this dialog was opened from the SSL-certificate-on-error dialog or
3301 * not. This is important, since we need to know whether to return to
3302 * the parent dialog or simply dismiss.
3303 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003304 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003305 final boolean fromShowSSLCertificateOnError) {
3306 final LayoutInflater factory = LayoutInflater
3307 .from(this);
3308
3309 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3310
3311 final WebView view = tab.getWebView();
3312
3313 String url = null;
3314 String title = null;
3315
3316 if (view == null) {
3317 url = tab.getUrl();
3318 title = tab.getTitle();
3319 } else if (view == mTabControl.getCurrentWebView()) {
3320 // Use the cached title and url if this is the current WebView
3321 url = mUrl;
3322 title = mTitle;
3323 } else {
3324 url = view.getUrl();
3325 title = view.getTitle();
3326 }
3327
3328 if (url == null) {
3329 url = "";
3330 }
3331 if (title == null) {
3332 title = "";
3333 }
3334
3335 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3336 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3337
3338 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003339 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003340
3341 AlertDialog.Builder alertDialogBuilder =
3342 new AlertDialog.Builder(this)
3343 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3344 .setView(pageInfoView)
3345 .setPositiveButton(
3346 R.string.ok,
3347 new DialogInterface.OnClickListener() {
3348 public void onClick(DialogInterface dialog,
3349 int whichButton) {
3350 mPageInfoDialog = null;
3351 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003352
3353 // if we came here from the SSL error dialog
3354 if (fromShowSSLCertificateOnError) {
3355 // go back to the SSL error dialog
3356 showSSLCertificateOnError(
3357 mSSLCertificateOnErrorView,
3358 mSSLCertificateOnErrorHandler,
3359 mSSLCertificateOnErrorError);
3360 }
3361 }
3362 })
3363 .setOnCancelListener(
3364 new DialogInterface.OnCancelListener() {
3365 public void onCancel(DialogInterface dialog) {
3366 mPageInfoDialog = null;
3367 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003368
3369 // if we came here from the SSL error dialog
3370 if (fromShowSSLCertificateOnError) {
3371 // go back to the SSL error dialog
3372 showSSLCertificateOnError(
3373 mSSLCertificateOnErrorView,
3374 mSSLCertificateOnErrorHandler,
3375 mSSLCertificateOnErrorError);
3376 }
3377 }
3378 });
3379
3380 // if we have a main top-level page SSL certificate set or a certificate
3381 // error
3382 if (fromShowSSLCertificateOnError ||
3383 (view != null && view.getCertificate() != null)) {
3384 // add a 'View Certificate' button
3385 alertDialogBuilder.setNeutralButton(
3386 R.string.view_certificate,
3387 new DialogInterface.OnClickListener() {
3388 public void onClick(DialogInterface dialog,
3389 int whichButton) {
3390 mPageInfoDialog = null;
3391 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003392
3393 // if we came here from the SSL error dialog
3394 if (fromShowSSLCertificateOnError) {
3395 // go back to the SSL error dialog
3396 showSSLCertificateOnError(
3397 mSSLCertificateOnErrorView,
3398 mSSLCertificateOnErrorHandler,
3399 mSSLCertificateOnErrorError);
3400 } else {
3401 // otherwise, display the top-most certificate from
3402 // the chain
3403 if (view.getCertificate() != null) {
3404 showSSLCertificate(tab);
3405 }
3406 }
3407 }
3408 });
3409 }
3410
3411 mPageInfoDialog = alertDialogBuilder.show();
3412 }
3413
3414 /**
3415 * Displays the main top-level page SSL certificate dialog
3416 * (accessible from the Page-Info dialog).
3417 * @param tab The tab to show certificate for.
3418 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003419 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003420 final View certificateView =
3421 inflateCertificateView(tab.getWebView().getCertificate());
3422 if (certificateView == null) {
3423 return;
3424 }
3425
3426 LayoutInflater factory = LayoutInflater.from(this);
3427
3428 final LinearLayout placeholder =
3429 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3430
3431 LinearLayout ll = (LinearLayout) factory.inflate(
3432 R.layout.ssl_success, placeholder);
3433 ((TextView)ll.findViewById(R.id.success))
3434 .setText(R.string.ssl_certificate_is_valid);
3435
3436 mSSLCertificateView = tab;
3437 mSSLCertificateDialog =
3438 new AlertDialog.Builder(this)
3439 .setTitle(R.string.ssl_certificate).setIcon(
3440 R.drawable.ic_dialog_browser_certificate_secure)
3441 .setView(certificateView)
3442 .setPositiveButton(R.string.ok,
3443 new DialogInterface.OnClickListener() {
3444 public void onClick(DialogInterface dialog,
3445 int whichButton) {
3446 mSSLCertificateDialog = null;
3447 mSSLCertificateView = null;
3448
3449 showPageInfo(tab, false);
3450 }
3451 })
3452 .setOnCancelListener(
3453 new DialogInterface.OnCancelListener() {
3454 public void onCancel(DialogInterface dialog) {
3455 mSSLCertificateDialog = null;
3456 mSSLCertificateView = null;
3457
3458 showPageInfo(tab, false);
3459 }
3460 })
3461 .show();
3462 }
3463
3464 /**
3465 * Displays the SSL error certificate dialog.
3466 * @param view The target web-view.
3467 * @param handler The SSL error handler responsible for cancelling the
3468 * connection that resulted in an SSL error or proceeding per user request.
3469 * @param error The SSL error object.
3470 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003471 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003472 final WebView view, final SslErrorHandler handler, final SslError error) {
3473
3474 final View certificateView =
3475 inflateCertificateView(error.getCertificate());
3476 if (certificateView == null) {
3477 return;
3478 }
3479
3480 LayoutInflater factory = LayoutInflater.from(this);
3481
3482 final LinearLayout placeholder =
3483 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3484
3485 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3486 LinearLayout ll = (LinearLayout)factory
3487 .inflate(R.layout.ssl_warning, placeholder);
3488 ((TextView)ll.findViewById(R.id.warning))
3489 .setText(R.string.ssl_untrusted);
3490 }
3491
3492 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3493 LinearLayout ll = (LinearLayout)factory
3494 .inflate(R.layout.ssl_warning, placeholder);
3495 ((TextView)ll.findViewById(R.id.warning))
3496 .setText(R.string.ssl_mismatch);
3497 }
3498
3499 if (error.hasError(SslError.SSL_EXPIRED)) {
3500 LinearLayout ll = (LinearLayout)factory
3501 .inflate(R.layout.ssl_warning, placeholder);
3502 ((TextView)ll.findViewById(R.id.warning))
3503 .setText(R.string.ssl_expired);
3504 }
3505
3506 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3507 LinearLayout ll = (LinearLayout)factory
3508 .inflate(R.layout.ssl_warning, placeholder);
3509 ((TextView)ll.findViewById(R.id.warning))
3510 .setText(R.string.ssl_not_yet_valid);
3511 }
3512
3513 mSSLCertificateOnErrorHandler = handler;
3514 mSSLCertificateOnErrorView = view;
3515 mSSLCertificateOnErrorError = error;
3516 mSSLCertificateOnErrorDialog =
3517 new AlertDialog.Builder(this)
3518 .setTitle(R.string.ssl_certificate).setIcon(
3519 R.drawable.ic_dialog_browser_certificate_partially_secure)
3520 .setView(certificateView)
3521 .setPositiveButton(R.string.ok,
3522 new DialogInterface.OnClickListener() {
3523 public void onClick(DialogInterface dialog,
3524 int whichButton) {
3525 mSSLCertificateOnErrorDialog = null;
3526 mSSLCertificateOnErrorView = null;
3527 mSSLCertificateOnErrorHandler = null;
3528 mSSLCertificateOnErrorError = null;
3529
Grace Kloba22ac16e2009-10-07 18:00:23 -07003530 view.getWebViewClient().onReceivedSslError(
3531 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003532 }
3533 })
3534 .setNeutralButton(R.string.page_info_view,
3535 new DialogInterface.OnClickListener() {
3536 public void onClick(DialogInterface dialog,
3537 int whichButton) {
3538 mSSLCertificateOnErrorDialog = null;
3539
3540 // do not clear the dialog state: we will
3541 // need to show the dialog again once the
3542 // user is done exploring the page-info details
3543
3544 showPageInfo(mTabControl.getTabFromView(view),
3545 true);
3546 }
3547 })
3548 .setOnCancelListener(
3549 new DialogInterface.OnCancelListener() {
3550 public void onCancel(DialogInterface dialog) {
3551 mSSLCertificateOnErrorDialog = null;
3552 mSSLCertificateOnErrorView = null;
3553 mSSLCertificateOnErrorHandler = null;
3554 mSSLCertificateOnErrorError = null;
3555
Grace Kloba22ac16e2009-10-07 18:00:23 -07003556 view.getWebViewClient().onReceivedSslError(
3557 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003558 }
3559 })
3560 .show();
3561 }
3562
3563 /**
3564 * Inflates the SSL certificate view (helper method).
3565 * @param certificate The SSL certificate.
3566 * @return The resultant certificate view with issued-to, issued-by,
3567 * issued-on, expires-on, and possibly other fields set.
3568 * If the input certificate is null, returns null.
3569 */
3570 private View inflateCertificateView(SslCertificate certificate) {
3571 if (certificate == null) {
3572 return null;
3573 }
3574
3575 LayoutInflater factory = LayoutInflater.from(this);
3576
3577 View certificateView = factory.inflate(
3578 R.layout.ssl_certificate, null);
3579
3580 // issued to:
3581 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3582 if (issuedTo != null) {
3583 ((TextView) certificateView.findViewById(R.id.to_common))
3584 .setText(issuedTo.getCName());
3585 ((TextView) certificateView.findViewById(R.id.to_org))
3586 .setText(issuedTo.getOName());
3587 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3588 .setText(issuedTo.getUName());
3589 }
3590
3591 // issued by:
3592 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3593 if (issuedBy != null) {
3594 ((TextView) certificateView.findViewById(R.id.by_common))
3595 .setText(issuedBy.getCName());
3596 ((TextView) certificateView.findViewById(R.id.by_org))
3597 .setText(issuedBy.getOName());
3598 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3599 .setText(issuedBy.getUName());
3600 }
3601
3602 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003603 String issuedOn = formatCertificateDate(
3604 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003605 ((TextView) certificateView.findViewById(R.id.issued_on))
3606 .setText(issuedOn);
3607
3608 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003609 String expiresOn = formatCertificateDate(
3610 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003611 ((TextView) certificateView.findViewById(R.id.expires_on))
3612 .setText(expiresOn);
3613
3614 return certificateView;
3615 }
3616
3617 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003618 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003619 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003620 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003621 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003622 private String formatCertificateDate(Date certificateDate) {
3623 if (certificateDate == null) {
3624 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003625 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003626 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3627 if (formattedDate == null) {
3628 return "";
3629 }
3630 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003631 }
3632
3633 /**
3634 * Displays an http-authentication dialog.
3635 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003636 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003637 final String host, final String realm, final String title,
3638 final String name, final String password, int focusId) {
3639 LayoutInflater factory = LayoutInflater.from(this);
3640 final View v = factory
3641 .inflate(R.layout.http_authentication, null);
3642 if (name != null) {
3643 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3644 }
3645 if (password != null) {
3646 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3647 }
3648
3649 String titleText = title;
3650 if (titleText == null) {
3651 titleText = getText(R.string.sign_in_to).toString().replace(
3652 "%s1", host).replace("%s2", realm);
3653 }
3654
3655 mHttpAuthHandler = handler;
3656 AlertDialog dialog = new AlertDialog.Builder(this)
3657 .setTitle(titleText)
3658 .setIcon(android.R.drawable.ic_dialog_alert)
3659 .setView(v)
3660 .setPositiveButton(R.string.action,
3661 new DialogInterface.OnClickListener() {
3662 public void onClick(DialogInterface dialog,
3663 int whichButton) {
3664 String nm = ((EditText) v
3665 .findViewById(R.id.username_edit))
3666 .getText().toString();
3667 String pw = ((EditText) v
3668 .findViewById(R.id.password_edit))
3669 .getText().toString();
3670 BrowserActivity.this.setHttpAuthUsernamePassword
3671 (host, realm, nm, pw);
3672 handler.proceed(nm, pw);
3673 mHttpAuthenticationDialog = null;
3674 mHttpAuthHandler = null;
3675 }})
3676 .setNegativeButton(R.string.cancel,
3677 new DialogInterface.OnClickListener() {
3678 public void onClick(DialogInterface dialog,
3679 int whichButton) {
3680 handler.cancel();
3681 BrowserActivity.this.resetTitleAndRevertLockIcon();
3682 mHttpAuthenticationDialog = null;
3683 mHttpAuthHandler = null;
3684 }})
3685 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3686 public void onCancel(DialogInterface dialog) {
3687 handler.cancel();
3688 BrowserActivity.this.resetTitleAndRevertLockIcon();
3689 mHttpAuthenticationDialog = null;
3690 mHttpAuthHandler = null;
3691 }})
3692 .create();
3693 // Make the IME appear when the dialog is displayed if applicable.
3694 dialog.getWindow().setSoftInputMode(
3695 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3696 dialog.show();
3697 if (focusId != 0) {
3698 dialog.findViewById(focusId).requestFocus();
3699 } else {
3700 v.findViewById(R.id.username_edit).requestFocus();
3701 }
3702 mHttpAuthenticationDialog = dialog;
3703 }
3704
3705 public int getProgress() {
3706 WebView w = mTabControl.getCurrentWebView();
3707 if (w != null) {
3708 return w.getProgress();
3709 } else {
3710 return 100;
3711 }
3712 }
3713
3714 /**
3715 * Set HTTP authentication password.
3716 *
3717 * @param host The host for the password
3718 * @param realm The realm for the password
3719 * @param username The username for the password. If it is null, it means
3720 * password can't be saved.
3721 * @param password The password
3722 */
3723 public void setHttpAuthUsernamePassword(String host, String realm,
3724 String username,
3725 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003726 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003727 if (w != null) {
3728 w.setHttpAuthUsernamePassword(host, realm, username, password);
3729 }
3730 }
3731
3732 /**
3733 * connectivity manager says net has come or gone... inform the user
3734 * @param up true if net has come up, false if net has gone down
3735 */
3736 public void onNetworkToggle(boolean up) {
3737 if (up == mIsNetworkUp) {
3738 return;
3739 } else if (up) {
3740 mIsNetworkUp = true;
3741 if (mAlertDialog != null) {
3742 mAlertDialog.cancel();
3743 mAlertDialog = null;
3744 }
3745 } else {
3746 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003747 if (mInLoad) {
3748 createAndShowNetworkDialog();
3749 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003750 }
3751 WebView w = mTabControl.getCurrentWebView();
3752 if (w != null) {
3753 w.setNetworkAvailable(up);
3754 }
3755 }
3756
Grace Kloba22ac16e2009-10-07 18:00:23 -07003757 boolean isNetworkUp() {
3758 return mIsNetworkUp;
3759 }
3760
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003761 // This method shows the network dialog alerting the user that the net is
3762 // down. It will only show the dialog if mAlertDialog is null.
3763 private void createAndShowNetworkDialog() {
3764 if (mAlertDialog == null) {
3765 mAlertDialog = new AlertDialog.Builder(this)
3766 .setTitle(R.string.loadSuspendedTitle)
3767 .setMessage(R.string.loadSuspended)
3768 .setPositiveButton(R.string.ok, null)
3769 .show();
3770 }
3771 }
3772
The Android Open Source Project0c908882009-03-03 19:32:16 -08003773 @Override
3774 protected void onActivityResult(int requestCode, int resultCode,
3775 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003776 if (getTopWindow() == null) return;
3777
The Android Open Source Project0c908882009-03-03 19:32:16 -08003778 switch (requestCode) {
3779 case COMBO_PAGE:
3780 if (resultCode == RESULT_OK && intent != null) {
3781 String data = intent.getAction();
3782 Bundle extras = intent.getExtras();
Michael Kolb300b7f02010-08-25 13:47:24 -07003783 if (extras != null &&
3784 extras.getBoolean(
3785 CombinedBookmarkHistoryActivity.EXTRA_OPEN_NEW_WINDOW,
3786 false)) {
Michael Kolb68792c82010-08-09 16:39:18 -07003787 openTab(data, false);
3788 } else if ((extras != null) &&
3789 extras.getBoolean(CombinedBookmarkHistoryActivity.NEWTAB_MODE)) {
3790 openTab(data, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003791 } else {
Michael Kolb68792c82010-08-09 16:39:18 -07003792 final Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003793 dismissSubWindow(currentTab);
3794 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003795 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003796 }
3797 }
Michael Kolb3f65c382010-08-20 15:31:16 -07003798 } else if (resultCode == RESULT_CANCELED) {
3799 if (intent != null) {
3800 float evtx = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_X, -1);
3801 float evty = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_Y, -1);
3802 long now = System.currentTimeMillis();
3803 MotionEvent evt = MotionEvent.obtain(now, now,
3804 MotionEvent.ACTION_DOWN, evtx, evty, 0);
3805 dispatchTouchEvent(evt);
3806 MotionEvent up = MotionEvent.obtain(evt);
3807 up.setAction(MotionEvent.ACTION_UP);
3808 dispatchTouchEvent(up);
3809 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003810 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003811 // Deliberately fall through to PREFERENCES_PAGE, since the
3812 // same extra may be attached to the COMBO_PAGE
3813 case PREFERENCES_PAGE:
3814 if (resultCode == RESULT_OK && intent != null) {
3815 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3816 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3817 mTabControl.removeParentChildRelationShips();
3818 }
3819 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003820 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003821 // Choose a file from the file picker.
3822 case FILE_SELECTED:
3823 if (null == mUploadMessage) break;
3824 Uri result = intent == null || resultCode != RESULT_OK ? null
3825 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003826
3827 // As we ask the camera to save the result of the user taking
3828 // a picture, the camera application does not return anything other
3829 // than RESULT_OK. So we need to check whether the file we expected
3830 // was written to disk in the in the case that we
3831 // did not get an intent returned but did get a RESULT_OK. If it was,
3832 // we assume that this result has came back from the camera.
3833 if (result == null && intent == null && resultCode == RESULT_OK) {
3834 File cameraFile = new File(mCameraFilePath);
3835 if (cameraFile.exists()) {
3836 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003837 // Broadcast to the media scanner that we have a new photo
3838 // so it will be added into the gallery for the user.
3839 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003840 }
3841 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003842 mUploadMessage.onReceiveValue(result);
3843 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003844 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003845 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003846 default:
3847 break;
3848 }
Leon Scroggins30444232009-09-04 18:36:20 -04003849 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003850 }
3851
3852 /*
3853 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003854 * menu to see the download window. It shows the download window on top of
3855 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003856 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003857 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003858 Intent intent = new Intent(this,
3859 BrowserDownloadPage.class);
3860 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003861 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003862
3863 }
3864
Ben Murdocheecb4e62010-07-06 16:30:38 +01003865 /* package*/ void promptAddOrInstallBookmark() {
3866 final Tab current = mTabControl.getCurrentTab();
3867 Resources resources = getResources();
3868 CharSequence[] choices = {
3869 resources.getString(R.string.save_to_bookmarks),
3870 resources.getString(R.string.create_shortcut_bookmark)
3871 };
3872
3873 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3874 builder.setTitle(R.string.add_new_bookmark);
3875 builder.setItems(choices, new DialogInterface.OnClickListener() {
3876 public void onClick(DialogInterface dialog, int item) {
3877 if (item == 0) {
3878 bookmarkCurrentPage();
3879 } else if (item == 1) {
3880 current.populatePickerData();
3881 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3882 if (touchIconUrl != null) {
3883 // Download the touch icon for this site then save it to the
3884 // homescreen.
3885 Bundle b = new Bundle();
3886 b.putString("url", current.getUrl());
3887 b.putString("title", current.getTitle());
3888 b.putParcelable("favicon", current.getFavicon());
3889 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3890 msg.setData(b);
Ben Murdochccb5de02010-07-19 18:38:17 +01003891 new DownloadTouchIcon(BrowserActivity.this, msg,
Ben Murdocheecb4e62010-07-06 16:30:38 +01003892 mTabControl.getCurrentWebView().getSettings()
3893 .getUserAgentString()).execute(touchIconUrl);
3894 } else {
3895 // add to homescreen, can do it immediately as there is no touch
3896 // icon.
3897 showSaveToHomescreenDialog(current.getUrl(), current.getTitle(),
3898 null, current.getFavicon());
3899 }
3900 }
3901 }
3902 });
3903 builder.create().show();
3904 }
3905
Leon Scroggins160a7e72009-08-14 18:28:01 -04003906 /**
3907 * Open the Go page.
3908 * @param startWithHistory If true, open starting on the history tab.
3909 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003910 */
Michael Kolb68792c82010-08-09 16:39:18 -07003911 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory, boolean newTabMode) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003912 WebView current = mTabControl.getCurrentWebView();
3913 if (current == null) {
3914 return;
3915 }
3916 Intent intent = new Intent(this,
3917 CombinedBookmarkHistoryActivity.class);
3918 String title = current.getTitle();
3919 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003920 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3921 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003922
The Android Open Source Project0c908882009-03-03 19:32:16 -08003923 // Just in case the user opens bookmarks before a page finishes loading
3924 // so the current history item, and therefore the page, is null.
3925 if (null == url) {
3926 url = mLastEnteredUrl;
3927 // This can happen.
3928 if (null == url) {
3929 url = mSettings.getHomePage();
3930 }
3931 }
3932 // In case the web page has not yet received its associated title.
3933 if (title == null) {
3934 title = url;
3935 }
3936 intent.putExtra("title", title);
3937 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003938 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003939 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003940 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003941 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003942 if (startWithHistory) {
Jeff Hamilton64144e42010-08-18 16:31:59 -05003943 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_FRAGMENT,
3944 CombinedBookmarkHistoryActivity.FRAGMENT_ID_HISTORY);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003945 }
Michael Kolb300b7f02010-08-25 13:47:24 -07003946 intent.putExtra(CombinedBookmarkHistoryActivity.NEWTAB_MODE, newTabMode);
Michael Kolb0998b0a2010-08-23 17:45:35 -07003947 int top = -1;
3948 int height = -1;
Michael Kolb3f65c382010-08-20 15:31:16 -07003949 if (mXLargeScreenSize) {
3950 showFakeTitleBar();
3951 int titleBarHeight = ((TitleBarXLarge)mFakeTitleBar).getHeightWithoutProgress();
Michael Kolb0998b0a2010-08-23 17:45:35 -07003952 top = mTabBar.getBottom() + titleBarHeight;
3953 height = getTopWindow().getHeight() - titleBarHeight;
Michael Kolb68792c82010-08-09 16:39:18 -07003954 }
Michael Kolb0998b0a2010-08-23 17:45:35 -07003955 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_TOP, top);
3956 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_HEIGHT, height);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003957 startActivityForResult(intent, COMBO_PAGE);
3958 }
3959
Ben Murdocheecb4e62010-07-06 16:30:38 +01003960 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3961 Bitmap favicon) {
3962 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3963
3964 // Just in case the user tries to save before a page finishes loading
3965 // so the current history item, and therefore the page, is null.
3966 if (null == url) {
3967 url = mLastEnteredUrl;
3968 // This can happen.
3969 if (null == url) {
3970 url = mSettings.getHomePage();
3971 }
3972 }
3973
3974 // In case the web page has not yet received its associated title.
3975 if (title == null) {
3976 title = url;
3977 }
3978
3979 intent.putExtra("title", title);
3980 intent.putExtra("url", url);
3981 intent.putExtra("favicon", favicon);
3982 intent.putExtra("touchIcon", touchIcon);
3983 startActivity(intent);
3984 }
3985
3986
The Android Open Source Project0c908882009-03-03 19:32:16 -08003987 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003988 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003989 // In case the user enters nothing.
3990 if (url != null && url.length() != 0 && view != null) {
3991 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003992 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003993 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003994 }
3995 }
3996 }
3997
Leon Scroggins92472e82010-02-17 16:32:28 -05003998 /**
3999 * Load the URL into the given WebView and update the title bar
4000 * to reflect the new load. Call this instead of WebView.loadUrl
4001 * directly.
4002 * @param view The WebView used to load url.
4003 * @param url The URL to load.
4004 */
4005 private void loadUrl(WebView view, String url) {
4006 updateTitleBarForNewLoad(view, url);
4007 view.loadUrl(url);
4008 }
4009
4010 /**
4011 * Load UrlData into a Tab and update the title bar to reflect the new
4012 * load. Call this instead of UrlData.loadIn directly.
4013 * @param t The Tab used to load.
4014 * @param data The UrlData being loaded.
4015 */
4016 private void loadUrlDataIn(Tab t, UrlData data) {
4017 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
4018 data.loadIn(t);
4019 }
4020
4021 /**
4022 * If the WebView is the top window, update the title bar to reflect
4023 * loading the new URL. i.e. set its text, clear the favicon (which
4024 * will be set once the page begins loading), and set the progress to
4025 * INITIAL_PROGRESS to show that the page has begun to load. Called
4026 * by loadUrl and loadUrlDataIn.
4027 * @param view The WebView that is starting a load.
4028 * @param url The URL that is being loaded.
4029 */
4030 private void updateTitleBarForNewLoad(WebView view, String url) {
4031 if (view == getTopWindow()) {
4032 setUrlTitle(url, null);
4033 setFavicon(null);
4034 onProgressChanged(view, INITIAL_PROGRESS);
4035 }
4036 }
4037
The Android Open Source Project0c908882009-03-03 19:32:16 -08004038 private String smartUrlFilter(Uri inUri) {
4039 if (inUri != null) {
4040 return smartUrlFilter(inUri.toString());
4041 }
4042 return null;
4043 }
4044
Feng Qianb34f87a2009-03-24 21:27:26 -07004045 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004046 "(?i)" + // switch on case insensitive matching
4047 "(" + // begin group for schema
4048 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004049 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004050 ")" +
4051 "(.*)" );
4052
4053 /**
4054 * Attempts to determine whether user input is a URL or search
4055 * terms. Anything with a space is passed to search.
4056 *
4057 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4058 * "Http://" converts to "http://"
4059 *
4060 * @return Original or modified URL
4061 *
4062 */
4063 String smartUrlFilter(String url) {
4064
4065 String inUrl = url.trim();
4066 boolean hasSpace = inUrl.indexOf(' ') != -1;
4067
4068 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4069 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004070 // force scheme to lowercase
4071 String scheme = matcher.group(1);
4072 String lcScheme = scheme.toLowerCase();
4073 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004074 inUrl = lcScheme + matcher.group(2);
4075 }
4076 if (hasSpace) {
4077 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004078 }
4079 return inUrl;
4080 }
4081 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004082 // FIXME: Is this the correct place to add to searches?
4083 // what if someone else calls this function?
4084 int shortcut = parseUrlShortcut(inUrl);
4085 if (shortcut != SHORTCUT_INVALID) {
4086 Browser.addSearchUrl(mResolver, inUrl);
4087 String query = inUrl.substring(2);
4088 switch (shortcut) {
4089 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004090 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004091 case SHORTCUT_WIKIPEDIA_SEARCH:
4092 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4093 case SHORTCUT_DICTIONARY_SEARCH:
4094 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4095 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004096 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004097 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004098 }
4099 }
4100 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004101 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004102 return URLUtil.guessUrl(inUrl);
4103 }
4104 }
4105
4106 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004107 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004108 }
4109
Ben Murdochbff2d602009-07-01 20:19:05 +01004110 /* package */ void setShouldShowErrorConsole(boolean flag) {
4111 if (flag == mShouldShowErrorConsole) {
4112 // Nothing to do.
4113 return;
4114 }
4115
4116 mShouldShowErrorConsole = flag;
4117
Grace Kloba22ac16e2009-10-07 18:00:23 -07004118 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4119 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004120
4121 if (flag) {
4122 // Setting the show state of the console will cause it's the layout to be inflated.
4123 if (errorConsole.numberOfErrors() > 0) {
4124 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4125 } else {
4126 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4127 }
4128
4129 // Now we can add it to the main view.
4130 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004131 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004132 ViewGroup.LayoutParams.WRAP_CONTENT));
4133 } else {
4134 mErrorConsoleContainer.removeView(errorConsole);
4135 }
4136
4137 }
4138
Grace Kloba22ac16e2009-10-07 18:00:23 -07004139 boolean shouldShowErrorConsole() {
4140 return mShouldShowErrorConsole;
4141 }
4142
Andrei Popescu163ab742009-10-20 17:58:23 +01004143 private void setStatusBarVisibility(boolean visible) {
4144 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4145 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4146 }
4147
Andrei Popescu56199cc2010-01-12 22:39:16 +00004148
4149 private void sendNetworkType(String type, String subtype) {
4150 WebView w = mTabControl.getCurrentWebView();
4151 if (w != null) {
4152 w.setNetworkType(type, subtype);
4153 }
4154 }
4155
Grace Klobaeb6eef42009-09-15 17:56:32 -07004156 final static int LOCK_ICON_UNSECURE = 0;
4157 final static int LOCK_ICON_SECURE = 1;
4158 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004159
The Android Open Source Project0c908882009-03-03 19:32:16 -08004160 private BrowserSettings mSettings;
4161 private TabControl mTabControl;
4162 private ContentResolver mResolver;
4163 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004164 private View mCustomView;
4165 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004166 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004167
4168 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4169 // view, we should rewrite this.
4170 private int mCurrentMenuState = 0;
4171 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004172 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004173 private static final int EMPTY_MENU = -1;
4174 private Menu mMenu;
4175
The Android Open Source Project0c908882009-03-03 19:32:16 -08004176 // Used to prevent chording to result in firing two shortcuts immediately
4177 // one after another. Fixes bug 1211714.
4178 boolean mCanChord;
4179
4180 private boolean mInLoad;
4181 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004182 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004183
Cary Clark1f10cbf2010-03-22 11:45:23 -04004184 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004185
4186 private boolean mMenuIsDown;
4187
The Android Open Source Project0c908882009-03-03 19:32:16 -08004188 private static boolean mInTrace;
4189
4190 // Performance probe
4191 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4192 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4193 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4194 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4195 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4196 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4197 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4198 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4199 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4200 };
4201
4202 private long mStart;
4203 private long mProcessStart;
4204 private long mUserStart;
4205 private long mSystemStart;
4206 private long mIdleStart;
4207 private long mIrqStart;
4208
4209 private long mUiStart;
4210
4211 private Drawable mMixLockIcon;
4212 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004213
4214 /* hold a ref so we can auto-cancel if necessary */
4215 private AlertDialog mAlertDialog;
4216
The Android Open Source Project0c908882009-03-03 19:32:16 -08004217 // The up-to-date URL and title (these can be different from those stored
4218 // in WebView, since it takes some time for the information in WebView to
4219 // get updated)
4220 private String mUrl;
4221 private String mTitle;
4222
4223 // As PageInfo has different style for landscape / portrait, we have
4224 // to re-open it when configuration changed
4225 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004226 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004227 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4228 // dialog, we should not just dismiss it, but should get back to the
4229 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004230 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004231
4232 // as SSLCertificateOnError has different style for landscape / portrait,
4233 // we have to re-open it when configuration changed
4234 private AlertDialog mSSLCertificateOnErrorDialog;
4235 private WebView mSSLCertificateOnErrorView;
4236 private SslErrorHandler mSSLCertificateOnErrorHandler;
4237 private SslError mSSLCertificateOnErrorError;
4238
4239 // as SSLCertificate has different style for landscape / portrait, we
4240 // have to re-open it when configuration changed
4241 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004242 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004243
4244 // as HttpAuthentication has different style for landscape / portrait, we
4245 // have to re-open it when configuration changed
4246 private AlertDialog mHttpAuthenticationDialog;
4247 private HttpAuthHandler mHttpAuthHandler;
4248
4249 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4250 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004251 ViewGroup.LayoutParams.MATCH_PARENT,
4252 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004253 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4254 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004255 ViewGroup.LayoutParams.MATCH_PARENT,
4256 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004257 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004258 // Google search
4259 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004260 // Wikipedia search
4261 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4262 // Dictionary search
4263 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4264 // Google Mobile Local search
4265 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4266
4267 final static String QUERY_PLACE_HOLDER = "%s";
4268
4269 // "source" parameter for Google search through search key
4270 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4271 // "source" parameter for Google search through goto menu
4272 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4273 // "source" parameter for Google search through simplily type
4274 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4275 // "source" parameter for Google search suggested by the browser
4276 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4277 // "source" parameter for Google search from unknown source
4278 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4279
4280 private final static String LOGTAG = "browser";
4281
The Android Open Source Project0c908882009-03-03 19:32:16 -08004282 private String mLastEnteredUrl;
4283
4284 private PowerManager.WakeLock mWakeLock;
4285 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4286
4287 private Toast mStopToast;
4288
Leon Scroggins571b3762010-05-26 10:25:01 -04004289 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004290 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004291
Ben Murdochbff2d602009-07-01 20:19:05 +01004292 private LinearLayout mErrorConsoleContainer = null;
4293 private boolean mShouldShowErrorConsole = false;
4294
The Android Open Source Project0c908882009-03-03 19:32:16 -08004295 // As the ids are dynamically created, we can't guarantee that they will
4296 // be in sequence, so this static array maps ids to a window number.
4297 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4298 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4299 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4300 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4301
4302 // monitor platform changes
4303 private IntentFilter mNetworkStateChangedFilter;
4304 private BroadcastReceiver mNetworkStateIntentReceiver;
4305
Bjorn Bringerta7611812010-03-24 11:12:02 +00004306 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4307
The Android Open Source Project0c908882009-03-03 19:32:16 -08004308 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004309 final static int COMBO_PAGE = 1;
4310 final static int DOWNLOAD_PAGE = 2;
4311 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004312 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004313
Andrei Popescu540035d2009-09-18 18:59:20 +01004314 // the default <video> poster
4315 private Bitmap mDefaultVideoPoster;
4316 // the video progress view
4317 private View mVideoProgressView;
4318
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004319 /**
4320 * A UrlData class to abstract how the content will be set to WebView.
4321 * This base class uses loadUrl to show the content.
4322 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004323 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004324 final String mUrl;
4325 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004326 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004327
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004328 UrlData(String url) {
4329 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004330 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004331 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004332 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004333
Leon Scroggins58d56c62010-01-28 15:12:40 -05004334 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004335 this.mUrl = url;
4336 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004337 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4338 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004339 this.mVoiceIntent = intent;
4340 } else {
4341 this.mVoiceIntent = null;
4342 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004343 }
4344
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004345 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004346 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004347 }
4348
Leon Scroggins92472e82010-02-17 16:32:28 -05004349 /**
4350 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4351 * the title bar as well.
4352 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004353 public void loadIn(Tab t) {
4354 if (mVoiceIntent != null) {
4355 t.activateVoiceSearchMode(mVoiceIntent);
4356 } else {
4357 t.getWebView().loadUrl(mUrl, mHeaders);
4358 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004359 }
4360 };
4361
Leon Scroggins1f005d32009-08-10 17:36:42 -04004362 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004363}