blob: 69e0ee54b362ab8d62af1d38584e4f070bd3d157 [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
The Android Open Source Project0c908882009-03-03 19:32:16 -080019import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080020import android.app.AlertDialog;
21import android.app.ProgressDialog;
22import android.app.SearchManager;
23import android.content.ActivityNotFoundException;
24import android.content.BroadcastReceiver;
Dianne Hackborn80f32622010-08-05 14:17:53 -070025import android.content.ClipboardManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080026import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050027import android.content.ContentProvider;
28import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080029import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040030import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080031import android.content.ContentValues;
32import android.content.Context;
33import android.content.DialogInterface;
34import android.content.Intent;
35import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070036import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080037import android.content.pm.PackageManager;
38import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080039import android.content.res.Configuration;
40import android.content.res.Resources;
41import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080042import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010043import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080044import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040046import android.graphics.PixelFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080047import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000049import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.net.Uri;
51import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080052import android.net.http.SslCertificate;
53import android.net.http.SslError;
54import android.os.AsyncTask;
55import android.os.Bundle;
56import android.os.Debug;
57import android.os.Environment;
58import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080059import android.os.Message;
60import android.os.PowerManager;
61import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080062import android.os.ServiceManager;
63import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080064import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040065import android.provider.ContactsContract;
The Android Open Source Project0c908882009-03-03 19:32:16 -080066import android.provider.Downloads;
67import android.provider.MediaStore;
Michael Kolbe0a36662010-06-29 10:37:12 -070068import android.provider.ContactsContract.Intents.Insert;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050069import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080070import android.text.TextUtils;
71import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080072import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080073import android.util.Patterns;
The Android Open Source Project0c908882009-03-03 19:32:16 -080074import android.view.ContextMenu;
75import android.view.Gravity;
76import android.view.KeyEvent;
77import android.view.LayoutInflater;
78import android.view.Menu;
79import android.view.MenuInflater;
80import android.view.MenuItem;
81import android.view.View;
82import android.view.ViewGroup;
83import android.view.Window;
84import android.view.WindowManager;
85import android.view.ContextMenu.ContextMenuInfo;
86import android.view.MenuItem.OnMenuItemClickListener;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070087import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080088import android.webkit.CookieManager;
89import android.webkit.CookieSyncManager;
90import android.webkit.DownloadListener;
91import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070092import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080093import android.webkit.SslErrorHandler;
94import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010095import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080096import android.webkit.WebChromeClient;
97import android.webkit.WebHistoryItem;
98import android.webkit.WebIconDatabase;
99import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800100import android.widget.EditText;
101import android.widget.FrameLayout;
102import android.widget.LinearLayout;
103import android.widget.TextView;
104import android.widget.Toast;
105
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000106import com.android.common.Search;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500107import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800108
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400109import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800110import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000111import java.io.IOException;
112import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700114import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800115import java.net.URL;
116import java.net.URLEncoder;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000119import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800120import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000121import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800122import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000123import java.util.Set;
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
Grace Kloba22ac16e2009-10-07 18:00:23 -0700167 @Override
168 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700169 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800170 Log.v(LOGTAG, this + " onStart");
171 }
172 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800173 // test the browser in OpenGL
174 // requestWindowFeature(Window.FEATURE_OPENGL);
175
Mike Reedd334bf52010-01-26 15:21:44 -0500176 // enable this to test the browser in 32bit
177 if (false) {
178 getWindow().setFormat(PixelFormat.RGBX_8888);
179 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
180 }
181
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700182 if (AccessibilityManager.getInstance(this).isEnabled()) {
183 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
184 } else {
185 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
186 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800187
188 mResolver = getContentResolver();
189
Grace Kloba0923d692009-09-23 21:37:25 -0700190 // If this was a web search request, pass it on to the default web
191 // search provider and finish this activity.
192 if (handleWebSearchIntent(getIntent())) {
193 finish();
194 return;
195 }
196
The Android Open Source Project0c908882009-03-03 19:32:16 -0800197 mSecLockIcon = Resources.getSystem().getDrawable(
198 android.R.drawable.ic_secure);
199 mMixLockIcon = Resources.getSystem().getDrawable(
200 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800201
Leon Scroggins81db3662009-06-04 17:45:11 -0400202 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
203 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400204 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
205 .inflate(R.layout.custom_screen, null);
206 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
207 R.id.main_content);
208 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
209 .findViewById(R.id.error_console);
210 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
211 .findViewById(R.id.fullscreen_custom_content);
212 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400213 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
214 & Configuration.SCREENLAYOUT_SIZE_MASK)
215 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
Michael Kolbe0a36662010-06-29 10:37:12 -0700216
Michael Kolbfe251992010-07-08 15:41:55 -0700217 // Create the tab control and our initial tab
218 mTabControl = new TabControl(this);
219
220
Leon Scrogginsd746a942010-05-19 13:21:44 -0400221 if (mXLargeScreenSize) {
Michael Kolbfe251992010-07-08 15:41:55 -0700222 mTitleBar = new TitleBarXLarge(this, mTabControl);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400223 LinearLayout layout = (LinearLayout) mBrowserFrameLayout.
224 findViewById(R.id.vertical_layout);
225 layout.addView(mTitleBar, 0, new LinearLayout.LayoutParams(
226 ViewGroup.LayoutParams.MATCH_PARENT,
227 ViewGroup.LayoutParams.WRAP_CONTENT));
228 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400229 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400230 // mTitleBar will be always be shown in the fully loaded mode on
231 // phone
232 mTitleBar.setProgress(100);
233 // Fake title bar is not needed in xlarge layout
234 mFakeTitleBar = new TitleBar(this);
235 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800236
The Android Open Source Project0c908882009-03-03 19:32:16 -0800237
238 // Open the icon database and retain all the bookmark urls for favicons
239 retainIconsOnStartup();
240
241 // Keep a settings instance handy.
242 mSettings = BrowserSettings.getInstance();
243 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800244
245 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
246 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
247
Patrick Scott6adacc92010-03-05 08:24:51 -0500248 // Find out if the network is currently up.
249 ConnectivityManager cm = (ConnectivityManager) getSystemService(
250 Context.CONNECTIVITY_SERVICE);
251 NetworkInfo info = cm.getActiveNetworkInfo();
252 if (info != null) {
253 mIsNetworkUp = info.isAvailable();
254 }
255
Grace Klobaa34f6862009-07-31 16:28:17 -0700256 /* enables registration for changes in network status from
257 http stack */
258 mNetworkStateChangedFilter = new IntentFilter();
259 mNetworkStateChangedFilter.addAction(
260 ConnectivityManager.CONNECTIVITY_ACTION);
261 mNetworkStateIntentReceiver = new BroadcastReceiver() {
262 @Override
263 public void onReceive(Context context, Intent intent) {
264 if (intent.getAction().equals(
265 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000266
267 NetworkInfo info = intent.getParcelableExtra(
268 ConnectivityManager.EXTRA_NETWORK_INFO);
269 String typeName = info.getTypeName();
270 String subtypeName = info.getSubtypeName();
271 sendNetworkType(typeName.toLowerCase(),
272 (subtypeName != null ? subtypeName.toLowerCase() : ""));
273
274 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700275 }
276 }
277 };
278
Grace Kloba615c6c92009-08-03 10:22:44 -0700279 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
280 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
281 filter.addDataScheme("package");
282 mPackageInstallationReceiver = new BroadcastReceiver() {
283 @Override
284 public void onReceive(Context context, Intent intent) {
285 final String action = intent.getAction();
286 final String packageName = intent.getData()
287 .getSchemeSpecificPart();
288 final boolean replacing = intent.getBooleanExtra(
289 Intent.EXTRA_REPLACING, false);
290 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
291 // if it is replacing, refreshPlugins() when adding
292 return;
293 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000294
295 if (sGoogleApps.contains(packageName)) {
296 BrowserActivity.this.packageChanged(packageName,
297 Intent.ACTION_PACKAGE_ADDED.equals(action));
298 }
299
Grace Kloba615c6c92009-08-03 10:22:44 -0700300 PackageManager pm = BrowserActivity.this.getPackageManager();
301 PackageInfo pkgInfo = null;
302 try {
303 pkgInfo = pm.getPackageInfo(packageName,
304 PackageManager.GET_PERMISSIONS);
305 } catch (PackageManager.NameNotFoundException e) {
306 return;
307 }
308 if (pkgInfo != null) {
309 String permissions[] = pkgInfo.requestedPermissions;
310 if (permissions == null) {
311 return;
312 }
313 boolean permissionOk = false;
314 for (String permit : permissions) {
315 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
316 permissionOk = true;
317 break;
318 }
319 }
320 if (permissionOk) {
321 PluginManager.getInstance(BrowserActivity.this)
Grace Klobae56a0f22010-05-26 17:31:02 -0700322 .refreshPlugins(true);
Grace Kloba615c6c92009-08-03 10:22:44 -0700323 }
324 }
325 }
326 };
327 registerReceiver(mPackageInstallationReceiver, filter);
328
The Android Open Source Project0c908882009-03-03 19:32:16 -0800329 if (!mTabControl.restoreState(icicle)) {
330 // clear up the thumbnail directory if we can't restore the state as
331 // none of the files in the directory are referenced any more.
332 new ClearThumbnails().execute(
333 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700334 // there is no quit on Android. But if we can't restore the state,
335 // we can treat it as a new Browser, remove the old session cookies.
336 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800337 final Intent intent = getIntent();
338 final Bundle extra = intent.getExtras();
339 // Create an initial tab.
340 // If the intent is ACTION_VIEW and data is not null, the Browser is
341 // invoked to view the content by another application. In this case,
342 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700343 UrlData urlData = getUrlDataFromIntent(intent);
344
Leon Scroggins58d56c62010-01-28 15:12:40 -0500345 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700346 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500347 (Intent.ACTION_VIEW.equals(action) &&
348 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500349 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
350 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700351 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800352 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800353 attachTabToContentView(t);
354 WebView webView = t.getWebView();
355 if (extra != null) {
356 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
357 if (scale > 0 && scale <= 1000) {
358 webView.setInitialScale(scale);
359 }
360 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800361
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700362 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700363 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800364 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500365 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800366 }
367 } else {
368 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400369 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800370 attachTabToContentView(mTabControl.getCurrentTab());
371 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700372
Cary Clarkb4b83182010-07-01 12:36:56 -0400373 // Delete old thumbnails to save space
374 File dir = mTabControl.getThumbnailDir();
375 if (dir.exists()) {
376 for (String child : dir.list()) {
377 File f = new File(dir, child);
378 f.delete();
379 }
380 }
381
Feng Qianb3c02da2009-06-29 15:58:08 -0700382 // Read JavaScript flags if it exists.
383 String jsFlags = mSettings.getJsFlags();
384 if (jsFlags.trim().length() != 0) {
385 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
386 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000387 // Work out which packages are installed on the system.
388 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000389
390 // Start watching the default geolocation permissions
391 mSystemAllowGeolocationOrigins
392 = new SystemAllowGeolocationOrigins(getApplicationContext());
393 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800394 }
395
Leon Scroggins58d56c62010-01-28 15:12:40 -0500396 /**
397 * Feed the previously stored results strings to the BrowserProvider so that
398 * the SearchDialog will show them instead of the standard searches.
399 * @param result String to show on the editable line of the SearchDialog.
400 */
401 /* package */ void showVoiceSearchResults(String result) {
402 ContentProviderClient client = mResolver.acquireContentProviderClient(
403 Browser.BOOKMARKS_URI);
404 ContentProvider prov = client.getLocalContentProvider();
405 BrowserProvider bp = (BrowserProvider) prov;
406 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
407 client.release();
408
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500409 Bundle bundle = createGoogleSearchSourceBundle(
410 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
411 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
412 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500413 }
414
The Android Open Source Project0c908882009-03-03 19:32:16 -0800415 @Override
416 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700417 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800418 // When a tab is closed on exit, the current tab index is set to -1.
419 // Reset before proceed as Browser requires the current tab to be set.
420 if (current == null) {
421 // Try to reset the tab in case the index was incorrect.
422 current = mTabControl.getTab(0);
423 if (current == null) {
424 // No tabs at all so just ignore this intent.
425 return;
426 }
427 mTabControl.setCurrentTab(current);
428 attachTabToContentView(current);
429 resetTitleAndIcon(current.getWebView());
430 }
431 final String action = intent.getAction();
432 final int flags = intent.getFlags();
433 if (Intent.ACTION_MAIN.equals(action) ||
434 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
435 // just resume the browser
436 return;
437 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400438 // In case the SearchDialog is open.
439 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
440 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500441 boolean activateVoiceSearch = RecognizerResultsIntent
442 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800443 if (Intent.ACTION_VIEW.equals(action)
444 || Intent.ACTION_SEARCH.equals(action)
445 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500446 || Intent.ACTION_WEB_SEARCH.equals(action)
447 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500448 if (current.isInVoiceSearchMode()) {
449 String title = current.getVoiceDisplayTitle();
450 if (title != null && title.equals(intent.getStringExtra(
451 SearchManager.QUERY))) {
452 // The user submitted the same search as the last voice
453 // search, so do nothing.
454 return;
455 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500456 if (Intent.ACTION_SEARCH.equals(action)
457 && current.voiceSearchSourceIsGoogle()) {
458 Intent logIntent = new Intent(
459 LoggingEvents.ACTION_LOG_EVENT);
460 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
461 LoggingEvents.VoiceSearch.QUERY_UPDATED);
462 logIntent.putExtra(
463 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
464 intent.getDataString());
465 sendBroadcast(logIntent);
466 // Note, onPageStarted will revert the voice title bar
467 // When http://b/issue?id=2379215 is fixed, we should update
468 // the title bar here.
469 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500470 }
Satish Sampath565505b2009-05-29 15:37:27 +0100471 // If this was a search request (e.g. search query directly typed into the address bar),
472 // pass it on to the default web search provider.
473 if (handleWebSearchIntent(intent)) {
474 return;
475 }
476
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700477 UrlData urlData = getUrlDataFromIntent(intent);
478 if (urlData.isEmpty()) {
479 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800480 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700481
Grace Klobacc634032009-07-28 15:58:19 -0700482 final String appId = intent
483 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400484 if ((Intent.ACTION_VIEW.equals(action)
485 // If a voice search has no appId, it means that it came
486 // from the browser. In that case, reuse the current tab.
487 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700488 && !getPackageName().equals(appId)
489 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700490 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700491 if (appTab != null) {
492 Log.i(LOGTAG, "Reusing tab for " + appId);
493 // Dismiss the subwindow if applicable.
494 dismissSubWindow(appTab);
495 // Since we might kill the WebView, remove it from the
496 // content view first.
497 removeTabFromContentView(appTab);
498 // Recreate the main WebView after destroying the old one.
499 // If the WebView has the same original url and is on that
500 // page, it can be reused.
501 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400502 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100503
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700504 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400505 switchToTab(mTabControl.getTabIndex(appTab));
506 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500507 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400508 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700509 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400510 // If the tab was the current tab, we have to attach
511 // it to the view system again.
512 attachTabToContentView(appTab);
513 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500514 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700515 }
516 }
517 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400518 } else {
519 // No matching application tab, try to find a regular tab
520 // with a matching url.
521 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400522 if (appTab != null) {
523 if (current != appTab) {
524 switchToTab(mTabControl.getTabIndex(appTab));
525 }
526 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400527 } else {
528 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
529 // will be opened in a new tab unless we have reached
530 // MAX_TABS. Then the url will be opened in the current
531 // tab. If a new tab is created, it will have "true" for
532 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400533 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400534 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700535 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800536 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800537 if (!urlData.isEmpty()
538 && urlData.mUrl.startsWith("about:debug")) {
539 if ("about:debug.dom".equals(urlData.mUrl)) {
540 current.getWebView().dumpDomTree(false);
541 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
542 current.getWebView().dumpDomTree(true);
543 } else if ("about:debug.render".equals(urlData.mUrl)) {
544 current.getWebView().dumpRenderTree(false);
545 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
546 current.getWebView().dumpRenderTree(true);
547 } else if ("about:debug.display".equals(urlData.mUrl)) {
548 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800549 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
550 int index = urlData.mUrl.codePointAt(16) - '0';
551 if (index <= 0 || index > 9) {
552 current.getWebView().setDragTracker(null);
553 } else {
554 current.getWebView().setDragTracker(new MeshTracker(index));
555 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800556 } else {
557 mSettings.toggleDebugSettings();
558 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800559 return;
560 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400561 // Get rid of the subwindow if it exists
562 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400563 // If the current Tab is being used as an application tab,
564 // remove the association, since the new Intent means that it is
565 // no longer associated with that application.
566 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500567 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800568 }
569 }
570 }
571
Satish Sampath565505b2009-05-29 15:37:27 +0100572 private int parseUrlShortcut(String url) {
573 if (url == null) return SHORTCUT_INVALID;
574
575 // FIXME: quick search, need to be customized by setting
576 if (url.length() > 2 && url.charAt(1) == ' ') {
577 switch (url.charAt(0)) {
578 case 'g': return SHORTCUT_GOOGLE_SEARCH;
579 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
580 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
581 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
582 }
583 }
584 return SHORTCUT_INVALID;
585 }
586
587 /**
588 * Launches the default web search activity with the query parameters if the given intent's data
589 * are identified as plain search terms and not URLs/shortcuts.
590 * @return true if the intent was handled and web search activity was launched, false if not.
591 */
592 private boolean handleWebSearchIntent(Intent intent) {
593 if (intent == null) return false;
594
595 String url = null;
596 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500597 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
598 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500599 return false;
600 }
Satish Sampath565505b2009-05-29 15:37:27 +0100601 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700602 Uri data = intent.getData();
603 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100604 } else if (Intent.ACTION_SEARCH.equals(action)
605 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
606 || Intent.ACTION_WEB_SEARCH.equals(action)) {
607 url = intent.getStringExtra(SearchManager.QUERY);
608 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100609 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
610 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100611 }
612
613 /**
614 * Launches the default web search activity with the query parameters if the given url string
615 * was identified as plain search terms and not URL/shortcut.
616 * @return true if the request was handled and web search activity was launched, false if not.
617 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100618 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100619 if (inUrl == null) return false;
620
621 // In general, we shouldn't modify URL from Intent.
622 // But currently, we get the user-typed URL from search box as well.
623 String url = fixUrl(inUrl).trim();
624
625 // URLs and site specific search shortcuts are handled by the regular flow of control, so
626 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800627 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100628 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100629 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
630 return false;
631 }
632
Leon Scroggins8d06e362010-03-24 14:45:57 -0400633 final ContentResolver cr = mResolver;
634 final String newUrl = url;
635 new AsyncTask<Void, Void, Void>() {
Michael Kolbe0a36662010-06-29 10:37:12 -0700636 @Override
Leon Scroggins8d06e362010-03-24 14:45:57 -0400637 protected Void doInBackground(Void... unused) {
638 Browser.updateVisitedHistory(cr, newUrl, false);
639 Browser.addSearchUrl(cr, newUrl);
640 return null;
641 }
642 }.execute();
Satish Sampath565505b2009-05-29 15:37:27 +0100643
644 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
645 intent.addCategory(Intent.CATEGORY_DEFAULT);
646 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100647 if (appData != null) {
648 intent.putExtra(SearchManager.APP_DATA, appData);
649 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100650 if (extraData != null) {
651 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
652 }
Grace Klobacc634032009-07-28 15:58:19 -0700653 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100654 startActivity(intent);
655
656 return true;
657 }
658
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700659 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500660 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800661 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800662 if (intent != null) {
663 final String action = intent.getAction();
664 if (Intent.ACTION_VIEW.equals(action)) {
665 url = smartUrlFilter(intent.getData());
666 if (url != null && url.startsWith("content:")) {
667 /* Append mimetype so webview knows how to display */
668 String mimeType = intent.resolveType(getContentResolver());
669 if (mimeType != null) {
670 url += "?" + mimeType;
671 }
672 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800673 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800674 final Bundle pairs = intent
675 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800676 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800677 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800678 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800679 while (iter.hasNext()) {
680 String key = iter.next();
681 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800682 }
683 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700684 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800685 } else if (Intent.ACTION_SEARCH.equals(action)
686 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
687 || Intent.ACTION_WEB_SEARCH.equals(action)) {
688 url = intent.getStringExtra(SearchManager.QUERY);
689 if (url != null) {
690 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800691 // In general, we shouldn't modify URL from Intent.
692 // But currently, we get the user-typed URL from search box as well.
693 url = fixUrl(url);
694 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400695 final ContentResolver cr = mResolver;
696 final String newUrl = url;
697 new AsyncTask<Void, Void, Void>() {
Michael Kolbe0a36662010-06-29 10:37:12 -0700698 @Override
Leon Scroggins8d06e362010-03-24 14:45:57 -0400699 protected Void doInBackground(Void... unused) {
700 Browser.updateVisitedHistory(cr, newUrl, false);
701 return null;
702 }
703 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800704 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
705 if (url.contains(searchSource)) {
706 String source = null;
707 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
708 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000709 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800710 }
711 if (TextUtils.isEmpty(source)) {
712 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
713 }
714 url = url.replace(searchSource, "&source=android-"+source+"&");
715 }
716 }
717 }
718 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500719 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800720 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500721 /* package */ void showVoiceTitleBar(String title) {
722 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500723 mTitleBar.setDisplayTitle(title);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400724
725 if (!mXLargeScreenSize) {
726 mFakeTitleBar.setInVoiceMode(true);
727 mFakeTitleBar.setDisplayTitle(title);
728 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500729 }
730 /* package */ void revertVoiceTitleBar() {
731 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500732 mTitleBar.setDisplayTitle(mUrl);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400733
734 if (!mXLargeScreenSize) {
735 mFakeTitleBar.setInVoiceMode(false);
736 mFakeTitleBar.setDisplayTitle(mUrl);
737 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500738 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800739 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400740 // FIXME: Converting the url to lower case
741 // duplicates functionality in smartUrlFilter().
742 // However, changing all current callers of fixUrl to
743 // call smartUrlFilter in addition may have unwanted
744 // consequences, and is deferred for now.
745 int colon = inUrl.indexOf(':');
746 boolean allLower = true;
747 for (int index = 0; index < colon; index++) {
748 char ch = inUrl.charAt(index);
749 if (!Character.isLetter(ch)) {
750 break;
751 }
752 allLower &= Character.isLowerCase(ch);
753 if (index == colon - 1 && !allLower) {
754 inUrl = inUrl.substring(0, colon).toLowerCase()
755 + inUrl.substring(colon);
756 }
757 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800758 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
759 return inUrl;
760 if (inUrl.startsWith("http:") ||
761 inUrl.startsWith("https:")) {
762 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
763 inUrl = inUrl.replaceFirst("/", "//");
764 } else inUrl = inUrl.replaceFirst(":", "://");
765 }
766 return inUrl;
767 }
768
Grace Kloba22ac16e2009-10-07 18:00:23 -0700769 @Override
770 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800771 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700772 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800773 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
774 }
775
776 if (!mActivityInPause) {
777 Log.e(LOGTAG, "BrowserActivity is already resumed.");
778 return;
779 }
780
Mike Reed7bfa63b2009-05-28 11:08:32 -0400781 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800782 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400783 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800784
785 if (mWakeLock.isHeld()) {
786 mHandler.removeMessages(RELEASE_WAKELOCK);
787 mWakeLock.release();
788 }
789
The Android Open Source Project0c908882009-03-03 19:32:16 -0800790 registerReceiver(mNetworkStateIntentReceiver,
791 mNetworkStateChangedFilter);
792 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800793 }
794
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400795 /**
796 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400797 * would change its appearance, use a different TitleBar to show overlayed
798 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400799 */
800 private TitleBar mFakeTitleBar;
801
802 /**
803 * Keeps track of whether the options menu is open. This is important in
804 * determining whether to show or hide the title bar overlay.
805 */
806 private boolean mOptionsMenuOpen;
807
808 /**
809 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
810 * of whether the configuration has changed. The first onMenuOpened call
811 * after a configuration change is simply a reopening of the same menu
812 * (i.e. mIconView did not change).
813 */
814 private boolean mConfigChanged;
815
816 /**
817 * Whether or not the options menu is in its smaller, icon menu form. When
818 * true, we want the title bar overlay to be up. When false, we do not.
819 * Only meaningful if mOptionsMenuOpen is true.
820 */
821 private boolean mIconView;
822
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400823 @Override
824 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400825 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
826 if (mOptionsMenuOpen) {
827 if (mConfigChanged) {
828 // We do not need to make any changes to the state of the
829 // title bar, since the only thing that happened was a
830 // change in orientation
831 mConfigChanged = false;
832 } else {
833 if (mIconView) {
834 // Switching the menu to expanded view, so hide the
835 // title bar.
836 hideFakeTitleBar();
837 mIconView = false;
838 } else {
839 // Switching the menu back to icon view, so show the
840 // title bar once again.
841 showFakeTitleBar();
842 mIconView = true;
843 }
844 }
845 } else {
846 // The options menu is closed, so open it, and show the title
847 showFakeTitleBar();
848 mOptionsMenuOpen = true;
849 mConfigChanged = false;
850 mIconView = true;
851 }
852 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400853 return true;
854 }
855
Michael Kolbfe251992010-07-08 15:41:55 -0700856 private void rebuildTitleBar() {
857 if (mXLargeScreenSize) {
858 ((TitleBarXLarge) mTitleBar).rebuildLayout();
859 }
860 }
861
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400862 private void showFakeTitleBar() {
Leon Scrogginsd746a942010-05-19 13:21:44 -0400863 if (mXLargeScreenSize) return;
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400864 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Grace Kloba847c25b2010-03-30 16:00:26 -0700865 && !mActivityInPause) {
866 WebView mainView = mTabControl.getCurrentWebView();
867 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700868 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400869 return;
870 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100871 // Do not need to check for null, since the current tab will have
872 // at least a main WebView, or we would have returned above.
Cary Clark01cfcdd2010-06-04 16:36:45 -0400873 if (dialogIsUp()) {
Leon Scroggins79e36d92010-04-29 16:01:46 +0100874 // Do not show the fake title bar, which would cover up the
Cary Clark01cfcdd2010-06-04 16:36:45 -0400875 // find or select dialog.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100876 return;
877 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400878
879 WindowManager manager
880 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
881
882 // Add the title bar to the window manager so it can receive touches
883 // while the menu is up
884 WindowManager.LayoutParams params
885 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800886 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400887 ViewGroup.LayoutParams.WRAP_CONTENT,
Grace Kloba847c25b2010-03-30 16:00:26 -0700888 WindowManager.LayoutParams.TYPE_APPLICATION,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400889 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400890 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400891 params.gravity = Gravity.TOP;
Grace Kloba847c25b2010-03-30 16:00:26 -0700892 boolean atTop = mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400893 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Grace Kloba13f9ace2010-03-18 21:44:14 -0700894 manager.addView(mFakeTitleBar, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400895 }
896 }
897
898 @Override
899 public void onOptionsMenuClosed(Menu menu) {
900 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400901 if (!mInLoad) {
902 hideFakeTitleBar();
903 } else if (!mIconView) {
904 // The page is currently loading, and we are in expanded mode, so
905 // we were not showing the menu. Show it once again. It will be
906 // removed when the page finishes.
907 showFakeTitleBar();
908 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400909 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700910
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400911 private void hideFakeTitleBar() {
Leon Scrogginsd746a942010-05-19 13:21:44 -0400912 if (mXLargeScreenSize || mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400913 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
Grace Kloba13f9ace2010-03-18 21:44:14 -0700914 mFakeTitleBar.getLayoutParams();
Leon Scroggins20329572009-09-23 17:42:41 -0400915 WebView mainView = mTabControl.getCurrentWebView();
916 // Although we decided whether or not to animate based on the current
917 // scroll position, the scroll position may have changed since the
918 // fake title bar was displayed. Make sure it has the appropriate
919 // animation/lack thereof before removing.
920 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400921 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400922 WindowManager manager
923 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Grace Kloba13f9ace2010-03-18 21:44:14 -0700924 manager.updateViewLayout(mFakeTitleBar, params);
925 manager.removeView(mFakeTitleBar);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400926 }
927
The Android Open Source Project0c908882009-03-03 19:32:16 -0800928 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400929 * Special method for the fake title bar to call when displaying its context
930 * menu, since it is in its own Window, and its parent does not show a
931 * context menu.
932 */
933 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400934 if (null == mTitleBar.getParent()) {
935 return;
936 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400937 openContextMenu(mTitleBar);
938 }
939
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400940 @Override
941 public void onContextMenuClosed(Menu menu) {
942 super.onContextMenuClosed(menu);
943 if (mInLoad) {
944 showFakeTitleBar();
945 }
946 }
947
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400948 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800949 * onSaveInstanceState(Bundle map)
950 * onSaveInstanceState is called right before onStop(). The map contains
951 * the saved state.
952 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700953 @Override
954 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700955 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800956 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
957 }
958 // the default implementation requires each view to have an id. As the
959 // browser handles the state itself and it doesn't use id for the views,
960 // don't call the default implementation. Otherwise it will trigger the
961 // warning like this, "couldn't save which view has focus because the
962 // focused view XXX has no id".
963
964 // Save all the tabs
965 mTabControl.saveState(outState);
966 }
967
Grace Kloba22ac16e2009-10-07 18:00:23 -0700968 @Override
969 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800970 super.onPause();
971
972 if (mActivityInPause) {
973 Log.e(LOGTAG, "BrowserActivity is already paused.");
974 return;
975 }
976
Mike Reed7bfa63b2009-05-28 11:08:32 -0400977 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800978 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400979 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800980 mWakeLock.acquire();
981 mHandler.sendMessageDelayed(mHandler
982 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
983 }
984
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400985 // FIXME: This removes the active tabs page and resets the menu to
986 // MAIN_MENU. A better solution might be to do this work in onNewIntent
987 // but then we would need to save it in onSaveInstanceState and restore
988 // it in onCreate/onRestoreInstanceState
989 if (mActiveTabsPage != null) {
990 removeActiveTabPage(true);
991 }
992
The Android Open Source Project0c908882009-03-03 19:32:16 -0800993 cancelStopToast();
994
995 // unregister network state listener
996 unregisterReceiver(mNetworkStateIntentReceiver);
997 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800998 }
999
Grace Kloba22ac16e2009-10-07 18:00:23 -07001000 @Override
1001 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001002 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001003 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1004 }
1005 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001006
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001007 if (mUploadMessage != null) {
1008 mUploadMessage.onReceiveValue(null);
1009 mUploadMessage = null;
1010 }
1011
Grace Kloba0923d692009-09-23 21:37:25 -07001012 if (mTabControl == null) return;
1013
Grace Kloba1fc98a32009-10-21 13:23:08 -07001014 // Remove the fake title bar if it is there
1015 hideFakeTitleBar();
1016
The Android Open Source Project0c908882009-03-03 19:32:16 -08001017 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001018 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001019 if (t != null) {
1020 dismissSubWindow(t);
1021 removeTabFromContentView(t);
1022 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001023 // Destroy all the tabs
1024 mTabControl.destroy();
1025 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001026
Grace Klobab4da0ad2009-05-14 14:45:40 -07001027 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +00001028
1029 // Stop watching the default geolocation permissions
1030 mSystemAllowGeolocationOrigins.stop();
1031 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001032 }
1033
1034 @Override
1035 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001036 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001037 super.onConfigurationChanged(newConfig);
1038
1039 if (mPageInfoDialog != null) {
1040 mPageInfoDialog.dismiss();
1041 showPageInfo(
1042 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001043 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001044 }
1045 if (mSSLCertificateDialog != null) {
1046 mSSLCertificateDialog.dismiss();
1047 showSSLCertificate(
1048 mSSLCertificateView);
1049 }
1050 if (mSSLCertificateOnErrorDialog != null) {
1051 mSSLCertificateOnErrorDialog.dismiss();
1052 showSSLCertificateOnError(
1053 mSSLCertificateOnErrorView,
1054 mSSLCertificateOnErrorHandler,
1055 mSSLCertificateOnErrorError);
1056 }
1057 if (mHttpAuthenticationDialog != null) {
1058 String title = ((TextView) mHttpAuthenticationDialog
1059 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1060 .toString();
1061 String name = ((TextView) mHttpAuthenticationDialog
1062 .findViewById(R.id.username_edit)).getText().toString();
1063 String password = ((TextView) mHttpAuthenticationDialog
1064 .findViewById(R.id.password_edit)).getText().toString();
1065 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1066 .getId();
1067 mHttpAuthenticationDialog.dismiss();
1068 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1069 name, password, focusId);
1070 }
Michael Kolbfe251992010-07-08 15:41:55 -07001071 rebuildTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001072 }
1073
Grace Kloba22ac16e2009-10-07 18:00:23 -07001074 @Override
1075 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001076 super.onLowMemory();
1077 mTabControl.freeMemory();
1078 }
1079
Cary Clarkff4d92c2010-03-25 11:17:03 -04001080 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001081 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001082 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001083 boolean inLoad = tab.inLoad();
1084 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001085 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001086 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001087 if (w != null) {
1088 w.resumeTimers();
1089 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001090 }
1091 }
1092
Mike Reed7bfa63b2009-05-28 11:08:32 -04001093 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001094 Tab tab = mTabControl.getCurrentTab();
1095 boolean inLoad = tab.inLoad();
1096 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001097 CookieSyncManager.getInstance().stopSync();
1098 WebView w = mTabControl.getCurrentWebView();
1099 if (w != null) {
1100 w.pauseTimers();
1101 }
1102 return true;
1103 } else {
1104 return false;
1105 }
1106 }
1107
The Android Open Source Project0c908882009-03-03 19:32:16 -08001108 // Open the icon database and retain all the icons for visited sites.
1109 private void retainIconsOnStartup() {
1110 final WebIconDatabase db = WebIconDatabase.getInstance();
1111 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001112 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001113 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001114 c = Browser.getAllBookmarks(mResolver);
1115 if (c.moveToFirst()) {
1116 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1117 do {
1118 String url = c.getString(urlIndex);
1119 db.retainIconForPageUrl(url);
1120 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001121 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001122 } catch (IllegalStateException e) {
1123 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001124 } finally {
1125 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001126 }
1127 }
1128
1129 // Helper method for getting the top window.
1130 WebView getTopWindow() {
1131 return mTabControl.getCurrentTopWebView();
1132 }
1133
Grace Kloba22ac16e2009-10-07 18:00:23 -07001134 TabControl getTabControl() {
1135 return mTabControl;
1136 }
1137
The Android Open Source Project0c908882009-03-03 19:32:16 -08001138 @Override
1139 public boolean onCreateOptionsMenu(Menu menu) {
1140 super.onCreateOptionsMenu(menu);
1141
1142 MenuInflater inflater = getMenuInflater();
1143 inflater.inflate(R.menu.browser, menu);
1144 mMenu = menu;
1145 updateInLoadMenuItems();
1146 return true;
1147 }
1148
1149 /**
1150 * As the menu can be open when loading state changes
1151 * we must manually update the state of the stop/reload menu
1152 * item
1153 */
1154 private void updateInLoadMenuItems() {
1155 if (mMenu == null) {
1156 return;
1157 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001158 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001159 MenuItem src = mInLoad ?
1160 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001161 mMenu.findItem(R.id.reload_menu_id);
1162 if (src != null) {
1163 dest.setIcon(src.getIcon());
1164 dest.setTitle(src.getTitle());
1165 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001166 }
1167
1168 @Override
1169 public boolean onContextItemSelected(MenuItem item) {
1170 // chording is not an issue with context menus, but we use the same
1171 // options selector, so set mCanChord to true so we can access them.
1172 mCanChord = true;
1173 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001174 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001175 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001176 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001177 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001178 Tab currentTab = mTabControl.getCurrentTab();
1179 if (null == currentTab) {
1180 result = false;
1181 break;
1182 }
1183 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001184 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001185 result = false;
1186 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001187 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001188 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001189 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001190 // -- Browser context menu
1191 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001192 case R.id.bookmark_context_menu_id:
1193 case R.id.save_link_context_menu_id:
1194 case R.id.share_link_context_menu_id:
1195 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001196 final WebView webView = getTopWindow();
1197 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001198 result = false;
1199 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001200 }
1201 final HashMap hrefMap = new HashMap();
1202 hrefMap.put("webview", webView);
1203 final Message msg = mHandler.obtainMessage(
1204 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001205 webView.requestFocusNodeHref(msg);
1206 break;
1207
1208 default:
1209 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001210 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001211 }
1212 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001213 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001214 }
1215
1216 private Bundle createGoogleSearchSourceBundle(String source) {
1217 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001218 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001219 return bundle;
1220 }
1221
Leon Scroggins8ad29922010-02-16 12:33:55 -05001222 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001223 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001224 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001225 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001226 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001227 }
1228
Leon Scroggins8ad29922010-02-16 12:33:55 -05001229 /**
1230 * Overriding this to insert a local information bundle
1231 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001232 @Override
1233 public void startSearch(String initialQuery, boolean selectInitialQuery,
1234 Bundle appSearchData, boolean globalSearch) {
1235 if (appSearchData == null) {
1236 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1237 }
1238 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1239 }
1240
Leon Scroggins1f005d32009-08-10 17:36:42 -04001241 /**
1242 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1243 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001244 * @param index Index of the tab to change to, as defined by
1245 * mTabControl.getTabIndex(Tab t).
1246 * @return boolean True if we successfully switched to a different tab. If
1247 * the indexth tab is null, or if that tab is the same as
1248 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001249 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001250 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001251 Tab tab = mTabControl.getTab(index);
1252 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001253 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001254 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001255 }
1256 if (currentTab != null) {
1257 // currentTab may be null if it was just removed. In that case,
1258 // we do not need to remove it
1259 removeTabFromContentView(currentTab);
1260 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001261 mTabControl.setCurrentTab(tab);
1262 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001263 resetTitleIconAndProgress();
1264 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001265 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001266 }
1267
Grace Kloba22ac16e2009-10-07 18:00:23 -07001268 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001269 return openTabAndShow(mSettings.getHomePage(), false, null);
1270 }
1271
Leon Scroggins1f005d32009-08-10 17:36:42 -04001272 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001273 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001274 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001275 // This is the last tab. Open a new one, with the home
1276 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001277 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001278 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001279 return;
1280 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001281 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001282 int indexToShow = -1;
1283 if (parent != null) {
1284 indexToShow = mTabControl.getTabIndex(parent);
1285 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001286 final int currentIndex = mTabControl.getCurrentIndex();
1287 // Try to move to the tab to the right
1288 indexToShow = currentIndex + 1;
1289 if (indexToShow > mTabControl.getTabCount() - 1) {
1290 // Try to move to the tab to the left
1291 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001292 }
1293 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001294 if (switchToTab(indexToShow)) {
1295 // Close window
1296 closeTab(current);
1297 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001298 }
1299
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001300 private ActiveTabsPage mActiveTabsPage;
1301
1302 /**
1303 * Remove the active tabs page.
1304 * @param needToAttach If true, the active tabs page did not attach a tab
1305 * to the content view, so we need to do that here.
1306 */
1307 /* package */ void removeActiveTabPage(boolean needToAttach) {
1308 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001309 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001310 mActiveTabsPage = null;
1311 mMenuState = R.id.MAIN_MENU;
1312 if (needToAttach) {
1313 attachTabToContentView(mTabControl.getCurrentTab());
1314 }
1315 getTopWindow().requestFocus();
1316 }
1317
Cary Clark01cfcdd2010-06-04 16:36:45 -04001318 private WebView showDialog(WebDialog dialog) {
1319 // Need to do something special for Tablet
1320 Tab tab = mTabControl.getCurrentTab();
1321 if (tab.getSubWebView() == null) {
1322 // If the find or select is being performed on the main webview,
1323 // remove the embedded title bar.
1324 WebView mainView = tab.getWebView();
1325 if (mainView != null) {
1326 mainView.setEmbeddedTitleBar(null);
1327 }
1328 }
1329 hideFakeTitleBar();
1330 mMenuState = EMPTY_MENU;
1331 return tab.showDialog(dialog);
1332 }
1333
The Android Open Source Project0c908882009-03-03 19:32:16 -08001334 @Override
1335 public boolean onOptionsItemSelected(MenuItem item) {
1336 if (!mCanChord) {
1337 // The user has already fired a shortcut with this hold down of the
1338 // menu key.
1339 return false;
1340 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001341 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001342 return false;
1343 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001344 if (mMenuIsDown) {
1345 // The shortcut action consumes the MENU. Even if it is still down,
1346 // it won't trigger the next shortcut action. In the case of the
1347 // shortcut action triggering a new activity, like Bookmarks, we
1348 // won't get onKeyUp for MENU. So it is important to reset it here.
1349 mMenuIsDown = false;
1350 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001351 switch (item.getItemId()) {
1352 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001353 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001354 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001355 break;
1356
Leon Scroggins64b80f32009-08-07 12:03:34 -04001357 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001358 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001359 break;
1360
1361 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001362 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001363 break;
1364
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001365 case R.id.active_tabs_menu_id:
1366 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1367 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001368 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001369 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001370 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1371 mActiveTabsPage.requestFocus();
1372 mMenuState = EMPTY_MENU;
1373 break;
1374
Leon Scroggins1f005d32009-08-10 17:36:42 -04001375 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001376 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001377 break;
1378
1379 case R.id.stop_reload_menu_id:
1380 if (mInLoad) {
1381 stopLoading();
1382 } else {
1383 getTopWindow().reload();
1384 }
1385 break;
1386
1387 case R.id.back_menu_id:
1388 getTopWindow().goBack();
1389 break;
1390
1391 case R.id.forward_menu_id:
1392 getTopWindow().goForward();
1393 break;
1394
1395 case R.id.close_menu_id:
1396 // Close the subwindow if it exists.
1397 if (mTabControl.getCurrentSubWindow() != null) {
1398 dismissSubWindow(mTabControl.getCurrentTab());
1399 break;
1400 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001401 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001402 break;
1403
1404 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001405 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001406 if (current != null) {
1407 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001408 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001409 }
1410 break;
1411
1412 case R.id.preferences_menu_id:
1413 Intent intent = new Intent(this,
1414 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001415 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1416 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001417 startActivityForResult(intent, PREFERENCES_PAGE);
1418 break;
1419
1420 case R.id.find_menu_id:
Cary Clark01cfcdd2010-06-04 16:36:45 -04001421 showFindDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001422 break;
1423
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001424 case R.id.save_webarchive_menu_id:
1425 if (LOGD_ENABLED) {
1426 Log.d(LOGTAG, "Save as Web Archive");
1427 }
1428 String directory = getExternalFilesDir(null).getAbsolutePath() + File.separator;
1429 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1430 @Override
1431 public void onReceiveValue(String value) {
1432 if (value != null) {
1433 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved, Toast.LENGTH_SHORT).show();
1434 } else {
1435 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1436 }
1437 }
1438 });
1439 break;
1440
The Android Open Source Project0c908882009-03-03 19:32:16 -08001441 case R.id.page_info_menu_id:
1442 showPageInfo(mTabControl.getCurrentTab(), false);
1443 break;
1444
1445 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001446 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001447 break;
1448
Leon Scroggins96afcb12009-12-10 12:35:56 -05001449 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001450 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001451 Tab currentTab = mTabControl.getCurrentTab();
1452 if (null == currentTab) {
1453 mCanChord = false;
1454 return false;
1455 }
1456 currentTab.populatePickerData();
1457 sharePage(this, currentTab.getTitle(),
1458 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001459 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1460 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001461 break;
1462
1463 case R.id.dump_nav_menu_id:
1464 getTopWindow().debugDump();
1465 break;
1466
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001467 case R.id.dump_counters_menu_id:
1468 getTopWindow().dumpV8Counters();
1469 break;
1470
The Android Open Source Project0c908882009-03-03 19:32:16 -08001471 case R.id.zoom_in_menu_id:
1472 getTopWindow().zoomIn();
1473 break;
1474
1475 case R.id.zoom_out_menu_id:
1476 getTopWindow().zoomOut();
1477 break;
1478
1479 case R.id.view_downloads_menu_id:
1480 viewDownloads(null);
1481 break;
1482
The Android Open Source Project0c908882009-03-03 19:32:16 -08001483 case R.id.window_one_menu_id:
1484 case R.id.window_two_menu_id:
1485 case R.id.window_three_menu_id:
1486 case R.id.window_four_menu_id:
1487 case R.id.window_five_menu_id:
1488 case R.id.window_six_menu_id:
1489 case R.id.window_seven_menu_id:
1490 case R.id.window_eight_menu_id:
1491 {
1492 int menuid = item.getItemId();
1493 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1494 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001495 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001496 if (desiredTab != null &&
1497 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001498 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001499 }
1500 break;
1501 }
1502 }
1503 }
1504 break;
1505
1506 default:
1507 if (!super.onOptionsItemSelected(item)) {
1508 return false;
1509 }
1510 // Otherwise fall through.
1511 }
1512 mCanChord = false;
1513 return true;
1514 }
1515
Leon Scroggins571b3762010-05-26 10:25:01 -04001516 /* package */ void bookmarkCurrentPage() {
1517 Intent i = new Intent(BrowserActivity.this,
1518 AddBookmarkPage.class);
1519 WebView w = getTopWindow();
1520 i.putExtra("url", w.getUrl());
1521 i.putExtra("title", w.getTitle());
1522 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001523 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1524 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001525 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001526 startActivity(i);
1527 }
1528
Cary Clark01cfcdd2010-06-04 16:36:45 -04001529 private boolean dialogIsUp() {
1530 return null != mFindDialog && mFindDialog.isVisible() ||
1531 null != mSelectDialog && mSelectDialog.isVisible();
1532 }
1533
1534 private boolean closeDialog(WebDialog dialog) {
1535 if (null == dialog || !dialog.isVisible()) return false;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001536 Tab currentTab = mTabControl.getCurrentTab();
Cary Clark01cfcdd2010-06-04 16:36:45 -04001537 currentTab.closeDialog(dialog);
1538 dialog.dismiss();
1539 return true;
1540 }
1541
1542 /*
1543 * Remove the find dialog or select dialog.
1544 */
1545 public void closeDialogs() {
1546 if (!(closeDialog(mFindDialog) || closeDialog(mSelectDialog))) return;
Leon Scrogginsd746a942010-05-19 13:21:44 -04001547 if (!mXLargeScreenSize) {
1548 // If the Find was being performed in the main WebView, replace the
1549 // embedded title bar.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001550 Tab currentTab = mTabControl.getCurrentTab();
Leon Scrogginsd746a942010-05-19 13:21:44 -04001551 if (currentTab.getSubWebView() == null) {
1552 WebView mainView = currentTab.getWebView();
1553 if (mainView != null) {
1554 mainView.setEmbeddedTitleBar(mTitleBar);
1555 }
Leon Scroggins79e36d92010-04-29 16:01:46 +01001556 }
1557 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001558 mMenuState = R.id.MAIN_MENU;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001559 if (mInLoad) {
1560 // The title bar was hidden, because otherwise it would cover up the
Cary Clark01cfcdd2010-06-04 16:36:45 -04001561 // find or select dialog. Now that the dialog has been removed,
1562 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001563 showFakeTitleBar();
1564 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001565 }
1566
Cary Clark01cfcdd2010-06-04 16:36:45 -04001567 public void showFindDialog() {
1568 if (null == mFindDialog) {
1569 mFindDialog = new FindDialog(this);
1570 }
1571 showDialog(mFindDialog).setFindIsUp(true);
1572 }
1573
1574 public void setFindDialogText(String text) {
1575 mFindDialog.setText(text);
1576 }
1577
1578 public void showSelectDialog() {
1579 if (null == mSelectDialog) {
1580 mSelectDialog = new SelectDialog(this);
1581 }
1582 showDialog(mSelectDialog).setUpSelect();
1583 mSelectDialog.hideSoftInput();
1584 }
1585
Grace Kloba22ac16e2009-10-07 18:00:23 -07001586 @Override
1587 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001588 // This happens when the user begins to hold down the menu key, so
1589 // allow them to chord to get a shortcut.
1590 mCanChord = true;
1591 // Note: setVisible will decide whether an item is visible; while
1592 // setEnabled() will decide whether an item is enabled, which also means
1593 // whether the matching shortcut key will function.
1594 super.onPrepareOptionsMenu(menu);
1595 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001596 case EMPTY_MENU:
1597 if (mCurrentMenuState != mMenuState) {
1598 menu.setGroupVisible(R.id.MAIN_MENU, false);
1599 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1600 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001601 }
1602 break;
1603 default:
1604 if (mCurrentMenuState != mMenuState) {
1605 menu.setGroupVisible(R.id.MAIN_MENU, true);
1606 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1607 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001608 }
1609 final WebView w = getTopWindow();
1610 boolean canGoBack = false;
1611 boolean canGoForward = false;
1612 boolean isHome = false;
1613 if (w != null) {
1614 canGoBack = w.canGoBack();
1615 canGoForward = w.canGoForward();
1616 isHome = mSettings.getHomePage().equals(w.getUrl());
1617 }
1618 final MenuItem back = menu.findItem(R.id.back_menu_id);
1619 back.setEnabled(canGoBack);
1620
1621 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1622 home.setEnabled(!isHome);
1623
Michael Kolbe0a36662010-06-29 10:37:12 -07001624 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1625 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001626
Michael Kolbe0a36662010-06-29 10:37:12 -07001627 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1628 newtab.setEnabled(mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001629
The Android Open Source Project0c908882009-03-03 19:32:16 -08001630 // decide whether to show the share link option
1631 PackageManager pm = getPackageManager();
1632 Intent send = new Intent(Intent.ACTION_SEND);
1633 send.setType("text/plain");
1634 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1635 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1636
The Android Open Source Project0c908882009-03-03 19:32:16 -08001637 boolean isNavDump = mSettings.isNavDump();
1638 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1639 nav.setVisible(isNavDump);
1640 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001641
1642 boolean showDebugSettings = mSettings.showDebugSettings();
1643 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1644 counter.setVisible(showDebugSettings);
1645 counter.setEnabled(showDebugSettings);
1646
The Android Open Source Project0c908882009-03-03 19:32:16 -08001647 break;
1648 }
1649 mCurrentMenuState = mMenuState;
1650 return true;
1651 }
1652
1653 @Override
1654 public void onCreateContextMenu(ContextMenu menu, View v,
1655 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001656 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001657 return;
1658 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001659 WebView webview = (WebView) v;
1660 WebView.HitTestResult result = webview.getHitTestResult();
1661 if (result == null) {
1662 return;
1663 }
1664
1665 int type = result.getType();
1666 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1667 Log.w(LOGTAG,
1668 "We should not show context menu when nothing is touched");
1669 return;
1670 }
1671 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1672 // let TextView handles context menu
1673 return;
1674 }
1675
1676 // Note, http://b/issue?id=1106666 is requesting that
1677 // an inflated menu can be used again. This is not available
1678 // yet, so inflate each time (yuk!)
1679 MenuInflater inflater = getMenuInflater();
1680 inflater.inflate(R.menu.browsercontext, menu);
1681
1682 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001683 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001684 menu.setGroupVisible(R.id.PHONE_MENU,
1685 type == WebView.HitTestResult.PHONE_TYPE);
1686 menu.setGroupVisible(R.id.EMAIL_MENU,
1687 type == WebView.HitTestResult.EMAIL_TYPE);
1688 menu.setGroupVisible(R.id.GEO_MENU,
1689 type == WebView.HitTestResult.GEO_TYPE);
1690 menu.setGroupVisible(R.id.IMAGE_MENU,
1691 type == WebView.HitTestResult.IMAGE_TYPE
1692 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1693 menu.setGroupVisible(R.id.ANCHOR_MENU,
1694 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1695 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1696
1697 // Setup custom handling depending on the type
1698 switch (type) {
1699 case WebView.HitTestResult.PHONE_TYPE:
1700 menu.setHeaderTitle(Uri.decode(extra));
1701 menu.findItem(R.id.dial_context_menu_id).setIntent(
1702 new Intent(Intent.ACTION_VIEW, Uri
1703 .parse(WebView.SCHEME_TEL + extra)));
1704 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1705 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001706 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001707 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1708 addIntent);
1709 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1710 new Copy(extra));
1711 break;
1712
1713 case WebView.HitTestResult.EMAIL_TYPE:
1714 menu.setHeaderTitle(extra);
1715 menu.findItem(R.id.email_context_menu_id).setIntent(
1716 new Intent(Intent.ACTION_VIEW, Uri
1717 .parse(WebView.SCHEME_MAILTO + extra)));
1718 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1719 new Copy(extra));
1720 break;
1721
1722 case WebView.HitTestResult.GEO_TYPE:
1723 menu.setHeaderTitle(extra);
1724 menu.findItem(R.id.map_context_menu_id).setIntent(
1725 new Intent(Intent.ACTION_VIEW, Uri
1726 .parse(WebView.SCHEME_GEO
1727 + URLEncoder.encode(extra))));
1728 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1729 new Copy(extra));
1730 break;
1731
1732 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1733 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1734 TextView titleView = (TextView) LayoutInflater.from(this)
1735 .inflate(android.R.layout.browser_link_context_header,
1736 null);
1737 titleView.setText(extra);
1738 menu.setHeaderView(titleView);
1739 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001740 boolean showNewTab = mTabControl.canCreateNewTab();
1741 MenuItem newTabItem
1742 = menu.findItem(R.id.open_newtab_context_menu_id);
1743 newTabItem.setVisible(showNewTab);
1744 if (showNewTab) {
1745 newTabItem.setOnMenuItemClickListener(
1746 new MenuItem.OnMenuItemClickListener() {
1747 public boolean onMenuItemClick(MenuItem item) {
1748 final Tab parent = mTabControl.getCurrentTab();
1749 final Tab newTab = openTab(extra);
1750 if (newTab != parent) {
1751 parent.addChildTab(newTab);
1752 }
1753 return true;
1754 }
1755 });
1756 }
Ben Murdochde353622009-10-12 10:29:00 +01001757 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1758 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001759 PackageManager pm = getPackageManager();
1760 Intent send = new Intent(Intent.ACTION_SEND);
1761 send.setType("text/plain");
1762 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1763 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1764 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1765 break;
1766 }
1767 // otherwise fall through to handle image part
1768 case WebView.HitTestResult.IMAGE_TYPE:
1769 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1770 menu.setHeaderTitle(extra);
1771 }
1772 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1773 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1774 menu.findItem(R.id.download_context_menu_id).
1775 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001776 menu.findItem(R.id.set_wallpaper_context_menu_id).
1777 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001778 break;
1779
1780 default:
1781 Log.w(LOGTAG, "We should not get here.");
1782 break;
1783 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001784 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001785 }
1786
The Android Open Source Project0c908882009-03-03 19:32:16 -08001787 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001788 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001789 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001790 // Attach the container that contains the main WebView and any other UI
1791 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001792 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001793
1794 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001795 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001796 if (errorConsole.numberOfErrors() == 0) {
1797 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1798 } else {
1799 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1800 }
1801
1802 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001803 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001804 ViewGroup.LayoutParams.WRAP_CONTENT));
1805 }
1806
Leon Scrogginsd746a942010-05-19 13:21:44 -04001807 if (!mXLargeScreenSize){
1808 WebView view = t.getWebView();
1809 view.setEmbeddedTitleBar(mTitleBar);
1810 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001811 if (t.isInVoiceSearchMode()) {
1812 showVoiceTitleBar(t.getVoiceDisplayTitle());
1813 } else {
1814 revertVoiceTitleBar();
1815 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001816 // Request focus on the top window.
1817 t.getTopWindow().requestFocus();
1818 }
1819
1820 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001821 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001822 t.attachSubWindow(mContentView);
1823 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001824 }
1825
1826 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001827 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001828 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001829 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001830
Grace Kloba22ac16e2009-10-07 18:00:23 -07001831 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1832 if (errorConsole != null) {
1833 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001834 }
1835
Leon Scrogginsd746a942010-05-19 13:21:44 -04001836 if (!mXLargeScreenSize) {
1837 WebView view = t.getWebView();
1838 if (view != null) {
1839 view.setEmbeddedTitleBar(null);
1840 }
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001841 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001842 }
1843
1844 // Remove the sub window if it exists. Also called by TabControl when the
1845 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001846 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001847 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001848 // dismiss the subwindow. This will destroy the WebView.
1849 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001850 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001851 }
1852
Leon Scroggins1f005d32009-08-10 17:36:42 -04001853 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001854 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001855 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001856 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001857 }
1858
1859 // This method does a ton of stuff. It will attempt to create a new tab
1860 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001861 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001862 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1863 String appId) {
1864 final Tab currentTab = mTabControl.getCurrentTab();
1865 if (mTabControl.canCreateNewTab()) {
1866 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1867 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001868 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001869 // If the last tab was removed from the active tabs page, currentTab
1870 // will be null.
1871 if (currentTab != null) {
1872 removeTabFromContentView(currentTab);
1873 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001874 // We must set the new tab as the current tab to reflect the old
1875 // animation behavior.
1876 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001877 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001878 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001879 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001880 }
1881 return tab;
1882 } else {
1883 // Get rid of the subwindow if it exists
1884 dismissSubWindow(currentTab);
1885 if (!urlData.isEmpty()) {
1886 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001887 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001888 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001889 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001890 }
1891 }
1892
Grace Kloba22ac16e2009-10-07 18:00:23 -07001893 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001894 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001895 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001896 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001897 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001898 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001899 }
Grace Klobac9181842009-04-14 08:53:22 -07001900 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001901 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001902 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001903 }
1904 }
1905
1906 private class Copy implements OnMenuItemClickListener {
1907 private CharSequence mText;
1908
1909 public boolean onMenuItemClick(MenuItem item) {
1910 copy(mText);
1911 return true;
1912 }
1913
1914 public Copy(CharSequence toCopy) {
1915 mText = toCopy;
1916 }
1917 }
1918
1919 private class Download implements OnMenuItemClickListener {
1920 private String mText;
1921
1922 public boolean onMenuItemClick(MenuItem item) {
1923 onDownloadStartNoStream(mText, null, null, null, -1);
1924 return true;
1925 }
1926
1927 public Download(String toDownload) {
1928 mText = toDownload;
1929 }
1930 }
1931
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001932 private class SetAsWallpaper extends Thread implements
1933 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1934 private URL mUrl;
1935 private ProgressDialog mWallpaperProgress;
1936 private boolean mCanceled = false;
1937
1938 public SetAsWallpaper(String url) {
1939 try {
1940 mUrl = new URL(url);
1941 } catch (MalformedURLException e) {
1942 mUrl = null;
1943 }
1944 }
1945
1946 public void onCancel(DialogInterface dialog) {
1947 mCanceled = true;
1948 }
1949
1950 public boolean onMenuItemClick(MenuItem item) {
1951 if (mUrl != null) {
1952 // The user may have tried to set a image with a large file size as their
1953 // background so it may take a few moments to perform the operation. Display
1954 // a progress spinner while it is working.
1955 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1956 mWallpaperProgress.setIndeterminate(true);
1957 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1958 mWallpaperProgress.setCancelable(true);
1959 mWallpaperProgress.setOnCancelListener(this);
1960 mWallpaperProgress.show();
1961 start();
1962 }
1963 return true;
1964 }
1965
Michael Kolbe0a36662010-06-29 10:37:12 -07001966 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001967 public void run() {
1968 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1969 try {
1970 // TODO: This will cause the resource to be downloaded again, when we
1971 // should in most cases be able to grab it from the cache. To fix this
1972 // we should query WebCore to see if we can access a cached version and
1973 // instead open an input stream on that. This pattern could also be used
1974 // in the download manager where the same problem exists.
1975 InputStream inputstream = mUrl.openStream();
1976 if (inputstream != null) {
1977 setWallpaper(inputstream);
1978 }
1979 } catch (IOException e) {
1980 Log.e(LOGTAG, "Unable to set new wallpaper");
1981 // Act as though the user canceled the operation so we try to
1982 // restore the old wallpaper.
1983 mCanceled = true;
1984 }
1985
1986 if (mCanceled) {
1987 // Restore the old wallpaper if the user cancelled whilst we were setting
1988 // the new wallpaper.
1989 int width = oldWallpaper.getIntrinsicWidth();
1990 int height = oldWallpaper.getIntrinsicHeight();
1991 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1992 Canvas canvas = new Canvas(bm);
1993 oldWallpaper.setBounds(0, 0, width, height);
1994 oldWallpaper.draw(canvas);
1995 try {
1996 setWallpaper(bm);
1997 } catch (IOException e) {
1998 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1999 }
2000 mCanceled = false;
2001 }
2002
2003 if (mWallpaperProgress.isShowing()) {
2004 mWallpaperProgress.dismiss();
2005 }
2006 }
2007 }
2008
The Android Open Source Project0c908882009-03-03 19:32:16 -08002009 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07002010 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
2011 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002012 }
2013
2014 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002015 * Resets the browser title-view to whatever it must be
2016 * (for example, if we had a loading error)
2017 * When we have a new page, we call resetTitle, when we
2018 * have to reset the titlebar to whatever it used to be
2019 * (for example, if the user chose to stop loading), we
2020 * call resetTitleAndRevertLockIcon.
2021 */
2022 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002023 mTabControl.getCurrentTab().revertLockIcon();
2024 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002025 resetTitleIconAndProgress();
2026 }
2027
2028 /**
2029 * Reset the title, favicon, and progress.
2030 */
2031 private void resetTitleIconAndProgress() {
2032 WebView current = mTabControl.getCurrentWebView();
2033 if (current == null) {
2034 return;
2035 }
2036 resetTitleAndIcon(current);
2037 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002038 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002039 }
2040
2041 // Reset the title and the icon based on the given item.
2042 private void resetTitleAndIcon(WebView view) {
2043 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2044 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002045 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002046 setFavicon(item.getFavicon());
2047 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002048 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002049 setFavicon(null);
2050 }
2051 }
2052
2053 /**
2054 * Sets a title composed of the URL and the title string.
2055 * @param url The URL of the site being loaded.
2056 * @param title The title of the site being loaded.
2057 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002058 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002059 mUrl = url;
2060 mTitle = title;
2061
Leon Scroggins58d56c62010-01-28 15:12:40 -05002062 // If we are in voice search mode, the title has already been set.
2063 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2064 mTitleBar.setDisplayTitle(url);
Leon Scrogginsd746a942010-05-19 13:21:44 -04002065 if (!mXLargeScreenSize) {
2066 mFakeTitleBar.setDisplayTitle(url);
2067 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002068 }
2069
2070 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002071 * @param url The URL to build a title version of the URL from.
2072 * @return The title version of the URL or null if fails.
2073 * The title version of the URL can be either the URL hostname,
2074 * or the hostname with an "https://" prefix (for secure URLs),
2075 * or an empty string if, for example, the URL in question is a
2076 * file:// URL with no hostname.
2077 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002078 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002079 String titleUrl = null;
2080
2081 if (url != null) {
2082 try {
2083 // parse the url string
2084 URL urlObj = new URL(url);
2085 if (urlObj != null) {
2086 titleUrl = "";
2087
2088 String protocol = urlObj.getProtocol();
2089 String host = urlObj.getHost();
2090
2091 if (host != null && 0 < host.length()) {
2092 titleUrl = host;
2093 if (protocol != null) {
2094 // if a secure site, add an "https://" prefix!
2095 if (protocol.equalsIgnoreCase("https")) {
2096 titleUrl = protocol + "://" + host;
2097 }
2098 }
2099 }
2100 }
2101 } catch (MalformedURLException e) {}
2102 }
2103
2104 return titleUrl;
2105 }
2106
2107 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002108 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002109 mTitleBar.setFavicon(icon);
Leon Scrogginsd746a942010-05-19 13:21:44 -04002110 if (!mXLargeScreenSize) {
2111 mFakeTitleBar.setFavicon(icon);
2112 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002113 }
2114
2115 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002116 * Close the tab, remove its associated title bar, and adjust mTabControl's
2117 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002118 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002119 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002120 int currentIndex = mTabControl.getCurrentIndex();
2121 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002122 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002123 if (currentIndex >= removeIndex && currentIndex != 0) {
2124 currentIndex--;
2125 }
2126 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002127 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002128 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002129 }
2130
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002131 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002132 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002133 if (current == null) {
2134 /*
2135 * Instead of finishing the activity, simply push this to the back
2136 * of the stack and let ActivityManager to choose the foreground
2137 * activity. As BrowserActivity is singleTask, it will be always the
2138 * root of the task. So we can use either true or false for
2139 * moveTaskToBack().
2140 */
2141 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002142 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002143 }
2144 WebView w = current.getWebView();
2145 if (w.canGoBack()) {
2146 w.goBack();
2147 } else {
2148 // Check to see if we are closing a window that was created by
2149 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002150 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002151 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002152 switchToTab(mTabControl.getTabIndex(parent));
2153 // Now we close the other tab
2154 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002155 } else {
2156 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002157 // force the tab's inLoad() to be false as we are going to
2158 // either finish the activity or remove the tab. This will
2159 // ensure pauseWebViewTimers() taking action.
2160 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002161 if (mTabControl.getTabCount() == 1) {
2162 finish();
2163 return;
2164 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002165 // call pauseWebViewTimers() now, we won't be able to call
2166 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002167 // Temporarily change mActivityInPause to be true as
2168 // pauseWebViewTimers() will do nothing if mActivityInPause
2169 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002170 boolean savedState = mActivityInPause;
2171 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002172 Log.e(LOGTAG, "BrowserActivity is already paused "
2173 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002174 }
2175 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002176 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002177 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002178 removeTabFromContentView(current);
2179 mTabControl.removeTab(current);
2180 }
2181 /*
2182 * Instead of finishing the activity, simply push this to the back
2183 * of the stack and let ActivityManager to choose the foreground
2184 * activity. As BrowserActivity is singleTask, it will be always the
2185 * root of the task. So we can use either true or false for
2186 * moveTaskToBack().
2187 */
2188 moveTaskToBack(true);
2189 }
2190 }
2191 }
2192
Grace Kloba22ac16e2009-10-07 18:00:23 -07002193 boolean isMenuDown() {
2194 return mMenuIsDown;
2195 }
2196
Grace Kloba5942df02009-09-18 11:48:29 -07002197 @Override
2198 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002199 // Even if MENU is already held down, we need to call to super to open
2200 // the IME on long press.
2201 if (KeyEvent.KEYCODE_MENU == keyCode) {
2202 mMenuIsDown = true;
2203 return super.onKeyDown(keyCode, event);
2204 }
Grace Kloba5942df02009-09-18 11:48:29 -07002205 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2206 // still down, we don't want to trigger the search. Pretend to consume
2207 // the key and do nothing.
2208 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002209
Grace Kloba5942df02009-09-18 11:48:29 -07002210 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002211 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002212 // WebView/WebTextView handle the keys in the KeyDown. As
2213 // the Activity's shortcut keys are only handled when WebView
2214 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2215 if (event.isShiftPressed()) {
2216 getTopWindow().pageUp(false);
2217 } else {
2218 getTopWindow().pageDown(false);
2219 }
Grace Kloba5942df02009-09-18 11:48:29 -07002220 return true;
2221 case KeyEvent.KEYCODE_BACK:
2222 if (event.getRepeatCount() == 0) {
2223 event.startTracking();
2224 return true;
2225 } else if (mCustomView == null && mActiveTabsPage == null
2226 && event.isLongPress()) {
2227 bookmarksOrHistoryPicker(true);
2228 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002229 }
Grace Kloba5942df02009-09-18 11:48:29 -07002230 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002231 }
Grace Kloba5942df02009-09-18 11:48:29 -07002232 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002233 }
2234
Grace Kloba5942df02009-09-18 11:48:29 -07002235 @Override
2236 public boolean onKeyUp(int keyCode, KeyEvent event) {
2237 switch(keyCode) {
2238 case KeyEvent.KEYCODE_MENU:
2239 mMenuIsDown = false;
2240 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002241 case KeyEvent.KEYCODE_BACK:
2242 if (event.isTracking() && !event.isCanceled()) {
2243 if (mCustomView != null) {
2244 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002245 mTabControl.getCurrentWebView().getWebChromeClient()
2246 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002247 } else if (mActiveTabsPage != null) {
2248 // if tab page is showing, hide it
2249 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002250 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002251 WebView subwindow = mTabControl.getCurrentSubWindow();
2252 if (subwindow != null) {
2253 if (subwindow.canGoBack()) {
2254 subwindow.goBack();
2255 } else {
2256 dismissSubWindow(mTabControl.getCurrentTab());
2257 }
2258 } else {
2259 goBackOnePageOrQuit();
2260 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002261 }
Grace Kloba5942df02009-09-18 11:48:29 -07002262 return true;
2263 }
2264 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002265 }
Grace Kloba5942df02009-09-18 11:48:29 -07002266 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002267 }
2268
Leon Scroggins68579392009-09-15 15:31:54 -04002269 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002270 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002271 resetTitleAndRevertLockIcon();
2272 WebView w = getTopWindow();
2273 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002274 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2275 // same logic here. But for subwindow case, should we call into the main
2276 // WebView's onPageFinished as we never call its onPageStarted and if
2277 // the page finishes itself, we don't call onPageFinished.
2278 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2279 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002280
2281 cancelStopToast();
2282 mStopToast = Toast
2283 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2284 mStopToast.show();
2285 }
2286
Grace Kloba22ac16e2009-10-07 18:00:23 -07002287 boolean didUserStopLoading() {
2288 return mDidStopLoad;
2289 }
2290
The Android Open Source Project0c908882009-03-03 19:32:16 -08002291 private void cancelStopToast() {
2292 if (mStopToast != null) {
2293 mStopToast.cancel();
2294 mStopToast = null;
2295 }
2296 }
2297
Grace Kloba22ac16e2009-10-07 18:00:23 -07002298 // called by a UI or non-UI thread to post the message
2299 public void postMessage(int what, int arg1, int arg2, Object obj,
2300 long delayMillis) {
2301 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2302 obj), delayMillis);
2303 }
2304
2305 // called by a UI or non-UI thread to remove the message
2306 void removeMessages(int what, Object object) {
2307 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002308 }
2309
2310 // public message ids
2311 public final static int LOAD_URL = 1001;
2312 public final static int STOP_LOAD = 1002;
2313
2314 // Message Ids
2315 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002316 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002317
Grace Kloba22ac16e2009-10-07 18:00:23 -07002318 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002319
Ben Murdocheecb4e62010-07-06 16:30:38 +01002320 private static final int TOUCH_ICON_DOWNLOADED = 109;
2321
The Android Open Source Project0c908882009-03-03 19:32:16 -08002322 // Private handler for handling javascript and saving passwords
2323 private Handler mHandler = new Handler() {
2324
Michael Kolbe0a36662010-06-29 10:37:12 -07002325 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002326 public void handleMessage(Message msg) {
2327 switch (msg.what) {
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 {
2455 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2456 cr, originalUrl, url, true);
2457 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);
2463 values.put(Browser.BookmarkColumns.THUMBNAIL,
2464 os.toByteArray());
2465 do {
2466 cr.update(ContentUris.withAppendedId(
2467 Browser.BOOKMARKS_URI, c.getInt(0)),
2468 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 * Values for the size of the thumbnail created when taking a screenshot.
2484 * Lazily initialized. Instead of using these directly, use
2485 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002486 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002487 private static int THUMBNAIL_WIDTH = 0;
2488 private static int THUMBNAIL_HEIGHT = 0;
2489
2490 /**
2491 * Return the desired width for thumbnail screenshots, which are stored in
2492 * the database, and used on the bookmarks screen.
2493 * @param context Context for finding out the density of the screen.
2494 * @return int desired width for thumbnail screenshot.
2495 */
2496 /* package */ static int getDesiredThumbnailWidth(Context context) {
2497 if (THUMBNAIL_WIDTH == 0) {
2498 float density = context.getResources().getDisplayMetrics().density;
2499 THUMBNAIL_WIDTH = (int) (90 * density);
2500 THUMBNAIL_HEIGHT = (int) (80 * density);
2501 }
2502 return THUMBNAIL_WIDTH;
2503 }
2504
2505 /**
2506 * Return the desired height for thumbnail screenshots, which are stored in
2507 * the database, and used on the bookmarks screen.
2508 * @param context Context for finding out the density of the screen.
2509 * @return int desired height for thumbnail screenshot.
2510 */
2511 /* package */ static int getDesiredThumbnailHeight(Context context) {
2512 // To ensure that they are both initialized.
2513 getDesiredThumbnailWidth(context);
2514 return THUMBNAIL_HEIGHT;
2515 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002516
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002517 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002518 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002519 if (thumbnail == null) {
2520 return null;
2521 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002522 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002523 Canvas canvas = new Canvas(bm);
2524 // May need to tweak these values to determine what is the
2525 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002526 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002527 int thumbnailHeight = thumbnail.getHeight();
2528 float scaleFactorX = 1.0f;
2529 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002530 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002531 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002532 } else {
2533 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002534 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002535
2536 if (view.getWidth() > view.getHeight() &&
2537 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2538 // If the device is in landscape and the page is shorter
2539 // than the height of the view, stretch the thumbnail to fill the
2540 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002541 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002542 } else {
2543 // In the portrait case, this looks nice.
2544 scaleFactorY = scaleFactorX;
2545 }
2546
2547 canvas.scale(scaleFactorX, scaleFactorY);
2548
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002549 thumbnail.draw(canvas);
2550 return bm;
2551 }
2552
The Android Open Source Project0c908882009-03-03 19:32:16 -08002553 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002554 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002555 //-------------------------------------------------------------------------
2556
2557 // Use in overrideUrlLoading
2558 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2559 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2560 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2561 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2562
Leon Scroggins92472e82010-02-17 16:32:28 -05002563 // Keep this initial progress in sync with initialProgressValue (* 100)
2564 // in ProgressTracker.cpp
2565 private final static int INITIAL_PROGRESS = 10;
2566
Grace Kloba22ac16e2009-10-07 18:00:23 -07002567 void onPageStarted(WebView view, String url, Bitmap favicon) {
2568 // when BrowserActivity just starts, onPageStarted may be called before
2569 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2570 // to start the timer. As we won't switch tabs while an activity is in
2571 // pause state, we can ensure calling resume and pause in pair.
2572 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002573
Grace Kloba22ac16e2009-10-07 18:00:23 -07002574 resetLockIcon(url);
2575 setUrlTitle(url, null);
2576 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002577 // Show some progress so that the user knows the page is beginning to
2578 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002579 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002580 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002581 if (!mIsNetworkUp) createAndShowNetworkDialog();
Cary Clark01cfcdd2010-06-04 16:36:45 -04002582 closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002583 if (mSettings.isTracing()) {
2584 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002585 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002586 WebAddress uri = new WebAddress(url);
2587 host = uri.mHost;
2588 } catch (android.net.ParseException ex) {
2589 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002590 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002591 host = host.replace('.', '_');
2592 host += ".trace";
2593 mInTrace = true;
2594 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2595 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002596
Grace Kloba22ac16e2009-10-07 18:00:23 -07002597 // Performance probe
2598 if (false) {
2599 mStart = SystemClock.uptimeMillis();
2600 mProcessStart = Process.getElapsedCpuTime();
2601 long[] sysCpu = new long[7];
2602 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2603 sysCpu, null)) {
2604 mUserStart = sysCpu[0] + sysCpu[1];
2605 mSystemStart = sysCpu[2];
2606 mIdleStart = sysCpu[3];
2607 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2608 }
2609 mUiStart = SystemClock.currentThreadTimeMillis();
2610 }
2611 }
2612
2613 void onPageFinished(WebView view, String url) {
2614 // Reset the title and icon in case we stopped a provisional load.
2615 resetTitleAndIcon(view);
2616 // Update the lock icon image only once we are done loading
2617 updateLockIconToLatest();
2618 // pause the WebView timer and release the wake lock if it is finished
2619 // while BrowserActivity is in pause state.
2620 if (mActivityInPause && pauseWebViewTimers()) {
2621 if (mWakeLock.isHeld()) {
2622 mHandler.removeMessages(RELEASE_WAKELOCK);
2623 mWakeLock.release();
2624 }
2625 }
2626
2627 // Performance probe
2628 if (false) {
2629 long[] sysCpu = new long[7];
2630 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2631 sysCpu, null)) {
2632 String uiInfo = "UI thread used "
2633 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2634 + " ms";
2635 if (LOGD_ENABLED) {
2636 Log.d(LOGTAG, uiInfo);
2637 }
2638 //The string that gets written to the log
2639 String performanceString = "It took total "
2640 + (SystemClock.uptimeMillis() - mStart)
2641 + " ms clock time to load the page."
2642 + "\nbrowser process used "
2643 + (Process.getElapsedCpuTime() - mProcessStart)
2644 + " ms, user processes used "
2645 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2646 + " ms, kernel used "
2647 + (sysCpu[2] - mSystemStart) * 10
2648 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2649 + " ms and irq took "
2650 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2651 * 10 + " ms, " + uiInfo;
2652 if (LOGD_ENABLED) {
2653 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2654 }
2655 if (url != null) {
2656 // strip the url to maintain consistency
2657 String newUrl = new String(url);
2658 if (newUrl.startsWith("http://www.")) {
2659 newUrl = newUrl.substring(11);
2660 } else if (newUrl.startsWith("http://")) {
2661 newUrl = newUrl.substring(7);
2662 } else if (newUrl.startsWith("https://www.")) {
2663 newUrl = newUrl.substring(12);
2664 } else if (newUrl.startsWith("https://")) {
2665 newUrl = newUrl.substring(8);
2666 }
2667 if (LOGD_ENABLED) {
2668 Log.d(LOGTAG, newUrl + " loaded");
2669 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002670 }
2671 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002672 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002673
Grace Kloba22ac16e2009-10-07 18:00:23 -07002674 if (mInTrace) {
2675 mInTrace = false;
2676 Debug.stopMethodTracing();
2677 }
2678 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002679
Grace Klobae7fe26b2010-06-28 16:23:33 -07002680 private void closeEmptyChildTab() {
2681 Tab current = mTabControl.getCurrentTab();
2682 if (current != null
2683 && current.getWebView().copyBackForwardList().getSize() == 0) {
2684 Tab parent = current.getParentTab();
2685 if (parent != null) {
2686 switchToTab(mTabControl.getTabIndex(parent));
2687 closeTab(current);
2688 }
2689 }
2690 }
2691
Grace Kloba22ac16e2009-10-07 18:00:23 -07002692 boolean shouldOverrideUrlLoading(WebView view, String url) {
2693 if (url.startsWith(SCHEME_WTAI)) {
2694 // wtai://wp/mc;number
2695 // number=string(phone-number)
2696 if (url.startsWith(SCHEME_WTAI_MC)) {
2697 Intent intent = new Intent(Intent.ACTION_VIEW,
2698 Uri.parse(WebView.SCHEME_TEL +
2699 url.substring(SCHEME_WTAI_MC.length())));
2700 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002701 // before leaving BrowserActivity, close the empty child tab.
2702 // If a new tab is created through JavaScript open to load this
2703 // url, we would like to close it as we will load this url in a
2704 // different Activity.
2705 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002706 return true;
2707 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002708 // wtai://wp/sd;dtmf
2709 // dtmf=string(dialstring)
2710 if (url.startsWith(SCHEME_WTAI_SD)) {
2711 // TODO: only send when there is active voice connection
2712 return false;
2713 }
2714 // wtai://wp/ap;number;name
2715 // number=string(phone-number)
2716 // name=string
2717 if (url.startsWith(SCHEME_WTAI_AP)) {
2718 // TODO
2719 return false;
2720 }
2721 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002722
Grace Kloba22ac16e2009-10-07 18:00:23 -07002723 // The "about:" schemes are internal to the browser; don't want these to
2724 // be dispatched to other apps.
2725 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002726 return false;
2727 }
2728
Grace Kloba22ac16e2009-10-07 18:00:23 -07002729 Intent intent;
2730 // perform generic parsing of the URI to turn it into an Intent.
2731 try {
2732 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2733 } catch (URISyntaxException ex) {
2734 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2735 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002736 }
2737
Grace Kloba22ac16e2009-10-07 18:00:23 -07002738 // check whether the intent can be resolved. If not, we will see
2739 // whether we can download it from the Market.
2740 if (getPackageManager().resolveActivity(intent, 0) == null) {
2741 String packagename = intent.getPackage();
2742 if (packagename != null) {
2743 intent = new Intent(Intent.ACTION_VIEW, Uri
2744 .parse("market://search?q=pname:" + packagename));
2745 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2746 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002747 // before leaving BrowserActivity, close the empty child tab.
2748 // If a new tab is created through JavaScript open to load this
2749 // url, we would like to close it as we will load this url in a
2750 // different Activity.
2751 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002752 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002753 } else {
2754 return false;
2755 }
2756 }
2757
Grace Kloba22ac16e2009-10-07 18:00:23 -07002758 // sanitize the Intent, ensuring web pages can not bypass browser
2759 // security (only access to BROWSABLE activities).
2760 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2761 intent.setComponent(null);
2762 try {
2763 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002764 // before leaving BrowserActivity, close the empty child tab.
2765 // If a new tab is created through JavaScript open to load this
2766 // url, we would like to close it as we will load this url in a
2767 // different Activity.
2768 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002769 return true;
2770 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002771 } catch (ActivityNotFoundException ex) {
2772 // ignore the error. If no application can handle the URL,
2773 // eg about:blank, assume the browser can handle it.
2774 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002775
Grace Kloba22ac16e2009-10-07 18:00:23 -07002776 if (mMenuIsDown) {
2777 openTab(url);
2778 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002779 return true;
2780 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002781 return false;
2782 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002783
Grace Kloba22ac16e2009-10-07 18:00:23 -07002784 // -------------------------------------------------------------------------
2785 // Helper function for WebChromeClient
2786 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002787
Grace Kloba22ac16e2009-10-07 18:00:23 -07002788 void onProgressChanged(WebView view, int newProgress) {
Leon Scrogginsd746a942010-05-19 13:21:44 -04002789 if (mXLargeScreenSize) {
2790 mTitleBar.setProgress(newProgress);
2791 } else {
2792 // On the phone, the fake title bar will always cover up the
2793 // regular title bar (or the regular one is offscreen), so only the
2794 // fake title bar needs to change its progress
2795 mFakeTitleBar.setProgress(newProgress);
2796 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002797
Grace Kloba22ac16e2009-10-07 18:00:23 -07002798 if (newProgress == 100) {
2799 // onProgressChanged() may continue to be called after the main
2800 // frame has finished loading, as any remaining sub frames continue
2801 // to load. We'll only get called once though with newProgress as
2802 // 100 when everything is loaded. (onPageFinished is called once
2803 // when the main frame completes loading regardless of the state of
2804 // any sub frames so calls to onProgressChanges may continue after
2805 // onPageFinished has executed)
2806 if (mInLoad) {
2807 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002808 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002809 // If the options menu is open, leave the title bar
2810 if (!mOptionsMenuOpen || !mIconView) {
2811 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002812 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002813 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002814 } else {
2815 if (!mInLoad) {
2816 // onPageFinished may have already been called but a subframe is
2817 // still loading and updating the progress. Reset mInLoad and
2818 // update the menu items.
2819 mInLoad = true;
2820 updateInLoadMenuItems();
2821 }
2822 // When the page first begins to load, the Activity may still be
2823 // paused, in which case showFakeTitleBar will do nothing. Call
2824 // again as the page continues to load so that it will be shown.
2825 // (Calling it will the fake title bar is already showing will also
2826 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002827 if (!mOptionsMenuOpen || mIconView) {
2828 // This page has begun to load, so show the title bar
2829 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002830 }
2831 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002832 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002833
Grace Kloba22ac16e2009-10-07 18:00:23 -07002834 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002835 // if a view already exists then immediately terminate the new one
2836 if (mCustomView != null) {
2837 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002838 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002839 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002840
2841 // Add the custom view to its container.
2842 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2843 mCustomView = view;
2844 mCustomViewCallback = callback;
2845 // Save the menu state and set it to empty while the custom
2846 // view is showing.
2847 mOldMenuState = mMenuState;
2848 mMenuState = EMPTY_MENU;
2849 // Hide the content view.
2850 mContentView.setVisibility(View.GONE);
2851 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002852 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002853 mCustomViewContainer.setVisibility(View.VISIBLE);
2854 mCustomViewContainer.bringToFront();
2855 }
2856
2857 void onHideCustomView() {
2858 if (mCustomView == null)
2859 return;
2860
2861 // Hide the custom view.
2862 mCustomView.setVisibility(View.GONE);
2863 // Remove the custom view from its container.
2864 mCustomViewContainer.removeView(mCustomView);
2865 mCustomView = null;
2866 // Reset the old menu state.
2867 mMenuState = mOldMenuState;
2868 mOldMenuState = EMPTY_MENU;
2869 mCustomViewContainer.setVisibility(View.GONE);
2870 mCustomViewCallback.onCustomViewHidden();
2871 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002872 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002873 mContentView.setVisibility(View.VISIBLE);
2874 }
2875
2876 Bitmap getDefaultVideoPoster() {
2877 if (mDefaultVideoPoster == null) {
2878 mDefaultVideoPoster = BitmapFactory.decodeResource(
2879 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002880 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002881 return mDefaultVideoPoster;
2882 }
Patrick Scott3918d442009-08-04 13:22:29 -04002883
Grace Kloba22ac16e2009-10-07 18:00:23 -07002884 View getVideoLoadingProgressView() {
2885 if (mVideoProgressView == null) {
2886 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2887 mVideoProgressView = inflater.inflate(
2888 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002889 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002890 return mVideoProgressView;
2891 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002892
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002893 /*
2894 * The Object used to inform the WebView of the file to upload.
2895 */
2896 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002897 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002898
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002899 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2900
2901 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002902 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002903 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002904 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002905 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002906 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002907 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002908 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002909
Ben Murdoch039bd472010-07-21 21:26:57 +01002910 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002911 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002912
Ben Murdoch6af492a2010-06-15 12:38:17 +01002913 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002914 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002915 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2916 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002917
Ben Murdoch6af492a2010-06-15 12:38:17 +01002918 if (mUploadMessage != null) {
2919 // Already a file picker operation in progress.
2920 return;
2921 }
2922
Grace Kloba22ac16e2009-10-07 18:00:23 -07002923 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002924
2925 // Parse the accept type.
2926 String params[] = acceptType.split(";");
2927 String mimeType = params[0];
2928
2929 for (String p : params) {
2930 String[] keyValue = p.split("=");
2931 if (keyValue.length == 2) {
2932 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002933 if (mediaSourceKey.equals(keyValue[0])) {
2934 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002935 }
2936 }
2937 }
2938
2939 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002940 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2941 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002942
2943 // Create an intent to add to the standard file picker that will
2944 // capture an image from the camera. We'll combine this intent with
2945 // the standard OPENABLE picker unless the web developer specifically
2946 // requested the camera or gallery be opened by passing a parameter
2947 // in the accept type.
2948 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
2949 File externalDataDir = Environment.getExternalStoragePublicDirectory(
2950 Environment.DIRECTORY_DCIM);
2951 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
2952 File.separator + "browser-photos");
2953 cameraDataDir.mkdirs();
2954 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
2955 System.currentTimeMillis() + ".jpg";
2956 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
2957
Ben Murdoch6af492a2010-06-15 12:38:17 +01002958 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
2959
Ben Murdoch039bd472010-07-21 21:26:57 +01002960 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
2961
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002962 if (mimeType.equals(imageMimeType)) {
2963 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01002964 addCamcorderIntent = false;
2965 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002966 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
2967 // directly.
2968 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
2969 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01002970 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
2971 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002972 addCameraIntent = false;
2973 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01002974 } else if (mimeType.equals(videoMimeType)) {
2975 i.setType(videoMimeType);
2976 addCameraIntent = false;
2977 // The camcorder saves it's own file and returns it to us in the intent, so
2978 // we don't need to generate one here.
2979 mCameraFilePath = null;
2980
2981 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01002982 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
2983 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002984 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
2985 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01002986 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
2987 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002988 addCamcorderIntent = false;
2989 }
Ben Murdoch039bd472010-07-21 21:26:57 +01002990 } else if (mimeType.equals(audioMimeType)) {
2991 i.setType(audioMimeType);
2992 addCameraIntent = false;
2993 addCamcorderIntent = false;
2994 if (mediaSource.equals(mediaSourceValueMicrophone)) {
2995 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
2996 // recorder.
2997 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
2998 return;
2999 }
3000 // On a default system, there is no single option to open an audio "gallery". Both the
3001 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3002 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3003 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003004 } else {
3005 i.setType("*/*");
3006 }
3007
Ben Murdoch6af492a2010-06-15 12:38:17 +01003008 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003009 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3010 chooser.putExtra(Intent.EXTRA_INTENT, i);
3011
Ben Murdoch6af492a2010-06-15 12:38:17 +01003012 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3013
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003014 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003015 extraInitialIntents.add(cameraIntent);
3016 }
3017
3018 if (addCamcorderIntent) {
3019 extraInitialIntents.add(camcorderIntent);
3020 }
3021
3022 if (extraInitialIntents.size() > 0) {
3023 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3024 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003025 }
3026
3027 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3028 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003029 }
3030
3031 // -------------------------------------------------------------------------
3032 // Implement functions for DownloadListener
3033 // -------------------------------------------------------------------------
3034
The Android Open Source Project0c908882009-03-03 19:32:16 -08003035 /**
3036 * Notify the host application a download should be done, or that
3037 * the data should be streamed if a streaming viewer is available.
3038 * @param url The full url to the content that should be downloaded
3039 * @param contentDisposition Content-disposition http header, if
3040 * present.
3041 * @param mimetype The mimetype of the content reported by the server
3042 * @param contentLength The file size reported by the server
3043 */
3044 public void onDownloadStart(String url, String userAgent,
3045 String contentDisposition, String mimetype, long contentLength) {
3046 // if we're dealing wih A/V content that's not explicitly marked
3047 // for download, check if it's streamable.
3048 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003049 || !contentDisposition.regionMatches(
3050 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003051 // query the package manager to see if there's a registered handler
3052 // that matches.
3053 Intent intent = new Intent(Intent.ACTION_VIEW);
3054 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003055 ResolveInfo info = getPackageManager().resolveActivity(intent,
3056 PackageManager.MATCH_DEFAULT_ONLY);
3057 if (info != null) {
3058 ComponentName myName = getComponentName();
3059 // If we resolved to ourselves, we don't want to attempt to
3060 // load the url only to try and download it again.
3061 if (!myName.getPackageName().equals(
3062 info.activityInfo.packageName)
3063 || !myName.getClassName().equals(
3064 info.activityInfo.name)) {
3065 // someone (other than us) knows how to handle this mime
3066 // type with this scheme, don't download.
3067 try {
3068 startActivity(intent);
3069 return;
3070 } catch (ActivityNotFoundException ex) {
3071 if (LOGD_ENABLED) {
3072 Log.d(LOGTAG, "activity not found for " + mimetype
3073 + " over " + Uri.parse(url).getScheme(),
3074 ex);
3075 }
3076 // Best behavior is to fall back to a download in this
3077 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003078 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003079 }
3080 }
3081 }
3082 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3083 }
3084
Kristian Monsenfa52d172010-03-25 18:29:21 +00003085 // This is to work around the fact that java.net.URI throws Exceptions
3086 // instead of just encoding URL's properly
3087 // Helper method for onDownloadStartNoStream
3088 private static String encodePath(String path) {
3089 char[] chars = path.toCharArray();
3090
3091 boolean needed = false;
3092 for (char c : chars) {
3093 if (c == '[' || c == ']') {
3094 needed = true;
3095 break;
3096 }
3097 }
3098 if (needed == false) {
3099 return path;
3100 }
3101
3102 StringBuilder sb = new StringBuilder("");
3103 for (char c : chars) {
3104 if (c == '[' || c == ']') {
3105 sb.append('%');
3106 sb.append(Integer.toHexString(c));
3107 } else {
3108 sb.append(c);
3109 }
3110 }
3111
3112 return sb.toString();
3113 }
3114
The Android Open Source Project0c908882009-03-03 19:32:16 -08003115 /**
3116 * Notify the host application a download should be done, even if there
3117 * is a streaming viewer available for thise type.
3118 * @param url The full url to the content that should be downloaded
3119 * @param contentDisposition Content-disposition http header, if
3120 * present.
3121 * @param mimetype The mimetype of the content reported by the server
3122 * @param contentLength The file size reported by the server
3123 */
3124 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3125 String contentDisposition, String mimetype, long contentLength) {
3126
3127 String filename = URLUtil.guessFileName(url,
3128 contentDisposition, mimetype);
3129
3130 // Check to see if we have an SDCard
3131 String status = Environment.getExternalStorageState();
3132 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3133 int title;
3134 String msg;
3135
3136 // Check to see if the SDCard is busy, same as the music app
3137 if (status.equals(Environment.MEDIA_SHARED)) {
3138 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3139 title = R.string.download_sdcard_busy_dlg_title;
3140 } else {
3141 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3142 title = R.string.download_no_sdcard_dlg_title;
3143 }
3144
3145 new AlertDialog.Builder(this)
3146 .setTitle(title)
3147 .setIcon(android.R.drawable.ic_dialog_alert)
3148 .setMessage(msg)
3149 .setPositiveButton(R.string.ok, null)
3150 .show();
3151 return;
3152 }
3153
Kristian Monsenfa52d172010-03-25 18:29:21 +00003154 // java.net.URI is a lot stricter than KURL so we have to encode some
3155 // extra characters. Fix for b 2538060 and b 1634719
3156 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003157 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003158 webAddress = new WebAddress(url);
3159 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003160 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003161 // This only happens for very bad urls, we want to chatch the
3162 // exception here
3163 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003164 return;
3165 }
3166
3167 // XXX: Have to use the old url since the cookies were stored using the
3168 // old percent-encoded url.
3169 String cookies = CookieManager.getInstance().getCookie(url);
3170
3171 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003172 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003173 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3174 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3175 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003176 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003177 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003178 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003179 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3180 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3181 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3182 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003183 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003184 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003185 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003186 }
3187 if (mimetype == null) {
3188 // We must have long pressed on a link or image to download it. We
3189 // are not sure of the mimetype in this case, so do a head request
3190 new FetchUrlMimeType(this).execute(values);
3191 } else {
3192 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003193 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003194 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003195 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3196 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003197 }
3198
Grace Kloba22ac16e2009-10-07 18:00:23 -07003199 // -------------------------------------------------------------------------
3200
The Android Open Source Project0c908882009-03-03 19:32:16 -08003201 /**
3202 * Resets the lock icon. This method is called when we start a new load and
3203 * know the url to be loaded.
3204 */
3205 private void resetLockIcon(String url) {
3206 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003207 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003208 updateLockIconImage(LOCK_ICON_UNSECURE);
3209 }
3210
The Android Open Source Project0c908882009-03-03 19:32:16 -08003211 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003212 * Update the lock icon to correspond to our latest state.
3213 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003214 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003215 Tab t = mTabControl.getCurrentTab();
3216 if (t != null) {
3217 updateLockIconImage(t.getLockIconType());
3218 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003219 }
3220
3221 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003222 * Updates the lock-icon image in the title-bar.
3223 */
3224 private void updateLockIconImage(int lockIconType) {
3225 Drawable d = null;
3226 if (lockIconType == LOCK_ICON_SECURE) {
3227 d = mSecLockIcon;
3228 } else if (lockIconType == LOCK_ICON_MIXED) {
3229 d = mMixLockIcon;
3230 }
Leon Scroggins68579392009-09-15 15:31:54 -04003231 mTitleBar.setLock(d);
Leon Scrogginsd746a942010-05-19 13:21:44 -04003232 if (!mXLargeScreenSize) {
3233 mFakeTitleBar.setLock(d);
3234 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003235 }
3236
3237 /**
3238 * Displays a page-info dialog.
3239 * @param tab The tab to show info about
3240 * @param fromShowSSLCertificateOnError The flag that indicates whether
3241 * this dialog was opened from the SSL-certificate-on-error dialog or
3242 * not. This is important, since we need to know whether to return to
3243 * the parent dialog or simply dismiss.
3244 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003245 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003246 final boolean fromShowSSLCertificateOnError) {
3247 final LayoutInflater factory = LayoutInflater
3248 .from(this);
3249
3250 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3251
3252 final WebView view = tab.getWebView();
3253
3254 String url = null;
3255 String title = null;
3256
3257 if (view == null) {
3258 url = tab.getUrl();
3259 title = tab.getTitle();
3260 } else if (view == mTabControl.getCurrentWebView()) {
3261 // Use the cached title and url if this is the current WebView
3262 url = mUrl;
3263 title = mTitle;
3264 } else {
3265 url = view.getUrl();
3266 title = view.getTitle();
3267 }
3268
3269 if (url == null) {
3270 url = "";
3271 }
3272 if (title == null) {
3273 title = "";
3274 }
3275
3276 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3277 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3278
3279 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003280 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003281
3282 AlertDialog.Builder alertDialogBuilder =
3283 new AlertDialog.Builder(this)
3284 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3285 .setView(pageInfoView)
3286 .setPositiveButton(
3287 R.string.ok,
3288 new DialogInterface.OnClickListener() {
3289 public void onClick(DialogInterface dialog,
3290 int whichButton) {
3291 mPageInfoDialog = null;
3292 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003293
3294 // if we came here from the SSL error dialog
3295 if (fromShowSSLCertificateOnError) {
3296 // go back to the SSL error dialog
3297 showSSLCertificateOnError(
3298 mSSLCertificateOnErrorView,
3299 mSSLCertificateOnErrorHandler,
3300 mSSLCertificateOnErrorError);
3301 }
3302 }
3303 })
3304 .setOnCancelListener(
3305 new DialogInterface.OnCancelListener() {
3306 public void onCancel(DialogInterface dialog) {
3307 mPageInfoDialog = null;
3308 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003309
3310 // if we came here from the SSL error dialog
3311 if (fromShowSSLCertificateOnError) {
3312 // go back to the SSL error dialog
3313 showSSLCertificateOnError(
3314 mSSLCertificateOnErrorView,
3315 mSSLCertificateOnErrorHandler,
3316 mSSLCertificateOnErrorError);
3317 }
3318 }
3319 });
3320
3321 // if we have a main top-level page SSL certificate set or a certificate
3322 // error
3323 if (fromShowSSLCertificateOnError ||
3324 (view != null && view.getCertificate() != null)) {
3325 // add a 'View Certificate' button
3326 alertDialogBuilder.setNeutralButton(
3327 R.string.view_certificate,
3328 new DialogInterface.OnClickListener() {
3329 public void onClick(DialogInterface dialog,
3330 int whichButton) {
3331 mPageInfoDialog = null;
3332 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003333
3334 // if we came here from the SSL error dialog
3335 if (fromShowSSLCertificateOnError) {
3336 // go back to the SSL error dialog
3337 showSSLCertificateOnError(
3338 mSSLCertificateOnErrorView,
3339 mSSLCertificateOnErrorHandler,
3340 mSSLCertificateOnErrorError);
3341 } else {
3342 // otherwise, display the top-most certificate from
3343 // the chain
3344 if (view.getCertificate() != null) {
3345 showSSLCertificate(tab);
3346 }
3347 }
3348 }
3349 });
3350 }
3351
3352 mPageInfoDialog = alertDialogBuilder.show();
3353 }
3354
3355 /**
3356 * Displays the main top-level page SSL certificate dialog
3357 * (accessible from the Page-Info dialog).
3358 * @param tab The tab to show certificate for.
3359 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003360 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003361 final View certificateView =
3362 inflateCertificateView(tab.getWebView().getCertificate());
3363 if (certificateView == null) {
3364 return;
3365 }
3366
3367 LayoutInflater factory = LayoutInflater.from(this);
3368
3369 final LinearLayout placeholder =
3370 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3371
3372 LinearLayout ll = (LinearLayout) factory.inflate(
3373 R.layout.ssl_success, placeholder);
3374 ((TextView)ll.findViewById(R.id.success))
3375 .setText(R.string.ssl_certificate_is_valid);
3376
3377 mSSLCertificateView = tab;
3378 mSSLCertificateDialog =
3379 new AlertDialog.Builder(this)
3380 .setTitle(R.string.ssl_certificate).setIcon(
3381 R.drawable.ic_dialog_browser_certificate_secure)
3382 .setView(certificateView)
3383 .setPositiveButton(R.string.ok,
3384 new DialogInterface.OnClickListener() {
3385 public void onClick(DialogInterface dialog,
3386 int whichButton) {
3387 mSSLCertificateDialog = null;
3388 mSSLCertificateView = null;
3389
3390 showPageInfo(tab, false);
3391 }
3392 })
3393 .setOnCancelListener(
3394 new DialogInterface.OnCancelListener() {
3395 public void onCancel(DialogInterface dialog) {
3396 mSSLCertificateDialog = null;
3397 mSSLCertificateView = null;
3398
3399 showPageInfo(tab, false);
3400 }
3401 })
3402 .show();
3403 }
3404
3405 /**
3406 * Displays the SSL error certificate dialog.
3407 * @param view The target web-view.
3408 * @param handler The SSL error handler responsible for cancelling the
3409 * connection that resulted in an SSL error or proceeding per user request.
3410 * @param error The SSL error object.
3411 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003412 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003413 final WebView view, final SslErrorHandler handler, final SslError error) {
3414
3415 final View certificateView =
3416 inflateCertificateView(error.getCertificate());
3417 if (certificateView == null) {
3418 return;
3419 }
3420
3421 LayoutInflater factory = LayoutInflater.from(this);
3422
3423 final LinearLayout placeholder =
3424 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3425
3426 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3427 LinearLayout ll = (LinearLayout)factory
3428 .inflate(R.layout.ssl_warning, placeholder);
3429 ((TextView)ll.findViewById(R.id.warning))
3430 .setText(R.string.ssl_untrusted);
3431 }
3432
3433 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3434 LinearLayout ll = (LinearLayout)factory
3435 .inflate(R.layout.ssl_warning, placeholder);
3436 ((TextView)ll.findViewById(R.id.warning))
3437 .setText(R.string.ssl_mismatch);
3438 }
3439
3440 if (error.hasError(SslError.SSL_EXPIRED)) {
3441 LinearLayout ll = (LinearLayout)factory
3442 .inflate(R.layout.ssl_warning, placeholder);
3443 ((TextView)ll.findViewById(R.id.warning))
3444 .setText(R.string.ssl_expired);
3445 }
3446
3447 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3448 LinearLayout ll = (LinearLayout)factory
3449 .inflate(R.layout.ssl_warning, placeholder);
3450 ((TextView)ll.findViewById(R.id.warning))
3451 .setText(R.string.ssl_not_yet_valid);
3452 }
3453
3454 mSSLCertificateOnErrorHandler = handler;
3455 mSSLCertificateOnErrorView = view;
3456 mSSLCertificateOnErrorError = error;
3457 mSSLCertificateOnErrorDialog =
3458 new AlertDialog.Builder(this)
3459 .setTitle(R.string.ssl_certificate).setIcon(
3460 R.drawable.ic_dialog_browser_certificate_partially_secure)
3461 .setView(certificateView)
3462 .setPositiveButton(R.string.ok,
3463 new DialogInterface.OnClickListener() {
3464 public void onClick(DialogInterface dialog,
3465 int whichButton) {
3466 mSSLCertificateOnErrorDialog = null;
3467 mSSLCertificateOnErrorView = null;
3468 mSSLCertificateOnErrorHandler = null;
3469 mSSLCertificateOnErrorError = null;
3470
Grace Kloba22ac16e2009-10-07 18:00:23 -07003471 view.getWebViewClient().onReceivedSslError(
3472 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003473 }
3474 })
3475 .setNeutralButton(R.string.page_info_view,
3476 new DialogInterface.OnClickListener() {
3477 public void onClick(DialogInterface dialog,
3478 int whichButton) {
3479 mSSLCertificateOnErrorDialog = null;
3480
3481 // do not clear the dialog state: we will
3482 // need to show the dialog again once the
3483 // user is done exploring the page-info details
3484
3485 showPageInfo(mTabControl.getTabFromView(view),
3486 true);
3487 }
3488 })
3489 .setOnCancelListener(
3490 new DialogInterface.OnCancelListener() {
3491 public void onCancel(DialogInterface dialog) {
3492 mSSLCertificateOnErrorDialog = null;
3493 mSSLCertificateOnErrorView = null;
3494 mSSLCertificateOnErrorHandler = null;
3495 mSSLCertificateOnErrorError = null;
3496
Grace Kloba22ac16e2009-10-07 18:00:23 -07003497 view.getWebViewClient().onReceivedSslError(
3498 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003499 }
3500 })
3501 .show();
3502 }
3503
3504 /**
3505 * Inflates the SSL certificate view (helper method).
3506 * @param certificate The SSL certificate.
3507 * @return The resultant certificate view with issued-to, issued-by,
3508 * issued-on, expires-on, and possibly other fields set.
3509 * If the input certificate is null, returns null.
3510 */
3511 private View inflateCertificateView(SslCertificate certificate) {
3512 if (certificate == null) {
3513 return null;
3514 }
3515
3516 LayoutInflater factory = LayoutInflater.from(this);
3517
3518 View certificateView = factory.inflate(
3519 R.layout.ssl_certificate, null);
3520
3521 // issued to:
3522 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3523 if (issuedTo != null) {
3524 ((TextView) certificateView.findViewById(R.id.to_common))
3525 .setText(issuedTo.getCName());
3526 ((TextView) certificateView.findViewById(R.id.to_org))
3527 .setText(issuedTo.getOName());
3528 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3529 .setText(issuedTo.getUName());
3530 }
3531
3532 // issued by:
3533 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3534 if (issuedBy != null) {
3535 ((TextView) certificateView.findViewById(R.id.by_common))
3536 .setText(issuedBy.getCName());
3537 ((TextView) certificateView.findViewById(R.id.by_org))
3538 .setText(issuedBy.getOName());
3539 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3540 .setText(issuedBy.getUName());
3541 }
3542
3543 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003544 String issuedOn = formatCertificateDate(
3545 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003546 ((TextView) certificateView.findViewById(R.id.issued_on))
3547 .setText(issuedOn);
3548
3549 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003550 String expiresOn = formatCertificateDate(
3551 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003552 ((TextView) certificateView.findViewById(R.id.expires_on))
3553 .setText(expiresOn);
3554
3555 return certificateView;
3556 }
3557
3558 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003559 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003560 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003561 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003562 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003563 private String formatCertificateDate(Date certificateDate) {
3564 if (certificateDate == null) {
3565 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003566 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003567 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3568 if (formattedDate == null) {
3569 return "";
3570 }
3571 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003572 }
3573
3574 /**
3575 * Displays an http-authentication dialog.
3576 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003577 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003578 final String host, final String realm, final String title,
3579 final String name, final String password, int focusId) {
3580 LayoutInflater factory = LayoutInflater.from(this);
3581 final View v = factory
3582 .inflate(R.layout.http_authentication, null);
3583 if (name != null) {
3584 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3585 }
3586 if (password != null) {
3587 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3588 }
3589
3590 String titleText = title;
3591 if (titleText == null) {
3592 titleText = getText(R.string.sign_in_to).toString().replace(
3593 "%s1", host).replace("%s2", realm);
3594 }
3595
3596 mHttpAuthHandler = handler;
3597 AlertDialog dialog = new AlertDialog.Builder(this)
3598 .setTitle(titleText)
3599 .setIcon(android.R.drawable.ic_dialog_alert)
3600 .setView(v)
3601 .setPositiveButton(R.string.action,
3602 new DialogInterface.OnClickListener() {
3603 public void onClick(DialogInterface dialog,
3604 int whichButton) {
3605 String nm = ((EditText) v
3606 .findViewById(R.id.username_edit))
3607 .getText().toString();
3608 String pw = ((EditText) v
3609 .findViewById(R.id.password_edit))
3610 .getText().toString();
3611 BrowserActivity.this.setHttpAuthUsernamePassword
3612 (host, realm, nm, pw);
3613 handler.proceed(nm, pw);
3614 mHttpAuthenticationDialog = null;
3615 mHttpAuthHandler = null;
3616 }})
3617 .setNegativeButton(R.string.cancel,
3618 new DialogInterface.OnClickListener() {
3619 public void onClick(DialogInterface dialog,
3620 int whichButton) {
3621 handler.cancel();
3622 BrowserActivity.this.resetTitleAndRevertLockIcon();
3623 mHttpAuthenticationDialog = null;
3624 mHttpAuthHandler = null;
3625 }})
3626 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3627 public void onCancel(DialogInterface dialog) {
3628 handler.cancel();
3629 BrowserActivity.this.resetTitleAndRevertLockIcon();
3630 mHttpAuthenticationDialog = null;
3631 mHttpAuthHandler = null;
3632 }})
3633 .create();
3634 // Make the IME appear when the dialog is displayed if applicable.
3635 dialog.getWindow().setSoftInputMode(
3636 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3637 dialog.show();
3638 if (focusId != 0) {
3639 dialog.findViewById(focusId).requestFocus();
3640 } else {
3641 v.findViewById(R.id.username_edit).requestFocus();
3642 }
3643 mHttpAuthenticationDialog = dialog;
3644 }
3645
3646 public int getProgress() {
3647 WebView w = mTabControl.getCurrentWebView();
3648 if (w != null) {
3649 return w.getProgress();
3650 } else {
3651 return 100;
3652 }
3653 }
3654
3655 /**
3656 * Set HTTP authentication password.
3657 *
3658 * @param host The host for the password
3659 * @param realm The realm for the password
3660 * @param username The username for the password. If it is null, it means
3661 * password can't be saved.
3662 * @param password The password
3663 */
3664 public void setHttpAuthUsernamePassword(String host, String realm,
3665 String username,
3666 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003667 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003668 if (w != null) {
3669 w.setHttpAuthUsernamePassword(host, realm, username, password);
3670 }
3671 }
3672
3673 /**
3674 * connectivity manager says net has come or gone... inform the user
3675 * @param up true if net has come up, false if net has gone down
3676 */
3677 public void onNetworkToggle(boolean up) {
3678 if (up == mIsNetworkUp) {
3679 return;
3680 } else if (up) {
3681 mIsNetworkUp = true;
3682 if (mAlertDialog != null) {
3683 mAlertDialog.cancel();
3684 mAlertDialog = null;
3685 }
3686 } else {
3687 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003688 if (mInLoad) {
3689 createAndShowNetworkDialog();
3690 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003691 }
3692 WebView w = mTabControl.getCurrentWebView();
3693 if (w != null) {
3694 w.setNetworkAvailable(up);
3695 }
3696 }
3697
Grace Kloba22ac16e2009-10-07 18:00:23 -07003698 boolean isNetworkUp() {
3699 return mIsNetworkUp;
3700 }
3701
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003702 // This method shows the network dialog alerting the user that the net is
3703 // down. It will only show the dialog if mAlertDialog is null.
3704 private void createAndShowNetworkDialog() {
3705 if (mAlertDialog == null) {
3706 mAlertDialog = new AlertDialog.Builder(this)
3707 .setTitle(R.string.loadSuspendedTitle)
3708 .setMessage(R.string.loadSuspended)
3709 .setPositiveButton(R.string.ok, null)
3710 .show();
3711 }
3712 }
3713
The Android Open Source Project0c908882009-03-03 19:32:16 -08003714 @Override
3715 protected void onActivityResult(int requestCode, int resultCode,
3716 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003717 if (getTopWindow() == null) return;
3718
The Android Open Source Project0c908882009-03-03 19:32:16 -08003719 switch (requestCode) {
3720 case COMBO_PAGE:
3721 if (resultCode == RESULT_OK && intent != null) {
3722 String data = intent.getAction();
3723 Bundle extras = intent.getExtras();
3724 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003725 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003726 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003727 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003728 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003729 dismissSubWindow(currentTab);
3730 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003731 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003732 }
3733 }
3734 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003735 // Deliberately fall through to PREFERENCES_PAGE, since the
3736 // same extra may be attached to the COMBO_PAGE
3737 case PREFERENCES_PAGE:
3738 if (resultCode == RESULT_OK && intent != null) {
3739 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3740 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3741 mTabControl.removeParentChildRelationShips();
3742 }
3743 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003744 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003745 // Choose a file from the file picker.
3746 case FILE_SELECTED:
3747 if (null == mUploadMessage) break;
3748 Uri result = intent == null || resultCode != RESULT_OK ? null
3749 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003750
3751 // As we ask the camera to save the result of the user taking
3752 // a picture, the camera application does not return anything other
3753 // than RESULT_OK. So we need to check whether the file we expected
3754 // was written to disk in the in the case that we
3755 // did not get an intent returned but did get a RESULT_OK. If it was,
3756 // we assume that this result has came back from the camera.
3757 if (result == null && intent == null && resultCode == RESULT_OK) {
3758 File cameraFile = new File(mCameraFilePath);
3759 if (cameraFile.exists()) {
3760 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003761 // Broadcast to the media scanner that we have a new photo
3762 // so it will be added into the gallery for the user.
3763 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003764 }
3765 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003766 mUploadMessage.onReceiveValue(result);
3767 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003768 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003769 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003770 default:
3771 break;
3772 }
Leon Scroggins30444232009-09-04 18:36:20 -04003773 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003774 }
3775
3776 /*
3777 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003778 * menu to see the download window. It shows the download window on top of
3779 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003780 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003781 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003782 Intent intent = new Intent(this,
3783 BrowserDownloadPage.class);
3784 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003785 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003786
3787 }
3788
Ben Murdocheecb4e62010-07-06 16:30:38 +01003789 /* package*/ void promptAddOrInstallBookmark() {
3790 final Tab current = mTabControl.getCurrentTab();
3791 Resources resources = getResources();
3792 CharSequence[] choices = {
3793 resources.getString(R.string.save_to_bookmarks),
3794 resources.getString(R.string.create_shortcut_bookmark)
3795 };
3796
3797 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3798 builder.setTitle(R.string.add_new_bookmark);
3799 builder.setItems(choices, new DialogInterface.OnClickListener() {
3800 public void onClick(DialogInterface dialog, int item) {
3801 if (item == 0) {
3802 bookmarkCurrentPage();
3803 } else if (item == 1) {
3804 current.populatePickerData();
3805 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3806 if (touchIconUrl != null) {
3807 // Download the touch icon for this site then save it to the
3808 // homescreen.
3809 Bundle b = new Bundle();
3810 b.putString("url", current.getUrl());
3811 b.putString("title", current.getTitle());
3812 b.putParcelable("favicon", current.getFavicon());
3813 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3814 msg.setData(b);
Ben Murdochccb5de02010-07-19 18:38:17 +01003815 new DownloadTouchIcon(BrowserActivity.this, msg,
Ben Murdocheecb4e62010-07-06 16:30:38 +01003816 mTabControl.getCurrentWebView().getSettings()
3817 .getUserAgentString()).execute(touchIconUrl);
3818 } else {
3819 // add to homescreen, can do it immediately as there is no touch
3820 // icon.
3821 showSaveToHomescreenDialog(current.getUrl(), current.getTitle(),
3822 null, current.getFavicon());
3823 }
3824 }
3825 }
3826 });
3827 builder.create().show();
3828 }
3829
Leon Scroggins160a7e72009-08-14 18:28:01 -04003830 /**
3831 * Open the Go page.
3832 * @param startWithHistory If true, open starting on the history tab.
3833 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003834 */
Leon Scroggins30444232009-09-04 18:36:20 -04003835 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003836 WebView current = mTabControl.getCurrentWebView();
3837 if (current == null) {
3838 return;
3839 }
3840 Intent intent = new Intent(this,
3841 CombinedBookmarkHistoryActivity.class);
3842 String title = current.getTitle();
3843 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003844 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3845 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003846
The Android Open Source Project0c908882009-03-03 19:32:16 -08003847 // Just in case the user opens bookmarks before a page finishes loading
3848 // so the current history item, and therefore the page, is null.
3849 if (null == url) {
3850 url = mLastEnteredUrl;
3851 // This can happen.
3852 if (null == url) {
3853 url = mSettings.getHomePage();
3854 }
3855 }
3856 // In case the web page has not yet received its associated title.
3857 if (title == null) {
3858 title = url;
3859 }
3860 intent.putExtra("title", title);
3861 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003862 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003863 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003864 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003865 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003866 if (startWithHistory) {
3867 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3868 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3869 }
3870 startActivityForResult(intent, COMBO_PAGE);
3871 }
3872
Ben Murdocheecb4e62010-07-06 16:30:38 +01003873 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3874 Bitmap favicon) {
3875 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3876
3877 // Just in case the user tries to save before a page finishes loading
3878 // so the current history item, and therefore the page, is null.
3879 if (null == url) {
3880 url = mLastEnteredUrl;
3881 // This can happen.
3882 if (null == url) {
3883 url = mSettings.getHomePage();
3884 }
3885 }
3886
3887 // In case the web page has not yet received its associated title.
3888 if (title == null) {
3889 title = url;
3890 }
3891
3892 intent.putExtra("title", title);
3893 intent.putExtra("url", url);
3894 intent.putExtra("favicon", favicon);
3895 intent.putExtra("touchIcon", touchIcon);
3896 startActivity(intent);
3897 }
3898
3899
The Android Open Source Project0c908882009-03-03 19:32:16 -08003900 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003901 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003902 // In case the user enters nothing.
3903 if (url != null && url.length() != 0 && view != null) {
3904 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003905 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003906 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003907 }
3908 }
3909 }
3910
Leon Scroggins92472e82010-02-17 16:32:28 -05003911 /**
3912 * Load the URL into the given WebView and update the title bar
3913 * to reflect the new load. Call this instead of WebView.loadUrl
3914 * directly.
3915 * @param view The WebView used to load url.
3916 * @param url The URL to load.
3917 */
3918 private void loadUrl(WebView view, String url) {
3919 updateTitleBarForNewLoad(view, url);
3920 view.loadUrl(url);
3921 }
3922
3923 /**
3924 * Load UrlData into a Tab and update the title bar to reflect the new
3925 * load. Call this instead of UrlData.loadIn directly.
3926 * @param t The Tab used to load.
3927 * @param data The UrlData being loaded.
3928 */
3929 private void loadUrlDataIn(Tab t, UrlData data) {
3930 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3931 data.loadIn(t);
3932 }
3933
3934 /**
3935 * If the WebView is the top window, update the title bar to reflect
3936 * loading the new URL. i.e. set its text, clear the favicon (which
3937 * will be set once the page begins loading), and set the progress to
3938 * INITIAL_PROGRESS to show that the page has begun to load. Called
3939 * by loadUrl and loadUrlDataIn.
3940 * @param view The WebView that is starting a load.
3941 * @param url The URL that is being loaded.
3942 */
3943 private void updateTitleBarForNewLoad(WebView view, String url) {
3944 if (view == getTopWindow()) {
3945 setUrlTitle(url, null);
3946 setFavicon(null);
3947 onProgressChanged(view, INITIAL_PROGRESS);
3948 }
3949 }
3950
The Android Open Source Project0c908882009-03-03 19:32:16 -08003951 private String smartUrlFilter(Uri inUri) {
3952 if (inUri != null) {
3953 return smartUrlFilter(inUri.toString());
3954 }
3955 return null;
3956 }
3957
Feng Qianb34f87a2009-03-24 21:27:26 -07003958 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003959 "(?i)" + // switch on case insensitive matching
3960 "(" + // begin group for schema
3961 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003962 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003963 ")" +
3964 "(.*)" );
3965
3966 /**
3967 * Attempts to determine whether user input is a URL or search
3968 * terms. Anything with a space is passed to search.
3969 *
3970 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3971 * "Http://" converts to "http://"
3972 *
3973 * @return Original or modified URL
3974 *
3975 */
3976 String smartUrlFilter(String url) {
3977
3978 String inUrl = url.trim();
3979 boolean hasSpace = inUrl.indexOf(' ') != -1;
3980
3981 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3982 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003983 // force scheme to lowercase
3984 String scheme = matcher.group(1);
3985 String lcScheme = scheme.toLowerCase();
3986 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003987 inUrl = lcScheme + matcher.group(2);
3988 }
3989 if (hasSpace) {
3990 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003991 }
3992 return inUrl;
3993 }
3994 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003995 // FIXME: Is this the correct place to add to searches?
3996 // what if someone else calls this function?
3997 int shortcut = parseUrlShortcut(inUrl);
3998 if (shortcut != SHORTCUT_INVALID) {
3999 Browser.addSearchUrl(mResolver, inUrl);
4000 String query = inUrl.substring(2);
4001 switch (shortcut) {
4002 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004003 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004004 case SHORTCUT_WIKIPEDIA_SEARCH:
4005 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4006 case SHORTCUT_DICTIONARY_SEARCH:
4007 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4008 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004009 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004010 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004011 }
4012 }
4013 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004014 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004015 return URLUtil.guessUrl(inUrl);
4016 }
4017 }
4018
4019 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004020 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004021 }
4022
Ben Murdochbff2d602009-07-01 20:19:05 +01004023 /* package */ void setShouldShowErrorConsole(boolean flag) {
4024 if (flag == mShouldShowErrorConsole) {
4025 // Nothing to do.
4026 return;
4027 }
4028
4029 mShouldShowErrorConsole = flag;
4030
Grace Kloba22ac16e2009-10-07 18:00:23 -07004031 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4032 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004033
4034 if (flag) {
4035 // Setting the show state of the console will cause it's the layout to be inflated.
4036 if (errorConsole.numberOfErrors() > 0) {
4037 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4038 } else {
4039 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4040 }
4041
4042 // Now we can add it to the main view.
4043 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004044 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004045 ViewGroup.LayoutParams.WRAP_CONTENT));
4046 } else {
4047 mErrorConsoleContainer.removeView(errorConsole);
4048 }
4049
4050 }
4051
Grace Kloba22ac16e2009-10-07 18:00:23 -07004052 boolean shouldShowErrorConsole() {
4053 return mShouldShowErrorConsole;
4054 }
4055
Andrei Popescu163ab742009-10-20 17:58:23 +01004056 private void setStatusBarVisibility(boolean visible) {
4057 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4058 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4059 }
4060
Andrei Popescu56199cc2010-01-12 22:39:16 +00004061
4062 private void sendNetworkType(String type, String subtype) {
4063 WebView w = mTabControl.getCurrentWebView();
4064 if (w != null) {
4065 w.setNetworkType(type, subtype);
4066 }
4067 }
4068
Andrei Popescu30995e72010-02-09 16:59:58 +00004069 private void packageChanged(String packageName, boolean wasAdded) {
4070 WebView w = mTabControl.getCurrentWebView();
4071 if (w == null) {
4072 return;
4073 }
4074
4075 if (wasAdded) {
4076 w.addPackageName(packageName);
4077 } else {
4078 w.removePackageName(packageName);
4079 }
4080 }
4081
4082 private void addPackageNames(Set<String> packageNames) {
4083 WebView w = mTabControl.getCurrentWebView();
4084 if (w == null) {
4085 return;
4086 }
4087
4088 w.addPackageNames(packageNames);
4089 }
4090
4091 private void getInstalledPackages() {
4092 AsyncTask<Void, Void, Set<String> > task =
4093 new AsyncTask<Void, Void, Set<String> >() {
Michael Kolbe0a36662010-06-29 10:37:12 -07004094 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004095 protected Set<String> doInBackground(Void... unused) {
4096 Set<String> installedPackages = new HashSet<String>();
4097 PackageManager pm = BrowserActivity.this.getPackageManager();
4098 if (pm != null) {
4099 List<PackageInfo> packages = pm.getInstalledPackages(0);
4100 for (PackageInfo p : packages) {
4101 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
4102 installedPackages.add(p.packageName);
4103 }
4104 }
4105 }
4106
4107 return installedPackages;
4108 }
4109
4110 // Executes on the UI thread
Michael Kolbe0a36662010-06-29 10:37:12 -07004111 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004112 protected void onPostExecute(Set<String> installedPackages) {
4113 addPackageNames(installedPackages);
4114 }
4115 };
4116 task.execute();
4117 }
4118
Grace Klobaeb6eef42009-09-15 17:56:32 -07004119 final static int LOCK_ICON_UNSECURE = 0;
4120 final static int LOCK_ICON_SECURE = 1;
4121 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004122
The Android Open Source Project0c908882009-03-03 19:32:16 -08004123 private BrowserSettings mSettings;
4124 private TabControl mTabControl;
4125 private ContentResolver mResolver;
4126 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004127 private View mCustomView;
4128 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004129 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004130
4131 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4132 // view, we should rewrite this.
4133 private int mCurrentMenuState = 0;
4134 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004135 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004136 private static final int EMPTY_MENU = -1;
4137 private Menu mMenu;
4138
4139 private FindDialog mFindDialog;
Cary Clark01cfcdd2010-06-04 16:36:45 -04004140 private SelectDialog mSelectDialog;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004141 // Used to prevent chording to result in firing two shortcuts immediately
4142 // one after another. Fixes bug 1211714.
4143 boolean mCanChord;
4144
4145 private boolean mInLoad;
4146 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004147 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004148
Cary Clark1f10cbf2010-03-22 11:45:23 -04004149 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004150
4151 private boolean mMenuIsDown;
4152
The Android Open Source Project0c908882009-03-03 19:32:16 -08004153 private static boolean mInTrace;
4154
4155 // Performance probe
4156 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4157 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4158 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4159 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4160 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4161 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4162 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4163 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4164 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4165 };
4166
4167 private long mStart;
4168 private long mProcessStart;
4169 private long mUserStart;
4170 private long mSystemStart;
4171 private long mIdleStart;
4172 private long mIrqStart;
4173
4174 private long mUiStart;
4175
4176 private Drawable mMixLockIcon;
4177 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004178
4179 /* hold a ref so we can auto-cancel if necessary */
4180 private AlertDialog mAlertDialog;
4181
The Android Open Source Project0c908882009-03-03 19:32:16 -08004182 // The up-to-date URL and title (these can be different from those stored
4183 // in WebView, since it takes some time for the information in WebView to
4184 // get updated)
4185 private String mUrl;
4186 private String mTitle;
4187
4188 // As PageInfo has different style for landscape / portrait, we have
4189 // to re-open it when configuration changed
4190 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004191 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004192 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4193 // dialog, we should not just dismiss it, but should get back to the
4194 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004195 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004196
4197 // as SSLCertificateOnError has different style for landscape / portrait,
4198 // we have to re-open it when configuration changed
4199 private AlertDialog mSSLCertificateOnErrorDialog;
4200 private WebView mSSLCertificateOnErrorView;
4201 private SslErrorHandler mSSLCertificateOnErrorHandler;
4202 private SslError mSSLCertificateOnErrorError;
4203
4204 // as SSLCertificate has different style for landscape / portrait, we
4205 // have to re-open it when configuration changed
4206 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004207 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004208
4209 // as HttpAuthentication has different style for landscape / portrait, we
4210 // have to re-open it when configuration changed
4211 private AlertDialog mHttpAuthenticationDialog;
4212 private HttpAuthHandler mHttpAuthHandler;
4213
4214 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4215 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004216 ViewGroup.LayoutParams.MATCH_PARENT,
4217 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004218 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4219 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004220 ViewGroup.LayoutParams.MATCH_PARENT,
4221 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004222 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004223 // Google search
4224 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004225 // Wikipedia search
4226 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4227 // Dictionary search
4228 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4229 // Google Mobile Local search
4230 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4231
4232 final static String QUERY_PLACE_HOLDER = "%s";
4233
4234 // "source" parameter for Google search through search key
4235 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4236 // "source" parameter for Google search through goto menu
4237 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4238 // "source" parameter for Google search through simplily type
4239 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4240 // "source" parameter for Google search suggested by the browser
4241 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4242 // "source" parameter for Google search from unknown source
4243 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4244
4245 private final static String LOGTAG = "browser";
4246
The Android Open Source Project0c908882009-03-03 19:32:16 -08004247 private String mLastEnteredUrl;
4248
4249 private PowerManager.WakeLock mWakeLock;
4250 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4251
4252 private Toast mStopToast;
4253
Leon Scroggins571b3762010-05-26 10:25:01 -04004254 private TitleBarBase mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004255
Ben Murdochbff2d602009-07-01 20:19:05 +01004256 private LinearLayout mErrorConsoleContainer = null;
4257 private boolean mShouldShowErrorConsole = false;
4258
The Android Open Source Project0c908882009-03-03 19:32:16 -08004259 // As the ids are dynamically created, we can't guarantee that they will
4260 // be in sequence, so this static array maps ids to a window number.
4261 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4262 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4263 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4264 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4265
4266 // monitor platform changes
4267 private IntentFilter mNetworkStateChangedFilter;
4268 private BroadcastReceiver mNetworkStateIntentReceiver;
4269
Grace Klobab4da0ad2009-05-14 14:45:40 -07004270 private BroadcastReceiver mPackageInstallationReceiver;
4271
Bjorn Bringerta7611812010-03-24 11:12:02 +00004272 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4273
The Android Open Source Project0c908882009-03-03 19:32:16 -08004274 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004275 final static int COMBO_PAGE = 1;
4276 final static int DOWNLOAD_PAGE = 2;
4277 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004278 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004279
Andrei Popescu540035d2009-09-18 18:59:20 +01004280 // the default <video> poster
4281 private Bitmap mDefaultVideoPoster;
4282 // the video progress view
4283 private View mVideoProgressView;
4284
Andrei Popescu30995e72010-02-09 16:59:58 +00004285 // The Google packages we monitor for the navigator.isApplicationInstalled()
4286 // API. Add as needed.
4287 private static Set<String> sGoogleApps;
4288 static {
4289 sGoogleApps = new HashSet<String>();
4290 sGoogleApps.add("com.google.android.youtube");
4291 }
4292
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004293 /**
4294 * A UrlData class to abstract how the content will be set to WebView.
4295 * This base class uses loadUrl to show the content.
4296 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004297 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004298 final String mUrl;
4299 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004300 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004301
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004302 UrlData(String url) {
4303 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004304 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004305 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004306 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004307
Leon Scroggins58d56c62010-01-28 15:12:40 -05004308 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004309 this.mUrl = url;
4310 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004311 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4312 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004313 this.mVoiceIntent = intent;
4314 } else {
4315 this.mVoiceIntent = null;
4316 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004317 }
4318
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004319 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004320 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004321 }
4322
Leon Scroggins92472e82010-02-17 16:32:28 -05004323 /**
4324 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4325 * the title bar as well.
4326 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004327 public void loadIn(Tab t) {
4328 if (mVoiceIntent != null) {
4329 t.activateVoiceSearchMode(mVoiceIntent);
4330 } else {
4331 t.getWebView().loadUrl(mUrl, mHeaders);
4332 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004333 }
4334 };
4335
Leon Scroggins1f005d32009-08-10 17:36:42 -04004336 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004337}