blob: b1a3abee65bae19598d843d89d992b1449ffa129 [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
19import com.google.android.googleapps.IGoogleLoginService;
20import com.google.android.googlelogin.GoogleLoginServiceConstants;
21
22import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080023import android.app.AlertDialog;
24import android.app.ProgressDialog;
25import android.app.SearchManager;
26import android.content.ActivityNotFoundException;
27import android.content.BroadcastReceiver;
28import android.content.ComponentName;
29import 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;
36import android.content.ServiceConnection;
37import android.content.DialogInterface.OnCancelListener;
Grace Klobab4da0ad2009-05-14 14:45:40 -070038import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080039import android.content.pm.PackageManager;
40import android.content.pm.ResolveInfo;
41import android.content.res.AssetManager;
42import android.content.res.Configuration;
43import android.content.res.Resources;
44import android.database.Cursor;
45import android.database.sqlite.SQLiteDatabase;
46import android.database.sqlite.SQLiteException;
47import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010048import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.graphics.DrawFilter;
51import android.graphics.Paint;
52import android.graphics.PaintFlagsDrawFilter;
53import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040054import android.graphics.PixelFormat;
55import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080056import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080057import android.hardware.SensorListener;
58import android.hardware.SensorManager;
59import android.net.ConnectivityManager;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -040060import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080061import android.net.Uri;
62import android.net.WebAddress;
63import android.net.http.EventHandler;
64import android.net.http.SslCertificate;
65import android.net.http.SslError;
66import android.os.AsyncTask;
67import android.os.Bundle;
68import android.os.Debug;
69import android.os.Environment;
70import android.os.Handler;
71import android.os.IBinder;
72import android.os.Message;
73import android.os.PowerManager;
74import android.os.Process;
75import android.os.RemoteException;
76import android.os.ServiceManager;
77import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080078import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040079import android.provider.ContactsContract;
80import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080081import android.provider.Downloads;
82import android.provider.MediaStore;
The Android Open Source Project0c908882009-03-03 19:32:16 -080083import android.text.IClipboard;
84import android.text.TextUtils;
85import android.text.format.DateFormat;
86import android.text.util.Regex;
The Android Open Source Project0c908882009-03-03 19:32:16 -080087import android.util.Log;
88import android.view.ContextMenu;
89import android.view.Gravity;
90import android.view.KeyEvent;
91import android.view.LayoutInflater;
92import android.view.Menu;
93import android.view.MenuInflater;
94import android.view.MenuItem;
95import android.view.View;
96import android.view.ViewGroup;
97import android.view.Window;
98import android.view.WindowManager;
99import android.view.ContextMenu.ContextMenuInfo;
100import android.view.MenuItem.OnMenuItemClickListener;
101import android.view.animation.AlphaAnimation;
102import android.view.animation.Animation;
103import android.view.animation.AnimationSet;
104import android.view.animation.DecelerateInterpolator;
105import android.view.animation.ScaleAnimation;
106import android.view.animation.TranslateAnimation;
107import android.webkit.CookieManager;
108import android.webkit.CookieSyncManager;
109import android.webkit.DownloadListener;
Steve Block2bc69912009-07-30 14:45:13 +0100110import android.webkit.GeolocationPermissions;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800111import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -0700112import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113import android.webkit.SslErrorHandler;
114import android.webkit.URLUtil;
115import android.webkit.WebChromeClient;
Andrei Popescuc9b55562009-07-07 10:51:15 +0100116import android.webkit.WebChromeClient.CustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import android.webkit.WebHistoryItem;
118import android.webkit.WebIconDatabase;
Ben Murdoch092dd5d2009-04-22 12:34:12 +0100119import android.webkit.WebStorage;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import android.webkit.WebView;
121import android.webkit.WebViewClient;
122import android.widget.EditText;
123import android.widget.FrameLayout;
124import android.widget.LinearLayout;
125import android.widget.TextView;
126import android.widget.Toast;
127
128import java.io.BufferedOutputStream;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400129import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130import java.io.File;
131import java.io.FileInputStream;
132import java.io.FileOutputStream;
133import java.io.IOException;
134import java.io.InputStream;
135import java.net.MalformedURLException;
136import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700137import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800138import java.net.URL;
139import java.net.URLEncoder;
140import java.text.ParseException;
141import java.util.Date;
142import java.util.Enumeration;
143import java.util.HashMap;
Patrick Scott37911c72009-03-24 18:02:58 -0700144import java.util.LinkedList;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800145import java.util.Vector;
146import java.util.regex.Matcher;
147import java.util.regex.Pattern;
148import java.util.zip.ZipEntry;
149import java.util.zip.ZipFile;
150
151public class BrowserActivity extends Activity
Grace Kloba5942df02009-09-18 11:48:29 -0700152 implements View.OnCreateContextMenuListener,
The Android Open Source Project0c908882009-03-03 19:32:16 -0800153 DownloadListener {
154
Dave Bort31a6d1c2009-04-13 15:56:49 -0700155 /* Define some aliases to make these debugging flags easier to refer to.
156 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
157 */
158 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
159 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
160 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
161
The Android Open Source Project0c908882009-03-03 19:32:16 -0800162 private IGoogleLoginService mGls = null;
163 private ServiceConnection mGlsConnection = null;
164
165 private SensorManager mSensorManager = null;
166
Satish Sampath565505b2009-05-29 15:37:27 +0100167 // These are single-character shortcuts for searching popular sources.
168 private static final int SHORTCUT_INVALID = 0;
169 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
170 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
171 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
172 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
173
The Android Open Source Project0c908882009-03-03 19:32:16 -0800174 /* Whitelisted webpages
175 private static HashSet<String> sWhiteList;
176
177 static {
178 sWhiteList = new HashSet<String>();
179 sWhiteList.add("cnn.com/");
180 sWhiteList.add("espn.go.com/");
181 sWhiteList.add("nytimes.com/");
182 sWhiteList.add("engadget.com/");
183 sWhiteList.add("yahoo.com/");
184 sWhiteList.add("msn.com/");
185 sWhiteList.add("amazon.com/");
186 sWhiteList.add("consumerist.com/");
187 sWhiteList.add("google.com/m/news");
188 }
189 */
190
191 private void setupHomePage() {
192 final Runnable getAccount = new Runnable() {
193 public void run() {
194 // Lower priority
195 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
196 // get the default home page
197 String homepage = mSettings.getHomePage();
198
199 try {
200 if (mGls == null) return;
201
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700202 if (!homepage.startsWith("http://www.google.")) return;
203 if (homepage.indexOf('?') == -1) return;
204
The Android Open Source Project0c908882009-03-03 19:32:16 -0800205 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
206 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
207
208 // three cases:
209 //
210 // hostedUser == googleUser
211 // The device has only a google account
212 //
213 // hostedUser != googleUser
214 // The device has a hosted account and a google account
215 //
216 // hostedUser != null, googleUser == null
217 // The device has only a hosted account (so far)
218
219 // developers might have no accounts at all
220 if (hostedUser == null) return;
221
222 if (googleUser == null || !hostedUser.equals(googleUser)) {
223 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700224 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800225 }
226 } catch (RemoteException ignore) {
227 // Login service died; carry on
228 } catch (RuntimeException ignore) {
229 // Login service died; carry on
230 } finally {
231 finish(homepage);
232 }
233 }
234
235 private void finish(final String homepage) {
236 mHandler.post(new Runnable() {
237 public void run() {
238 mSettings.setHomePage(BrowserActivity.this, homepage);
239 resumeAfterCredentials();
240
241 // as this is running in a separate thread,
242 // BrowserActivity's onDestroy() may have been called,
243 // which also calls unbindService().
244 if (mGlsConnection != null) {
245 // we no longer need to keep GLS open
246 unbindService(mGlsConnection);
247 mGlsConnection = null;
248 }
249 } });
250 } };
251
252 final boolean[] done = { false };
253
254 // Open a connection to the Google Login Service. The first
255 // time the connection is established, set up the homepage depending on
256 // the account in a background thread.
257 mGlsConnection = new ServiceConnection() {
258 public void onServiceConnected(ComponentName className, IBinder service) {
259 mGls = IGoogleLoginService.Stub.asInterface(service);
260 if (done[0] == false) {
261 done[0] = true;
262 Thread account = new Thread(getAccount);
263 account.setName("GLSAccount");
264 account.start();
265 }
266 }
267 public void onServiceDisconnected(ComponentName className) {
268 mGls = null;
269 }
270 };
271
272 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
273 mGlsConnection, Context.BIND_AUTO_CREATE);
274 }
275
Cary Clarka9771242009-08-11 16:42:26 -0400276 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800277 @Override
278 public Void doInBackground(File... files) {
279 if (files != null) {
280 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400281 if (!f.delete()) {
282 Log.e(LOGTAG, f.getPath() + " was not deleted");
283 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800284 }
285 }
286 return null;
287 }
288 }
289
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400290 /**
291 * This layout holds everything you see below the status bar, including the
292 * error console, the custom view container, and the webviews.
293 */
294 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400295
The Android Open Source Project0c908882009-03-03 19:32:16 -0800296 @Override public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700297 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800298 Log.v(LOGTAG, this + " onStart");
299 }
300 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800301 // test the browser in OpenGL
302 // requestWindowFeature(Window.FEATURE_OPENGL);
303
304 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
305
306 mResolver = getContentResolver();
307
Grace Kloba0923d692009-09-23 21:37:25 -0700308 // If this was a web search request, pass it on to the default web
309 // search provider and finish this activity.
310 if (handleWebSearchIntent(getIntent())) {
311 finish();
312 return;
313 }
314
The Android Open Source Project0c908882009-03-03 19:32:16 -0800315 //
316 // start MASF proxy service
317 //
318 //Intent proxyServiceIntent = new Intent();
319 //proxyServiceIntent.setComponent
320 // (new ComponentName(
321 // "com.android.masfproxyservice",
322 // "com.android.masfproxyservice.MasfProxyService"));
323 //startService(proxyServiceIntent, null);
324
325 mSecLockIcon = Resources.getSystem().getDrawable(
326 android.R.drawable.ic_secure);
327 mMixLockIcon = Resources.getSystem().getDrawable(
328 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800329
Leon Scroggins81db3662009-06-04 17:45:11 -0400330 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
331 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400332 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
333 .inflate(R.layout.custom_screen, null);
334 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
335 R.id.main_content);
336 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
337 .findViewById(R.id.error_console);
338 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
339 .findViewById(R.id.fullscreen_custom_content);
340 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400341 mTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800342
343 // Create the tab control and our initial tab
344 mTabControl = new TabControl(this);
345
346 // Open the icon database and retain all the bookmark urls for favicons
347 retainIconsOnStartup();
348
349 // Keep a settings instance handy.
350 mSettings = BrowserSettings.getInstance();
351 mSettings.setTabControl(mTabControl);
352 mSettings.loadFromDb(this);
353
354 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
355 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
356
Grace Klobaa34f6862009-07-31 16:28:17 -0700357 /* enables registration for changes in network status from
358 http stack */
359 mNetworkStateChangedFilter = new IntentFilter();
360 mNetworkStateChangedFilter.addAction(
361 ConnectivityManager.CONNECTIVITY_ACTION);
362 mNetworkStateIntentReceiver = new BroadcastReceiver() {
363 @Override
364 public void onReceive(Context context, Intent intent) {
365 if (intent.getAction().equals(
366 ConnectivityManager.CONNECTIVITY_ACTION)) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -0400367 NetworkInfo info =
368 (NetworkInfo) intent.getParcelableExtra(
369 ConnectivityManager.EXTRA_NETWORK_INFO);
370 onNetworkToggle(
371 (info != null) ? info.isConnected() : false);
Grace Klobaa34f6862009-07-31 16:28:17 -0700372 }
373 }
374 };
375
Grace Kloba615c6c92009-08-03 10:22:44 -0700376 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
377 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
378 filter.addDataScheme("package");
379 mPackageInstallationReceiver = new BroadcastReceiver() {
380 @Override
381 public void onReceive(Context context, Intent intent) {
382 final String action = intent.getAction();
383 final String packageName = intent.getData()
384 .getSchemeSpecificPart();
385 final boolean replacing = intent.getBooleanExtra(
386 Intent.EXTRA_REPLACING, false);
387 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
388 // if it is replacing, refreshPlugins() when adding
389 return;
390 }
391 PackageManager pm = BrowserActivity.this.getPackageManager();
392 PackageInfo pkgInfo = null;
393 try {
394 pkgInfo = pm.getPackageInfo(packageName,
395 PackageManager.GET_PERMISSIONS);
396 } catch (PackageManager.NameNotFoundException e) {
397 return;
398 }
399 if (pkgInfo != null) {
400 String permissions[] = pkgInfo.requestedPermissions;
401 if (permissions == null) {
402 return;
403 }
404 boolean permissionOk = false;
405 for (String permit : permissions) {
406 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
407 permissionOk = true;
408 break;
409 }
410 }
411 if (permissionOk) {
412 PluginManager.getInstance(BrowserActivity.this)
413 .refreshPlugins(
414 Intent.ACTION_PACKAGE_ADDED
415 .equals(action));
416 }
417 }
418 }
419 };
420 registerReceiver(mPackageInstallationReceiver, filter);
421
The Android Open Source Project0c908882009-03-03 19:32:16 -0800422 if (!mTabControl.restoreState(icicle)) {
423 // clear up the thumbnail directory if we can't restore the state as
424 // none of the files in the directory are referenced any more.
425 new ClearThumbnails().execute(
426 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700427 // there is no quit on Android. But if we can't restore the state,
428 // we can treat it as a new Browser, remove the old session cookies.
429 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800430 final Intent intent = getIntent();
431 final Bundle extra = intent.getExtras();
432 // Create an initial tab.
433 // If the intent is ACTION_VIEW and data is not null, the Browser is
434 // invoked to view the content by another application. In this case,
435 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700436 UrlData urlData = getUrlDataFromIntent(intent);
437
The Android Open Source Project0c908882009-03-03 19:32:16 -0800438 final TabControl.Tab t = mTabControl.createNewTab(
439 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700440 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700441 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800442 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800443 attachTabToContentView(t);
444 WebView webView = t.getWebView();
445 if (extra != null) {
446 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
447 if (scale > 0 && scale <= 1000) {
448 webView.setInitialScale(scale);
449 }
450 }
451 // If we are not restoring from an icicle, then there is a high
452 // likely hood this is the first run. So, check to see if the
453 // homepage needs to be configured and copy any plugins from our
454 // asset directory to the data partition.
455 if ((extra == null || !extra.getBoolean("testing"))
456 && !mSettings.isLoginInitialized()) {
457 setupHomePage();
458 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800459
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700460 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400461 if (mSettings.isLoginInitialized()) {
462 webView.loadUrl(mSettings.getHomePage());
463 } else {
464 waitForCredentials();
465 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800466 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700467 if (extra != null) {
468 urlData.setPostData(extra
469 .getByteArray(Browser.EXTRA_POST_DATA));
470 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700471 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800472 }
473 } else {
474 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400475 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800476 attachTabToContentView(mTabControl.getCurrentTab());
477 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700478
Feng Qianb3c02da2009-06-29 15:58:08 -0700479 // Read JavaScript flags if it exists.
480 String jsFlags = mSettings.getJsFlags();
481 if (jsFlags.trim().length() != 0) {
482 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
483 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800484 }
485
486 @Override
487 protected void onNewIntent(Intent intent) {
488 TabControl.Tab current = mTabControl.getCurrentTab();
489 // When a tab is closed on exit, the current tab index is set to -1.
490 // Reset before proceed as Browser requires the current tab to be set.
491 if (current == null) {
492 // Try to reset the tab in case the index was incorrect.
493 current = mTabControl.getTab(0);
494 if (current == null) {
495 // No tabs at all so just ignore this intent.
496 return;
497 }
498 mTabControl.setCurrentTab(current);
499 attachTabToContentView(current);
500 resetTitleAndIcon(current.getWebView());
501 }
502 final String action = intent.getAction();
503 final int flags = intent.getFlags();
504 if (Intent.ACTION_MAIN.equals(action) ||
505 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
506 // just resume the browser
507 return;
508 }
509 if (Intent.ACTION_VIEW.equals(action)
510 || Intent.ACTION_SEARCH.equals(action)
511 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
512 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100513 // If this was a search request (e.g. search query directly typed into the address bar),
514 // pass it on to the default web search provider.
515 if (handleWebSearchIntent(intent)) {
516 return;
517 }
518
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700519 UrlData urlData = getUrlDataFromIntent(intent);
520 if (urlData.isEmpty()) {
521 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800522 }
Grace Kloba81678d92009-06-30 07:09:56 -0700523 urlData.setPostData(intent
524 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700525
Grace Klobacc634032009-07-28 15:58:19 -0700526 final String appId = intent
527 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
528 if (Intent.ACTION_VIEW.equals(action)
529 && !getPackageName().equals(appId)
530 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Patrick Scottcd115892009-07-16 09:42:58 -0400531 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700532 if (appTab != null) {
533 Log.i(LOGTAG, "Reusing tab for " + appId);
534 // Dismiss the subwindow if applicable.
535 dismissSubWindow(appTab);
536 // Since we might kill the WebView, remove it from the
537 // content view first.
538 removeTabFromContentView(appTab);
539 // Recreate the main WebView after destroying the old one.
540 // If the WebView has the same original url and is on that
541 // page, it can be reused.
542 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700543 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100544
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700545 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400546 switchToTab(mTabControl.getTabIndex(appTab));
547 if (needsLoad) {
548 urlData.loadIn(appTab.getWebView());
549 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700550 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400551 // If the tab was the current tab, we have to attach
552 // it to the view system again.
553 attachTabToContentView(appTab);
554 if (needsLoad) {
555 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700556 }
557 }
558 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400559 } else {
560 // No matching application tab, try to find a regular tab
561 // with a matching url.
562 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400563 if (appTab != null) {
564 if (current != appTab) {
565 switchToTab(mTabControl.getTabIndex(appTab));
566 }
567 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400568 } else {
569 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
570 // will be opened in a new tab unless we have reached
571 // MAX_TABS. Then the url will be opened in the current
572 // tab. If a new tab is created, it will have "true" for
573 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400574 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400575 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700576 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800577 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700578 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800579 mSettings.toggleDebugSettings();
580 return;
581 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400582 // Get rid of the subwindow if it exists
583 dismissSubWindow(current);
584 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800585 }
586 }
587 }
588
Satish Sampath565505b2009-05-29 15:37:27 +0100589 private int parseUrlShortcut(String url) {
590 if (url == null) return SHORTCUT_INVALID;
591
592 // FIXME: quick search, need to be customized by setting
593 if (url.length() > 2 && url.charAt(1) == ' ') {
594 switch (url.charAt(0)) {
595 case 'g': return SHORTCUT_GOOGLE_SEARCH;
596 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
597 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
598 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
599 }
600 }
601 return SHORTCUT_INVALID;
602 }
603
604 /**
605 * Launches the default web search activity with the query parameters if the given intent's data
606 * are identified as plain search terms and not URLs/shortcuts.
607 * @return true if the intent was handled and web search activity was launched, false if not.
608 */
609 private boolean handleWebSearchIntent(Intent intent) {
610 if (intent == null) return false;
611
612 String url = null;
613 final String action = intent.getAction();
614 if (Intent.ACTION_VIEW.equals(action)) {
615 url = intent.getData().toString();
616 } else if (Intent.ACTION_SEARCH.equals(action)
617 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
618 || Intent.ACTION_WEB_SEARCH.equals(action)) {
619 url = intent.getStringExtra(SearchManager.QUERY);
620 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100621 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
622 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100623 }
624
625 /**
626 * Launches the default web search activity with the query parameters if the given url string
627 * was identified as plain search terms and not URL/shortcut.
628 * @return true if the request was handled and web search activity was launched, false if not.
629 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100630 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100631 if (inUrl == null) return false;
632
633 // In general, we shouldn't modify URL from Intent.
634 // But currently, we get the user-typed URL from search box as well.
635 String url = fixUrl(inUrl).trim();
636
637 // URLs and site specific search shortcuts are handled by the regular flow of control, so
638 // return early.
639 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100640 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100641 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
642 return false;
643 }
644
645 Browser.updateVisitedHistory(mResolver, url, false);
646 Browser.addSearchUrl(mResolver, url);
647
648 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
649 intent.addCategory(Intent.CATEGORY_DEFAULT);
650 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100651 if (appData != null) {
652 intent.putExtra(SearchManager.APP_DATA, appData);
653 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100654 if (extraData != null) {
655 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
656 }
Grace Klobacc634032009-07-28 15:58:19 -0700657 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100658 startActivity(intent);
659
660 return true;
661 }
662
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700663 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800664 String url = null;
665 if (intent != null) {
666 final String action = intent.getAction();
667 if (Intent.ACTION_VIEW.equals(action)) {
668 url = smartUrlFilter(intent.getData());
669 if (url != null && url.startsWith("content:")) {
670 /* Append mimetype so webview knows how to display */
671 String mimeType = intent.resolveType(getContentResolver());
672 if (mimeType != null) {
673 url += "?" + mimeType;
674 }
675 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700676 if ("inline:".equals(url)) {
677 return new InlinedUrlData(
678 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
679 intent.getType(),
680 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
681 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
682 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800683 } else if (Intent.ACTION_SEARCH.equals(action)
684 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
685 || Intent.ACTION_WEB_SEARCH.equals(action)) {
686 url = intent.getStringExtra(SearchManager.QUERY);
687 if (url != null) {
688 mLastEnteredUrl = url;
689 // Don't add Urls, just search terms.
690 // Urls will get added when the page is loaded.
691 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
692 Browser.updateVisitedHistory(mResolver, url, false);
693 }
694 // In general, we shouldn't modify URL from Intent.
695 // But currently, we get the user-typed URL from search box as well.
696 url = fixUrl(url);
697 url = smartUrlFilter(url);
698 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
699 if (url.contains(searchSource)) {
700 String source = null;
701 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
702 if (appData != null) {
703 source = appData.getString(SearchManager.SOURCE);
704 }
705 if (TextUtils.isEmpty(source)) {
706 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
707 }
708 url = url.replace(searchSource, "&source=android-"+source+"&");
709 }
710 }
711 }
712 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700713 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800714 }
715
716 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400717 // FIXME: Converting the url to lower case
718 // duplicates functionality in smartUrlFilter().
719 // However, changing all current callers of fixUrl to
720 // call smartUrlFilter in addition may have unwanted
721 // consequences, and is deferred for now.
722 int colon = inUrl.indexOf(':');
723 boolean allLower = true;
724 for (int index = 0; index < colon; index++) {
725 char ch = inUrl.charAt(index);
726 if (!Character.isLetter(ch)) {
727 break;
728 }
729 allLower &= Character.isLowerCase(ch);
730 if (index == colon - 1 && !allLower) {
731 inUrl = inUrl.substring(0, colon).toLowerCase()
732 + inUrl.substring(colon);
733 }
734 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800735 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
736 return inUrl;
737 if (inUrl.startsWith("http:") ||
738 inUrl.startsWith("https:")) {
739 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
740 inUrl = inUrl.replaceFirst("/", "//");
741 } else inUrl = inUrl.replaceFirst(":", "://");
742 }
743 return inUrl;
744 }
745
746 /**
747 * Looking for the pattern like this
748 *
749 * *
750 * * *
751 * *** * *******
752 * * *
753 * * *
754 * *
755 */
756 private final SensorListener mSensorListener = new SensorListener() {
757 private long mLastGestureTime;
758 private float[] mPrev = new float[3];
759 private float[] mPrevDiff = new float[3];
760 private float[] mDiff = new float[3];
761 private float[] mRevertDiff = new float[3];
762
763 public void onSensorChanged(int sensor, float[] values) {
764 boolean show = false;
765 float[] diff = new float[3];
766
767 for (int i = 0; i < 3; i++) {
768 diff[i] = values[i] - mPrev[i];
769 if (Math.abs(diff[i]) > 1) {
770 show = true;
771 }
772 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
773 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
774 // start track when there is a big move, or revert
775 mRevertDiff[i] = mDiff[i];
776 mDiff[i] = 0;
777 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
778 // reset when it is flat
779 mDiff[i] = mRevertDiff[i] = 0;
780 }
781 mDiff[i] += diff[i];
782 mPrevDiff[i] = diff[i];
783 mPrev[i] = values[i];
784 }
785
786 if (false) {
787 // only shows if we think the delta is big enough, in an attempt
788 // to detect "serious" moves left/right or up/down
789 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
790 + values[0] + ", " + values[1] + ", " + values[2] + ")"
791 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
792 + ")");
793 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
794 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
795 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
796 + mRevertDiff[2] + ")");
797 }
798
799 long now = android.os.SystemClock.uptimeMillis();
800 if (now - mLastGestureTime > 1000) {
801 mLastGestureTime = 0;
802
803 float y = mDiff[1];
804 float z = mDiff[2];
805 float ay = Math.abs(y);
806 float az = Math.abs(z);
807 float ry = mRevertDiff[1];
808 float rz = mRevertDiff[2];
809 float ary = Math.abs(ry);
810 float arz = Math.abs(rz);
811 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
812 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
813
814 if ((gestY || gestZ) && !(gestY && gestZ)) {
815 WebView view = mTabControl.getCurrentWebView();
816
817 if (view != null) {
818 if (gestZ) {
819 if (z < 0) {
820 view.zoomOut();
821 } else {
822 view.zoomIn();
823 }
824 } else {
825 view.flingScroll(0, Math.round(y * 100));
826 }
827 }
828 mLastGestureTime = now;
829 }
830 }
831 }
832
833 public void onAccuracyChanged(int sensor, int accuracy) {
834 // TODO Auto-generated method stub
835
836 }
837 };
838
839 @Override protected void onResume() {
840 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700841 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800842 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
843 }
844
845 if (!mActivityInPause) {
846 Log.e(LOGTAG, "BrowserActivity is already resumed.");
847 return;
848 }
849
Mike Reed7bfa63b2009-05-28 11:08:32 -0400850 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800851 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400852 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800853
854 if (mWakeLock.isHeld()) {
855 mHandler.removeMessages(RELEASE_WAKELOCK);
856 mWakeLock.release();
857 }
858
859 if (mCredsDlg != null) {
860 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
861 // In case credential request never comes back
862 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
863 }
864 }
865
866 registerReceiver(mNetworkStateIntentReceiver,
867 mNetworkStateChangedFilter);
868 WebView.enablePlatformNotifications();
869
870 if (mSettings.doFlick()) {
871 if (mSensorManager == null) {
872 mSensorManager = (SensorManager) getSystemService(
873 Context.SENSOR_SERVICE);
874 }
875 mSensorManager.registerListener(mSensorListener,
876 SensorManager.SENSOR_ACCELEROMETER,
877 SensorManager.SENSOR_DELAY_FASTEST);
878 } else {
879 mSensorManager = null;
880 }
881 }
882
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400883 /**
884 * Since the actual title bar is embedded in the WebView, and removing it
885 * would change its appearance, create a temporary title bar to go at
886 * the top of the screen while the menu is open.
887 */
888 private TitleBar mFakeTitleBar;
889
890 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400891 * Holder for the fake title bar. It will have a foreground shadow, as well
892 * as a white background, so the fake title bar looks like the real one.
893 */
894 private ViewGroup mFakeTitleBarHolder;
895
896 /**
897 * Layout parameters for the fake title bar within mFakeTitleBarHolder
898 */
899 private FrameLayout.LayoutParams mFakeTitleBarParams
900 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400901 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400902 ViewGroup.LayoutParams.WRAP_CONTENT);
903 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400904 * Keeps track of whether the options menu is open. This is important in
905 * determining whether to show or hide the title bar overlay.
906 */
907 private boolean mOptionsMenuOpen;
908
909 /**
910 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
911 * of whether the configuration has changed. The first onMenuOpened call
912 * after a configuration change is simply a reopening of the same menu
913 * (i.e. mIconView did not change).
914 */
915 private boolean mConfigChanged;
916
917 /**
918 * Whether or not the options menu is in its smaller, icon menu form. When
919 * true, we want the title bar overlay to be up. When false, we do not.
920 * Only meaningful if mOptionsMenuOpen is true.
921 */
922 private boolean mIconView;
923
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400924 @Override
925 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400926 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
927 if (mOptionsMenuOpen) {
928 if (mConfigChanged) {
929 // We do not need to make any changes to the state of the
930 // title bar, since the only thing that happened was a
931 // change in orientation
932 mConfigChanged = false;
933 } else {
934 if (mIconView) {
935 // Switching the menu to expanded view, so hide the
936 // title bar.
937 hideFakeTitleBar();
938 mIconView = false;
939 } else {
940 // Switching the menu back to icon view, so show the
941 // title bar once again.
942 showFakeTitleBar();
943 mIconView = true;
944 }
945 }
946 } else {
947 // The options menu is closed, so open it, and show the title
948 showFakeTitleBar();
949 mOptionsMenuOpen = true;
950 mConfigChanged = false;
951 mIconView = true;
952 }
953 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400954 return true;
955 }
956
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400957 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400958 final View decor = getWindow().peekDecorView();
Leon Scroggins4d7e4062009-09-15 15:49:45 -0400959 if (mFakeTitleBar == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400960 && !mActivityInPause && decor != null
961 && decor.getWindowToken() != null) {
Leon Scrogginsf4bb18a2009-09-11 18:37:53 -0400962 final WebView webView = getTopWindow();
Leon Scroggins68579392009-09-15 15:31:54 -0400963 mFakeTitleBar = new TitleBar(this);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400964 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
965 mFakeTitleBar.setProgress(webView.getProgress());
966 mFakeTitleBar.setFavicon(webView.getFavicon());
967 updateLockIconToLatest();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400968
969 WindowManager manager
970 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
971
972 // Add the title bar to the window manager so it can receive touches
973 // while the menu is up
974 WindowManager.LayoutParams params
975 = new WindowManager.LayoutParams(
976 ViewGroup.LayoutParams.FILL_PARENT,
977 ViewGroup.LayoutParams.WRAP_CONTENT,
978 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
979 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400980 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400981 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400982 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400983 boolean atTop = mainView != null && mainView.getScrollY() == 0;
984 params.windowAnimations = atTop ? 0
985 : com.android.internal.R.style.Animation_DropDownDown;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400986 // XXX : Without providing an offset, the fake title bar will be
987 // placed underneath the status bar. Use the global visible rect
988 // of mBrowserFrameLayout to determine the bottom of the status bar
989 Rect rectangle = new Rect();
990 mBrowserFrameLayout.getGlobalVisibleRect(rectangle);
991 params.y = rectangle.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400992 // Add a holder for the title bar. It also holds a shadow to show
993 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400994 if (mFakeTitleBarHolder == null) {
995 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
996 .inflate(R.layout.title_bar_bg, null);
997 }
Leon Scroggins68549862009-09-21 16:02:01 -0400998 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400999 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001000 }
1001 }
1002
1003 @Override
1004 public void onOptionsMenuClosed(Menu menu) {
1005 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04001006 if (!mInLoad) {
1007 hideFakeTitleBar();
1008 } else if (!mIconView) {
1009 // The page is currently loading, and we are in expanded mode, so
1010 // we were not showing the menu. Show it once again. It will be
1011 // removed when the page finishes.
1012 showFakeTitleBar();
1013 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001014 }
1015 private void hideFakeTitleBar() {
1016 if (mFakeTitleBar == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -04001017 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
1018 mFakeTitleBarHolder.getLayoutParams();
1019 WebView mainView = mTabControl.getCurrentWebView();
1020 // Although we decided whether or not to animate based on the current
1021 // scroll position, the scroll position may have changed since the
1022 // fake title bar was displayed. Make sure it has the appropriate
1023 // animation/lack thereof before removing.
1024 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
1025 ? 0 : com.android.internal.R.style.Animation_DropDownDown;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001026 WindowManager manager
1027 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -04001028 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001029 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1030 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001031 mFakeTitleBar = null;
1032 }
1033
The Android Open Source Project0c908882009-03-03 19:32:16 -08001034 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001035 * Special method for the fake title bar to call when displaying its context
1036 * menu, since it is in its own Window, and its parent does not show a
1037 * context menu.
1038 */
1039 /* package */ void showTitleBarContextMenu() {
1040 openContextMenu(mTitleBar);
1041 }
1042
1043 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001044 * onSaveInstanceState(Bundle map)
1045 * onSaveInstanceState is called right before onStop(). The map contains
1046 * the saved state.
1047 */
1048 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001049 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001050 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1051 }
1052 // the default implementation requires each view to have an id. As the
1053 // browser handles the state itself and it doesn't use id for the views,
1054 // don't call the default implementation. Otherwise it will trigger the
1055 // warning like this, "couldn't save which view has focus because the
1056 // focused view XXX has no id".
1057
1058 // Save all the tabs
1059 mTabControl.saveState(outState);
1060 }
1061
1062 @Override protected void onPause() {
1063 super.onPause();
1064
1065 if (mActivityInPause) {
1066 Log.e(LOGTAG, "BrowserActivity is already paused.");
1067 return;
1068 }
1069
Mike Reed7bfa63b2009-05-28 11:08:32 -04001070 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001071 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001072 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001073 mWakeLock.acquire();
1074 mHandler.sendMessageDelayed(mHandler
1075 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1076 }
1077
1078 // Clear the credentials toast if it is up
1079 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1080 mCredsDlg.dismiss();
1081 }
1082 mCredsDlg = null;
1083
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001084 // FIXME: This removes the active tabs page and resets the menu to
1085 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1086 // but then we would need to save it in onSaveInstanceState and restore
1087 // it in onCreate/onRestoreInstanceState
1088 if (mActiveTabsPage != null) {
1089 removeActiveTabPage(true);
1090 }
1091
The Android Open Source Project0c908882009-03-03 19:32:16 -08001092 cancelStopToast();
1093
1094 // unregister network state listener
1095 unregisterReceiver(mNetworkStateIntentReceiver);
1096 WebView.disablePlatformNotifications();
1097
1098 if (mSensorManager != null) {
1099 mSensorManager.unregisterListener(mSensorListener);
1100 }
1101 }
1102
1103 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001104 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001105 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1106 }
1107 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001108
1109 if (mTabControl == null) return;
1110
The Android Open Source Project0c908882009-03-03 19:32:16 -08001111 // Remove the current tab and sub window
1112 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001113 if (t != null) {
1114 dismissSubWindow(t);
1115 removeTabFromContentView(t);
1116 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001117 // Destroy all the tabs
1118 mTabControl.destroy();
1119 WebIconDatabase.getInstance().close();
1120 if (mGlsConnection != null) {
1121 unbindService(mGlsConnection);
1122 mGlsConnection = null;
1123 }
1124
1125 //
1126 // stop MASF proxy service
1127 //
1128 //Intent proxyServiceIntent = new Intent();
1129 //proxyServiceIntent.setComponent
1130 // (new ComponentName(
1131 // "com.android.masfproxyservice",
1132 // "com.android.masfproxyservice.MasfProxyService"));
1133 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001134
1135 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001136 }
1137
1138 @Override
1139 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001140 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001141 super.onConfigurationChanged(newConfig);
1142
1143 if (mPageInfoDialog != null) {
1144 mPageInfoDialog.dismiss();
1145 showPageInfo(
1146 mPageInfoView,
1147 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1148 }
1149 if (mSSLCertificateDialog != null) {
1150 mSSLCertificateDialog.dismiss();
1151 showSSLCertificate(
1152 mSSLCertificateView);
1153 }
1154 if (mSSLCertificateOnErrorDialog != null) {
1155 mSSLCertificateOnErrorDialog.dismiss();
1156 showSSLCertificateOnError(
1157 mSSLCertificateOnErrorView,
1158 mSSLCertificateOnErrorHandler,
1159 mSSLCertificateOnErrorError);
1160 }
1161 if (mHttpAuthenticationDialog != null) {
1162 String title = ((TextView) mHttpAuthenticationDialog
1163 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1164 .toString();
1165 String name = ((TextView) mHttpAuthenticationDialog
1166 .findViewById(R.id.username_edit)).getText().toString();
1167 String password = ((TextView) mHttpAuthenticationDialog
1168 .findViewById(R.id.password_edit)).getText().toString();
1169 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1170 .getId();
1171 mHttpAuthenticationDialog.dismiss();
1172 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1173 name, password, focusId);
1174 }
1175 if (mFindDialog != null && mFindDialog.isShowing()) {
1176 mFindDialog.onConfigurationChanged(newConfig);
1177 }
1178 }
1179
1180 @Override public void onLowMemory() {
1181 super.onLowMemory();
1182 mTabControl.freeMemory();
1183 }
1184
Mike Reed7bfa63b2009-05-28 11:08:32 -04001185 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001186 if ((!mActivityInPause && !mPageStarted) ||
1187 (mActivityInPause && mPageStarted)) {
1188 CookieSyncManager.getInstance().startSync();
1189 WebView w = mTabControl.getCurrentWebView();
1190 if (w != null) {
1191 w.resumeTimers();
1192 }
1193 return true;
1194 } else {
1195 return false;
1196 }
1197 }
1198
Mike Reed7bfa63b2009-05-28 11:08:32 -04001199 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001200 if (mActivityInPause && !mPageStarted) {
1201 CookieSyncManager.getInstance().stopSync();
1202 WebView w = mTabControl.getCurrentWebView();
1203 if (w != null) {
1204 w.pauseTimers();
1205 }
1206 return true;
1207 } else {
1208 return false;
1209 }
1210 }
1211
Leon Scroggins1f005d32009-08-10 17:36:42 -04001212 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001213 /*
1214 * This function is called when we are launching for the first time. We
1215 * are waiting for the login credentials before loading Google home
1216 * pages. This way the user will be logged in straight away.
1217 */
1218 private void waitForCredentials() {
1219 // Show a toast
1220 mCredsDlg = new ProgressDialog(this);
1221 mCredsDlg.setIndeterminate(true);
1222 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1223 // If the user cancels the operation, then cancel the Google
1224 // Credentials request.
1225 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1226 mCredsDlg.show();
1227
1228 // We set a timeout for the retrieval of credentials in onResume()
1229 // as that is when we have freed up some CPU time to get
1230 // the login credentials.
1231 }
1232
1233 /*
1234 * If we have received the credentials or we have timed out and we are
1235 * showing the credentials dialog, then it is time to move on.
1236 */
1237 private void resumeAfterCredentials() {
1238 if (mCredsDlg == null) {
1239 return;
1240 }
1241
1242 // Clear the toast
1243 if (mCredsDlg.isShowing()) {
1244 mCredsDlg.dismiss();
1245 }
1246 mCredsDlg = null;
1247
1248 // Clear any pending timeout
1249 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1250
1251 // Load the page
1252 WebView w = mTabControl.getCurrentWebView();
1253 if (w != null) {
1254 w.loadUrl(mSettings.getHomePage());
1255 }
1256
1257 // Update the settings, need to do this last as it can take a moment
1258 // to persist the settings. In the mean time we could be loading
1259 // content.
1260 mSettings.setLoginInitialized(this);
1261 }
1262
1263 // Open the icon database and retain all the icons for visited sites.
1264 private void retainIconsOnStartup() {
1265 final WebIconDatabase db = WebIconDatabase.getInstance();
1266 db.open(getDir("icons", 0).getPath());
1267 try {
1268 Cursor c = Browser.getAllBookmarks(mResolver);
1269 if (!c.moveToFirst()) {
1270 c.deactivate();
1271 return;
1272 }
1273 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1274 do {
1275 String url = c.getString(urlIndex);
1276 db.retainIconForPageUrl(url);
1277 } while (c.moveToNext());
1278 c.deactivate();
1279 } catch (IllegalStateException e) {
1280 Log.e(LOGTAG, "retainIconsOnStartup", e);
1281 }
1282 }
1283
1284 // Helper method for getting the top window.
1285 WebView getTopWindow() {
1286 return mTabControl.getCurrentTopWebView();
1287 }
1288
1289 @Override
1290 public boolean onCreateOptionsMenu(Menu menu) {
1291 super.onCreateOptionsMenu(menu);
1292
1293 MenuInflater inflater = getMenuInflater();
1294 inflater.inflate(R.menu.browser, menu);
1295 mMenu = menu;
1296 updateInLoadMenuItems();
1297 return true;
1298 }
1299
1300 /**
1301 * As the menu can be open when loading state changes
1302 * we must manually update the state of the stop/reload menu
1303 * item
1304 */
1305 private void updateInLoadMenuItems() {
1306 if (mMenu == null) {
1307 return;
1308 }
1309 MenuItem src = mInLoad ?
1310 mMenu.findItem(R.id.stop_menu_id):
1311 mMenu.findItem(R.id.reload_menu_id);
1312 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1313 dest.setIcon(src.getIcon());
1314 dest.setTitle(src.getTitle());
1315 }
1316
1317 @Override
1318 public boolean onContextItemSelected(MenuItem item) {
1319 // chording is not an issue with context menus, but we use the same
1320 // options selector, so set mCanChord to true so we can access them.
1321 mCanChord = true;
1322 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001323 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001324 // For the context menu from the title bar
1325 case R.id.title_bar_share_page_url:
1326 case R.id.title_bar_copy_page_url:
1327 WebView mainView = mTabControl.getCurrentWebView();
1328 if (null == mainView) {
1329 return false;
1330 }
1331 if (id == R.id.title_bar_share_page_url) {
1332 Browser.sendString(this, mainView.getUrl());
1333 } else {
1334 copy(mainView.getUrl());
1335 }
1336 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001337 // -- Browser context menu
1338 case R.id.open_context_menu_id:
1339 case R.id.open_newtab_context_menu_id:
1340 case R.id.bookmark_context_menu_id:
1341 case R.id.save_link_context_menu_id:
1342 case R.id.share_link_context_menu_id:
1343 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001344 final WebView webView = getTopWindow();
1345 if (null == webView) {
1346 return false;
1347 }
1348 final HashMap hrefMap = new HashMap();
1349 hrefMap.put("webview", webView);
1350 final Message msg = mHandler.obtainMessage(
1351 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001352 webView.requestFocusNodeHref(msg);
1353 break;
1354
1355 default:
1356 // For other context menus
1357 return onOptionsItemSelected(item);
1358 }
1359 mCanChord = false;
1360 return true;
1361 }
1362
1363 private Bundle createGoogleSearchSourceBundle(String source) {
1364 Bundle bundle = new Bundle();
1365 bundle.putString(SearchManager.SOURCE, source);
1366 return bundle;
1367 }
1368
1369 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001370 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001371 */
1372 @Override
1373 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001374 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001375 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001376 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001377 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001378 return true;
1379 }
1380
1381 @Override
1382 public void startSearch(String initialQuery, boolean selectInitialQuery,
1383 Bundle appSearchData, boolean globalSearch) {
1384 if (appSearchData == null) {
1385 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1386 }
1387 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1388 }
1389
Leon Scroggins1f005d32009-08-10 17:36:42 -04001390 /**
1391 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1392 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001393 * @param index Index of the tab to change to, as defined by
1394 * mTabControl.getTabIndex(Tab t).
1395 * @return boolean True if we successfully switched to a different tab. If
1396 * the indexth tab is null, or if that tab is the same as
1397 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001398 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001399 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001400 TabControl.Tab tab = mTabControl.getTab(index);
1401 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1402 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001403 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001404 }
1405 if (currentTab != null) {
1406 // currentTab may be null if it was just removed. In that case,
1407 // we do not need to remove it
1408 removeTabFromContentView(currentTab);
1409 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001410 mTabControl.setCurrentTab(tab);
1411 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001412 resetTitleIconAndProgress();
1413 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001414 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001415 }
1416
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001417 /* package */ TabControl.Tab openTabToHomePage() {
1418 return openTabAndShow(mSettings.getHomePage(), false, null);
1419 }
1420
Leon Scroggins1f005d32009-08-10 17:36:42 -04001421 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001422 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001423 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001424 // This is the last tab. Open a new one, with the home
1425 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001426 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001427 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001428 return;
1429 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001430 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001431 int indexToShow = -1;
1432 if (parent != null) {
1433 indexToShow = mTabControl.getTabIndex(parent);
1434 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001435 final int currentIndex = mTabControl.getCurrentIndex();
1436 // Try to move to the tab to the right
1437 indexToShow = currentIndex + 1;
1438 if (indexToShow > mTabControl.getTabCount() - 1) {
1439 // Try to move to the tab to the left
1440 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001441 }
1442 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001443 if (switchToTab(indexToShow)) {
1444 // Close window
1445 closeTab(current);
1446 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001447 }
1448
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001449 private ActiveTabsPage mActiveTabsPage;
1450
1451 /**
1452 * Remove the active tabs page.
1453 * @param needToAttach If true, the active tabs page did not attach a tab
1454 * to the content view, so we need to do that here.
1455 */
1456 /* package */ void removeActiveTabPage(boolean needToAttach) {
1457 mContentView.removeView(mActiveTabsPage);
1458 mActiveTabsPage = null;
1459 mMenuState = R.id.MAIN_MENU;
1460 if (needToAttach) {
1461 attachTabToContentView(mTabControl.getCurrentTab());
1462 }
1463 getTopWindow().requestFocus();
1464 }
1465
The Android Open Source Project0c908882009-03-03 19:32:16 -08001466 @Override
1467 public boolean onOptionsItemSelected(MenuItem item) {
1468 if (!mCanChord) {
1469 // The user has already fired a shortcut with this hold down of the
1470 // menu key.
1471 return false;
1472 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001473 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001474 return false;
1475 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001476 if (mMenuIsDown) {
1477 // The shortcut action consumes the MENU. Even if it is still down,
1478 // it won't trigger the next shortcut action. In the case of the
1479 // shortcut action triggering a new activity, like Bookmarks, we
1480 // won't get onKeyUp for MENU. So it is important to reset it here.
1481 mMenuIsDown = false;
1482 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001483 switch (item.getItemId()) {
1484 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001485 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001486 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001487 break;
1488
Leon Scroggins64b80f32009-08-07 12:03:34 -04001489 case R.id.goto_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001490 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001491 break;
1492
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001493 case R.id.active_tabs_menu_id:
1494 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1495 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001496 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001497 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1498 mActiveTabsPage.requestFocus();
1499 mMenuState = EMPTY_MENU;
1500 break;
1501
Leon Scroggins1f005d32009-08-10 17:36:42 -04001502 case R.id.add_bookmark_menu_id:
1503 Intent i = new Intent(BrowserActivity.this,
1504 AddBookmarkPage.class);
1505 WebView w = getTopWindow();
1506 i.putExtra("url", w.getUrl());
1507 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001508 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001509 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001510 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001511 break;
1512
1513 case R.id.stop_reload_menu_id:
1514 if (mInLoad) {
1515 stopLoading();
1516 } else {
1517 getTopWindow().reload();
1518 }
1519 break;
1520
1521 case R.id.back_menu_id:
1522 getTopWindow().goBack();
1523 break;
1524
1525 case R.id.forward_menu_id:
1526 getTopWindow().goForward();
1527 break;
1528
1529 case R.id.close_menu_id:
1530 // Close the subwindow if it exists.
1531 if (mTabControl.getCurrentSubWindow() != null) {
1532 dismissSubWindow(mTabControl.getCurrentTab());
1533 break;
1534 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001535 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001536 break;
1537
1538 case R.id.homepage_menu_id:
1539 TabControl.Tab current = mTabControl.getCurrentTab();
1540 if (current != null) {
1541 dismissSubWindow(current);
1542 current.getWebView().loadUrl(mSettings.getHomePage());
1543 }
1544 break;
1545
1546 case R.id.preferences_menu_id:
1547 Intent intent = new Intent(this,
1548 BrowserPreferencesPage.class);
1549 startActivityForResult(intent, PREFERENCES_PAGE);
1550 break;
1551
1552 case R.id.find_menu_id:
1553 if (null == mFindDialog) {
1554 mFindDialog = new FindDialog(this);
1555 }
1556 mFindDialog.setWebView(getTopWindow());
1557 mFindDialog.show();
1558 mMenuState = EMPTY_MENU;
1559 break;
1560
1561 case R.id.select_text_id:
1562 getTopWindow().emulateShiftHeld();
1563 break;
1564 case R.id.page_info_menu_id:
1565 showPageInfo(mTabControl.getCurrentTab(), false);
1566 break;
1567
1568 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001569 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001570 break;
1571
1572 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001573 Browser.sendString(this, getTopWindow().getUrl(),
1574 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001575 break;
1576
1577 case R.id.dump_nav_menu_id:
1578 getTopWindow().debugDump();
1579 break;
1580
1581 case R.id.zoom_in_menu_id:
1582 getTopWindow().zoomIn();
1583 break;
1584
1585 case R.id.zoom_out_menu_id:
1586 getTopWindow().zoomOut();
1587 break;
1588
1589 case R.id.view_downloads_menu_id:
1590 viewDownloads(null);
1591 break;
1592
The Android Open Source Project0c908882009-03-03 19:32:16 -08001593 case R.id.window_one_menu_id:
1594 case R.id.window_two_menu_id:
1595 case R.id.window_three_menu_id:
1596 case R.id.window_four_menu_id:
1597 case R.id.window_five_menu_id:
1598 case R.id.window_six_menu_id:
1599 case R.id.window_seven_menu_id:
1600 case R.id.window_eight_menu_id:
1601 {
1602 int menuid = item.getItemId();
1603 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1604 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1605 TabControl.Tab desiredTab = mTabControl.getTab(id);
1606 if (desiredTab != null &&
1607 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001608 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001609 }
1610 break;
1611 }
1612 }
1613 }
1614 break;
1615
1616 default:
1617 if (!super.onOptionsItemSelected(item)) {
1618 return false;
1619 }
1620 // Otherwise fall through.
1621 }
1622 mCanChord = false;
1623 return true;
1624 }
1625
1626 public void closeFind() {
1627 mMenuState = R.id.MAIN_MENU;
1628 }
1629
1630 @Override public boolean onPrepareOptionsMenu(Menu menu)
1631 {
1632 // This happens when the user begins to hold down the menu key, so
1633 // allow them to chord to get a shortcut.
1634 mCanChord = true;
1635 // Note: setVisible will decide whether an item is visible; while
1636 // setEnabled() will decide whether an item is enabled, which also means
1637 // whether the matching shortcut key will function.
1638 super.onPrepareOptionsMenu(menu);
1639 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001640 case EMPTY_MENU:
1641 if (mCurrentMenuState != mMenuState) {
1642 menu.setGroupVisible(R.id.MAIN_MENU, false);
1643 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1644 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001645 }
1646 break;
1647 default:
1648 if (mCurrentMenuState != mMenuState) {
1649 menu.setGroupVisible(R.id.MAIN_MENU, true);
1650 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1651 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001652 }
1653 final WebView w = getTopWindow();
1654 boolean canGoBack = false;
1655 boolean canGoForward = false;
1656 boolean isHome = false;
1657 if (w != null) {
1658 canGoBack = w.canGoBack();
1659 canGoForward = w.canGoForward();
1660 isHome = mSettings.getHomePage().equals(w.getUrl());
1661 }
1662 final MenuItem back = menu.findItem(R.id.back_menu_id);
1663 back.setEnabled(canGoBack);
1664
1665 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1666 home.setEnabled(!isHome);
1667
1668 menu.findItem(R.id.forward_menu_id)
1669 .setEnabled(canGoForward);
1670
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001671 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1672 mTabControl.getTabCount() < TabControl.MAX_TABS);
1673
The Android Open Source Project0c908882009-03-03 19:32:16 -08001674 // decide whether to show the share link option
1675 PackageManager pm = getPackageManager();
1676 Intent send = new Intent(Intent.ACTION_SEND);
1677 send.setType("text/plain");
1678 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1679 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1680
The Android Open Source Project0c908882009-03-03 19:32:16 -08001681 boolean isNavDump = mSettings.isNavDump();
1682 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1683 nav.setVisible(isNavDump);
1684 nav.setEnabled(isNavDump);
1685 break;
1686 }
1687 mCurrentMenuState = mMenuState;
1688 return true;
1689 }
1690
1691 @Override
1692 public void onCreateContextMenu(ContextMenu menu, View v,
1693 ContextMenuInfo menuInfo) {
1694 WebView webview = (WebView) v;
1695 WebView.HitTestResult result = webview.getHitTestResult();
1696 if (result == null) {
1697 return;
1698 }
1699
1700 int type = result.getType();
1701 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1702 Log.w(LOGTAG,
1703 "We should not show context menu when nothing is touched");
1704 return;
1705 }
1706 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1707 // let TextView handles context menu
1708 return;
1709 }
1710
1711 // Note, http://b/issue?id=1106666 is requesting that
1712 // an inflated menu can be used again. This is not available
1713 // yet, so inflate each time (yuk!)
1714 MenuInflater inflater = getMenuInflater();
1715 inflater.inflate(R.menu.browsercontext, menu);
1716
1717 // Show the correct menu group
1718 String extra = result.getExtra();
1719 menu.setGroupVisible(R.id.PHONE_MENU,
1720 type == WebView.HitTestResult.PHONE_TYPE);
1721 menu.setGroupVisible(R.id.EMAIL_MENU,
1722 type == WebView.HitTestResult.EMAIL_TYPE);
1723 menu.setGroupVisible(R.id.GEO_MENU,
1724 type == WebView.HitTestResult.GEO_TYPE);
1725 menu.setGroupVisible(R.id.IMAGE_MENU,
1726 type == WebView.HitTestResult.IMAGE_TYPE
1727 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1728 menu.setGroupVisible(R.id.ANCHOR_MENU,
1729 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1730 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1731
1732 // Setup custom handling depending on the type
1733 switch (type) {
1734 case WebView.HitTestResult.PHONE_TYPE:
1735 menu.setHeaderTitle(Uri.decode(extra));
1736 menu.findItem(R.id.dial_context_menu_id).setIntent(
1737 new Intent(Intent.ACTION_VIEW, Uri
1738 .parse(WebView.SCHEME_TEL + extra)));
1739 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1740 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001741 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001742 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1743 addIntent);
1744 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1745 new Copy(extra));
1746 break;
1747
1748 case WebView.HitTestResult.EMAIL_TYPE:
1749 menu.setHeaderTitle(extra);
1750 menu.findItem(R.id.email_context_menu_id).setIntent(
1751 new Intent(Intent.ACTION_VIEW, Uri
1752 .parse(WebView.SCHEME_MAILTO + extra)));
1753 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1754 new Copy(extra));
1755 break;
1756
1757 case WebView.HitTestResult.GEO_TYPE:
1758 menu.setHeaderTitle(extra);
1759 menu.findItem(R.id.map_context_menu_id).setIntent(
1760 new Intent(Intent.ACTION_VIEW, Uri
1761 .parse(WebView.SCHEME_GEO
1762 + URLEncoder.encode(extra))));
1763 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1764 new Copy(extra));
1765 break;
1766
1767 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1768 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1769 TextView titleView = (TextView) LayoutInflater.from(this)
1770 .inflate(android.R.layout.browser_link_context_header,
1771 null);
1772 titleView.setText(extra);
1773 menu.setHeaderView(titleView);
1774 // decide whether to show the open link in new tab option
1775 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1776 mTabControl.getTabCount() < TabControl.MAX_TABS);
1777 PackageManager pm = getPackageManager();
1778 Intent send = new Intent(Intent.ACTION_SEND);
1779 send.setType("text/plain");
1780 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1781 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1782 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1783 break;
1784 }
1785 // otherwise fall through to handle image part
1786 case WebView.HitTestResult.IMAGE_TYPE:
1787 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1788 menu.setHeaderTitle(extra);
1789 }
1790 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1791 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1792 menu.findItem(R.id.download_context_menu_id).
1793 setOnMenuItemClickListener(new Download(extra));
1794 break;
1795
1796 default:
1797 Log.w(LOGTAG, "We should not get here.");
1798 break;
1799 }
1800 }
1801
The Android Open Source Project0c908882009-03-03 19:32:16 -08001802 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001803 // this should only be called for the current tab.
The Android Open Source Project0c908882009-03-03 19:32:16 -08001804 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001805 // Attach the container that contains the main WebView and any other UI
1806 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001807 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001808
1809 if (mShouldShowErrorConsole) {
1810 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1811 if (errorConsole.numberOfErrors() == 0) {
1812 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1813 } else {
1814 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1815 }
1816
1817 mErrorConsoleContainer.addView(errorConsole,
1818 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1819 ViewGroup.LayoutParams.WRAP_CONTENT));
1820 }
1821
Grace Klobac928c302009-09-17 11:51:21 -07001822 setLockIconType(t.getLockIconType());
1823 setPrevLockType(t.getPrevLockIconType());
1824
1825 // this is to match the code in removeTabFromContentView()
1826 if (!mPageStarted && t.getTopWindow().getProgress() < 100) {
1827 mPageStarted = true;
Grace Klobaeb6eef42009-09-15 17:56:32 -07001828 }
1829
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001830 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001831 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001832 // Request focus on the top window.
1833 t.getTopWindow().requestFocus();
1834 }
1835
1836 // Attach a sub window to the main WebView of the given tab.
1837 private void attachSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001838 t.attachSubWindow(mContentView);
1839 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001840 }
1841
1842 // Remove the given tab from the content view.
1843 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001844 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001845 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001846
1847 if (mTabControl.getCurrentErrorConsole(false) != null) {
1848 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1849 }
1850
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001851 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001852 if (view != null) {
1853 view.setEmbeddedTitleBar(null);
1854 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001855
Grace Klobac928c302009-09-17 11:51:21 -07001856 // unlike attachTabToContentView(), removeTabFromContentView() can be
1857 // called for the non-current tab. Need to add the check.
Grace Klobaeb6eef42009-09-15 17:56:32 -07001858 if (t == mTabControl.getCurrentTab()) {
1859 t.setLockIconType(getLockIconType());
1860 t.setPrevLockIconType(getPrevLockType());
Grace Klobac928c302009-09-17 11:51:21 -07001861
1862 // this is not a perfect solution. But currently there is one
1863 // WebViewClient for all the WebView. if user switches from an
1864 // in-load window to an already loaded window, mPageStarted will not
1865 // be set to false. If user leaves the Browser, pauseWebViewTimers()
1866 // won't do anything and leaves the timer running even Browser is in
1867 // the background.
1868 if (mPageStarted) {
1869 mPageStarted = false;
1870 }
Grace Klobaeb6eef42009-09-15 17:56:32 -07001871 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001872 }
1873
1874 // Remove the sub window if it exists. Also called by TabControl when the
1875 // user clicks the 'X' to dismiss a sub window.
1876 /* package */ void dismissSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001877 t.removeSubWindow(mContentView);
1878 // Tell the TabControl to dismiss the subwindow. This will destroy
1879 // the WebView.
1880 mTabControl.dismissSubWindow(t);
1881 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001882 }
1883
Leon Scroggins1f005d32009-08-10 17:36:42 -04001884 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001885 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001886 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1887 String appId) {
1888 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001889 }
1890
1891 // This method does a ton of stuff. It will attempt to create a new tab
1892 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001893 // url isn't null, it will load the given url.
1894 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001895 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001896 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1897 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1898 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001899 final TabControl.Tab tab = mTabControl.createNewTab(
1900 closeOnExit, appId, urlData.mUrl);
1901 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001902 // If the last tab was removed from the active tabs page, currentTab
1903 // will be null.
1904 if (currentTab != null) {
1905 removeTabFromContentView(currentTab);
1906 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001907 // We must set the new tab as the current tab to reflect the old
1908 // animation behavior.
1909 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001910 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001911 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001912 urlData.loadIn(webview);
1913 }
1914 return tab;
1915 } else {
1916 // Get rid of the subwindow if it exists
1917 dismissSubWindow(currentTab);
1918 if (!urlData.isEmpty()) {
1919 // Load the given url.
1920 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001921 }
1922 }
Grace Klobac9181842009-04-14 08:53:22 -07001923 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001924 }
1925
Grace Klobac9181842009-04-14 08:53:22 -07001926 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001927 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001928 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001929 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001930 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001931 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001932 }
Grace Klobac9181842009-04-14 08:53:22 -07001933 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001934 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001935 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001936 }
1937 }
1938
1939 private class Copy implements OnMenuItemClickListener {
1940 private CharSequence mText;
1941
1942 public boolean onMenuItemClick(MenuItem item) {
1943 copy(mText);
1944 return true;
1945 }
1946
1947 public Copy(CharSequence toCopy) {
1948 mText = toCopy;
1949 }
1950 }
1951
1952 private class Download implements OnMenuItemClickListener {
1953 private String mText;
1954
1955 public boolean onMenuItemClick(MenuItem item) {
1956 onDownloadStartNoStream(mText, null, null, null, -1);
1957 return true;
1958 }
1959
1960 public Download(String toDownload) {
1961 mText = toDownload;
1962 }
1963 }
1964
1965 private void copy(CharSequence text) {
1966 try {
1967 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1968 if (clip != null) {
1969 clip.setClipboardText(text);
1970 }
1971 } catch (android.os.RemoteException e) {
1972 Log.e(LOGTAG, "Copy failed", e);
1973 }
1974 }
1975
1976 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001977 * Resets the browser title-view to whatever it must be
1978 * (for example, if we had a loading error)
1979 * When we have a new page, we call resetTitle, when we
1980 * have to reset the titlebar to whatever it used to be
1981 * (for example, if the user chose to stop loading), we
1982 * call resetTitleAndRevertLockIcon.
1983 */
1984 /* package */ void resetTitleAndRevertLockIcon() {
1985 revertLockIcon();
1986 resetTitleIconAndProgress();
1987 }
1988
1989 /**
1990 * Reset the title, favicon, and progress.
1991 */
1992 private void resetTitleIconAndProgress() {
1993 WebView current = mTabControl.getCurrentWebView();
1994 if (current == null) {
1995 return;
1996 }
1997 resetTitleAndIcon(current);
1998 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001999 mWebChromeClient.onProgressChanged(current, progress);
2000 }
2001
2002 // Reset the title and the icon based on the given item.
2003 private void resetTitleAndIcon(WebView view) {
2004 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2005 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002006 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002007 setFavicon(item.getFavicon());
2008 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002009 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002010 setFavicon(null);
2011 }
2012 }
2013
2014 /**
2015 * Sets a title composed of the URL and the title string.
2016 * @param url The URL of the site being loaded.
2017 * @param title The title of the site being loaded.
2018 */
Leon Scroggins68579392009-09-15 15:31:54 -04002019 private void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002020 mUrl = url;
2021 mTitle = title;
2022
Leon Scroggins68579392009-09-15 15:31:54 -04002023 mTitleBar.setTitleAndUrl(title, url);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002024 if (mFakeTitleBar != null) {
2025 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002026 }
2027 }
2028
2029 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002030 * @param url The URL to build a title version of the URL from.
2031 * @return The title version of the URL or null if fails.
2032 * The title version of the URL can be either the URL hostname,
2033 * or the hostname with an "https://" prefix (for secure URLs),
2034 * or an empty string if, for example, the URL in question is a
2035 * file:// URL with no hostname.
2036 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002037 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002038 String titleUrl = null;
2039
2040 if (url != null) {
2041 try {
2042 // parse the url string
2043 URL urlObj = new URL(url);
2044 if (urlObj != null) {
2045 titleUrl = "";
2046
2047 String protocol = urlObj.getProtocol();
2048 String host = urlObj.getHost();
2049
2050 if (host != null && 0 < host.length()) {
2051 titleUrl = host;
2052 if (protocol != null) {
2053 // if a secure site, add an "https://" prefix!
2054 if (protocol.equalsIgnoreCase("https")) {
2055 titleUrl = protocol + "://" + host;
2056 }
2057 }
2058 }
2059 }
2060 } catch (MalformedURLException e) {}
2061 }
2062
2063 return titleUrl;
2064 }
2065
2066 // Set the favicon in the title bar.
2067 private void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002068 mTitleBar.setFavicon(icon);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002069 if (mFakeTitleBar != null) {
2070 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002071 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002072 }
2073
2074 /**
2075 * Saves the current lock-icon state before resetting
2076 * the lock icon. If we have an error, we may need to
2077 * roll back to the previous state.
2078 */
2079 private void saveLockIcon() {
2080 mPrevLockType = mLockIconType;
2081 }
2082
2083 /**
2084 * Reverts the lock-icon state to the last saved state,
2085 * for example, if we had an error, and need to cancel
2086 * the load.
2087 */
2088 private void revertLockIcon() {
2089 mLockIconType = mPrevLockType;
2090
Dave Bort31a6d1c2009-04-13 15:56:49 -07002091 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002092 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2093 " revert lock icon to " + mLockIconType);
2094 }
2095
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002096 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002097 }
2098
Leon Scroggins1f005d32009-08-10 17:36:42 -04002099 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002100 * Close the tab, remove its associated title bar, and adjust mTabControl's
2101 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002102 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002103 /* package */ void closeTab(TabControl.Tab t) {
2104 int currentIndex = mTabControl.getCurrentIndex();
2105 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002106 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002107 if (currentIndex >= removeIndex && currentIndex != 0) {
2108 currentIndex--;
2109 }
2110 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002111 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002112 }
2113
2114 private void goBackOnePageOrQuit() {
2115 TabControl.Tab current = mTabControl.getCurrentTab();
2116 if (current == null) {
2117 /*
2118 * Instead of finishing the activity, simply push this to the back
2119 * of the stack and let ActivityManager to choose the foreground
2120 * activity. As BrowserActivity is singleTask, it will be always the
2121 * root of the task. So we can use either true or false for
2122 * moveTaskToBack().
2123 */
2124 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002125 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002126 }
2127 WebView w = current.getWebView();
2128 if (w.canGoBack()) {
2129 w.goBack();
2130 } else {
2131 // Check to see if we are closing a window that was created by
2132 // another window. If so, we switch back to that window.
2133 TabControl.Tab parent = current.getParentTab();
2134 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002135 switchToTab(mTabControl.getTabIndex(parent));
2136 // Now we close the other tab
2137 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002138 } else {
2139 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002140 // force mPageStarted to be false as we are going to either
2141 // finish the activity or remove the tab. This will ensure
2142 // pauseWebView() taking action.
2143 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002144 if (mTabControl.getTabCount() == 1) {
2145 finish();
2146 return;
2147 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002148 // call pauseWebViewTimers() now, we won't be able to call
2149 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002150 // Temporarily change mActivityInPause to be true as
2151 // pauseWebViewTimers() will do nothing if mActivityInPause
2152 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002153 boolean savedState = mActivityInPause;
2154 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002155 Log.e(LOGTAG, "BrowserActivity is already paused "
2156 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002157 }
2158 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002159 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002160 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002161 removeTabFromContentView(current);
2162 mTabControl.removeTab(current);
2163 }
2164 /*
2165 * Instead of finishing the activity, simply push this to the back
2166 * of the stack and let ActivityManager to choose the foreground
2167 * activity. As BrowserActivity is singleTask, it will be always the
2168 * root of the task. So we can use either true or false for
2169 * moveTaskToBack().
2170 */
2171 moveTaskToBack(true);
2172 }
2173 }
2174 }
2175
Grace Kloba5942df02009-09-18 11:48:29 -07002176 @Override
2177 public boolean onKeyDown(int keyCode, KeyEvent event) {
2178 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2179 // still down, we don't want to trigger the search. Pretend to consume
2180 // the key and do nothing.
2181 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002182
Grace Kloba5942df02009-09-18 11:48:29 -07002183 switch(keyCode) {
2184 case KeyEvent.KEYCODE_MENU:
2185 mMenuIsDown = true;
2186 break;
2187 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002188 // WebView/WebTextView handle the keys in the KeyDown. As
2189 // the Activity's shortcut keys are only handled when WebView
2190 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2191 if (event.isShiftPressed()) {
2192 getTopWindow().pageUp(false);
2193 } else {
2194 getTopWindow().pageDown(false);
2195 }
Grace Kloba5942df02009-09-18 11:48:29 -07002196 return true;
2197 case KeyEvent.KEYCODE_BACK:
2198 if (event.getRepeatCount() == 0) {
2199 event.startTracking();
2200 return true;
2201 } else if (mCustomView == null && mActiveTabsPage == null
2202 && event.isLongPress()) {
2203 bookmarksOrHistoryPicker(true);
2204 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002205 }
Grace Kloba5942df02009-09-18 11:48:29 -07002206 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002207 }
Grace Kloba5942df02009-09-18 11:48:29 -07002208 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002209 }
2210
Grace Kloba5942df02009-09-18 11:48:29 -07002211 @Override
2212 public boolean onKeyUp(int keyCode, KeyEvent event) {
2213 switch(keyCode) {
2214 case KeyEvent.KEYCODE_MENU:
2215 mMenuIsDown = false;
2216 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002217 case KeyEvent.KEYCODE_BACK:
2218 if (event.isTracking() && !event.isCanceled()) {
2219 if (mCustomView != null) {
2220 // if a custom view is showing, hide it
2221 mWebChromeClient.onHideCustomView();
2222 } else if (mActiveTabsPage != null) {
2223 // if tab page is showing, hide it
2224 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002225 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002226 WebView subwindow = mTabControl.getCurrentSubWindow();
2227 if (subwindow != null) {
2228 if (subwindow.canGoBack()) {
2229 subwindow.goBack();
2230 } else {
2231 dismissSubWindow(mTabControl.getCurrentTab());
2232 }
2233 } else {
2234 goBackOnePageOrQuit();
2235 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002236 }
Grace Kloba5942df02009-09-18 11:48:29 -07002237 return true;
2238 }
2239 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002240 }
Grace Kloba5942df02009-09-18 11:48:29 -07002241 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002242 }
2243
Leon Scroggins68579392009-09-15 15:31:54 -04002244 /* package */ void stopLoading() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002245 resetTitleAndRevertLockIcon();
2246 WebView w = getTopWindow();
2247 w.stopLoading();
2248 mWebViewClient.onPageFinished(w, w.getUrl());
2249
2250 cancelStopToast();
2251 mStopToast = Toast
2252 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2253 mStopToast.show();
2254 }
2255
2256 private void cancelStopToast() {
2257 if (mStopToast != null) {
2258 mStopToast.cancel();
2259 mStopToast = null;
2260 }
2261 }
2262
2263 // called by a non-UI thread to post the message
2264 public void postMessage(int what, int arg1, int arg2, Object obj) {
2265 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2266 }
2267
2268 // public message ids
2269 public final static int LOAD_URL = 1001;
2270 public final static int STOP_LOAD = 1002;
2271
2272 // Message Ids
2273 private static final int FOCUS_NODE_HREF = 102;
2274 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002275 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002276
2277 // Private handler for handling javascript and saving passwords
2278 private Handler mHandler = new Handler() {
2279
2280 public void handleMessage(Message msg) {
2281 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002282 case FOCUS_NODE_HREF:
2283 String url = (String) msg.getData().get("url");
2284 if (url == null || url.length() == 0) {
2285 break;
2286 }
2287 HashMap focusNodeMap = (HashMap) msg.obj;
2288 WebView view = (WebView) focusNodeMap.get("webview");
2289 // Only apply the action if the top window did not change.
2290 if (getTopWindow() != view) {
2291 break;
2292 }
2293 switch (msg.arg1) {
2294 case R.id.open_context_menu_id:
2295 case R.id.view_image_context_menu_id:
2296 loadURL(getTopWindow(), url);
2297 break;
2298 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002299 final TabControl.Tab parent = mTabControl
2300 .getCurrentTab();
2301 final TabControl.Tab newTab = openTab(url);
2302 if (newTab != parent) {
2303 parent.addChildTab(newTab);
2304 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002305 break;
2306 case R.id.bookmark_context_menu_id:
2307 Intent intent = new Intent(BrowserActivity.this,
2308 AddBookmarkPage.class);
2309 intent.putExtra("url", url);
2310 startActivity(intent);
2311 break;
2312 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002313 Browser.sendString(BrowserActivity.this, url,
2314 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002315 break;
2316 case R.id.copy_link_context_menu_id:
2317 copy(url);
2318 break;
2319 case R.id.save_link_context_menu_id:
2320 case R.id.download_context_menu_id:
2321 onDownloadStartNoStream(url, null, null, null, -1);
2322 break;
2323 }
2324 break;
2325
2326 case LOAD_URL:
2327 loadURL(getTopWindow(), (String) msg.obj);
2328 break;
2329
2330 case STOP_LOAD:
2331 stopLoading();
2332 break;
2333
2334 case CANCEL_CREDS_REQUEST:
2335 resumeAfterCredentials();
2336 break;
2337
The Android Open Source Project0c908882009-03-03 19:32:16 -08002338 case RELEASE_WAKELOCK:
2339 if (mWakeLock.isHeld()) {
2340 mWakeLock.release();
2341 }
2342 break;
2343 }
2344 }
2345 };
2346
Leon Scroggins89c6d362009-07-15 16:54:37 -04002347 private void updateScreenshot(WebView view) {
2348 // If this is a bookmarked site, add a screenshot to the database.
2349 // FIXME: When should we update? Every time?
2350 // FIXME: Would like to make sure there is actually something to
2351 // draw, but the API for that (WebViewCore.pictureReady()) is not
2352 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002353
Patrick Scott3918d442009-08-04 13:22:29 -04002354 ContentResolver cr = getContentResolver();
2355 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002356 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002357 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002358 boolean succeed = c.moveToFirst();
2359 ContentValues values = null;
2360 while (succeed) {
2361 if (values == null) {
2362 final ByteArrayOutputStream os
2363 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002364 Bitmap bm = createScreenshot(view);
Leon Scroggins89c6d362009-07-15 16:54:37 -04002365 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2366 values = new ContentValues();
2367 values.put(Browser.BookmarkColumns.THUMBNAIL,
2368 os.toByteArray());
2369 }
2370 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2371 c.getInt(0)), values, null, null);
2372 succeed = c.moveToNext();
2373 }
2374 c.close();
2375 }
2376 }
2377
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002378 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002379 * Values for the size of the thumbnail created when taking a screenshot.
2380 * Lazily initialized. Instead of using these directly, use
2381 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002382 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002383 private static int THUMBNAIL_WIDTH = 0;
2384 private static int THUMBNAIL_HEIGHT = 0;
2385
2386 /**
2387 * Return the desired width for thumbnail screenshots, which are stored in
2388 * the database, and used on the bookmarks screen.
2389 * @param context Context for finding out the density of the screen.
2390 * @return int desired width for thumbnail screenshot.
2391 */
2392 /* package */ static int getDesiredThumbnailWidth(Context context) {
2393 if (THUMBNAIL_WIDTH == 0) {
2394 float density = context.getResources().getDisplayMetrics().density;
2395 THUMBNAIL_WIDTH = (int) (90 * density);
2396 THUMBNAIL_HEIGHT = (int) (80 * density);
2397 }
2398 return THUMBNAIL_WIDTH;
2399 }
2400
2401 /**
2402 * Return the desired height for thumbnail screenshots, which are stored in
2403 * the database, and used on the bookmarks screen.
2404 * @param context Context for finding out the density of the screen.
2405 * @return int desired height for thumbnail screenshot.
2406 */
2407 /* package */ static int getDesiredThumbnailHeight(Context context) {
2408 // To ensure that they are both initialized.
2409 getDesiredThumbnailWidth(context);
2410 return THUMBNAIL_HEIGHT;
2411 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002412
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002413 private Bitmap createScreenshot(WebView view) {
2414 Picture thumbnail = view.capturePicture();
Leon Scrogginsf8551612009-09-24 16:06:02 -04002415 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2416 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002417 Canvas canvas = new Canvas(bm);
2418 // May need to tweak these values to determine what is the
2419 // best scale factor
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002420 int contentWidth = view.getContentWidth();
2421 if (contentWidth > 0) {
Leon Scrogginsf8551612009-09-24 16:06:02 -04002422 float scaleFactor = (float) getDesiredThumbnailWidth(this)
2423 / (float) contentWidth;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002424 canvas.scale(scaleFactor, scaleFactor);
2425 }
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002426 thumbnail.draw(canvas);
2427 return bm;
2428 }
2429
The Android Open Source Project0c908882009-03-03 19:32:16 -08002430 // -------------------------------------------------------------------------
2431 // WebViewClient implementation.
2432 //-------------------------------------------------------------------------
2433
2434 // Use in overrideUrlLoading
2435 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2436 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2437 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2438 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2439
2440 /* package */ WebViewClient getWebViewClient() {
2441 return mWebViewClient;
2442 }
2443
Patrick Scott3918d442009-08-04 13:22:29 -04002444 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002445 if (icon != null) {
2446 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott15525d42009-09-21 13:39:37 -04002447 view.getOriginalUrl(), view.getUrl(), icon);
2448 }
2449 setFavicon(icon);
2450 }
2451
2452 private void updateIcon(String url, Bitmap icon) {
2453 if (icon != null) {
2454 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2455 null, url, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002456 }
2457 setFavicon(icon);
2458 }
2459
2460 private final WebViewClient mWebViewClient = new WebViewClient() {
2461 @Override
2462 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2463 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002464 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002465
Patrick Scott59ce8302009-09-18 16:29:38 -04002466 // If we start a touch icon load and then load a new page, we don't
2467 // want to cancel the current touch icon loader. But, we do want to
2468 // create a new one when the touch icon url is known.
2469 if (mTouchIconLoader != null) {
2470 mTouchIconLoader.mActivity = null;
2471 mTouchIconLoader = null;
2472 }
2473
Ben Murdochbff2d602009-07-01 20:19:05 +01002474 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2475 if (errorConsole != null) {
2476 errorConsole.clearErrorMessages();
2477 if (mShouldShowErrorConsole) {
2478 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2479 }
2480 }
2481
The Android Open Source Project0c908882009-03-03 19:32:16 -08002482 // Call updateIcon instead of setFavicon so the bookmark
2483 // database can be updated.
Patrick Scott15525d42009-09-21 13:39:37 -04002484 updateIcon(url, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002485
Grace Kloba4d7880f2009-08-12 09:35:42 -07002486 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002487 String host;
2488 try {
2489 WebAddress uri = new WebAddress(url);
2490 host = uri.mHost;
2491 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002492 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002493 }
2494 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002495 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002496 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002497 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002498 }
2499
2500 // Performance probe
2501 if (false) {
2502 mStart = SystemClock.uptimeMillis();
2503 mProcessStart = Process.getElapsedCpuTime();
2504 long[] sysCpu = new long[7];
2505 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2506 sysCpu, null)) {
2507 mUserStart = sysCpu[0] + sysCpu[1];
2508 mSystemStart = sysCpu[2];
2509 mIdleStart = sysCpu[3];
2510 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2511 }
2512 mUiStart = SystemClock.currentThreadTimeMillis();
2513 }
2514
2515 if (!mPageStarted) {
2516 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002517 // if onResume() has been called, resumeWebViewTimers() does
2518 // nothing.
2519 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002520 }
2521
2522 // reset sync timer to avoid sync starts during loading a page
2523 CookieSyncManager.getInstance().resetSync();
2524
2525 mInLoad = true;
Leon Scroggins184f5e32009-09-21 10:38:24 -04002526 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002527 updateInLoadMenuItems();
2528 if (!mIsNetworkUp) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04002529 createAndShowNetworkDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002530 if (view != null) {
2531 view.setNetworkAvailable(false);
2532 }
2533 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002534 }
2535
2536 @Override
2537 public void onPageFinished(WebView view, String url) {
2538 // Reset the title and icon in case we stopped a provisional
2539 // load.
2540 resetTitleAndIcon(view);
Ben Murdochaac7aa62009-09-17 16:57:40 +01002541 updateScreenshot(view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002542
2543 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002544 updateLockIconToLatest();
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002545
The Android Open Source Project0c908882009-03-03 19:32:16 -08002546 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002547 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002548 long[] sysCpu = new long[7];
2549 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2550 sysCpu, null)) {
2551 String uiInfo = "UI thread used "
2552 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2553 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002554 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002555 Log.d(LOGTAG, uiInfo);
2556 }
2557 //The string that gets written to the log
2558 String performanceString = "It took total "
2559 + (SystemClock.uptimeMillis() - mStart)
2560 + " ms clock time to load the page."
2561 + "\nbrowser process used "
2562 + (Process.getElapsedCpuTime() - mProcessStart)
2563 + " ms, user processes used "
2564 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2565 + " ms, kernel used "
2566 + (sysCpu[2] - mSystemStart) * 10
2567 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2568 + " ms and irq took "
2569 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2570 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002571 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002572 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2573 }
2574 if (url != null) {
2575 // strip the url to maintain consistency
2576 String newUrl = new String(url);
2577 if (newUrl.startsWith("http://www.")) {
2578 newUrl = newUrl.substring(11);
2579 } else if (newUrl.startsWith("http://")) {
2580 newUrl = newUrl.substring(7);
2581 } else if (newUrl.startsWith("https://www.")) {
2582 newUrl = newUrl.substring(12);
2583 } else if (newUrl.startsWith("https://")) {
2584 newUrl = newUrl.substring(8);
2585 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002586 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002587 Log.d(LOGTAG, newUrl + " loaded");
2588 }
2589 /*
2590 if (sWhiteList.contains(newUrl)) {
2591 // The string that gets pushed to the statistcs
2592 // service
2593 performanceString = performanceString
2594 + "\nWebpage: "
2595 + newUrl
2596 + "\nCarrier: "
2597 + android.os.SystemProperties
2598 .get("gsm.sim.operator.alpha");
2599 if (mWebView != null
2600 && mWebView.getContext() != null
2601 && mWebView.getContext().getSystemService(
2602 Context.CONNECTIVITY_SERVICE) != null) {
2603 ConnectivityManager cManager =
2604 (ConnectivityManager) mWebView
2605 .getContext().getSystemService(
2606 Context.CONNECTIVITY_SERVICE);
2607 NetworkInfo nInfo = cManager
2608 .getActiveNetworkInfo();
2609 if (nInfo != null) {
2610 performanceString = performanceString
2611 + "\nNetwork Type: "
2612 + nInfo.getType().toString();
2613 }
2614 }
2615 Checkin.logEvent(mResolver,
2616 Checkin.Events.Tag.WEBPAGE_LOAD,
2617 performanceString);
2618 Log.w(LOGTAG, "pushed to the statistics service");
2619 }
2620 */
2621 }
2622 }
2623 }
2624
2625 if (mInTrace) {
2626 mInTrace = false;
2627 Debug.stopMethodTracing();
2628 }
2629
2630 if (mPageStarted) {
2631 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002632 // pauseWebViewTimers() will do nothing and return false if
2633 // onPause() is not called yet.
2634 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002635 if (mWakeLock.isHeld()) {
2636 mHandler.removeMessages(RELEASE_WAKELOCK);
2637 mWakeLock.release();
2638 }
2639 }
2640 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002641 }
2642
2643 // return true if want to hijack the url to let another app to handle it
2644 @Override
2645 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2646 if (url.startsWith(SCHEME_WTAI)) {
2647 // wtai://wp/mc;number
2648 // number=string(phone-number)
2649 if (url.startsWith(SCHEME_WTAI_MC)) {
2650 Intent intent = new Intent(Intent.ACTION_VIEW,
2651 Uri.parse(WebView.SCHEME_TEL +
2652 url.substring(SCHEME_WTAI_MC.length())));
2653 startActivity(intent);
2654 return true;
2655 }
2656 // wtai://wp/sd;dtmf
2657 // dtmf=string(dialstring)
2658 if (url.startsWith(SCHEME_WTAI_SD)) {
2659 // TODO
2660 // only send when there is active voice connection
2661 return false;
2662 }
2663 // wtai://wp/ap;number;name
2664 // number=string(phone-number)
2665 // name=string
2666 if (url.startsWith(SCHEME_WTAI_AP)) {
2667 // TODO
2668 return false;
2669 }
2670 }
2671
Dianne Hackborn99189432009-06-17 18:06:18 -07002672 // The "about:" schemes are internal to the browser; don't
2673 // want these to be dispatched to other apps.
2674 if (url.startsWith("about:")) {
2675 return false;
2676 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002677
Dianne Hackborn99189432009-06-17 18:06:18 -07002678 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002679
Dianne Hackborn99189432009-06-17 18:06:18 -07002680 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002681 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002682 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2683 } catch (URISyntaxException ex) {
2684 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002685 return false;
2686 }
2687
Grace Kloba5b078b52009-06-24 20:23:41 -07002688 // check whether the intent can be resolved. If not, we will see
2689 // whether we can download it from the Market.
2690 if (getPackageManager().resolveActivity(intent, 0) == null) {
2691 String packagename = intent.getPackage();
2692 if (packagename != null) {
2693 intent = new Intent(Intent.ACTION_VIEW, Uri
2694 .parse("market://search?q=pname:" + packagename));
2695 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2696 startActivity(intent);
2697 return true;
2698 } else {
2699 return false;
2700 }
2701 }
2702
Dianne Hackborn99189432009-06-17 18:06:18 -07002703 // sanitize the Intent, ensuring web pages can not bypass browser
2704 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002705 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002706 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002707 try {
2708 if (startActivityIfNeeded(intent, -1)) {
2709 return true;
2710 }
2711 } catch (ActivityNotFoundException ex) {
2712 // ignore the error. If no application can handle the URL,
2713 // eg about:blank, assume the browser can handle it.
2714 }
2715
2716 if (mMenuIsDown) {
2717 openTab(url);
2718 closeOptionsMenu();
2719 return true;
2720 }
2721
2722 return false;
2723 }
2724
2725 /**
2726 * Updates the lock icon. This method is called when we discover another
2727 * resource to be loaded for this page (for example, javascript). While
2728 * we update the icon type, we do not update the lock icon itself until
2729 * we are done loading, it is slightly more secure this way.
2730 */
2731 @Override
2732 public void onLoadResource(WebView view, String url) {
2733 if (url != null && url.length() > 0) {
2734 // It is only if the page claims to be secure
2735 // that we may have to update the lock:
2736 if (mLockIconType == LOCK_ICON_SECURE) {
2737 // If NOT a 'safe' url, change the lock to mixed content!
2738 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2739 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002740 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002741 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2742 " updated lock icon to " + mLockIconType + " due to " + url);
2743 }
2744 }
2745 }
2746 }
2747 }
2748
2749 /**
2750 * Show the dialog, asking the user if they would like to continue after
2751 * an excessive number of HTTP redirects.
2752 */
2753 @Override
2754 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2755 final Message continueMsg) {
2756 new AlertDialog.Builder(BrowserActivity.this)
2757 .setTitle(R.string.browserFrameRedirect)
2758 .setMessage(R.string.browserFrame307Post)
2759 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2760 public void onClick(DialogInterface dialog, int which) {
2761 continueMsg.sendToTarget();
2762 }})
2763 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2764 public void onClick(DialogInterface dialog, int which) {
2765 cancelMsg.sendToTarget();
2766 }})
2767 .setOnCancelListener(new OnCancelListener() {
2768 public void onCancel(DialogInterface dialog) {
2769 cancelMsg.sendToTarget();
2770 }})
2771 .show();
2772 }
2773
Patrick Scott37911c72009-03-24 18:02:58 -07002774 // Container class for the next error dialog that needs to be
2775 // displayed.
2776 class ErrorDialog {
2777 public final int mTitle;
2778 public final String mDescription;
2779 public final int mError;
2780 ErrorDialog(int title, String desc, int error) {
2781 mTitle = title;
2782 mDescription = desc;
2783 mError = error;
2784 }
2785 };
2786
2787 private void processNextError() {
2788 if (mQueuedErrors == null) {
2789 return;
2790 }
2791 // The first one is currently displayed so just remove it.
2792 mQueuedErrors.removeFirst();
2793 if (mQueuedErrors.size() == 0) {
2794 mQueuedErrors = null;
2795 return;
2796 }
2797 showError(mQueuedErrors.getFirst());
2798 }
2799
2800 private DialogInterface.OnDismissListener mDialogListener =
2801 new DialogInterface.OnDismissListener() {
2802 public void onDismiss(DialogInterface d) {
2803 processNextError();
2804 }
2805 };
2806 private LinkedList<ErrorDialog> mQueuedErrors;
2807
2808 private void queueError(int err, String desc) {
2809 if (mQueuedErrors == null) {
2810 mQueuedErrors = new LinkedList<ErrorDialog>();
2811 }
2812 for (ErrorDialog d : mQueuedErrors) {
2813 if (d.mError == err) {
2814 // Already saw a similar error, ignore the new one.
2815 return;
2816 }
2817 }
2818 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002819 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002820 R.string.browserFrameFileErrorLabel :
2821 R.string.browserFrameNetworkErrorLabel,
2822 desc, err);
2823 mQueuedErrors.addLast(errDialog);
2824
2825 // Show the dialog now if the queue was empty.
2826 if (mQueuedErrors.size() == 1) {
2827 showError(errDialog);
2828 }
2829 }
2830
2831 private void showError(ErrorDialog errDialog) {
2832 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2833 .setTitle(errDialog.mTitle)
2834 .setMessage(errDialog.mDescription)
2835 .setPositiveButton(R.string.ok, null)
2836 .create();
2837 d.setOnDismissListener(mDialogListener);
2838 d.show();
2839 }
2840
The Android Open Source Project0c908882009-03-03 19:32:16 -08002841 /**
2842 * Show a dialog informing the user of the network error reported by
2843 * WebCore.
2844 */
2845 @Override
2846 public void onReceivedError(WebView view, int errorCode,
2847 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002848 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2849 errorCode != WebViewClient.ERROR_CONNECT &&
2850 errorCode != WebViewClient.ERROR_BAD_URL &&
2851 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2852 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002853 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002854 }
Patrick Scott37911c72009-03-24 18:02:58 -07002855 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2856 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002857
Ben Murdochaac7aa62009-09-17 16:57:40 +01002858 mNeedExtraScreenShot = true;
2859
The Android Open Source Project0c908882009-03-03 19:32:16 -08002860 // We need to reset the title after an error.
2861 resetTitleAndRevertLockIcon();
2862 }
2863
2864 /**
2865 * Check with the user if it is ok to resend POST data as the page they
2866 * are trying to navigate to is the result of a POST.
2867 */
2868 @Override
2869 public void onFormResubmission(WebView view, final Message dontResend,
2870 final Message resend) {
2871 new AlertDialog.Builder(BrowserActivity.this)
2872 .setTitle(R.string.browserFrameFormResubmitLabel)
2873 .setMessage(R.string.browserFrameFormResubmitMessage)
2874 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2875 public void onClick(DialogInterface dialog, int which) {
2876 resend.sendToTarget();
2877 }})
2878 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2879 public void onClick(DialogInterface dialog, int which) {
2880 dontResend.sendToTarget();
2881 }})
2882 .setOnCancelListener(new OnCancelListener() {
2883 public void onCancel(DialogInterface dialog) {
2884 dontResend.sendToTarget();
2885 }})
2886 .show();
2887 }
2888
2889 /**
2890 * Insert the url into the visited history database.
2891 * @param url The url to be inserted.
2892 * @param isReload True if this url is being reloaded.
2893 * FIXME: Not sure what to do when reloading the page.
2894 */
2895 @Override
2896 public void doUpdateVisitedHistory(WebView view, String url,
2897 boolean isReload) {
2898 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2899 return;
2900 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002901 // remove "client" before updating it to the history so that it wont
2902 // show up in the auto-complete list.
2903 int index = url.indexOf("client=ms-");
2904 if (index > 0 && url.contains(".google.")) {
2905 int end = url.indexOf('&', index);
2906 if (end > 0) {
2907 url = url.substring(0, index-1).concat(url.substring(end));
2908 } else {
2909 url = url.substring(0, index-1);
2910 }
2911 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002912 Browser.updateVisitedHistory(mResolver, url, true);
2913 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2914 }
2915
2916 /**
2917 * Displays SSL error(s) dialog to the user.
2918 */
2919 @Override
2920 public void onReceivedSslError(
2921 final WebView view, final SslErrorHandler handler, final SslError error) {
2922
2923 if (mSettings.showSecurityWarnings()) {
2924 final LayoutInflater factory =
2925 LayoutInflater.from(BrowserActivity.this);
2926 final View warningsView =
2927 factory.inflate(R.layout.ssl_warnings, null);
2928 final LinearLayout placeholder =
2929 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2930
2931 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2932 LinearLayout ll = (LinearLayout)factory
2933 .inflate(R.layout.ssl_warning, null);
2934 ((TextView)ll.findViewById(R.id.warning))
2935 .setText(R.string.ssl_untrusted);
2936 placeholder.addView(ll);
2937 }
2938
2939 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2940 LinearLayout ll = (LinearLayout)factory
2941 .inflate(R.layout.ssl_warning, null);
2942 ((TextView)ll.findViewById(R.id.warning))
2943 .setText(R.string.ssl_mismatch);
2944 placeholder.addView(ll);
2945 }
2946
2947 if (error.hasError(SslError.SSL_EXPIRED)) {
2948 LinearLayout ll = (LinearLayout)factory
2949 .inflate(R.layout.ssl_warning, null);
2950 ((TextView)ll.findViewById(R.id.warning))
2951 .setText(R.string.ssl_expired);
2952 placeholder.addView(ll);
2953 }
2954
2955 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2956 LinearLayout ll = (LinearLayout)factory
2957 .inflate(R.layout.ssl_warning, null);
2958 ((TextView)ll.findViewById(R.id.warning))
2959 .setText(R.string.ssl_not_yet_valid);
2960 placeholder.addView(ll);
2961 }
2962
2963 new AlertDialog.Builder(BrowserActivity.this)
2964 .setTitle(R.string.security_warning)
2965 .setIcon(android.R.drawable.ic_dialog_alert)
2966 .setView(warningsView)
2967 .setPositiveButton(R.string.ssl_continue,
2968 new DialogInterface.OnClickListener() {
2969 public void onClick(DialogInterface dialog, int whichButton) {
2970 handler.proceed();
2971 }
2972 })
2973 .setNeutralButton(R.string.view_certificate,
2974 new DialogInterface.OnClickListener() {
2975 public void onClick(DialogInterface dialog, int whichButton) {
2976 showSSLCertificateOnError(view, handler, error);
2977 }
2978 })
2979 .setNegativeButton(R.string.cancel,
2980 new DialogInterface.OnClickListener() {
2981 public void onClick(DialogInterface dialog, int whichButton) {
2982 handler.cancel();
2983 BrowserActivity.this.resetTitleAndRevertLockIcon();
2984 }
2985 })
2986 .setOnCancelListener(
2987 new DialogInterface.OnCancelListener() {
2988 public void onCancel(DialogInterface dialog) {
2989 handler.cancel();
2990 BrowserActivity.this.resetTitleAndRevertLockIcon();
2991 }
2992 })
2993 .show();
2994 } else {
2995 handler.proceed();
2996 }
2997 }
2998
2999 /**
3000 * Handles an HTTP authentication request.
3001 *
3002 * @param handler The authentication handler
3003 * @param host The host
3004 * @param realm The realm
3005 */
3006 @Override
3007 public void onReceivedHttpAuthRequest(WebView view,
3008 final HttpAuthHandler handler, final String host, final String realm) {
3009 String username = null;
3010 String password = null;
3011
3012 boolean reuseHttpAuthUsernamePassword =
3013 handler.useHttpAuthUsernamePassword();
3014
3015 if (reuseHttpAuthUsernamePassword &&
3016 (mTabControl.getCurrentWebView() != null)) {
3017 String[] credentials =
3018 mTabControl.getCurrentWebView()
3019 .getHttpAuthUsernamePassword(host, realm);
3020 if (credentials != null && credentials.length == 2) {
3021 username = credentials[0];
3022 password = credentials[1];
3023 }
3024 }
3025
3026 if (username != null && password != null) {
3027 handler.proceed(username, password);
3028 } else {
3029 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3030 }
3031 }
3032
3033 @Override
3034 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3035 if (mMenuIsDown) {
3036 // only check shortcut key when MENU is held
3037 return getWindow().isShortcutKey(event.getKeyCode(), event);
3038 } else {
3039 return false;
3040 }
3041 }
3042
3043 @Override
3044 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3045 if (view != mTabControl.getCurrentTopWebView()) {
3046 return;
3047 }
3048 if (event.isDown()) {
3049 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3050 } else {
3051 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3052 }
3053 }
3054 };
3055
3056 //--------------------------------------------------------------------------
3057 // WebChromeClient implementation
3058 //--------------------------------------------------------------------------
3059
3060 /* package */ WebChromeClient getWebChromeClient() {
3061 return mWebChromeClient;
3062 }
3063
3064 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3065 // Helper method to create a new tab or sub window.
3066 private void createWindow(final boolean dialog, final Message msg) {
3067 if (dialog) {
3068 mTabControl.createSubWindow();
3069 final TabControl.Tab t = mTabControl.getCurrentTab();
3070 attachSubWindow(t);
3071 WebView.WebViewTransport transport =
3072 (WebView.WebViewTransport) msg.obj;
3073 transport.setWebView(t.getSubWebView());
3074 msg.sendToTarget();
3075 } else {
3076 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003077 final TabControl.Tab newTab
3078 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07003079 if (newTab != parent) {
3080 parent.addChildTab(newTab);
3081 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003082 WebView.WebViewTransport transport =
3083 (WebView.WebViewTransport) msg.obj;
3084 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04003085 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003086 }
3087 }
3088
3089 @Override
3090 public boolean onCreateWindow(WebView view, final boolean dialog,
3091 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003092 // Short-circuit if we can't create any more tabs or sub windows.
3093 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3094 new AlertDialog.Builder(BrowserActivity.this)
3095 .setTitle(R.string.too_many_subwindows_dialog_title)
3096 .setIcon(android.R.drawable.ic_dialog_alert)
3097 .setMessage(R.string.too_many_subwindows_dialog_message)
3098 .setPositiveButton(R.string.ok, null)
3099 .show();
3100 return false;
3101 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3102 new AlertDialog.Builder(BrowserActivity.this)
3103 .setTitle(R.string.too_many_windows_dialog_title)
3104 .setIcon(android.R.drawable.ic_dialog_alert)
3105 .setMessage(R.string.too_many_windows_dialog_message)
3106 .setPositiveButton(R.string.ok, null)
3107 .show();
3108 return false;
3109 }
3110
3111 // Short-circuit if this was a user gesture.
3112 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003113 createWindow(dialog, resultMsg);
3114 return true;
3115 }
3116
3117 // Allow the popup and create the appropriate window.
3118 final AlertDialog.OnClickListener allowListener =
3119 new AlertDialog.OnClickListener() {
3120 public void onClick(DialogInterface d,
3121 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003122 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003123 }
3124 };
3125
3126 // Block the popup by returning a null WebView.
3127 final AlertDialog.OnClickListener blockListener =
3128 new AlertDialog.OnClickListener() {
3129 public void onClick(DialogInterface d, int which) {
3130 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003131 }
3132 };
3133
3134 // Build a confirmation dialog to display to the user.
3135 final AlertDialog d =
3136 new AlertDialog.Builder(BrowserActivity.this)
3137 .setTitle(R.string.attention)
3138 .setIcon(android.R.drawable.ic_dialog_alert)
3139 .setMessage(R.string.popup_window_attempt)
3140 .setPositiveButton(R.string.allow, allowListener)
3141 .setNegativeButton(R.string.block, blockListener)
3142 .setCancelable(false)
3143 .create();
3144
3145 // Show the confirmation dialog.
3146 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003147 return true;
3148 }
3149
3150 @Override
3151 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003152 final TabControl.Tab current = mTabControl.getCurrentTab();
3153 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003154 if (parent != null) {
3155 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003156 switchToTab(mTabControl.getTabIndex(parent));
3157 // Now we need to close the window
3158 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003159 }
3160 }
3161
3162 @Override
3163 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003164 mTitleBar.setProgress(newProgress);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003165 if (mFakeTitleBar != null) {
3166 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003167 }
3168
3169 if (newProgress == 100) {
Ben Murdochaac7aa62009-09-17 16:57:40 +01003170 // onProgressChanged() may continue to be called after the main
3171 // frame has finished loading, as any remaining sub frames
3172 // continue to load. We'll only get called once though with
3173 // newProgress as 100 when everything is loaded.
3174 // (onPageFinished is called once when the main frame completes
3175 // loading regardless of the state of any sub frames so calls
3176 // to onProgressChanges may continue after onPageFinished has
3177 // executed)
3178
3179 // sync cookies and cache promptly here.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003180 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003181 if (mInLoad) {
3182 mInLoad = false;
3183 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003184 // If the options menu is open, leave the title bar
3185 if (!mOptionsMenuOpen || !mIconView) {
3186 hideFakeTitleBar();
3187 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003188 }
Ben Murdochaac7aa62009-09-17 16:57:40 +01003189 if (mNeedExtraScreenShot) {
3190 // if there was an error loading this page, capture a new
3191 // screenshot to ensure that we get the correct thumbnail
3192 // as onPageFinished may have been called before the error
3193 // page was displayed.
3194 updateScreenshot(view);
3195 mNeedExtraScreenShot = false;
3196 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003197 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003198 // onPageFinished may have already been called but a subframe
3199 // is still loading and updating the progress. Reset mInLoad
3200 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003201 mInLoad = true;
3202 updateInLoadMenuItems();
Leon Scroggins184f5e32009-09-21 10:38:24 -04003203 if (!mOptionsMenuOpen || mIconView) {
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003204 // This page has begun to load, so show the title bar
3205 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003206 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003207 }
3208 }
3209
3210 @Override
3211 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003212 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003213
3214 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003215 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003216
3217 if (url == null ||
3218 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3219 return;
3220 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003221 // See if we can find the current url in our history database and
3222 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003223 if (url.startsWith("http://www.")) {
3224 url = url.substring(11);
3225 } else if (url.startsWith("http://")) {
3226 url = url.substring(4);
3227 }
3228 try {
3229 url = "%" + url;
3230 String [] selArgs = new String[] { url };
3231
3232 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3233 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3234 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3235 Browser.HISTORY_PROJECTION, where, selArgs, null);
3236 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003237 // Current implementation of database only has one entry per
3238 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003239 ContentValues map = new ContentValues();
3240 map.put(Browser.BookmarkColumns.TITLE, title);
3241 mResolver.update(Browser.BOOKMARKS_URI, map,
3242 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003243 }
3244 c.close();
3245 } catch (IllegalStateException e) {
3246 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3247 } catch (SQLiteException ex) {
3248 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3249 }
3250 }
3251
3252 @Override
3253 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003254 updateIcon(view, icon);
3255 }
3256
3257 @Override
Patrick Scott59ce8302009-09-18 16:29:38 -04003258 public void onReceivedTouchIconUrl(WebView view, String url,
3259 boolean precomposed) {
Patrick Scott3918d442009-08-04 13:22:29 -04003260 final ContentResolver cr = getContentResolver();
3261 final Cursor c =
3262 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003263 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003264 if (c != null) {
3265 if (c.getCount() > 0) {
Patrick Scott59ce8302009-09-18 16:29:38 -04003266 // Let precomposed icons take precedence over non-composed
3267 // icons.
3268 if (precomposed && mTouchIconLoader != null) {
3269 mTouchIconLoader.cancel(false);
3270 mTouchIconLoader = null;
3271 }
3272 // Have only one async task at a time.
3273 if (mTouchIconLoader == null) {
3274 mTouchIconLoader = new DownloadTouchIcon(
3275 BrowserActivity.this, cr, c, view);
3276 mTouchIconLoader.execute(url);
3277 }
Patrick Scott3918d442009-08-04 13:22:29 -04003278 } else {
3279 c.close();
3280 }
3281 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003282 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003283
Andrei Popescuadc008d2009-06-26 14:11:30 +01003284 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003285 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003286 if (mCustomView != null)
3287 return;
3288
3289 // Add the custom view to its container.
3290 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3291 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003292 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003293 // Save the menu state and set it to empty while the custom
3294 // view is showing.
3295 mOldMenuState = mMenuState;
3296 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003297 // Hide the content view.
3298 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003299 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003300 mCustomViewContainer.setVisibility(View.VISIBLE);
3301 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003302 }
3303
3304 @Override
3305 public void onHideCustomView() {
3306 if (mCustomView == null)
3307 return;
3308
Andrei Popescuc9b55562009-07-07 10:51:15 +01003309 // Hide the custom view.
3310 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003311 // Remove the custom view from its container.
3312 mCustomViewContainer.removeView(mCustomView);
3313 mCustomView = null;
3314 // Reset the old menu state.
3315 mMenuState = mOldMenuState;
3316 mOldMenuState = EMPTY_MENU;
3317 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003318 mCustomViewCallback.onCustomViewHidden();
3319 // Show the content view.
3320 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003321 }
3322
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003323 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003324 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003325 * @param url the URL that exceeded the quota
3326 * @param databaseIdentifier the identifier of the database on
3327 * which the transaction that caused the quota overflow was run
3328 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003329 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003330 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003331 * @param quotaUpdater The callback to run when a decision to allow or
3332 * deny quota has been made. Don't forget to call this!
3333 */
3334 @Override
3335 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003336 String databaseIdentifier, long currentQuota, long estimatedSize,
3337 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003338 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003339 url, databaseIdentifier, currentQuota, estimatedSize,
3340 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003341 }
3342
3343 /**
3344 * The Application Cache has exceeded its max size.
3345 * @param spaceNeeded is the amount of disk space that would be needed
3346 * in order for the last appcache operation to succeed.
3347 * @param totalUsedQuota is the sum of all origins' quota.
3348 * @param quotaUpdater A callback to inform the WebCore thread that a new
3349 * app cache size is available. This callback must always be executed at
3350 * some point to ensure that the sleeping WebCore thread is woken up.
3351 */
3352 @Override
3353 public void onReachedMaxAppCacheSize(long spaceNeeded,
3354 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3355 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3356 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003357 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003358
Steve Block2bc69912009-07-30 14:45:13 +01003359 /**
3360 * Instructs the browser to show a prompt to ask the user to set the
3361 * Geolocation permission state for the specified origin.
3362 * @param origin The origin for which Geolocation permissions are
3363 * requested.
3364 * @param callback The callback to call once the user has set the
3365 * Geolocation permission state.
3366 */
3367 @Override
3368 public void onGeolocationPermissionsShowPrompt(String origin,
3369 GeolocationPermissions.Callback callback) {
3370 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3371 origin, callback);
3372 }
3373
3374 /**
3375 * Instructs the browser to hide the Geolocation permissions prompt.
3376 */
3377 @Override
3378 public void onGeolocationPermissionsHidePrompt() {
3379 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3380 }
3381
Ben Murdoch7db26342009-06-03 18:21:19 +01003382 /* Adds a JavaScript error message to the system log.
3383 * @param message The error message to report.
3384 * @param lineNumber The line number of the error.
3385 * @param sourceID The name of the source file that caused the error.
3386 */
3387 @Override
3388 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003389 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3390 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3391 if (mShouldShowErrorConsole &&
3392 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3393 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3394 }
3395 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003396 }
Andrei Popescu540035d2009-09-18 18:59:20 +01003397
3398 /**
3399 * Ask the browser for an icon to represent a <video> element.
3400 * This icon will be used if the Web page did not specify a poster attribute.
3401 *
3402 * @return Bitmap The icon or null if no such icon is available.
3403 * @hide pending API Council approval
3404 */
3405 @Override
3406 public Bitmap getDefaultVideoPoster() {
3407 if (mDefaultVideoPoster == null) {
3408 mDefaultVideoPoster = BitmapFactory.decodeResource(
3409 getResources(), R.drawable.default_video_poster);
3410 }
3411 return mDefaultVideoPoster;
3412 }
3413
3414 /**
3415 * Ask the host application for a custom progress view to show while
3416 * a <video> is loading.
3417 *
3418 * @return View The progress view.
3419 * @hide pending API Council approval
3420 */
3421 @Override
3422 public View getVideoLoadingProgressView() {
3423 if (mVideoProgressView == null) {
3424 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
3425 mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
3426 }
3427 return mVideoProgressView;
3428 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003429 };
3430
3431 /**
3432 * Notify the host application a download should be done, or that
3433 * the data should be streamed if a streaming viewer is available.
3434 * @param url The full url to the content that should be downloaded
3435 * @param contentDisposition Content-disposition http header, if
3436 * present.
3437 * @param mimetype The mimetype of the content reported by the server
3438 * @param contentLength The file size reported by the server
3439 */
3440 public void onDownloadStart(String url, String userAgent,
3441 String contentDisposition, String mimetype, long contentLength) {
3442 // if we're dealing wih A/V content that's not explicitly marked
3443 // for download, check if it's streamable.
3444 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003445 || !contentDisposition.regionMatches(
3446 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003447 // query the package manager to see if there's a registered handler
3448 // that matches.
3449 Intent intent = new Intent(Intent.ACTION_VIEW);
3450 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003451 ResolveInfo info = getPackageManager().resolveActivity(intent,
3452 PackageManager.MATCH_DEFAULT_ONLY);
3453 if (info != null) {
3454 ComponentName myName = getComponentName();
3455 // If we resolved to ourselves, we don't want to attempt to
3456 // load the url only to try and download it again.
3457 if (!myName.getPackageName().equals(
3458 info.activityInfo.packageName)
3459 || !myName.getClassName().equals(
3460 info.activityInfo.name)) {
3461 // someone (other than us) knows how to handle this mime
3462 // type with this scheme, don't download.
3463 try {
3464 startActivity(intent);
3465 return;
3466 } catch (ActivityNotFoundException ex) {
3467 if (LOGD_ENABLED) {
3468 Log.d(LOGTAG, "activity not found for " + mimetype
3469 + " over " + Uri.parse(url).getScheme(),
3470 ex);
3471 }
3472 // Best behavior is to fall back to a download in this
3473 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003474 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003475 }
3476 }
3477 }
3478 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3479 }
3480
3481 /**
3482 * Notify the host application a download should be done, even if there
3483 * is a streaming viewer available for thise type.
3484 * @param url The full url to the content that should be downloaded
3485 * @param contentDisposition Content-disposition http header, if
3486 * present.
3487 * @param mimetype The mimetype of the content reported by the server
3488 * @param contentLength The file size reported by the server
3489 */
3490 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3491 String contentDisposition, String mimetype, long contentLength) {
3492
3493 String filename = URLUtil.guessFileName(url,
3494 contentDisposition, mimetype);
3495
3496 // Check to see if we have an SDCard
3497 String status = Environment.getExternalStorageState();
3498 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3499 int title;
3500 String msg;
3501
3502 // Check to see if the SDCard is busy, same as the music app
3503 if (status.equals(Environment.MEDIA_SHARED)) {
3504 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3505 title = R.string.download_sdcard_busy_dlg_title;
3506 } else {
3507 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3508 title = R.string.download_no_sdcard_dlg_title;
3509 }
3510
3511 new AlertDialog.Builder(this)
3512 .setTitle(title)
3513 .setIcon(android.R.drawable.ic_dialog_alert)
3514 .setMessage(msg)
3515 .setPositiveButton(R.string.ok, null)
3516 .show();
3517 return;
3518 }
3519
3520 // java.net.URI is a lot stricter than KURL so we have to undo
3521 // KURL's percent-encoding and redo the encoding using java.net.URI.
3522 URI uri = null;
3523 try {
3524 // Undo the percent-encoding that KURL may have done.
3525 String newUrl = new String(URLUtil.decode(url.getBytes()));
3526 // Parse the url into pieces
3527 WebAddress w = new WebAddress(newUrl);
3528 String frag = null;
3529 String query = null;
3530 String path = w.mPath;
3531 // Break the path into path, query, and fragment
3532 if (path.length() > 0) {
3533 // Strip the fragment
3534 int idx = path.lastIndexOf('#');
3535 if (idx != -1) {
3536 frag = path.substring(idx + 1);
3537 path = path.substring(0, idx);
3538 }
3539 idx = path.lastIndexOf('?');
3540 if (idx != -1) {
3541 query = path.substring(idx + 1);
3542 path = path.substring(0, idx);
3543 }
3544 }
3545 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3546 query, frag);
3547 } catch (Exception e) {
3548 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3549 return;
3550 }
3551
3552 // XXX: Have to use the old url since the cookies were stored using the
3553 // old percent-encoded url.
3554 String cookies = CookieManager.getInstance().getCookie(url);
3555
3556 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003557 values.put(Downloads.COLUMN_URI, uri.toString());
3558 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3559 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3560 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003561 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003562 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003563 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003564 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3565 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3566 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3567 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003568 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003569 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003570 }
3571 if (mimetype == null) {
3572 // We must have long pressed on a link or image to download it. We
3573 // are not sure of the mimetype in this case, so do a head request
3574 new FetchUrlMimeType(this).execute(values);
3575 } else {
3576 final Uri contentUri =
3577 getContentResolver().insert(Downloads.CONTENT_URI, values);
3578 viewDownloads(contentUri);
3579 }
3580
3581 }
3582
3583 /**
3584 * Resets the lock icon. This method is called when we start a new load and
3585 * know the url to be loaded.
3586 */
3587 private void resetLockIcon(String url) {
3588 // Save the lock-icon state (we revert to it if the load gets cancelled)
3589 saveLockIcon();
3590
3591 mLockIconType = LOCK_ICON_UNSECURE;
3592 if (URLUtil.isHttpsUrl(url)) {
3593 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003594 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003595 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3596 " reset lock icon to " + mLockIconType);
3597 }
3598 }
3599
3600 updateLockIconImage(LOCK_ICON_UNSECURE);
3601 }
3602
Grace Klobaeb6eef42009-09-15 17:56:32 -07003603 /* package */ void setLockIconType(int type) {
3604 mLockIconType = type;
3605 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003606
Grace Klobaeb6eef42009-09-15 17:56:32 -07003607 /* package */ int getLockIconType() {
3608 return mLockIconType;
3609 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003610
Grace Klobaeb6eef42009-09-15 17:56:32 -07003611 /* package */ void setPrevLockType(int type) {
3612 mPrevLockType = type;
3613 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003614
Grace Klobaeb6eef42009-09-15 17:56:32 -07003615 /* package */ int getPrevLockType() {
3616 return mPrevLockType;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003617 }
3618
3619 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003620 * Update the lock icon to correspond to our latest state.
3621 */
3622 /* package */ void updateLockIconToLatest() {
3623 updateLockIconImage(mLockIconType);
3624 }
3625
3626 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003627 * Updates the lock-icon image in the title-bar.
3628 */
3629 private void updateLockIconImage(int lockIconType) {
3630 Drawable d = null;
3631 if (lockIconType == LOCK_ICON_SECURE) {
3632 d = mSecLockIcon;
3633 } else if (lockIconType == LOCK_ICON_MIXED) {
3634 d = mMixLockIcon;
3635 }
Leon Scroggins68579392009-09-15 15:31:54 -04003636 mTitleBar.setLock(d);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003637 if (mFakeTitleBar != null) {
3638 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003639 }
3640 }
3641
3642 /**
3643 * Displays a page-info dialog.
3644 * @param tab The tab to show info about
3645 * @param fromShowSSLCertificateOnError The flag that indicates whether
3646 * this dialog was opened from the SSL-certificate-on-error dialog or
3647 * not. This is important, since we need to know whether to return to
3648 * the parent dialog or simply dismiss.
3649 */
3650 private void showPageInfo(final TabControl.Tab tab,
3651 final boolean fromShowSSLCertificateOnError) {
3652 final LayoutInflater factory = LayoutInflater
3653 .from(this);
3654
3655 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3656
3657 final WebView view = tab.getWebView();
3658
3659 String url = null;
3660 String title = null;
3661
3662 if (view == null) {
3663 url = tab.getUrl();
3664 title = tab.getTitle();
3665 } else if (view == mTabControl.getCurrentWebView()) {
3666 // Use the cached title and url if this is the current WebView
3667 url = mUrl;
3668 title = mTitle;
3669 } else {
3670 url = view.getUrl();
3671 title = view.getTitle();
3672 }
3673
3674 if (url == null) {
3675 url = "";
3676 }
3677 if (title == null) {
3678 title = "";
3679 }
3680
3681 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3682 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3683
3684 mPageInfoView = tab;
3685 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3686
3687 AlertDialog.Builder alertDialogBuilder =
3688 new AlertDialog.Builder(this)
3689 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3690 .setView(pageInfoView)
3691 .setPositiveButton(
3692 R.string.ok,
3693 new DialogInterface.OnClickListener() {
3694 public void onClick(DialogInterface dialog,
3695 int whichButton) {
3696 mPageInfoDialog = null;
3697 mPageInfoView = null;
3698 mPageInfoFromShowSSLCertificateOnError = null;
3699
3700 // if we came here from the SSL error dialog
3701 if (fromShowSSLCertificateOnError) {
3702 // go back to the SSL error dialog
3703 showSSLCertificateOnError(
3704 mSSLCertificateOnErrorView,
3705 mSSLCertificateOnErrorHandler,
3706 mSSLCertificateOnErrorError);
3707 }
3708 }
3709 })
3710 .setOnCancelListener(
3711 new DialogInterface.OnCancelListener() {
3712 public void onCancel(DialogInterface dialog) {
3713 mPageInfoDialog = null;
3714 mPageInfoView = null;
3715 mPageInfoFromShowSSLCertificateOnError = null;
3716
3717 // if we came here from the SSL error dialog
3718 if (fromShowSSLCertificateOnError) {
3719 // go back to the SSL error dialog
3720 showSSLCertificateOnError(
3721 mSSLCertificateOnErrorView,
3722 mSSLCertificateOnErrorHandler,
3723 mSSLCertificateOnErrorError);
3724 }
3725 }
3726 });
3727
3728 // if we have a main top-level page SSL certificate set or a certificate
3729 // error
3730 if (fromShowSSLCertificateOnError ||
3731 (view != null && view.getCertificate() != null)) {
3732 // add a 'View Certificate' button
3733 alertDialogBuilder.setNeutralButton(
3734 R.string.view_certificate,
3735 new DialogInterface.OnClickListener() {
3736 public void onClick(DialogInterface dialog,
3737 int whichButton) {
3738 mPageInfoDialog = null;
3739 mPageInfoView = null;
3740 mPageInfoFromShowSSLCertificateOnError = null;
3741
3742 // if we came here from the SSL error dialog
3743 if (fromShowSSLCertificateOnError) {
3744 // go back to the SSL error dialog
3745 showSSLCertificateOnError(
3746 mSSLCertificateOnErrorView,
3747 mSSLCertificateOnErrorHandler,
3748 mSSLCertificateOnErrorError);
3749 } else {
3750 // otherwise, display the top-most certificate from
3751 // the chain
3752 if (view.getCertificate() != null) {
3753 showSSLCertificate(tab);
3754 }
3755 }
3756 }
3757 });
3758 }
3759
3760 mPageInfoDialog = alertDialogBuilder.show();
3761 }
3762
3763 /**
3764 * Displays the main top-level page SSL certificate dialog
3765 * (accessible from the Page-Info dialog).
3766 * @param tab The tab to show certificate for.
3767 */
3768 private void showSSLCertificate(final TabControl.Tab tab) {
3769 final View certificateView =
3770 inflateCertificateView(tab.getWebView().getCertificate());
3771 if (certificateView == null) {
3772 return;
3773 }
3774
3775 LayoutInflater factory = LayoutInflater.from(this);
3776
3777 final LinearLayout placeholder =
3778 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3779
3780 LinearLayout ll = (LinearLayout) factory.inflate(
3781 R.layout.ssl_success, placeholder);
3782 ((TextView)ll.findViewById(R.id.success))
3783 .setText(R.string.ssl_certificate_is_valid);
3784
3785 mSSLCertificateView = tab;
3786 mSSLCertificateDialog =
3787 new AlertDialog.Builder(this)
3788 .setTitle(R.string.ssl_certificate).setIcon(
3789 R.drawable.ic_dialog_browser_certificate_secure)
3790 .setView(certificateView)
3791 .setPositiveButton(R.string.ok,
3792 new DialogInterface.OnClickListener() {
3793 public void onClick(DialogInterface dialog,
3794 int whichButton) {
3795 mSSLCertificateDialog = null;
3796 mSSLCertificateView = null;
3797
3798 showPageInfo(tab, false);
3799 }
3800 })
3801 .setOnCancelListener(
3802 new DialogInterface.OnCancelListener() {
3803 public void onCancel(DialogInterface dialog) {
3804 mSSLCertificateDialog = null;
3805 mSSLCertificateView = null;
3806
3807 showPageInfo(tab, false);
3808 }
3809 })
3810 .show();
3811 }
3812
3813 /**
3814 * Displays the SSL error certificate dialog.
3815 * @param view The target web-view.
3816 * @param handler The SSL error handler responsible for cancelling the
3817 * connection that resulted in an SSL error or proceeding per user request.
3818 * @param error The SSL error object.
3819 */
3820 private void showSSLCertificateOnError(
3821 final WebView view, final SslErrorHandler handler, final SslError error) {
3822
3823 final View certificateView =
3824 inflateCertificateView(error.getCertificate());
3825 if (certificateView == null) {
3826 return;
3827 }
3828
3829 LayoutInflater factory = LayoutInflater.from(this);
3830
3831 final LinearLayout placeholder =
3832 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3833
3834 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3835 LinearLayout ll = (LinearLayout)factory
3836 .inflate(R.layout.ssl_warning, placeholder);
3837 ((TextView)ll.findViewById(R.id.warning))
3838 .setText(R.string.ssl_untrusted);
3839 }
3840
3841 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3842 LinearLayout ll = (LinearLayout)factory
3843 .inflate(R.layout.ssl_warning, placeholder);
3844 ((TextView)ll.findViewById(R.id.warning))
3845 .setText(R.string.ssl_mismatch);
3846 }
3847
3848 if (error.hasError(SslError.SSL_EXPIRED)) {
3849 LinearLayout ll = (LinearLayout)factory
3850 .inflate(R.layout.ssl_warning, placeholder);
3851 ((TextView)ll.findViewById(R.id.warning))
3852 .setText(R.string.ssl_expired);
3853 }
3854
3855 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3856 LinearLayout ll = (LinearLayout)factory
3857 .inflate(R.layout.ssl_warning, placeholder);
3858 ((TextView)ll.findViewById(R.id.warning))
3859 .setText(R.string.ssl_not_yet_valid);
3860 }
3861
3862 mSSLCertificateOnErrorHandler = handler;
3863 mSSLCertificateOnErrorView = view;
3864 mSSLCertificateOnErrorError = error;
3865 mSSLCertificateOnErrorDialog =
3866 new AlertDialog.Builder(this)
3867 .setTitle(R.string.ssl_certificate).setIcon(
3868 R.drawable.ic_dialog_browser_certificate_partially_secure)
3869 .setView(certificateView)
3870 .setPositiveButton(R.string.ok,
3871 new DialogInterface.OnClickListener() {
3872 public void onClick(DialogInterface dialog,
3873 int whichButton) {
3874 mSSLCertificateOnErrorDialog = null;
3875 mSSLCertificateOnErrorView = null;
3876 mSSLCertificateOnErrorHandler = null;
3877 mSSLCertificateOnErrorError = null;
3878
3879 mWebViewClient.onReceivedSslError(
3880 view, handler, error);
3881 }
3882 })
3883 .setNeutralButton(R.string.page_info_view,
3884 new DialogInterface.OnClickListener() {
3885 public void onClick(DialogInterface dialog,
3886 int whichButton) {
3887 mSSLCertificateOnErrorDialog = null;
3888
3889 // do not clear the dialog state: we will
3890 // need to show the dialog again once the
3891 // user is done exploring the page-info details
3892
3893 showPageInfo(mTabControl.getTabFromView(view),
3894 true);
3895 }
3896 })
3897 .setOnCancelListener(
3898 new DialogInterface.OnCancelListener() {
3899 public void onCancel(DialogInterface dialog) {
3900 mSSLCertificateOnErrorDialog = null;
3901 mSSLCertificateOnErrorView = null;
3902 mSSLCertificateOnErrorHandler = null;
3903 mSSLCertificateOnErrorError = null;
3904
3905 mWebViewClient.onReceivedSslError(
3906 view, handler, error);
3907 }
3908 })
3909 .show();
3910 }
3911
3912 /**
3913 * Inflates the SSL certificate view (helper method).
3914 * @param certificate The SSL certificate.
3915 * @return The resultant certificate view with issued-to, issued-by,
3916 * issued-on, expires-on, and possibly other fields set.
3917 * If the input certificate is null, returns null.
3918 */
3919 private View inflateCertificateView(SslCertificate certificate) {
3920 if (certificate == null) {
3921 return null;
3922 }
3923
3924 LayoutInflater factory = LayoutInflater.from(this);
3925
3926 View certificateView = factory.inflate(
3927 R.layout.ssl_certificate, null);
3928
3929 // issued to:
3930 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3931 if (issuedTo != null) {
3932 ((TextView) certificateView.findViewById(R.id.to_common))
3933 .setText(issuedTo.getCName());
3934 ((TextView) certificateView.findViewById(R.id.to_org))
3935 .setText(issuedTo.getOName());
3936 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3937 .setText(issuedTo.getUName());
3938 }
3939
3940 // issued by:
3941 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3942 if (issuedBy != null) {
3943 ((TextView) certificateView.findViewById(R.id.by_common))
3944 .setText(issuedBy.getCName());
3945 ((TextView) certificateView.findViewById(R.id.by_org))
3946 .setText(issuedBy.getOName());
3947 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3948 .setText(issuedBy.getUName());
3949 }
3950
3951 // issued on:
3952 String issuedOn = reformatCertificateDate(
3953 certificate.getValidNotBefore());
3954 ((TextView) certificateView.findViewById(R.id.issued_on))
3955 .setText(issuedOn);
3956
3957 // expires on:
3958 String expiresOn = reformatCertificateDate(
3959 certificate.getValidNotAfter());
3960 ((TextView) certificateView.findViewById(R.id.expires_on))
3961 .setText(expiresOn);
3962
3963 return certificateView;
3964 }
3965
3966 /**
3967 * Re-formats the certificate date (Date.toString()) string to
3968 * a properly localized date string.
3969 * @return Properly localized version of the certificate date string and
3970 * the original certificate date string if fails to localize.
3971 * If the original string is null, returns an empty string "".
3972 */
3973 private String reformatCertificateDate(String certificateDate) {
3974 String reformattedDate = null;
3975
3976 if (certificateDate != null) {
3977 Date date = null;
3978 try {
3979 date = java.text.DateFormat.getInstance().parse(certificateDate);
3980 } catch (ParseException e) {
3981 date = null;
3982 }
3983
3984 if (date != null) {
3985 reformattedDate =
3986 DateFormat.getDateFormat(this).format(date);
3987 }
3988 }
3989
3990 return reformattedDate != null ? reformattedDate :
3991 (certificateDate != null ? certificateDate : "");
3992 }
3993
3994 /**
3995 * Displays an http-authentication dialog.
3996 */
3997 private void showHttpAuthentication(final HttpAuthHandler handler,
3998 final String host, final String realm, final String title,
3999 final String name, final String password, int focusId) {
4000 LayoutInflater factory = LayoutInflater.from(this);
4001 final View v = factory
4002 .inflate(R.layout.http_authentication, null);
4003 if (name != null) {
4004 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4005 }
4006 if (password != null) {
4007 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4008 }
4009
4010 String titleText = title;
4011 if (titleText == null) {
4012 titleText = getText(R.string.sign_in_to).toString().replace(
4013 "%s1", host).replace("%s2", realm);
4014 }
4015
4016 mHttpAuthHandler = handler;
4017 AlertDialog dialog = new AlertDialog.Builder(this)
4018 .setTitle(titleText)
4019 .setIcon(android.R.drawable.ic_dialog_alert)
4020 .setView(v)
4021 .setPositiveButton(R.string.action,
4022 new DialogInterface.OnClickListener() {
4023 public void onClick(DialogInterface dialog,
4024 int whichButton) {
4025 String nm = ((EditText) v
4026 .findViewById(R.id.username_edit))
4027 .getText().toString();
4028 String pw = ((EditText) v
4029 .findViewById(R.id.password_edit))
4030 .getText().toString();
4031 BrowserActivity.this.setHttpAuthUsernamePassword
4032 (host, realm, nm, pw);
4033 handler.proceed(nm, pw);
4034 mHttpAuthenticationDialog = null;
4035 mHttpAuthHandler = null;
4036 }})
4037 .setNegativeButton(R.string.cancel,
4038 new DialogInterface.OnClickListener() {
4039 public void onClick(DialogInterface dialog,
4040 int whichButton) {
4041 handler.cancel();
4042 BrowserActivity.this.resetTitleAndRevertLockIcon();
4043 mHttpAuthenticationDialog = null;
4044 mHttpAuthHandler = null;
4045 }})
4046 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4047 public void onCancel(DialogInterface dialog) {
4048 handler.cancel();
4049 BrowserActivity.this.resetTitleAndRevertLockIcon();
4050 mHttpAuthenticationDialog = null;
4051 mHttpAuthHandler = null;
4052 }})
4053 .create();
4054 // Make the IME appear when the dialog is displayed if applicable.
4055 dialog.getWindow().setSoftInputMode(
4056 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4057 dialog.show();
4058 if (focusId != 0) {
4059 dialog.findViewById(focusId).requestFocus();
4060 } else {
4061 v.findViewById(R.id.username_edit).requestFocus();
4062 }
4063 mHttpAuthenticationDialog = dialog;
4064 }
4065
4066 public int getProgress() {
4067 WebView w = mTabControl.getCurrentWebView();
4068 if (w != null) {
4069 return w.getProgress();
4070 } else {
4071 return 100;
4072 }
4073 }
4074
4075 /**
4076 * Set HTTP authentication password.
4077 *
4078 * @param host The host for the password
4079 * @param realm The realm for the password
4080 * @param username The username for the password. If it is null, it means
4081 * password can't be saved.
4082 * @param password The password
4083 */
4084 public void setHttpAuthUsernamePassword(String host, String realm,
4085 String username,
4086 String password) {
4087 WebView w = mTabControl.getCurrentWebView();
4088 if (w != null) {
4089 w.setHttpAuthUsernamePassword(host, realm, username, password);
4090 }
4091 }
4092
4093 /**
4094 * connectivity manager says net has come or gone... inform the user
4095 * @param up true if net has come up, false if net has gone down
4096 */
4097 public void onNetworkToggle(boolean up) {
4098 if (up == mIsNetworkUp) {
4099 return;
4100 } else if (up) {
4101 mIsNetworkUp = true;
4102 if (mAlertDialog != null) {
4103 mAlertDialog.cancel();
4104 mAlertDialog = null;
4105 }
4106 } else {
4107 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004108 if (mInLoad) {
4109 createAndShowNetworkDialog();
4110 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004111 }
4112 WebView w = mTabControl.getCurrentWebView();
4113 if (w != null) {
4114 w.setNetworkAvailable(up);
4115 }
4116 }
4117
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004118 // This method shows the network dialog alerting the user that the net is
4119 // down. It will only show the dialog if mAlertDialog is null.
4120 private void createAndShowNetworkDialog() {
4121 if (mAlertDialog == null) {
4122 mAlertDialog = new AlertDialog.Builder(this)
4123 .setTitle(R.string.loadSuspendedTitle)
4124 .setMessage(R.string.loadSuspended)
4125 .setPositiveButton(R.string.ok, null)
4126 .show();
4127 }
4128 }
4129
The Android Open Source Project0c908882009-03-03 19:32:16 -08004130 @Override
4131 protected void onActivityResult(int requestCode, int resultCode,
4132 Intent intent) {
4133 switch (requestCode) {
4134 case COMBO_PAGE:
4135 if (resultCode == RESULT_OK && intent != null) {
4136 String data = intent.getAction();
4137 Bundle extras = intent.getExtras();
4138 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04004139 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004140 } else {
4141 final TabControl.Tab currentTab =
4142 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04004143 dismissSubWindow(currentTab);
4144 if (data != null && data.length() != 0) {
4145 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004146 }
4147 }
4148 }
4149 break;
4150 default:
4151 break;
4152 }
Leon Scroggins30444232009-09-04 18:36:20 -04004153 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004154 }
4155
4156 /*
4157 * This method is called as a result of the user selecting the options
4158 * menu to see the download window, or when a download changes state. It
4159 * shows the download window ontop of the current window.
4160 */
4161 /* package */ void viewDownloads(Uri downloadRecord) {
4162 Intent intent = new Intent(this,
4163 BrowserDownloadPage.class);
4164 intent.setData(downloadRecord);
4165 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4166
4167 }
4168
Leon Scroggins160a7e72009-08-14 18:28:01 -04004169 /**
4170 * Open the Go page.
4171 * @param startWithHistory If true, open starting on the history tab.
4172 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004173 */
Leon Scroggins30444232009-09-04 18:36:20 -04004174 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004175 WebView current = mTabControl.getCurrentWebView();
4176 if (current == null) {
4177 return;
4178 }
4179 Intent intent = new Intent(this,
4180 CombinedBookmarkHistoryActivity.class);
4181 String title = current.getTitle();
4182 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004183 Bitmap thumbnail = createScreenshot(current);
4184
The Android Open Source Project0c908882009-03-03 19:32:16 -08004185 // Just in case the user opens bookmarks before a page finishes loading
4186 // so the current history item, and therefore the page, is null.
4187 if (null == url) {
4188 url = mLastEnteredUrl;
4189 // This can happen.
4190 if (null == url) {
4191 url = mSettings.getHomePage();
4192 }
4193 }
4194 // In case the web page has not yet received its associated title.
4195 if (title == null) {
4196 title = url;
4197 }
4198 intent.putExtra("title", title);
4199 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004200 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04004201 // Disable opening in a new window if we have maxed out the windows
4202 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4203 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004204 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004205 if (startWithHistory) {
4206 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4207 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4208 }
4209 startActivityForResult(intent, COMBO_PAGE);
4210 }
4211
4212 // Called when loading from context menu or LOAD_URL message
4213 private void loadURL(WebView view, String url) {
4214 // In case the user enters nothing.
4215 if (url != null && url.length() != 0 && view != null) {
4216 url = smartUrlFilter(url);
4217 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4218 view.loadUrl(url);
4219 }
4220 }
4221 }
4222
The Android Open Source Project0c908882009-03-03 19:32:16 -08004223 private String smartUrlFilter(Uri inUri) {
4224 if (inUri != null) {
4225 return smartUrlFilter(inUri.toString());
4226 }
4227 return null;
4228 }
4229
4230
4231 // get window count
4232
4233 int getWindowCount(){
4234 if(mTabControl != null){
4235 return mTabControl.getTabCount();
4236 }
4237 return 0;
4238 }
4239
Feng Qianb34f87a2009-03-24 21:27:26 -07004240 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004241 "(?i)" + // switch on case insensitive matching
4242 "(" + // begin group for schema
4243 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004244 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004245 ")" +
4246 "(.*)" );
4247
4248 /**
4249 * Attempts to determine whether user input is a URL or search
4250 * terms. Anything with a space is passed to search.
4251 *
4252 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4253 * "Http://" converts to "http://"
4254 *
4255 * @return Original or modified URL
4256 *
4257 */
4258 String smartUrlFilter(String url) {
4259
4260 String inUrl = url.trim();
4261 boolean hasSpace = inUrl.indexOf(' ') != -1;
4262
4263 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4264 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004265 // force scheme to lowercase
4266 String scheme = matcher.group(1);
4267 String lcScheme = scheme.toLowerCase();
4268 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004269 inUrl = lcScheme + matcher.group(2);
4270 }
4271 if (hasSpace) {
4272 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004273 }
4274 return inUrl;
4275 }
4276 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004277 // FIXME: Is this the correct place to add to searches?
4278 // what if someone else calls this function?
4279 int shortcut = parseUrlShortcut(inUrl);
4280 if (shortcut != SHORTCUT_INVALID) {
4281 Browser.addSearchUrl(mResolver, inUrl);
4282 String query = inUrl.substring(2);
4283 switch (shortcut) {
4284 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004285 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004286 case SHORTCUT_WIKIPEDIA_SEARCH:
4287 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4288 case SHORTCUT_DICTIONARY_SEARCH:
4289 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4290 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004291 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004292 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004293 }
4294 }
4295 } else {
4296 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4297 return URLUtil.guessUrl(inUrl);
4298 }
4299 }
4300
4301 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004302 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004303 }
4304
Ben Murdochbff2d602009-07-01 20:19:05 +01004305 /* package */ void setShouldShowErrorConsole(boolean flag) {
4306 if (flag == mShouldShowErrorConsole) {
4307 // Nothing to do.
4308 return;
4309 }
4310
4311 mShouldShowErrorConsole = flag;
4312
4313 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4314
4315 if (flag) {
4316 // Setting the show state of the console will cause it's the layout to be inflated.
4317 if (errorConsole.numberOfErrors() > 0) {
4318 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4319 } else {
4320 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4321 }
4322
4323 // Now we can add it to the main view.
4324 mErrorConsoleContainer.addView(errorConsole,
4325 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4326 ViewGroup.LayoutParams.WRAP_CONTENT));
4327 } else {
4328 mErrorConsoleContainer.removeView(errorConsole);
4329 }
4330
4331 }
4332
Grace Klobaeb6eef42009-09-15 17:56:32 -07004333 final static int LOCK_ICON_UNSECURE = 0;
4334 final static int LOCK_ICON_SECURE = 1;
4335 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004336
4337 private int mLockIconType = LOCK_ICON_UNSECURE;
4338 private int mPrevLockType = LOCK_ICON_UNSECURE;
4339
4340 private BrowserSettings mSettings;
4341 private TabControl mTabControl;
4342 private ContentResolver mResolver;
4343 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004344 private View mCustomView;
4345 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004346 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004347
4348 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4349 // view, we should rewrite this.
4350 private int mCurrentMenuState = 0;
4351 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004352 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004353 private static final int EMPTY_MENU = -1;
4354 private Menu mMenu;
4355
4356 private FindDialog mFindDialog;
4357 // Used to prevent chording to result in firing two shortcuts immediately
4358 // one after another. Fixes bug 1211714.
4359 boolean mCanChord;
4360
4361 private boolean mInLoad;
4362 private boolean mIsNetworkUp;
4363
4364 private boolean mPageStarted;
4365 private boolean mActivityInPause = true;
4366
Ben Murdochaac7aa62009-09-17 16:57:40 +01004367 // If the frame fails to load, we should snap a second screenshot
4368 // to ensure that we get the right thumbnail (i.e. of the error page).
4369 private boolean mNeedExtraScreenShot = false;
4370
The Android Open Source Project0c908882009-03-03 19:32:16 -08004371 private boolean mMenuIsDown;
4372
The Android Open Source Project0c908882009-03-03 19:32:16 -08004373 private static boolean mInTrace;
4374
4375 // Performance probe
4376 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4377 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4378 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4379 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4380 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4381 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4382 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4383 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4384 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4385 };
4386
4387 private long mStart;
4388 private long mProcessStart;
4389 private long mUserStart;
4390 private long mSystemStart;
4391 private long mIdleStart;
4392 private long mIrqStart;
4393
4394 private long mUiStart;
4395
4396 private Drawable mMixLockIcon;
4397 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004398
4399 /* hold a ref so we can auto-cancel if necessary */
4400 private AlertDialog mAlertDialog;
4401
4402 // Wait for credentials before loading google.com
4403 private ProgressDialog mCredsDlg;
4404
4405 // The up-to-date URL and title (these can be different from those stored
4406 // in WebView, since it takes some time for the information in WebView to
4407 // get updated)
4408 private String mUrl;
4409 private String mTitle;
4410
4411 // As PageInfo has different style for landscape / portrait, we have
4412 // to re-open it when configuration changed
4413 private AlertDialog mPageInfoDialog;
4414 private TabControl.Tab mPageInfoView;
4415 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4416 // dialog, we should not just dismiss it, but should get back to the
4417 // SSL-certificate-on-error dialog. This flag is used to store this state
4418 private Boolean mPageInfoFromShowSSLCertificateOnError;
4419
4420 // as SSLCertificateOnError has different style for landscape / portrait,
4421 // we have to re-open it when configuration changed
4422 private AlertDialog mSSLCertificateOnErrorDialog;
4423 private WebView mSSLCertificateOnErrorView;
4424 private SslErrorHandler mSSLCertificateOnErrorHandler;
4425 private SslError mSSLCertificateOnErrorError;
4426
4427 // as SSLCertificate has different style for landscape / portrait, we
4428 // have to re-open it when configuration changed
4429 private AlertDialog mSSLCertificateDialog;
4430 private TabControl.Tab mSSLCertificateView;
4431
4432 // as HttpAuthentication has different style for landscape / portrait, we
4433 // have to re-open it when configuration changed
4434 private AlertDialog mHttpAuthenticationDialog;
4435 private HttpAuthHandler mHttpAuthHandler;
4436
4437 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4438 new FrameLayout.LayoutParams(
4439 ViewGroup.LayoutParams.FILL_PARENT,
4440 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004441 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4442 new FrameLayout.LayoutParams(
4443 ViewGroup.LayoutParams.FILL_PARENT,
4444 ViewGroup.LayoutParams.FILL_PARENT,
4445 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004446 // Google search
4447 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004448 // Wikipedia search
4449 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4450 // Dictionary search
4451 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4452 // Google Mobile Local search
4453 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4454
4455 final static String QUERY_PLACE_HOLDER = "%s";
4456
4457 // "source" parameter for Google search through search key
4458 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4459 // "source" parameter for Google search through goto menu
4460 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4461 // "source" parameter for Google search through simplily type
4462 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4463 // "source" parameter for Google search suggested by the browser
4464 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4465 // "source" parameter for Google search from unknown source
4466 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4467
4468 private final static String LOGTAG = "browser";
4469
The Android Open Source Project0c908882009-03-03 19:32:16 -08004470 private String mLastEnteredUrl;
4471
4472 private PowerManager.WakeLock mWakeLock;
4473 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4474
4475 private Toast mStopToast;
4476
Leon Scroggins68579392009-09-15 15:31:54 -04004477 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004478
Ben Murdochbff2d602009-07-01 20:19:05 +01004479 private LinearLayout mErrorConsoleContainer = null;
4480 private boolean mShouldShowErrorConsole = false;
4481
The Android Open Source Project0c908882009-03-03 19:32:16 -08004482 // As the ids are dynamically created, we can't guarantee that they will
4483 // be in sequence, so this static array maps ids to a window number.
4484 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4485 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4486 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4487 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4488
4489 // monitor platform changes
4490 private IntentFilter mNetworkStateChangedFilter;
4491 private BroadcastReceiver mNetworkStateIntentReceiver;
4492
Grace Klobab4da0ad2009-05-14 14:45:40 -07004493 private BroadcastReceiver mPackageInstallationReceiver;
4494
Patrick Scott59ce8302009-09-18 16:29:38 -04004495 // AsyncTask for downloading touch icons
4496 /* package */ DownloadTouchIcon mTouchIconLoader;
4497
The Android Open Source Project0c908882009-03-03 19:32:16 -08004498 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004499 final static int COMBO_PAGE = 1;
4500 final static int DOWNLOAD_PAGE = 2;
4501 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004502
Andrei Popescu540035d2009-09-18 18:59:20 +01004503 // the default <video> poster
4504 private Bitmap mDefaultVideoPoster;
4505 // the video progress view
4506 private View mVideoProgressView;
4507
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004508 /**
4509 * A UrlData class to abstract how the content will be set to WebView.
4510 * This base class uses loadUrl to show the content.
4511 */
4512 private static class UrlData {
4513 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004514 byte[] mPostData;
4515
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004516 UrlData(String url) {
4517 this.mUrl = url;
4518 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004519
4520 void setPostData(byte[] postData) {
4521 mPostData = postData;
4522 }
4523
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004524 boolean isEmpty() {
4525 return mUrl == null || mUrl.length() == 0;
4526 }
4527
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004528 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004529 if (mPostData != null) {
4530 webView.postUrl(mUrl, mPostData);
4531 } else {
4532 webView.loadUrl(mUrl);
4533 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004534 }
4535 };
4536
4537 /**
4538 * A subclass of UrlData class that can display inlined content using
4539 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4540 */
4541 private static class InlinedUrlData extends UrlData {
4542 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4543 super(failUrl);
4544 mInlined = inlined;
4545 mMimeType = mimeType;
4546 mEncoding = encoding;
4547 }
4548 String mMimeType;
4549 String mInlined;
4550 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004551 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004552 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004553 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004554 }
4555
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004556 @Override
4557 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004558 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4559 }
4560 }
4561
Leon Scroggins1f005d32009-08-10 17:36:42 -04004562 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004563}