blob: 887f8321d1c9c5530f033c4f6238bef19b12bad0 [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;
48import android.graphics.Canvas;
49import android.graphics.Color;
50import android.graphics.DrawFilter;
51import android.graphics.Paint;
52import android.graphics.PaintFlagsDrawFilter;
53import android.graphics.Picture;
54import android.graphics.drawable.BitmapDrawable;
55import android.graphics.drawable.Drawable;
56import android.graphics.drawable.LayerDrawable;
57import android.graphics.drawable.PaintDrawable;
58import android.hardware.SensorListener;
59import android.hardware.SensorManager;
60import android.net.ConnectivityManager;
61import 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;
79import android.provider.Contacts;
80import android.provider.Downloads;
81import android.provider.MediaStore;
82import android.provider.Contacts.Intents.Insert;
83import 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
152 implements KeyTracker.OnKeyTracker,
153 View.OnCreateContextMenuListener,
154 DownloadListener {
155
Dave Bort31a6d1c2009-04-13 15:56:49 -0700156 /* Define some aliases to make these debugging flags easier to refer to.
157 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
158 */
159 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
160 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
161 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
162
The Android Open Source Project0c908882009-03-03 19:32:16 -0800163 private IGoogleLoginService mGls = null;
164 private ServiceConnection mGlsConnection = null;
165
166 private SensorManager mSensorManager = null;
167
Satish Sampath565505b2009-05-29 15:37:27 +0100168 // These are single-character shortcuts for searching popular sources.
169 private static final int SHORTCUT_INVALID = 0;
170 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
171 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
172 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
173 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
174
The Android Open Source Project0c908882009-03-03 19:32:16 -0800175 /* Whitelisted webpages
176 private static HashSet<String> sWhiteList;
177
178 static {
179 sWhiteList = new HashSet<String>();
180 sWhiteList.add("cnn.com/");
181 sWhiteList.add("espn.go.com/");
182 sWhiteList.add("nytimes.com/");
183 sWhiteList.add("engadget.com/");
184 sWhiteList.add("yahoo.com/");
185 sWhiteList.add("msn.com/");
186 sWhiteList.add("amazon.com/");
187 sWhiteList.add("consumerist.com/");
188 sWhiteList.add("google.com/m/news");
189 }
190 */
191
192 private void setupHomePage() {
193 final Runnable getAccount = new Runnable() {
194 public void run() {
195 // Lower priority
196 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
197 // get the default home page
198 String homepage = mSettings.getHomePage();
199
200 try {
201 if (mGls == null) return;
202
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700203 if (!homepage.startsWith("http://www.google.")) return;
204 if (homepage.indexOf('?') == -1) return;
205
The Android Open Source Project0c908882009-03-03 19:32:16 -0800206 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
207 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
208
209 // three cases:
210 //
211 // hostedUser == googleUser
212 // The device has only a google account
213 //
214 // hostedUser != googleUser
215 // The device has a hosted account and a google account
216 //
217 // hostedUser != null, googleUser == null
218 // The device has only a hosted account (so far)
219
220 // developers might have no accounts at all
221 if (hostedUser == null) return;
222
223 if (googleUser == null || !hostedUser.equals(googleUser)) {
224 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700225 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800226 }
227 } catch (RemoteException ignore) {
228 // Login service died; carry on
229 } catch (RuntimeException ignore) {
230 // Login service died; carry on
231 } finally {
232 finish(homepage);
233 }
234 }
235
236 private void finish(final String homepage) {
237 mHandler.post(new Runnable() {
238 public void run() {
239 mSettings.setHomePage(BrowserActivity.this, homepage);
240 resumeAfterCredentials();
241
242 // as this is running in a separate thread,
243 // BrowserActivity's onDestroy() may have been called,
244 // which also calls unbindService().
245 if (mGlsConnection != null) {
246 // we no longer need to keep GLS open
247 unbindService(mGlsConnection);
248 mGlsConnection = null;
249 }
250 } });
251 } };
252
253 final boolean[] done = { false };
254
255 // Open a connection to the Google Login Service. The first
256 // time the connection is established, set up the homepage depending on
257 // the account in a background thread.
258 mGlsConnection = new ServiceConnection() {
259 public void onServiceConnected(ComponentName className, IBinder service) {
260 mGls = IGoogleLoginService.Stub.asInterface(service);
261 if (done[0] == false) {
262 done[0] = true;
263 Thread account = new Thread(getAccount);
264 account.setName("GLSAccount");
265 account.start();
266 }
267 }
268 public void onServiceDisconnected(ComponentName className) {
269 mGls = null;
270 }
271 };
272
273 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
274 mGlsConnection, Context.BIND_AUTO_CREATE);
275 }
276
Cary Clarka9771242009-08-11 16:42:26 -0400277 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800278 @Override
279 public Void doInBackground(File... files) {
280 if (files != null) {
281 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400282 if (!f.delete()) {
283 Log.e(LOGTAG, f.getPath() + " was not deleted");
284 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800285 }
286 }
287 return null;
288 }
289 }
290
Leon Scroggins81db3662009-06-04 17:45:11 -0400291 // Flag to enable the touchable browser bar with buttons
292 private final boolean CUSTOM_BROWSER_BAR = true;
293
The Android Open Source Project0c908882009-03-03 19:32:16 -0800294 @Override public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700295 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800296 Log.v(LOGTAG, this + " onStart");
297 }
298 super.onCreate(icicle);
Leon Scroggins81db3662009-06-04 17:45:11 -0400299 if (CUSTOM_BROWSER_BAR) {
300 this.requestWindowFeature(Window.FEATURE_NO_TITLE);
Leon Scroggins81db3662009-06-04 17:45:11 -0400301 } else {
302 this.requestWindowFeature(Window.FEATURE_LEFT_ICON);
303 this.requestWindowFeature(Window.FEATURE_RIGHT_ICON);
304 this.requestWindowFeature(Window.FEATURE_PROGRESS);
305 this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
306 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800307 // test the browser in OpenGL
308 // requestWindowFeature(Window.FEATURE_OPENGL);
309
310 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
311
312 mResolver = getContentResolver();
313
The Android Open Source Project0c908882009-03-03 19:32:16 -0800314 //
315 // start MASF proxy service
316 //
317 //Intent proxyServiceIntent = new Intent();
318 //proxyServiceIntent.setComponent
319 // (new ComponentName(
320 // "com.android.masfproxyservice",
321 // "com.android.masfproxyservice.MasfProxyService"));
322 //startService(proxyServiceIntent, null);
323
324 mSecLockIcon = Resources.getSystem().getDrawable(
325 android.R.drawable.ic_secure);
326 mMixLockIcon = Resources.getSystem().getDrawable(
327 android.R.drawable.ic_partial_secure);
328 mGenericFavicon = getResources().getDrawable(
329 R.drawable.app_web_browser_sm);
330
Leon Scroggins81db3662009-06-04 17:45:11 -0400331 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
332 .findViewById(com.android.internal.R.id.content);
333 if (CUSTOM_BROWSER_BAR) {
Andrei Popescuadc008d2009-06-26 14:11:30 +0100334 // This FrameLayout will hold the custom FrameLayout and a LinearLayout
335 // that contains the title bar and a FrameLayout, which
Leon Scroggins81db3662009-06-04 17:45:11 -0400336 // holds everything else.
Andrei Popescuadc008d2009-06-26 14:11:30 +0100337 FrameLayout browserFrameLayout = (FrameLayout) LayoutInflater.from(this)
Leon Scrogginse4b3bda2009-06-09 15:46:41 -0400338 .inflate(R.layout.custom_screen, null);
Andrei Popescuadc008d2009-06-26 14:11:30 +0100339 mContentView = (FrameLayout) browserFrameLayout.findViewById(
Leon Scrogginse4b3bda2009-06-09 15:46:41 -0400340 R.id.main_content);
Ben Murdochbff2d602009-07-01 20:19:05 +0100341 mErrorConsoleContainer = (LinearLayout) browserFrameLayout.findViewById(
342 R.id.error_console);
Andrei Popescuadc008d2009-06-26 14:11:30 +0100343 mCustomViewContainer = (FrameLayout) browserFrameLayout
344 .findViewById(R.id.fullscreen_custom_content);
345 frameLayout.addView(browserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins39ab28e2009-09-02 21:20:30 -0400346 mTitleBar = new TitleBarSet(this);
Leon Scroggins81db3662009-06-04 17:45:11 -0400347 } else {
Andrei Popescuadc008d2009-06-26 14:11:30 +0100348 mCustomViewContainer = new FrameLayout(this);
Andrei Popescu78f75702009-06-26 16:50:04 +0100349 mCustomViewContainer.setBackgroundColor(Color.BLACK);
Andrei Popescuadc008d2009-06-26 14:11:30 +0100350 mContentView = new FrameLayout(this);
Ben Murdochbff2d602009-07-01 20:19:05 +0100351
352 LinearLayout linearLayout = new LinearLayout(this);
353 linearLayout.setOrientation(LinearLayout.VERTICAL);
354 mErrorConsoleContainer = new LinearLayout(this);
355 linearLayout.addView(mErrorConsoleContainer, new LinearLayout.LayoutParams(
356 ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
357 linearLayout.addView(mContentView, COVER_SCREEN_PARAMS);
Andrei Popescuadc008d2009-06-26 14:11:30 +0100358 frameLayout.addView(mCustomViewContainer, COVER_SCREEN_PARAMS);
Ben Murdochbff2d602009-07-01 20:19:05 +0100359 frameLayout.addView(linearLayout, COVER_SCREEN_PARAMS);
Leon Scroggins81db3662009-06-04 17:45:11 -0400360 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800361
362 // Create the tab control and our initial tab
363 mTabControl = new TabControl(this);
364
365 // Open the icon database and retain all the bookmark urls for favicons
366 retainIconsOnStartup();
367
368 // Keep a settings instance handy.
369 mSettings = BrowserSettings.getInstance();
370 mSettings.setTabControl(mTabControl);
371 mSettings.loadFromDb(this);
372
373 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
374 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
375
Grace Klobaa34f6862009-07-31 16:28:17 -0700376 /* enables registration for changes in network status from
377 http stack */
378 mNetworkStateChangedFilter = new IntentFilter();
379 mNetworkStateChangedFilter.addAction(
380 ConnectivityManager.CONNECTIVITY_ACTION);
381 mNetworkStateIntentReceiver = new BroadcastReceiver() {
382 @Override
383 public void onReceive(Context context, Intent intent) {
384 if (intent.getAction().equals(
385 ConnectivityManager.CONNECTIVITY_ACTION)) {
386 boolean down = intent.getBooleanExtra(
387 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
388 onNetworkToggle(!down);
389 }
390 }
391 };
392
Grace Kloba615c6c92009-08-03 10:22:44 -0700393 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
394 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
395 filter.addDataScheme("package");
396 mPackageInstallationReceiver = new BroadcastReceiver() {
397 @Override
398 public void onReceive(Context context, Intent intent) {
399 final String action = intent.getAction();
400 final String packageName = intent.getData()
401 .getSchemeSpecificPart();
402 final boolean replacing = intent.getBooleanExtra(
403 Intent.EXTRA_REPLACING, false);
404 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
405 // if it is replacing, refreshPlugins() when adding
406 return;
407 }
408 PackageManager pm = BrowserActivity.this.getPackageManager();
409 PackageInfo pkgInfo = null;
410 try {
411 pkgInfo = pm.getPackageInfo(packageName,
412 PackageManager.GET_PERMISSIONS);
413 } catch (PackageManager.NameNotFoundException e) {
414 return;
415 }
416 if (pkgInfo != null) {
417 String permissions[] = pkgInfo.requestedPermissions;
418 if (permissions == null) {
419 return;
420 }
421 boolean permissionOk = false;
422 for (String permit : permissions) {
423 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
424 permissionOk = true;
425 break;
426 }
427 }
428 if (permissionOk) {
429 PluginManager.getInstance(BrowserActivity.this)
430 .refreshPlugins(
431 Intent.ACTION_PACKAGE_ADDED
432 .equals(action));
433 }
434 }
435 }
436 };
437 registerReceiver(mPackageInstallationReceiver, filter);
438
Satish Sampath565505b2009-05-29 15:37:27 +0100439 // If this was a web search request, pass it on to the default web search provider.
440 if (handleWebSearchIntent(getIntent())) {
441 moveTaskToBack(true);
442 return;
443 }
444
The Android Open Source Project0c908882009-03-03 19:32:16 -0800445 if (!mTabControl.restoreState(icicle)) {
446 // clear up the thumbnail directory if we can't restore the state as
447 // none of the files in the directory are referenced any more.
448 new ClearThumbnails().execute(
449 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700450 // there is no quit on Android. But if we can't restore the state,
451 // we can treat it as a new Browser, remove the old session cookies.
452 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800453 final Intent intent = getIntent();
454 final Bundle extra = intent.getExtras();
455 // Create an initial tab.
456 // If the intent is ACTION_VIEW and data is not null, the Browser is
457 // invoked to view the content by another application. In this case,
458 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700459 UrlData urlData = getUrlDataFromIntent(intent);
460
The Android Open Source Project0c908882009-03-03 19:32:16 -0800461 final TabControl.Tab t = mTabControl.createNewTab(
462 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700463 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700464 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800465 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800466 attachTabToContentView(t);
467 WebView webView = t.getWebView();
468 if (extra != null) {
469 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
470 if (scale > 0 && scale <= 1000) {
471 webView.setInitialScale(scale);
472 }
473 }
474 // If we are not restoring from an icicle, then there is a high
475 // likely hood this is the first run. So, check to see if the
476 // homepage needs to be configured and copy any plugins from our
477 // asset directory to the data partition.
478 if ((extra == null || !extra.getBoolean("testing"))
479 && !mSettings.isLoginInitialized()) {
480 setupHomePage();
481 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800482
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700483 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400484 if (mSettings.isLoginInitialized()) {
485 webView.loadUrl(mSettings.getHomePage());
486 } else {
487 waitForCredentials();
488 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800489 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700490 if (extra != null) {
491 urlData.setPostData(extra
492 .getByteArray(Browser.EXTRA_POST_DATA));
493 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700494 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800495 }
496 } else {
497 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400498 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800499 attachTabToContentView(mTabControl.getCurrentTab());
500 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700501
Leon Scroggins1f005d32009-08-10 17:36:42 -0400502 if (CUSTOM_BROWSER_BAR) {
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400503 mTitleBar.init(this);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400504 // Create title bars for all of the tabs that have been created
505 for (int i = 0; i < mTabControl.getTabCount(); i ++) {
506 WebView view = mTabControl.getTab(i).getWebView();
507 mTitleBar.addTab(view, false);
508 }
509
Leon Scroggins1f005d32009-08-10 17:36:42 -0400510 mTitleBar.setCurrentTab(mTabControl.getCurrentIndex());
511 }
512
Feng Qianb3c02da2009-06-29 15:58:08 -0700513 // Read JavaScript flags if it exists.
514 String jsFlags = mSettings.getJsFlags();
515 if (jsFlags.trim().length() != 0) {
516 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
517 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800518 }
519
520 @Override
521 protected void onNewIntent(Intent intent) {
522 TabControl.Tab current = mTabControl.getCurrentTab();
523 // When a tab is closed on exit, the current tab index is set to -1.
524 // Reset before proceed as Browser requires the current tab to be set.
525 if (current == null) {
526 // Try to reset the tab in case the index was incorrect.
527 current = mTabControl.getTab(0);
528 if (current == null) {
529 // No tabs at all so just ignore this intent.
530 return;
531 }
532 mTabControl.setCurrentTab(current);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400533 if (CUSTOM_BROWSER_BAR) {
534 mTitleBar.setCurrentTab(mTabControl.getTabIndex(current));
535 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800536 attachTabToContentView(current);
537 resetTitleAndIcon(current.getWebView());
538 }
539 final String action = intent.getAction();
540 final int flags = intent.getFlags();
541 if (Intent.ACTION_MAIN.equals(action) ||
542 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
543 // just resume the browser
544 return;
545 }
546 if (Intent.ACTION_VIEW.equals(action)
547 || Intent.ACTION_SEARCH.equals(action)
548 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
549 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100550 // If this was a search request (e.g. search query directly typed into the address bar),
551 // pass it on to the default web search provider.
552 if (handleWebSearchIntent(intent)) {
553 return;
554 }
555
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700556 UrlData urlData = getUrlDataFromIntent(intent);
557 if (urlData.isEmpty()) {
558 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800559 }
Grace Kloba81678d92009-06-30 07:09:56 -0700560 urlData.setPostData(intent
561 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700562
Grace Klobacc634032009-07-28 15:58:19 -0700563 final String appId = intent
564 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
565 if (Intent.ACTION_VIEW.equals(action)
566 && !getPackageName().equals(appId)
567 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Patrick Scottcd115892009-07-16 09:42:58 -0400568 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700569 if (appTab != null) {
570 Log.i(LOGTAG, "Reusing tab for " + appId);
571 // Dismiss the subwindow if applicable.
572 dismissSubWindow(appTab);
573 // Since we might kill the WebView, remove it from the
574 // content view first.
575 removeTabFromContentView(appTab);
576 // Recreate the main WebView after destroying the old one.
577 // If the WebView has the same original url and is on that
578 // page, it can be reused.
579 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700580 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100581
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700582 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400583 switchToTab(mTabControl.getTabIndex(appTab));
584 if (needsLoad) {
585 urlData.loadIn(appTab.getWebView());
586 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700587 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400588 // If the tab was the current tab, we have to attach
589 // it to the view system again.
590 attachTabToContentView(appTab);
591 if (needsLoad) {
592 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700593 }
594 }
595 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400596 } else {
597 // No matching application tab, try to find a regular tab
598 // with a matching url.
599 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400600 if (appTab != null) {
601 if (current != appTab) {
602 switchToTab(mTabControl.getTabIndex(appTab));
603 }
604 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400605 } else {
606 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
607 // will be opened in a new tab unless we have reached
608 // MAX_TABS. Then the url will be opened in the current
609 // tab. If a new tab is created, it will have "true" for
610 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400611 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400612 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700613 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800614 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700615 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800616 mSettings.toggleDebugSettings();
617 return;
618 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400619 // Get rid of the subwindow if it exists
620 dismissSubWindow(current);
621 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800622 }
623 }
624 }
625
Satish Sampath565505b2009-05-29 15:37:27 +0100626 private int parseUrlShortcut(String url) {
627 if (url == null) return SHORTCUT_INVALID;
628
629 // FIXME: quick search, need to be customized by setting
630 if (url.length() > 2 && url.charAt(1) == ' ') {
631 switch (url.charAt(0)) {
632 case 'g': return SHORTCUT_GOOGLE_SEARCH;
633 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
634 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
635 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
636 }
637 }
638 return SHORTCUT_INVALID;
639 }
640
641 /**
642 * Launches the default web search activity with the query parameters if the given intent's data
643 * are identified as plain search terms and not URLs/shortcuts.
644 * @return true if the intent was handled and web search activity was launched, false if not.
645 */
646 private boolean handleWebSearchIntent(Intent intent) {
647 if (intent == null) return false;
648
649 String url = null;
650 final String action = intent.getAction();
651 if (Intent.ACTION_VIEW.equals(action)) {
652 url = intent.getData().toString();
653 } else if (Intent.ACTION_SEARCH.equals(action)
654 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
655 || Intent.ACTION_WEB_SEARCH.equals(action)) {
656 url = intent.getStringExtra(SearchManager.QUERY);
657 }
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100658 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA));
Satish Sampath565505b2009-05-29 15:37:27 +0100659 }
660
661 /**
662 * Launches the default web search activity with the query parameters if the given url string
663 * was identified as plain search terms and not URL/shortcut.
664 * @return true if the request was handled and web search activity was launched, false if not.
665 */
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100666 private boolean handleWebSearchRequest(String inUrl, Bundle appData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100667 if (inUrl == null) return false;
668
669 // In general, we shouldn't modify URL from Intent.
670 // But currently, we get the user-typed URL from search box as well.
671 String url = fixUrl(inUrl).trim();
672
673 // URLs and site specific search shortcuts are handled by the regular flow of control, so
674 // return early.
675 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100676 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100677 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
678 return false;
679 }
680
681 Browser.updateVisitedHistory(mResolver, url, false);
682 Browser.addSearchUrl(mResolver, url);
683
684 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
685 intent.addCategory(Intent.CATEGORY_DEFAULT);
686 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100687 if (appData != null) {
688 intent.putExtra(SearchManager.APP_DATA, appData);
689 }
Grace Klobacc634032009-07-28 15:58:19 -0700690 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100691 startActivity(intent);
692
693 return true;
694 }
695
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700696 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800697 String url = null;
698 if (intent != null) {
699 final String action = intent.getAction();
700 if (Intent.ACTION_VIEW.equals(action)) {
701 url = smartUrlFilter(intent.getData());
702 if (url != null && url.startsWith("content:")) {
703 /* Append mimetype so webview knows how to display */
704 String mimeType = intent.resolveType(getContentResolver());
705 if (mimeType != null) {
706 url += "?" + mimeType;
707 }
708 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700709 if ("inline:".equals(url)) {
710 return new InlinedUrlData(
711 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
712 intent.getType(),
713 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
714 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
715 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800716 } else if (Intent.ACTION_SEARCH.equals(action)
717 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
718 || Intent.ACTION_WEB_SEARCH.equals(action)) {
719 url = intent.getStringExtra(SearchManager.QUERY);
720 if (url != null) {
721 mLastEnteredUrl = url;
722 // Don't add Urls, just search terms.
723 // Urls will get added when the page is loaded.
724 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
725 Browser.updateVisitedHistory(mResolver, url, false);
726 }
727 // In general, we shouldn't modify URL from Intent.
728 // But currently, we get the user-typed URL from search box as well.
729 url = fixUrl(url);
730 url = smartUrlFilter(url);
731 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
732 if (url.contains(searchSource)) {
733 String source = null;
734 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
735 if (appData != null) {
736 source = appData.getString(SearchManager.SOURCE);
737 }
738 if (TextUtils.isEmpty(source)) {
739 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
740 }
741 url = url.replace(searchSource, "&source=android-"+source+"&");
742 }
743 }
744 }
745 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700746 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800747 }
748
749 /* package */ static String fixUrl(String inUrl) {
750 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
751 return inUrl;
752 if (inUrl.startsWith("http:") ||
753 inUrl.startsWith("https:")) {
754 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
755 inUrl = inUrl.replaceFirst("/", "//");
756 } else inUrl = inUrl.replaceFirst(":", "://");
757 }
758 return inUrl;
759 }
760
761 /**
762 * Looking for the pattern like this
763 *
764 * *
765 * * *
766 * *** * *******
767 * * *
768 * * *
769 * *
770 */
771 private final SensorListener mSensorListener = new SensorListener() {
772 private long mLastGestureTime;
773 private float[] mPrev = new float[3];
774 private float[] mPrevDiff = new float[3];
775 private float[] mDiff = new float[3];
776 private float[] mRevertDiff = new float[3];
777
778 public void onSensorChanged(int sensor, float[] values) {
779 boolean show = false;
780 float[] diff = new float[3];
781
782 for (int i = 0; i < 3; i++) {
783 diff[i] = values[i] - mPrev[i];
784 if (Math.abs(diff[i]) > 1) {
785 show = true;
786 }
787 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
788 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
789 // start track when there is a big move, or revert
790 mRevertDiff[i] = mDiff[i];
791 mDiff[i] = 0;
792 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
793 // reset when it is flat
794 mDiff[i] = mRevertDiff[i] = 0;
795 }
796 mDiff[i] += diff[i];
797 mPrevDiff[i] = diff[i];
798 mPrev[i] = values[i];
799 }
800
801 if (false) {
802 // only shows if we think the delta is big enough, in an attempt
803 // to detect "serious" moves left/right or up/down
804 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
805 + values[0] + ", " + values[1] + ", " + values[2] + ")"
806 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
807 + ")");
808 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
809 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
810 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
811 + mRevertDiff[2] + ")");
812 }
813
814 long now = android.os.SystemClock.uptimeMillis();
815 if (now - mLastGestureTime > 1000) {
816 mLastGestureTime = 0;
817
818 float y = mDiff[1];
819 float z = mDiff[2];
820 float ay = Math.abs(y);
821 float az = Math.abs(z);
822 float ry = mRevertDiff[1];
823 float rz = mRevertDiff[2];
824 float ary = Math.abs(ry);
825 float arz = Math.abs(rz);
826 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
827 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
828
829 if ((gestY || gestZ) && !(gestY && gestZ)) {
830 WebView view = mTabControl.getCurrentWebView();
831
832 if (view != null) {
833 if (gestZ) {
834 if (z < 0) {
835 view.zoomOut();
836 } else {
837 view.zoomIn();
838 }
839 } else {
840 view.flingScroll(0, Math.round(y * 100));
841 }
842 }
843 mLastGestureTime = now;
844 }
845 }
846 }
847
848 public void onAccuracyChanged(int sensor, int accuracy) {
849 // TODO Auto-generated method stub
850
851 }
852 };
853
854 @Override protected void onResume() {
855 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700856 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800857 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
858 }
859
860 if (!mActivityInPause) {
861 Log.e(LOGTAG, "BrowserActivity is already resumed.");
862 return;
863 }
864
Mike Reed7bfa63b2009-05-28 11:08:32 -0400865 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800866 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400867 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800868
869 if (mWakeLock.isHeld()) {
870 mHandler.removeMessages(RELEASE_WAKELOCK);
871 mWakeLock.release();
872 }
873
874 if (mCredsDlg != null) {
875 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
876 // In case credential request never comes back
877 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
878 }
879 }
880
881 registerReceiver(mNetworkStateIntentReceiver,
882 mNetworkStateChangedFilter);
883 WebView.enablePlatformNotifications();
884
885 if (mSettings.doFlick()) {
886 if (mSensorManager == null) {
887 mSensorManager = (SensorManager) getSystemService(
888 Context.SENSOR_SERVICE);
889 }
890 mSensorManager.registerListener(mSensorListener,
891 SensorManager.SENSOR_ACCELEROMETER,
892 SensorManager.SENSOR_DELAY_FASTEST);
893 } else {
894 mSensorManager = null;
895 }
896 }
897
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400898 @Override
899 public boolean onMenuOpened(int featureId, Menu menu) {
900 mTitleBar.setVisibility(View.VISIBLE);
901 return true;
902 }
903
The Android Open Source Project0c908882009-03-03 19:32:16 -0800904 /**
905 * onSaveInstanceState(Bundle map)
906 * onSaveInstanceState is called right before onStop(). The map contains
907 * the saved state.
908 */
909 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700910 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800911 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
912 }
913 // the default implementation requires each view to have an id. As the
914 // browser handles the state itself and it doesn't use id for the views,
915 // don't call the default implementation. Otherwise it will trigger the
916 // warning like this, "couldn't save which view has focus because the
917 // focused view XXX has no id".
918
919 // Save all the tabs
920 mTabControl.saveState(outState);
921 }
922
923 @Override protected void onPause() {
924 super.onPause();
925
926 if (mActivityInPause) {
927 Log.e(LOGTAG, "BrowserActivity is already paused.");
928 return;
929 }
930
Mike Reed7bfa63b2009-05-28 11:08:32 -0400931 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800932 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400933 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800934 mWakeLock.acquire();
935 mHandler.sendMessageDelayed(mHandler
936 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
937 }
938
939 // Clear the credentials toast if it is up
940 if (mCredsDlg != null && mCredsDlg.isShowing()) {
941 mCredsDlg.dismiss();
942 }
943 mCredsDlg = null;
944
945 cancelStopToast();
946
947 // unregister network state listener
948 unregisterReceiver(mNetworkStateIntentReceiver);
949 WebView.disablePlatformNotifications();
950
951 if (mSensorManager != null) {
952 mSensorManager.unregisterListener(mSensorListener);
953 }
954 }
955
956 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700957 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800958 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
959 }
960 super.onDestroy();
961 // Remove the current tab and sub window
962 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700963 if (t != null) {
964 dismissSubWindow(t);
965 removeTabFromContentView(t);
966 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800967 // Destroy all the tabs
968 mTabControl.destroy();
969 WebIconDatabase.getInstance().close();
970 if (mGlsConnection != null) {
971 unbindService(mGlsConnection);
972 mGlsConnection = null;
973 }
974
975 //
976 // stop MASF proxy service
977 //
978 //Intent proxyServiceIntent = new Intent();
979 //proxyServiceIntent.setComponent
980 // (new ComponentName(
981 // "com.android.masfproxyservice",
982 // "com.android.masfproxyservice.MasfProxyService"));
983 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -0700984
985 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800986 }
987
988 @Override
989 public void onConfigurationChanged(Configuration newConfig) {
990 super.onConfigurationChanged(newConfig);
991
992 if (mPageInfoDialog != null) {
993 mPageInfoDialog.dismiss();
994 showPageInfo(
995 mPageInfoView,
996 mPageInfoFromShowSSLCertificateOnError.booleanValue());
997 }
998 if (mSSLCertificateDialog != null) {
999 mSSLCertificateDialog.dismiss();
1000 showSSLCertificate(
1001 mSSLCertificateView);
1002 }
1003 if (mSSLCertificateOnErrorDialog != null) {
1004 mSSLCertificateOnErrorDialog.dismiss();
1005 showSSLCertificateOnError(
1006 mSSLCertificateOnErrorView,
1007 mSSLCertificateOnErrorHandler,
1008 mSSLCertificateOnErrorError);
1009 }
1010 if (mHttpAuthenticationDialog != null) {
1011 String title = ((TextView) mHttpAuthenticationDialog
1012 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1013 .toString();
1014 String name = ((TextView) mHttpAuthenticationDialog
1015 .findViewById(R.id.username_edit)).getText().toString();
1016 String password = ((TextView) mHttpAuthenticationDialog
1017 .findViewById(R.id.password_edit)).getText().toString();
1018 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1019 .getId();
1020 mHttpAuthenticationDialog.dismiss();
1021 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1022 name, password, focusId);
1023 }
1024 if (mFindDialog != null && mFindDialog.isShowing()) {
1025 mFindDialog.onConfigurationChanged(newConfig);
1026 }
1027 }
1028
1029 @Override public void onLowMemory() {
1030 super.onLowMemory();
1031 mTabControl.freeMemory();
1032 }
1033
Mike Reed7bfa63b2009-05-28 11:08:32 -04001034 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001035 if ((!mActivityInPause && !mPageStarted) ||
1036 (mActivityInPause && mPageStarted)) {
1037 CookieSyncManager.getInstance().startSync();
1038 WebView w = mTabControl.getCurrentWebView();
1039 if (w != null) {
1040 w.resumeTimers();
1041 }
1042 return true;
1043 } else {
1044 return false;
1045 }
1046 }
1047
Mike Reed7bfa63b2009-05-28 11:08:32 -04001048 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001049 if (mActivityInPause && !mPageStarted) {
1050 CookieSyncManager.getInstance().stopSync();
1051 WebView w = mTabControl.getCurrentWebView();
1052 if (w != null) {
1053 w.pauseTimers();
1054 }
1055 return true;
1056 } else {
1057 return false;
1058 }
1059 }
1060
Leon Scroggins1f005d32009-08-10 17:36:42 -04001061 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001062 /*
1063 * This function is called when we are launching for the first time. We
1064 * are waiting for the login credentials before loading Google home
1065 * pages. This way the user will be logged in straight away.
1066 */
1067 private void waitForCredentials() {
1068 // Show a toast
1069 mCredsDlg = new ProgressDialog(this);
1070 mCredsDlg.setIndeterminate(true);
1071 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1072 // If the user cancels the operation, then cancel the Google
1073 // Credentials request.
1074 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1075 mCredsDlg.show();
1076
1077 // We set a timeout for the retrieval of credentials in onResume()
1078 // as that is when we have freed up some CPU time to get
1079 // the login credentials.
1080 }
1081
1082 /*
1083 * If we have received the credentials or we have timed out and we are
1084 * showing the credentials dialog, then it is time to move on.
1085 */
1086 private void resumeAfterCredentials() {
1087 if (mCredsDlg == null) {
1088 return;
1089 }
1090
1091 // Clear the toast
1092 if (mCredsDlg.isShowing()) {
1093 mCredsDlg.dismiss();
1094 }
1095 mCredsDlg = null;
1096
1097 // Clear any pending timeout
1098 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1099
1100 // Load the page
1101 WebView w = mTabControl.getCurrentWebView();
1102 if (w != null) {
1103 w.loadUrl(mSettings.getHomePage());
1104 }
1105
1106 // Update the settings, need to do this last as it can take a moment
1107 // to persist the settings. In the mean time we could be loading
1108 // content.
1109 mSettings.setLoginInitialized(this);
1110 }
1111
1112 // Open the icon database and retain all the icons for visited sites.
1113 private void retainIconsOnStartup() {
1114 final WebIconDatabase db = WebIconDatabase.getInstance();
1115 db.open(getDir("icons", 0).getPath());
1116 try {
1117 Cursor c = Browser.getAllBookmarks(mResolver);
1118 if (!c.moveToFirst()) {
1119 c.deactivate();
1120 return;
1121 }
1122 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1123 do {
1124 String url = c.getString(urlIndex);
1125 db.retainIconForPageUrl(url);
1126 } while (c.moveToNext());
1127 c.deactivate();
1128 } catch (IllegalStateException e) {
1129 Log.e(LOGTAG, "retainIconsOnStartup", e);
1130 }
1131 }
1132
1133 // Helper method for getting the top window.
1134 WebView getTopWindow() {
1135 return mTabControl.getCurrentTopWebView();
1136 }
1137
1138 @Override
1139 public boolean onCreateOptionsMenu(Menu menu) {
1140 super.onCreateOptionsMenu(menu);
1141
1142 MenuInflater inflater = getMenuInflater();
1143 inflater.inflate(R.menu.browser, menu);
1144 mMenu = menu;
1145 updateInLoadMenuItems();
1146 return true;
1147 }
1148
1149 /**
1150 * As the menu can be open when loading state changes
1151 * we must manually update the state of the stop/reload menu
1152 * item
1153 */
1154 private void updateInLoadMenuItems() {
1155 if (mMenu == null) {
1156 return;
1157 }
1158 MenuItem src = mInLoad ?
1159 mMenu.findItem(R.id.stop_menu_id):
1160 mMenu.findItem(R.id.reload_menu_id);
1161 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1162 dest.setIcon(src.getIcon());
1163 dest.setTitle(src.getTitle());
1164 }
1165
1166 @Override
1167 public boolean onContextItemSelected(MenuItem item) {
1168 // chording is not an issue with context menus, but we use the same
1169 // options selector, so set mCanChord to true so we can access them.
1170 mCanChord = true;
1171 int id = item.getItemId();
1172 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001173 if (null == webView) {
1174 return false;
1175 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001176 final HashMap hrefMap = new HashMap();
1177 hrefMap.put("webview", webView);
1178 final Message msg = mHandler.obtainMessage(
1179 FOCUS_NODE_HREF, id, 0, hrefMap);
1180 switch (id) {
1181 // -- Browser context menu
1182 case R.id.open_context_menu_id:
1183 case R.id.open_newtab_context_menu_id:
1184 case R.id.bookmark_context_menu_id:
1185 case R.id.save_link_context_menu_id:
1186 case R.id.share_link_context_menu_id:
1187 case R.id.copy_link_context_menu_id:
1188 webView.requestFocusNodeHref(msg);
1189 break;
1190
1191 default:
1192 // For other context menus
1193 return onOptionsItemSelected(item);
1194 }
1195 mCanChord = false;
1196 return true;
1197 }
1198
1199 private Bundle createGoogleSearchSourceBundle(String source) {
1200 Bundle bundle = new Bundle();
1201 bundle.putString(SearchManager.SOURCE, source);
1202 return bundle;
1203 }
1204
1205 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001206 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001207 */
1208 @Override
1209 public boolean onSearchRequested() {
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001210 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001211 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001212 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001213 return true;
1214 }
1215
1216 @Override
1217 public void startSearch(String initialQuery, boolean selectInitialQuery,
1218 Bundle appSearchData, boolean globalSearch) {
1219 if (appSearchData == null) {
1220 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1221 }
1222 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1223 }
1224
Leon Scroggins1f005d32009-08-10 17:36:42 -04001225 /**
1226 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1227 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001228 * @param index Index of the tab to change to, as defined by
1229 * mTabControl.getTabIndex(Tab t).
1230 * @return boolean True if we successfully switched to a different tab. If
1231 * the indexth tab is null, or if that tab is the same as
1232 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001233 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001234 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001235 TabControl.Tab tab = mTabControl.getTab(index);
1236 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1237 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001238 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001239 }
1240 if (currentTab != null) {
1241 // currentTab may be null if it was just removed. In that case,
1242 // we do not need to remove it
1243 removeTabFromContentView(currentTab);
1244 }
1245 removeTabFromContentView(tab);
1246 mTabControl.setCurrentTab(tab);
1247 attachTabToContentView(tab);
Leon Scrogginsa11b75a2009-08-18 10:22:05 -04001248 if (CUSTOM_BROWSER_BAR) {
1249 mTitleBar.setCurrentTab(index);
1250 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001251 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001252 }
1253
1254 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001255 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001256 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001257 // This is the last tab. Open a new one, with the home
1258 // page and close the current one.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001259 TabControl.Tab newTab = openTabAndShow(
Leon Scroggins30444232009-09-04 18:36:20 -04001260 mSettings.getHomePage(), false, null);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001261 closeTab(current);
1262 mTabControl.setCurrentTab(newTab);
1263 return;
1264 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001265 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001266 int indexToShow = -1;
1267 if (parent != null) {
1268 indexToShow = mTabControl.getTabIndex(parent);
1269 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001270 final int currentIndex = mTabControl.getCurrentIndex();
1271 // Try to move to the tab to the right
1272 indexToShow = currentIndex + 1;
1273 if (indexToShow > mTabControl.getTabCount() - 1) {
1274 // Try to move to the tab to the left
1275 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001276 }
1277 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001278 if (switchToTab(indexToShow)) {
1279 // Close window
1280 closeTab(current);
1281 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001282 }
1283
The Android Open Source Project0c908882009-03-03 19:32:16 -08001284 @Override
1285 public boolean onOptionsItemSelected(MenuItem item) {
1286 if (!mCanChord) {
1287 // The user has already fired a shortcut with this hold down of the
1288 // menu key.
1289 return false;
1290 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001291 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001292 return false;
1293 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001294 if (mMenuIsDown) {
1295 // The shortcut action consumes the MENU. Even if it is still down,
1296 // it won't trigger the next shortcut action. In the case of the
1297 // shortcut action triggering a new activity, like Bookmarks, we
1298 // won't get onKeyUp for MENU. So it is important to reset it here.
1299 mMenuIsDown = false;
1300 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001301 switch (item.getItemId()) {
1302 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001303 case R.id.new_tab_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001304 openTabAndShow(mSettings.getHomePage(), false, null);
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001305 break;
1306
Leon Scroggins64b80f32009-08-07 12:03:34 -04001307 case R.id.goto_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001308 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001309 break;
1310
Leon Scroggins1f005d32009-08-10 17:36:42 -04001311 case R.id.add_bookmark_menu_id:
1312 Intent i = new Intent(BrowserActivity.this,
1313 AddBookmarkPage.class);
1314 WebView w = getTopWindow();
1315 i.putExtra("url", w.getUrl());
1316 i.putExtra("title", w.getTitle());
1317 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001318 break;
1319
1320 case R.id.stop_reload_menu_id:
1321 if (mInLoad) {
1322 stopLoading();
1323 } else {
1324 getTopWindow().reload();
1325 }
1326 break;
1327
1328 case R.id.back_menu_id:
1329 getTopWindow().goBack();
1330 break;
1331
1332 case R.id.forward_menu_id:
1333 getTopWindow().goForward();
1334 break;
1335
1336 case R.id.close_menu_id:
1337 // Close the subwindow if it exists.
1338 if (mTabControl.getCurrentSubWindow() != null) {
1339 dismissSubWindow(mTabControl.getCurrentTab());
1340 break;
1341 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001342 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001343 break;
1344
1345 case R.id.homepage_menu_id:
1346 TabControl.Tab current = mTabControl.getCurrentTab();
1347 if (current != null) {
1348 dismissSubWindow(current);
1349 current.getWebView().loadUrl(mSettings.getHomePage());
1350 }
1351 break;
1352
1353 case R.id.preferences_menu_id:
1354 Intent intent = new Intent(this,
1355 BrowserPreferencesPage.class);
1356 startActivityForResult(intent, PREFERENCES_PAGE);
1357 break;
1358
1359 case R.id.find_menu_id:
1360 if (null == mFindDialog) {
1361 mFindDialog = new FindDialog(this);
1362 }
1363 mFindDialog.setWebView(getTopWindow());
1364 mFindDialog.show();
1365 mMenuState = EMPTY_MENU;
1366 break;
1367
1368 case R.id.select_text_id:
1369 getTopWindow().emulateShiftHeld();
1370 break;
1371 case R.id.page_info_menu_id:
1372 showPageInfo(mTabControl.getCurrentTab(), false);
1373 break;
1374
1375 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001376 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001377 break;
1378
1379 case R.id.share_page_menu_id:
1380 Browser.sendString(this, getTopWindow().getUrl());
1381 break;
1382
1383 case R.id.dump_nav_menu_id:
1384 getTopWindow().debugDump();
1385 break;
1386
1387 case R.id.zoom_in_menu_id:
1388 getTopWindow().zoomIn();
1389 break;
1390
1391 case R.id.zoom_out_menu_id:
1392 getTopWindow().zoomOut();
1393 break;
1394
1395 case R.id.view_downloads_menu_id:
1396 viewDownloads(null);
1397 break;
1398
The Android Open Source Project0c908882009-03-03 19:32:16 -08001399 case R.id.window_one_menu_id:
1400 case R.id.window_two_menu_id:
1401 case R.id.window_three_menu_id:
1402 case R.id.window_four_menu_id:
1403 case R.id.window_five_menu_id:
1404 case R.id.window_six_menu_id:
1405 case R.id.window_seven_menu_id:
1406 case R.id.window_eight_menu_id:
1407 {
1408 int menuid = item.getItemId();
1409 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1410 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1411 TabControl.Tab desiredTab = mTabControl.getTab(id);
1412 if (desiredTab != null &&
1413 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001414 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001415 }
1416 break;
1417 }
1418 }
1419 }
1420 break;
1421
1422 default:
1423 if (!super.onOptionsItemSelected(item)) {
1424 return false;
1425 }
1426 // Otherwise fall through.
1427 }
1428 mCanChord = false;
1429 return true;
1430 }
1431
1432 public void closeFind() {
1433 mMenuState = R.id.MAIN_MENU;
1434 }
1435
1436 @Override public boolean onPrepareOptionsMenu(Menu menu)
1437 {
1438 // This happens when the user begins to hold down the menu key, so
1439 // allow them to chord to get a shortcut.
1440 mCanChord = true;
1441 // Note: setVisible will decide whether an item is visible; while
1442 // setEnabled() will decide whether an item is enabled, which also means
1443 // whether the matching shortcut key will function.
1444 super.onPrepareOptionsMenu(menu);
1445 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001446 case EMPTY_MENU:
1447 if (mCurrentMenuState != mMenuState) {
1448 menu.setGroupVisible(R.id.MAIN_MENU, false);
1449 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1450 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001451 }
1452 break;
1453 default:
1454 if (mCurrentMenuState != mMenuState) {
1455 menu.setGroupVisible(R.id.MAIN_MENU, true);
1456 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1457 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001458 }
1459 final WebView w = getTopWindow();
1460 boolean canGoBack = false;
1461 boolean canGoForward = false;
1462 boolean isHome = false;
1463 if (w != null) {
1464 canGoBack = w.canGoBack();
1465 canGoForward = w.canGoForward();
1466 isHome = mSettings.getHomePage().equals(w.getUrl());
1467 }
1468 final MenuItem back = menu.findItem(R.id.back_menu_id);
1469 back.setEnabled(canGoBack);
1470
1471 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1472 home.setEnabled(!isHome);
1473
1474 menu.findItem(R.id.forward_menu_id)
1475 .setEnabled(canGoForward);
1476
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001477 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1478 mTabControl.getTabCount() < TabControl.MAX_TABS);
1479
The Android Open Source Project0c908882009-03-03 19:32:16 -08001480 // decide whether to show the share link option
1481 PackageManager pm = getPackageManager();
1482 Intent send = new Intent(Intent.ACTION_SEND);
1483 send.setType("text/plain");
1484 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1485 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1486
The Android Open Source Project0c908882009-03-03 19:32:16 -08001487 boolean isNavDump = mSettings.isNavDump();
1488 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1489 nav.setVisible(isNavDump);
1490 nav.setEnabled(isNavDump);
1491 break;
1492 }
1493 mCurrentMenuState = mMenuState;
1494 return true;
1495 }
1496
1497 @Override
1498 public void onCreateContextMenu(ContextMenu menu, View v,
1499 ContextMenuInfo menuInfo) {
1500 WebView webview = (WebView) v;
1501 WebView.HitTestResult result = webview.getHitTestResult();
1502 if (result == null) {
1503 return;
1504 }
1505
1506 int type = result.getType();
1507 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1508 Log.w(LOGTAG,
1509 "We should not show context menu when nothing is touched");
1510 return;
1511 }
1512 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1513 // let TextView handles context menu
1514 return;
1515 }
1516
1517 // Note, http://b/issue?id=1106666 is requesting that
1518 // an inflated menu can be used again. This is not available
1519 // yet, so inflate each time (yuk!)
1520 MenuInflater inflater = getMenuInflater();
1521 inflater.inflate(R.menu.browsercontext, menu);
1522
1523 // Show the correct menu group
1524 String extra = result.getExtra();
1525 menu.setGroupVisible(R.id.PHONE_MENU,
1526 type == WebView.HitTestResult.PHONE_TYPE);
1527 menu.setGroupVisible(R.id.EMAIL_MENU,
1528 type == WebView.HitTestResult.EMAIL_TYPE);
1529 menu.setGroupVisible(R.id.GEO_MENU,
1530 type == WebView.HitTestResult.GEO_TYPE);
1531 menu.setGroupVisible(R.id.IMAGE_MENU,
1532 type == WebView.HitTestResult.IMAGE_TYPE
1533 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1534 menu.setGroupVisible(R.id.ANCHOR_MENU,
1535 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1536 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1537
1538 // Setup custom handling depending on the type
1539 switch (type) {
1540 case WebView.HitTestResult.PHONE_TYPE:
1541 menu.setHeaderTitle(Uri.decode(extra));
1542 menu.findItem(R.id.dial_context_menu_id).setIntent(
1543 new Intent(Intent.ACTION_VIEW, Uri
1544 .parse(WebView.SCHEME_TEL + extra)));
1545 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1546 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1547 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1548 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1549 addIntent);
1550 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1551 new Copy(extra));
1552 break;
1553
1554 case WebView.HitTestResult.EMAIL_TYPE:
1555 menu.setHeaderTitle(extra);
1556 menu.findItem(R.id.email_context_menu_id).setIntent(
1557 new Intent(Intent.ACTION_VIEW, Uri
1558 .parse(WebView.SCHEME_MAILTO + extra)));
1559 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1560 new Copy(extra));
1561 break;
1562
1563 case WebView.HitTestResult.GEO_TYPE:
1564 menu.setHeaderTitle(extra);
1565 menu.findItem(R.id.map_context_menu_id).setIntent(
1566 new Intent(Intent.ACTION_VIEW, Uri
1567 .parse(WebView.SCHEME_GEO
1568 + URLEncoder.encode(extra))));
1569 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1570 new Copy(extra));
1571 break;
1572
1573 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1574 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1575 TextView titleView = (TextView) LayoutInflater.from(this)
1576 .inflate(android.R.layout.browser_link_context_header,
1577 null);
1578 titleView.setText(extra);
1579 menu.setHeaderView(titleView);
1580 // decide whether to show the open link in new tab option
1581 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1582 mTabControl.getTabCount() < TabControl.MAX_TABS);
1583 PackageManager pm = getPackageManager();
1584 Intent send = new Intent(Intent.ACTION_SEND);
1585 send.setType("text/plain");
1586 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1587 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1588 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1589 break;
1590 }
1591 // otherwise fall through to handle image part
1592 case WebView.HitTestResult.IMAGE_TYPE:
1593 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1594 menu.setHeaderTitle(extra);
1595 }
1596 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1597 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1598 menu.findItem(R.id.download_context_menu_id).
1599 setOnMenuItemClickListener(new Download(extra));
1600 break;
1601
1602 default:
1603 Log.w(LOGTAG, "We should not get here.");
1604 break;
1605 }
1606 }
1607
The Android Open Source Project0c908882009-03-03 19:32:16 -08001608 // Attach the given tab to the content view.
1609 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001610 // Attach the container that contains the main WebView and any other UI
1611 // associated with the tab.
1612 mContentView.addView(t.getContainer(), COVER_SCREEN_PARAMS);
Ben Murdochbff2d602009-07-01 20:19:05 +01001613
1614 if (mShouldShowErrorConsole) {
1615 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1616 if (errorConsole.numberOfErrors() == 0) {
1617 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1618 } else {
1619 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1620 }
1621
1622 mErrorConsoleContainer.addView(errorConsole,
1623 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1624 ViewGroup.LayoutParams.WRAP_CONTENT));
1625 }
1626
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001627 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001628 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001629 // Attach the sub window if necessary
1630 attachSubWindow(t);
1631 // Request focus on the top window.
1632 t.getTopWindow().requestFocus();
1633 }
1634
1635 // Attach a sub window to the main WebView of the given tab.
1636 private void attachSubWindow(TabControl.Tab t) {
1637 // If a sub window exists, attach it to the content view.
1638 final WebView subView = t.getSubWebView();
1639 if (subView != null) {
1640 final View container = t.getSubWebViewContainer();
1641 mContentView.addView(container, COVER_SCREEN_PARAMS);
1642 subView.requestFocus();
1643 }
1644 }
1645
1646 // Remove the given tab from the content view.
1647 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001648 // Remove the container that contains the main WebView.
1649 mContentView.removeView(t.getContainer());
Ben Murdochbff2d602009-07-01 20:19:05 +01001650
1651 if (mTabControl.getCurrentErrorConsole(false) != null) {
1652 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1653 }
1654
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001655 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001656 view.setEmbeddedTitleBar(null);
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001657
The Android Open Source Project0c908882009-03-03 19:32:16 -08001658 // Remove the sub window if it exists.
1659 if (t.getSubWebView() != null) {
1660 mContentView.removeView(t.getSubWebViewContainer());
1661 }
1662 }
1663
1664 // Remove the sub window if it exists. Also called by TabControl when the
1665 // user clicks the 'X' to dismiss a sub window.
1666 /* package */ void dismissSubWindow(TabControl.Tab t) {
1667 final WebView mainView = t.getWebView();
1668 if (t.getSubWebView() != null) {
1669 // Remove the container view and request focus on the main WebView.
1670 mContentView.removeView(t.getSubWebViewContainer());
1671 mainView.requestFocus();
1672 // Tell the TabControl to dismiss the subwindow. This will destroy
1673 // the WebView.
1674 mTabControl.dismissSubWindow(t);
1675 }
1676 }
1677
Leon Scroggins1f005d32009-08-10 17:36:42 -04001678 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001679 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001680 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1681 String appId) {
1682 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001683 }
1684
1685 // This method does a ton of stuff. It will attempt to create a new tab
1686 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001687 // url isn't null, it will load the given url.
1688 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001689 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001690 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1691 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1692 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001693 final TabControl.Tab tab = mTabControl.createNewTab(
1694 closeOnExit, appId, urlData.mUrl);
1695 WebView webview = tab.getWebView();
1696 if (CUSTOM_BROWSER_BAR) {
1697 mTitleBar.addTab(webview, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001698 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001699 removeTabFromContentView(currentTab);
1700 attachTabToContentView(tab);
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001701 // We must set the new tab as the current tab to reflect the old
1702 // animation behavior.
1703 mTabControl.setCurrentTab(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001704 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001705 urlData.loadIn(webview);
1706 }
1707 return tab;
1708 } else {
1709 // Get rid of the subwindow if it exists
1710 dismissSubWindow(currentTab);
1711 if (!urlData.isEmpty()) {
1712 // Load the given url.
1713 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001714 }
1715 }
Grace Klobac9181842009-04-14 08:53:22 -07001716 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001717 }
1718
Grace Klobac9181842009-04-14 08:53:22 -07001719 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001720 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001721 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001722 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001723 WebView view = t.getWebView();
1724 if (CUSTOM_BROWSER_BAR) {
1725 mTitleBar.addTab(view, false);
1726 }
1727 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001728 }
Grace Klobac9181842009-04-14 08:53:22 -07001729 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001730 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001731 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001732 }
1733 }
1734
1735 private class Copy implements OnMenuItemClickListener {
1736 private CharSequence mText;
1737
1738 public boolean onMenuItemClick(MenuItem item) {
1739 copy(mText);
1740 return true;
1741 }
1742
1743 public Copy(CharSequence toCopy) {
1744 mText = toCopy;
1745 }
1746 }
1747
1748 private class Download implements OnMenuItemClickListener {
1749 private String mText;
1750
1751 public boolean onMenuItemClick(MenuItem item) {
1752 onDownloadStartNoStream(mText, null, null, null, -1);
1753 return true;
1754 }
1755
1756 public Download(String toDownload) {
1757 mText = toDownload;
1758 }
1759 }
1760
1761 private void copy(CharSequence text) {
1762 try {
1763 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1764 if (clip != null) {
1765 clip.setClipboardText(text);
1766 }
1767 } catch (android.os.RemoteException e) {
1768 Log.e(LOGTAG, "Copy failed", e);
1769 }
1770 }
1771
1772 /**
1773 * Resets the browser title-view to whatever it must be (for example, if we
1774 * load a page from history).
1775 */
1776 private void resetTitle() {
1777 resetLockIcon();
1778 resetTitleIconAndProgress();
1779 }
1780
1781 /**
1782 * Resets the browser title-view to whatever it must be
1783 * (for example, if we had a loading error)
1784 * When we have a new page, we call resetTitle, when we
1785 * have to reset the titlebar to whatever it used to be
1786 * (for example, if the user chose to stop loading), we
1787 * call resetTitleAndRevertLockIcon.
1788 */
1789 /* package */ void resetTitleAndRevertLockIcon() {
1790 revertLockIcon();
1791 resetTitleIconAndProgress();
1792 }
1793
1794 /**
1795 * Reset the title, favicon, and progress.
1796 */
1797 private void resetTitleIconAndProgress() {
1798 WebView current = mTabControl.getCurrentWebView();
1799 if (current == null) {
1800 return;
1801 }
1802 resetTitleAndIcon(current);
1803 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001804 mWebChromeClient.onProgressChanged(current, progress);
1805 }
1806
1807 // Reset the title and the icon based on the given item.
1808 private void resetTitleAndIcon(WebView view) {
1809 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1810 if (item != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001811 setUrlTitle(item.getUrl(), item.getTitle(), view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001812 setFavicon(item.getFavicon());
1813 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001814 setUrlTitle(null, null, view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001815 setFavicon(null);
1816 }
1817 }
1818
1819 /**
1820 * Sets a title composed of the URL and the title string.
1821 * @param url The URL of the site being loaded.
1822 * @param title The title of the site being loaded.
1823 */
Leon Scroggins1f005d32009-08-10 17:36:42 -04001824 private void setUrlTitle(String url, String title, WebView view) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001825 mUrl = url;
1826 mTitle = title;
1827
Leon Scroggins1f005d32009-08-10 17:36:42 -04001828 if (CUSTOM_BROWSER_BAR) {
1829 mTitleBar.setTitleAndUrl(title, url, view);
1830 } else {
1831 setTitle(buildUrlTitle(url, title));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001832 }
1833 }
1834
1835 /**
1836 * Builds and returns the page title, which is some
1837 * combination of the page URL and title.
1838 * @param url The URL of the site being loaded.
1839 * @param title The title of the site being loaded.
1840 * @return The page title.
1841 */
1842 private String buildUrlTitle(String url, String title) {
1843 String urlTitle = "";
1844
1845 if (url != null) {
1846 String titleUrl = buildTitleUrl(url);
1847
1848 if (title != null && 0 < title.length()) {
1849 if (titleUrl != null && 0 < titleUrl.length()) {
1850 urlTitle = titleUrl + ": " + title;
1851 } else {
1852 urlTitle = title;
1853 }
1854 } else {
1855 if (titleUrl != null) {
1856 urlTitle = titleUrl;
1857 }
1858 }
1859 }
1860
1861 return urlTitle;
1862 }
1863
1864 /**
1865 * @param url The URL to build a title version of the URL from.
1866 * @return The title version of the URL or null if fails.
1867 * The title version of the URL can be either the URL hostname,
1868 * or the hostname with an "https://" prefix (for secure URLs),
1869 * or an empty string if, for example, the URL in question is a
1870 * file:// URL with no hostname.
1871 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001872 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001873 String titleUrl = null;
1874
1875 if (url != null) {
1876 try {
1877 // parse the url string
1878 URL urlObj = new URL(url);
1879 if (urlObj != null) {
1880 titleUrl = "";
1881
1882 String protocol = urlObj.getProtocol();
1883 String host = urlObj.getHost();
1884
1885 if (host != null && 0 < host.length()) {
1886 titleUrl = host;
1887 if (protocol != null) {
1888 // if a secure site, add an "https://" prefix!
1889 if (protocol.equalsIgnoreCase("https")) {
1890 titleUrl = protocol + "://" + host;
1891 }
1892 }
1893 }
1894 }
1895 } catch (MalformedURLException e) {}
1896 }
1897
1898 return titleUrl;
1899 }
1900
1901 // Set the favicon in the title bar.
1902 private void setFavicon(Bitmap icon) {
Leon Scroggins81db3662009-06-04 17:45:11 -04001903 if (CUSTOM_BROWSER_BAR) {
1904 Drawable[] array = new Drawable[3];
1905 array[0] = new PaintDrawable(Color.BLACK);
1906 PaintDrawable p = new PaintDrawable(Color.WHITE);
1907 array[1] = p;
1908 if (icon == null) {
1909 array[2] = mGenericFavicon;
1910 } else {
1911 array[2] = new BitmapDrawable(icon);
1912 }
1913 LayerDrawable d = new LayerDrawable(array);
1914 d.setLayerInset(1, 1, 1, 1, 1);
1915 d.setLayerInset(2, 2, 2, 2, 2);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001916 mTitleBar.setFavicon(d, getTopWindow());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001917 } else {
Leon Scroggins81db3662009-06-04 17:45:11 -04001918 Drawable[] array = new Drawable[2];
1919 PaintDrawable p = new PaintDrawable(Color.WHITE);
1920 p.setCornerRadius(3f);
1921 array[0] = p;
1922 if (icon == null) {
1923 array[1] = mGenericFavicon;
1924 } else {
1925 array[1] = new BitmapDrawable(icon);
1926 }
1927 LayerDrawable d = new LayerDrawable(array);
1928 d.setLayerInset(1, 2, 2, 2, 2);
1929 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001930 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001931 }
1932
1933 /**
1934 * Saves the current lock-icon state before resetting
1935 * the lock icon. If we have an error, we may need to
1936 * roll back to the previous state.
1937 */
1938 private void saveLockIcon() {
1939 mPrevLockType = mLockIconType;
1940 }
1941
1942 /**
1943 * Reverts the lock-icon state to the last saved state,
1944 * for example, if we had an error, and need to cancel
1945 * the load.
1946 */
1947 private void revertLockIcon() {
1948 mLockIconType = mPrevLockType;
1949
Dave Bort31a6d1c2009-04-13 15:56:49 -07001950 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001951 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
1952 " revert lock icon to " + mLockIconType);
1953 }
1954
1955 updateLockIconImage(mLockIconType);
1956 }
1957
Leon Scroggins1f005d32009-08-10 17:36:42 -04001958 /**
1959 * Close the tab after removing its associated title bar.
1960 */
1961 private void closeTab(TabControl.Tab t) {
Leon Scrogginsa11b75a2009-08-18 10:22:05 -04001962 if (CUSTOM_BROWSER_BAR) {
1963 mTitleBar.removeTab(mTabControl.getTabIndex(t));
1964 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001965 mTabControl.removeTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001966 }
1967
1968 private void goBackOnePageOrQuit() {
1969 TabControl.Tab current = mTabControl.getCurrentTab();
1970 if (current == null) {
1971 /*
1972 * Instead of finishing the activity, simply push this to the back
1973 * of the stack and let ActivityManager to choose the foreground
1974 * activity. As BrowserActivity is singleTask, it will be always the
1975 * root of the task. So we can use either true or false for
1976 * moveTaskToBack().
1977 */
1978 moveTaskToBack(true);
1979 }
1980 WebView w = current.getWebView();
1981 if (w.canGoBack()) {
1982 w.goBack();
1983 } else {
1984 // Check to see if we are closing a window that was created by
1985 // another window. If so, we switch back to that window.
1986 TabControl.Tab parent = current.getParentTab();
1987 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001988 switchToTab(mTabControl.getTabIndex(parent));
1989 // Now we close the other tab
1990 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001991 } else {
1992 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07001993 // force mPageStarted to be false as we are going to either
1994 // finish the activity or remove the tab. This will ensure
1995 // pauseWebView() taking action.
1996 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001997 if (mTabControl.getTabCount() == 1) {
1998 finish();
1999 return;
2000 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002001 // call pauseWebViewTimers() now, we won't be able to call
2002 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002003 // Temporarily change mActivityInPause to be true as
2004 // pauseWebViewTimers() will do nothing if mActivityInPause
2005 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002006 boolean savedState = mActivityInPause;
2007 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002008 Log.e(LOGTAG, "BrowserActivity is already paused "
2009 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002010 }
2011 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002012 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002013 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002014 removeTabFromContentView(current);
2015 mTabControl.removeTab(current);
2016 }
2017 /*
2018 * Instead of finishing the activity, simply push this to the back
2019 * of the stack and let ActivityManager to choose the foreground
2020 * activity. As BrowserActivity is singleTask, it will be always the
2021 * root of the task. So we can use either true or false for
2022 * moveTaskToBack().
2023 */
2024 moveTaskToBack(true);
2025 }
2026 }
2027 }
2028
2029 public KeyTracker.State onKeyTracker(int keyCode,
2030 KeyEvent event,
2031 KeyTracker.Stage stage,
2032 int duration) {
2033 // if onKeyTracker() is called after activity onStop()
2034 // because of accumulated key events,
2035 // we should ignore it as browser is not active any more.
2036 WebView topWindow = getTopWindow();
Andrei Popescuadc008d2009-06-26 14:11:30 +01002037 if (topWindow == null && mCustomView == null)
The Android Open Source Project0c908882009-03-03 19:32:16 -08002038 return KeyTracker.State.NOT_TRACKING;
2039
2040 if (keyCode == KeyEvent.KEYCODE_BACK) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01002041 // Check if a custom view is currently showing and, if it is, hide it.
2042 if (mCustomView != null) {
2043 mWebChromeClient.onHideCustomView();
2044 return KeyTracker.State.DONE_TRACKING;
2045 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002046 if (stage == KeyTracker.Stage.LONG_REPEAT) {
Leon Scroggins30444232009-09-04 18:36:20 -04002047 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002048 return KeyTracker.State.DONE_TRACKING;
2049 } else if (stage == KeyTracker.Stage.UP) {
2050 // FIXME: Currently, we do not have a notion of the
2051 // history picker for the subwindow, but maybe we
2052 // should?
2053 WebView subwindow = mTabControl.getCurrentSubWindow();
2054 if (subwindow != null) {
2055 if (subwindow.canGoBack()) {
2056 subwindow.goBack();
2057 } else {
2058 dismissSubWindow(mTabControl.getCurrentTab());
2059 }
2060 } else {
2061 goBackOnePageOrQuit();
2062 }
2063 return KeyTracker.State.DONE_TRACKING;
2064 }
2065 return KeyTracker.State.KEEP_TRACKING;
2066 }
2067 return KeyTracker.State.NOT_TRACKING;
2068 }
2069
2070 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2071 if (keyCode == KeyEvent.KEYCODE_MENU) {
2072 mMenuIsDown = true;
Grace Kloba6ee9c492009-07-13 10:04:34 -07002073 } else if (mMenuIsDown) {
2074 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2075 // still down, we don't want to trigger the search. Pretend to
2076 // consume the key and do nothing.
2077 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002078 }
2079 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2080 if (!handled) {
2081 switch (keyCode) {
2082 case KeyEvent.KEYCODE_SPACE:
2083 if (event.isShiftPressed()) {
2084 getTopWindow().pageUp(false);
2085 } else {
2086 getTopWindow().pageDown(false);
2087 }
2088 handled = true;
2089 break;
2090
2091 default:
2092 break;
2093 }
2094 }
2095 return handled || super.onKeyDown(keyCode, event);
2096 }
2097
2098 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2099 if (keyCode == KeyEvent.KEYCODE_MENU) {
2100 mMenuIsDown = false;
2101 }
2102 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2103 }
2104
2105 private void stopLoading() {
2106 resetTitleAndRevertLockIcon();
2107 WebView w = getTopWindow();
2108 w.stopLoading();
2109 mWebViewClient.onPageFinished(w, w.getUrl());
2110
2111 cancelStopToast();
2112 mStopToast = Toast
2113 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2114 mStopToast.show();
2115 }
2116
2117 private void cancelStopToast() {
2118 if (mStopToast != null) {
2119 mStopToast.cancel();
2120 mStopToast = null;
2121 }
2122 }
2123
2124 // called by a non-UI thread to post the message
2125 public void postMessage(int what, int arg1, int arg2, Object obj) {
2126 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2127 }
2128
2129 // public message ids
2130 public final static int LOAD_URL = 1001;
2131 public final static int STOP_LOAD = 1002;
2132
2133 // Message Ids
2134 private static final int FOCUS_NODE_HREF = 102;
2135 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002136 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002137
2138 // Private handler for handling javascript and saving passwords
2139 private Handler mHandler = new Handler() {
2140
2141 public void handleMessage(Message msg) {
2142 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002143 case FOCUS_NODE_HREF:
2144 String url = (String) msg.getData().get("url");
2145 if (url == null || url.length() == 0) {
2146 break;
2147 }
2148 HashMap focusNodeMap = (HashMap) msg.obj;
2149 WebView view = (WebView) focusNodeMap.get("webview");
2150 // Only apply the action if the top window did not change.
2151 if (getTopWindow() != view) {
2152 break;
2153 }
2154 switch (msg.arg1) {
2155 case R.id.open_context_menu_id:
2156 case R.id.view_image_context_menu_id:
2157 loadURL(getTopWindow(), url);
2158 break;
2159 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002160 final TabControl.Tab parent = mTabControl
2161 .getCurrentTab();
2162 final TabControl.Tab newTab = openTab(url);
2163 if (newTab != parent) {
2164 parent.addChildTab(newTab);
2165 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002166 break;
2167 case R.id.bookmark_context_menu_id:
2168 Intent intent = new Intent(BrowserActivity.this,
2169 AddBookmarkPage.class);
2170 intent.putExtra("url", url);
2171 startActivity(intent);
2172 break;
2173 case R.id.share_link_context_menu_id:
2174 Browser.sendString(BrowserActivity.this, url);
2175 break;
2176 case R.id.copy_link_context_menu_id:
2177 copy(url);
2178 break;
2179 case R.id.save_link_context_menu_id:
2180 case R.id.download_context_menu_id:
2181 onDownloadStartNoStream(url, null, null, null, -1);
2182 break;
2183 }
2184 break;
2185
2186 case LOAD_URL:
2187 loadURL(getTopWindow(), (String) msg.obj);
2188 break;
2189
2190 case STOP_LOAD:
2191 stopLoading();
2192 break;
2193
2194 case CANCEL_CREDS_REQUEST:
2195 resumeAfterCredentials();
2196 break;
2197
The Android Open Source Project0c908882009-03-03 19:32:16 -08002198 case RELEASE_WAKELOCK:
2199 if (mWakeLock.isHeld()) {
2200 mWakeLock.release();
2201 }
2202 break;
2203 }
2204 }
2205 };
2206
Leon Scroggins89c6d362009-07-15 16:54:37 -04002207 private void updateScreenshot(WebView view) {
2208 // If this is a bookmarked site, add a screenshot to the database.
2209 // FIXME: When should we update? Every time?
2210 // FIXME: Would like to make sure there is actually something to
2211 // draw, but the API for that (WebViewCore.pictureReady()) is not
2212 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002213 ContentResolver cr = getContentResolver();
2214 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002215 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002216 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002217 boolean succeed = c.moveToFirst();
2218 ContentValues values = null;
2219 while (succeed) {
2220 if (values == null) {
2221 final ByteArrayOutputStream os
2222 = new ByteArrayOutputStream();
2223 Picture thumbnail = view.capturePicture();
2224 // Keep width and height in sync with BrowserBookmarksPage
2225 // and bookmark_thumb
2226 Bitmap bm = Bitmap.createBitmap(100, 80,
2227 Bitmap.Config.ARGB_4444);
2228 Canvas canvas = new Canvas(bm);
2229 // May need to tweak these values to determine what is the
2230 // best scale factor
2231 canvas.scale(.5f, .5f);
2232 thumbnail.draw(canvas);
2233 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2234 values = new ContentValues();
2235 values.put(Browser.BookmarkColumns.THUMBNAIL,
2236 os.toByteArray());
2237 }
2238 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2239 c.getInt(0)), values, null, null);
2240 succeed = c.moveToNext();
2241 }
2242 c.close();
2243 }
2244 }
2245
The Android Open Source Project0c908882009-03-03 19:32:16 -08002246 // -------------------------------------------------------------------------
2247 // WebViewClient implementation.
2248 //-------------------------------------------------------------------------
2249
2250 // Use in overrideUrlLoading
2251 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2252 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2253 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2254 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2255
2256 /* package */ WebViewClient getWebViewClient() {
2257 return mWebViewClient;
2258 }
2259
Patrick Scott3918d442009-08-04 13:22:29 -04002260 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002261 if (icon != null) {
2262 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott3918d442009-08-04 13:22:29 -04002263 view, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002264 }
2265 setFavicon(icon);
2266 }
2267
2268 private final WebViewClient mWebViewClient = new WebViewClient() {
2269 @Override
2270 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2271 resetLockIcon(url);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002272 setUrlTitle(url, null, view);
Ben Murdochbff2d602009-07-01 20:19:05 +01002273
2274 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2275 if (errorConsole != null) {
2276 errorConsole.clearErrorMessages();
2277 if (mShouldShowErrorConsole) {
2278 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2279 }
2280 }
2281
The Android Open Source Project0c908882009-03-03 19:32:16 -08002282 // Call updateIcon instead of setFavicon so the bookmark
2283 // database can be updated.
Patrick Scott3918d442009-08-04 13:22:29 -04002284 updateIcon(view, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002285
Grace Kloba4d7880f2009-08-12 09:35:42 -07002286 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002287 String host;
2288 try {
2289 WebAddress uri = new WebAddress(url);
2290 host = uri.mHost;
2291 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002292 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002293 }
2294 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002295 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002296 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002297 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002298 }
2299
2300 // Performance probe
2301 if (false) {
2302 mStart = SystemClock.uptimeMillis();
2303 mProcessStart = Process.getElapsedCpuTime();
2304 long[] sysCpu = new long[7];
2305 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2306 sysCpu, null)) {
2307 mUserStart = sysCpu[0] + sysCpu[1];
2308 mSystemStart = sysCpu[2];
2309 mIdleStart = sysCpu[3];
2310 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2311 }
2312 mUiStart = SystemClock.currentThreadTimeMillis();
2313 }
2314
2315 if (!mPageStarted) {
2316 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002317 // if onResume() has been called, resumeWebViewTimers() does
2318 // nothing.
2319 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002320 }
2321
2322 // reset sync timer to avoid sync starts during loading a page
2323 CookieSyncManager.getInstance().resetSync();
2324
2325 mInLoad = true;
2326 updateInLoadMenuItems();
2327 if (!mIsNetworkUp) {
2328 if ( mAlertDialog == null) {
2329 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2330 .setTitle(R.string.loadSuspendedTitle)
2331 .setMessage(R.string.loadSuspended)
2332 .setPositiveButton(R.string.ok, null)
2333 .show();
2334 }
2335 if (view != null) {
2336 view.setNetworkAvailable(false);
2337 }
2338 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002339 }
2340
2341 @Override
2342 public void onPageFinished(WebView view, String url) {
2343 // Reset the title and icon in case we stopped a provisional
2344 // load.
2345 resetTitleAndIcon(view);
2346
2347 // Update the lock icon image only once we are done loading
2348 updateLockIconImage(mLockIconType);
Leon Scroggins89c6d362009-07-15 16:54:37 -04002349 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002350
The Android Open Source Project0c908882009-03-03 19:32:16 -08002351 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002352 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002353 long[] sysCpu = new long[7];
2354 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2355 sysCpu, null)) {
2356 String uiInfo = "UI thread used "
2357 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2358 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002359 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002360 Log.d(LOGTAG, uiInfo);
2361 }
2362 //The string that gets written to the log
2363 String performanceString = "It took total "
2364 + (SystemClock.uptimeMillis() - mStart)
2365 + " ms clock time to load the page."
2366 + "\nbrowser process used "
2367 + (Process.getElapsedCpuTime() - mProcessStart)
2368 + " ms, user processes used "
2369 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2370 + " ms, kernel used "
2371 + (sysCpu[2] - mSystemStart) * 10
2372 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2373 + " ms and irq took "
2374 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2375 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002376 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002377 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2378 }
2379 if (url != null) {
2380 // strip the url to maintain consistency
2381 String newUrl = new String(url);
2382 if (newUrl.startsWith("http://www.")) {
2383 newUrl = newUrl.substring(11);
2384 } else if (newUrl.startsWith("http://")) {
2385 newUrl = newUrl.substring(7);
2386 } else if (newUrl.startsWith("https://www.")) {
2387 newUrl = newUrl.substring(12);
2388 } else if (newUrl.startsWith("https://")) {
2389 newUrl = newUrl.substring(8);
2390 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002391 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002392 Log.d(LOGTAG, newUrl + " loaded");
2393 }
2394 /*
2395 if (sWhiteList.contains(newUrl)) {
2396 // The string that gets pushed to the statistcs
2397 // service
2398 performanceString = performanceString
2399 + "\nWebpage: "
2400 + newUrl
2401 + "\nCarrier: "
2402 + android.os.SystemProperties
2403 .get("gsm.sim.operator.alpha");
2404 if (mWebView != null
2405 && mWebView.getContext() != null
2406 && mWebView.getContext().getSystemService(
2407 Context.CONNECTIVITY_SERVICE) != null) {
2408 ConnectivityManager cManager =
2409 (ConnectivityManager) mWebView
2410 .getContext().getSystemService(
2411 Context.CONNECTIVITY_SERVICE);
2412 NetworkInfo nInfo = cManager
2413 .getActiveNetworkInfo();
2414 if (nInfo != null) {
2415 performanceString = performanceString
2416 + "\nNetwork Type: "
2417 + nInfo.getType().toString();
2418 }
2419 }
2420 Checkin.logEvent(mResolver,
2421 Checkin.Events.Tag.WEBPAGE_LOAD,
2422 performanceString);
2423 Log.w(LOGTAG, "pushed to the statistics service");
2424 }
2425 */
2426 }
2427 }
2428 }
2429
2430 if (mInTrace) {
2431 mInTrace = false;
2432 Debug.stopMethodTracing();
2433 }
2434
2435 if (mPageStarted) {
2436 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002437 // pauseWebViewTimers() will do nothing and return false if
2438 // onPause() is not called yet.
2439 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002440 if (mWakeLock.isHeld()) {
2441 mHandler.removeMessages(RELEASE_WAKELOCK);
2442 mWakeLock.release();
2443 }
2444 }
2445 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002446 }
2447
2448 // return true if want to hijack the url to let another app to handle it
2449 @Override
2450 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2451 if (url.startsWith(SCHEME_WTAI)) {
2452 // wtai://wp/mc;number
2453 // number=string(phone-number)
2454 if (url.startsWith(SCHEME_WTAI_MC)) {
2455 Intent intent = new Intent(Intent.ACTION_VIEW,
2456 Uri.parse(WebView.SCHEME_TEL +
2457 url.substring(SCHEME_WTAI_MC.length())));
2458 startActivity(intent);
2459 return true;
2460 }
2461 // wtai://wp/sd;dtmf
2462 // dtmf=string(dialstring)
2463 if (url.startsWith(SCHEME_WTAI_SD)) {
2464 // TODO
2465 // only send when there is active voice connection
2466 return false;
2467 }
2468 // wtai://wp/ap;number;name
2469 // number=string(phone-number)
2470 // name=string
2471 if (url.startsWith(SCHEME_WTAI_AP)) {
2472 // TODO
2473 return false;
2474 }
2475 }
2476
Dianne Hackborn99189432009-06-17 18:06:18 -07002477 // The "about:" schemes are internal to the browser; don't
2478 // want these to be dispatched to other apps.
2479 if (url.startsWith("about:")) {
2480 return false;
2481 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002482
Dianne Hackborn99189432009-06-17 18:06:18 -07002483 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002484
Dianne Hackborn99189432009-06-17 18:06:18 -07002485 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002486 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002487 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2488 } catch (URISyntaxException ex) {
2489 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002490 return false;
2491 }
2492
Grace Kloba5b078b52009-06-24 20:23:41 -07002493 // check whether the intent can be resolved. If not, we will see
2494 // whether we can download it from the Market.
2495 if (getPackageManager().resolveActivity(intent, 0) == null) {
2496 String packagename = intent.getPackage();
2497 if (packagename != null) {
2498 intent = new Intent(Intent.ACTION_VIEW, Uri
2499 .parse("market://search?q=pname:" + packagename));
2500 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2501 startActivity(intent);
2502 return true;
2503 } else {
2504 return false;
2505 }
2506 }
2507
Dianne Hackborn99189432009-06-17 18:06:18 -07002508 // sanitize the Intent, ensuring web pages can not bypass browser
2509 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002510 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002511 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002512 try {
2513 if (startActivityIfNeeded(intent, -1)) {
2514 return true;
2515 }
2516 } catch (ActivityNotFoundException ex) {
2517 // ignore the error. If no application can handle the URL,
2518 // eg about:blank, assume the browser can handle it.
2519 }
2520
2521 if (mMenuIsDown) {
2522 openTab(url);
2523 closeOptionsMenu();
2524 return true;
2525 }
2526
2527 return false;
2528 }
2529
2530 /**
2531 * Updates the lock icon. This method is called when we discover another
2532 * resource to be loaded for this page (for example, javascript). While
2533 * we update the icon type, we do not update the lock icon itself until
2534 * we are done loading, it is slightly more secure this way.
2535 */
2536 @Override
2537 public void onLoadResource(WebView view, String url) {
2538 if (url != null && url.length() > 0) {
2539 // It is only if the page claims to be secure
2540 // that we may have to update the lock:
2541 if (mLockIconType == LOCK_ICON_SECURE) {
2542 // If NOT a 'safe' url, change the lock to mixed content!
2543 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2544 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002545 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002546 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2547 " updated lock icon to " + mLockIconType + " due to " + url);
2548 }
2549 }
2550 }
2551 }
2552 }
2553
2554 /**
2555 * Show the dialog, asking the user if they would like to continue after
2556 * an excessive number of HTTP redirects.
2557 */
2558 @Override
2559 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2560 final Message continueMsg) {
2561 new AlertDialog.Builder(BrowserActivity.this)
2562 .setTitle(R.string.browserFrameRedirect)
2563 .setMessage(R.string.browserFrame307Post)
2564 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2565 public void onClick(DialogInterface dialog, int which) {
2566 continueMsg.sendToTarget();
2567 }})
2568 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2569 public void onClick(DialogInterface dialog, int which) {
2570 cancelMsg.sendToTarget();
2571 }})
2572 .setOnCancelListener(new OnCancelListener() {
2573 public void onCancel(DialogInterface dialog) {
2574 cancelMsg.sendToTarget();
2575 }})
2576 .show();
2577 }
2578
Patrick Scott37911c72009-03-24 18:02:58 -07002579 // Container class for the next error dialog that needs to be
2580 // displayed.
2581 class ErrorDialog {
2582 public final int mTitle;
2583 public final String mDescription;
2584 public final int mError;
2585 ErrorDialog(int title, String desc, int error) {
2586 mTitle = title;
2587 mDescription = desc;
2588 mError = error;
2589 }
2590 };
2591
2592 private void processNextError() {
2593 if (mQueuedErrors == null) {
2594 return;
2595 }
2596 // The first one is currently displayed so just remove it.
2597 mQueuedErrors.removeFirst();
2598 if (mQueuedErrors.size() == 0) {
2599 mQueuedErrors = null;
2600 return;
2601 }
2602 showError(mQueuedErrors.getFirst());
2603 }
2604
2605 private DialogInterface.OnDismissListener mDialogListener =
2606 new DialogInterface.OnDismissListener() {
2607 public void onDismiss(DialogInterface d) {
2608 processNextError();
2609 }
2610 };
2611 private LinkedList<ErrorDialog> mQueuedErrors;
2612
2613 private void queueError(int err, String desc) {
2614 if (mQueuedErrors == null) {
2615 mQueuedErrors = new LinkedList<ErrorDialog>();
2616 }
2617 for (ErrorDialog d : mQueuedErrors) {
2618 if (d.mError == err) {
2619 // Already saw a similar error, ignore the new one.
2620 return;
2621 }
2622 }
2623 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002624 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002625 R.string.browserFrameFileErrorLabel :
2626 R.string.browserFrameNetworkErrorLabel,
2627 desc, err);
2628 mQueuedErrors.addLast(errDialog);
2629
2630 // Show the dialog now if the queue was empty.
2631 if (mQueuedErrors.size() == 1) {
2632 showError(errDialog);
2633 }
2634 }
2635
2636 private void showError(ErrorDialog errDialog) {
2637 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2638 .setTitle(errDialog.mTitle)
2639 .setMessage(errDialog.mDescription)
2640 .setPositiveButton(R.string.ok, null)
2641 .create();
2642 d.setOnDismissListener(mDialogListener);
2643 d.show();
2644 }
2645
The Android Open Source Project0c908882009-03-03 19:32:16 -08002646 /**
2647 * Show a dialog informing the user of the network error reported by
2648 * WebCore.
2649 */
2650 @Override
2651 public void onReceivedError(WebView view, int errorCode,
2652 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002653 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2654 errorCode != WebViewClient.ERROR_CONNECT &&
2655 errorCode != WebViewClient.ERROR_BAD_URL &&
2656 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2657 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002658 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002659 }
Patrick Scott37911c72009-03-24 18:02:58 -07002660 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2661 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002662
2663 // We need to reset the title after an error.
2664 resetTitleAndRevertLockIcon();
2665 }
2666
2667 /**
2668 * Check with the user if it is ok to resend POST data as the page they
2669 * are trying to navigate to is the result of a POST.
2670 */
2671 @Override
2672 public void onFormResubmission(WebView view, final Message dontResend,
2673 final Message resend) {
2674 new AlertDialog.Builder(BrowserActivity.this)
2675 .setTitle(R.string.browserFrameFormResubmitLabel)
2676 .setMessage(R.string.browserFrameFormResubmitMessage)
2677 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2678 public void onClick(DialogInterface dialog, int which) {
2679 resend.sendToTarget();
2680 }})
2681 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2682 public void onClick(DialogInterface dialog, int which) {
2683 dontResend.sendToTarget();
2684 }})
2685 .setOnCancelListener(new OnCancelListener() {
2686 public void onCancel(DialogInterface dialog) {
2687 dontResend.sendToTarget();
2688 }})
2689 .show();
2690 }
2691
2692 /**
2693 * Insert the url into the visited history database.
2694 * @param url The url to be inserted.
2695 * @param isReload True if this url is being reloaded.
2696 * FIXME: Not sure what to do when reloading the page.
2697 */
2698 @Override
2699 public void doUpdateVisitedHistory(WebView view, String url,
2700 boolean isReload) {
2701 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2702 return;
2703 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002704 // remove "client" before updating it to the history so that it wont
2705 // show up in the auto-complete list.
2706 int index = url.indexOf("client=ms-");
2707 if (index > 0 && url.contains(".google.")) {
2708 int end = url.indexOf('&', index);
2709 if (end > 0) {
2710 url = url.substring(0, index-1).concat(url.substring(end));
2711 } else {
2712 url = url.substring(0, index-1);
2713 }
2714 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002715 Browser.updateVisitedHistory(mResolver, url, true);
2716 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2717 }
2718
2719 /**
2720 * Displays SSL error(s) dialog to the user.
2721 */
2722 @Override
2723 public void onReceivedSslError(
2724 final WebView view, final SslErrorHandler handler, final SslError error) {
2725
2726 if (mSettings.showSecurityWarnings()) {
2727 final LayoutInflater factory =
2728 LayoutInflater.from(BrowserActivity.this);
2729 final View warningsView =
2730 factory.inflate(R.layout.ssl_warnings, null);
2731 final LinearLayout placeholder =
2732 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2733
2734 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2735 LinearLayout ll = (LinearLayout)factory
2736 .inflate(R.layout.ssl_warning, null);
2737 ((TextView)ll.findViewById(R.id.warning))
2738 .setText(R.string.ssl_untrusted);
2739 placeholder.addView(ll);
2740 }
2741
2742 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2743 LinearLayout ll = (LinearLayout)factory
2744 .inflate(R.layout.ssl_warning, null);
2745 ((TextView)ll.findViewById(R.id.warning))
2746 .setText(R.string.ssl_mismatch);
2747 placeholder.addView(ll);
2748 }
2749
2750 if (error.hasError(SslError.SSL_EXPIRED)) {
2751 LinearLayout ll = (LinearLayout)factory
2752 .inflate(R.layout.ssl_warning, null);
2753 ((TextView)ll.findViewById(R.id.warning))
2754 .setText(R.string.ssl_expired);
2755 placeholder.addView(ll);
2756 }
2757
2758 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2759 LinearLayout ll = (LinearLayout)factory
2760 .inflate(R.layout.ssl_warning, null);
2761 ((TextView)ll.findViewById(R.id.warning))
2762 .setText(R.string.ssl_not_yet_valid);
2763 placeholder.addView(ll);
2764 }
2765
2766 new AlertDialog.Builder(BrowserActivity.this)
2767 .setTitle(R.string.security_warning)
2768 .setIcon(android.R.drawable.ic_dialog_alert)
2769 .setView(warningsView)
2770 .setPositiveButton(R.string.ssl_continue,
2771 new DialogInterface.OnClickListener() {
2772 public void onClick(DialogInterface dialog, int whichButton) {
2773 handler.proceed();
2774 }
2775 })
2776 .setNeutralButton(R.string.view_certificate,
2777 new DialogInterface.OnClickListener() {
2778 public void onClick(DialogInterface dialog, int whichButton) {
2779 showSSLCertificateOnError(view, handler, error);
2780 }
2781 })
2782 .setNegativeButton(R.string.cancel,
2783 new DialogInterface.OnClickListener() {
2784 public void onClick(DialogInterface dialog, int whichButton) {
2785 handler.cancel();
2786 BrowserActivity.this.resetTitleAndRevertLockIcon();
2787 }
2788 })
2789 .setOnCancelListener(
2790 new DialogInterface.OnCancelListener() {
2791 public void onCancel(DialogInterface dialog) {
2792 handler.cancel();
2793 BrowserActivity.this.resetTitleAndRevertLockIcon();
2794 }
2795 })
2796 .show();
2797 } else {
2798 handler.proceed();
2799 }
2800 }
2801
2802 /**
2803 * Handles an HTTP authentication request.
2804 *
2805 * @param handler The authentication handler
2806 * @param host The host
2807 * @param realm The realm
2808 */
2809 @Override
2810 public void onReceivedHttpAuthRequest(WebView view,
2811 final HttpAuthHandler handler, final String host, final String realm) {
2812 String username = null;
2813 String password = null;
2814
2815 boolean reuseHttpAuthUsernamePassword =
2816 handler.useHttpAuthUsernamePassword();
2817
2818 if (reuseHttpAuthUsernamePassword &&
2819 (mTabControl.getCurrentWebView() != null)) {
2820 String[] credentials =
2821 mTabControl.getCurrentWebView()
2822 .getHttpAuthUsernamePassword(host, realm);
2823 if (credentials != null && credentials.length == 2) {
2824 username = credentials[0];
2825 password = credentials[1];
2826 }
2827 }
2828
2829 if (username != null && password != null) {
2830 handler.proceed(username, password);
2831 } else {
2832 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2833 }
2834 }
2835
2836 @Override
2837 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2838 if (mMenuIsDown) {
2839 // only check shortcut key when MENU is held
2840 return getWindow().isShortcutKey(event.getKeyCode(), event);
2841 } else {
2842 return false;
2843 }
2844 }
2845
2846 @Override
2847 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2848 if (view != mTabControl.getCurrentTopWebView()) {
2849 return;
2850 }
2851 if (event.isDown()) {
2852 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2853 } else {
2854 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2855 }
2856 }
2857 };
2858
2859 //--------------------------------------------------------------------------
2860 // WebChromeClient implementation
2861 //--------------------------------------------------------------------------
2862
2863 /* package */ WebChromeClient getWebChromeClient() {
2864 return mWebChromeClient;
2865 }
2866
2867 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2868 // Helper method to create a new tab or sub window.
2869 private void createWindow(final boolean dialog, final Message msg) {
2870 if (dialog) {
2871 mTabControl.createSubWindow();
2872 final TabControl.Tab t = mTabControl.getCurrentTab();
2873 attachSubWindow(t);
2874 WebView.WebViewTransport transport =
2875 (WebView.WebViewTransport) msg.obj;
2876 transport.setWebView(t.getSubWebView());
2877 msg.sendToTarget();
2878 } else {
2879 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04002880 final TabControl.Tab newTab
2881 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07002882 if (newTab != parent) {
2883 parent.addChildTab(newTab);
2884 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002885 WebView.WebViewTransport transport =
2886 (WebView.WebViewTransport) msg.obj;
2887 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04002888 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002889 }
2890 }
2891
2892 @Override
2893 public boolean onCreateWindow(WebView view, final boolean dialog,
2894 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002895 // Short-circuit if we can't create any more tabs or sub windows.
2896 if (dialog && mTabControl.getCurrentSubWindow() != null) {
2897 new AlertDialog.Builder(BrowserActivity.this)
2898 .setTitle(R.string.too_many_subwindows_dialog_title)
2899 .setIcon(android.R.drawable.ic_dialog_alert)
2900 .setMessage(R.string.too_many_subwindows_dialog_message)
2901 .setPositiveButton(R.string.ok, null)
2902 .show();
2903 return false;
2904 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
2905 new AlertDialog.Builder(BrowserActivity.this)
2906 .setTitle(R.string.too_many_windows_dialog_title)
2907 .setIcon(android.R.drawable.ic_dialog_alert)
2908 .setMessage(R.string.too_many_windows_dialog_message)
2909 .setPositiveButton(R.string.ok, null)
2910 .show();
2911 return false;
2912 }
2913
2914 // Short-circuit if this was a user gesture.
2915 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002916 createWindow(dialog, resultMsg);
2917 return true;
2918 }
2919
2920 // Allow the popup and create the appropriate window.
2921 final AlertDialog.OnClickListener allowListener =
2922 new AlertDialog.OnClickListener() {
2923 public void onClick(DialogInterface d,
2924 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002925 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002926 }
2927 };
2928
2929 // Block the popup by returning a null WebView.
2930 final AlertDialog.OnClickListener blockListener =
2931 new AlertDialog.OnClickListener() {
2932 public void onClick(DialogInterface d, int which) {
2933 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002934 }
2935 };
2936
2937 // Build a confirmation dialog to display to the user.
2938 final AlertDialog d =
2939 new AlertDialog.Builder(BrowserActivity.this)
2940 .setTitle(R.string.attention)
2941 .setIcon(android.R.drawable.ic_dialog_alert)
2942 .setMessage(R.string.popup_window_attempt)
2943 .setPositiveButton(R.string.allow, allowListener)
2944 .setNegativeButton(R.string.block, blockListener)
2945 .setCancelable(false)
2946 .create();
2947
2948 // Show the confirmation dialog.
2949 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002950 return true;
2951 }
2952
2953 @Override
2954 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002955 final TabControl.Tab current = mTabControl.getCurrentTab();
2956 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002957 if (parent != null) {
2958 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002959 switchToTab(mTabControl.getTabIndex(parent));
2960 // Now we need to close the window
2961 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002962 }
2963 }
2964
2965 @Override
2966 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002967 if (CUSTOM_BROWSER_BAR) {
2968 mTitleBar.setProgress(newProgress, view);
2969 } else {
2970 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
2971 newProgress * 100);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002972 }
2973
2974 if (newProgress == 100) {
2975 // onProgressChanged() is called for sub-frame too while
2976 // onPageFinished() is only called for the main frame. sync
2977 // cookie and cache promptly here.
2978 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002979 if (mInLoad) {
2980 mInLoad = false;
2981 updateInLoadMenuItems();
2982 }
2983 } else {
2984 // onPageFinished may have already been called but a subframe
2985 // is still loading and updating the progress. Reset mInLoad
2986 // and update the menu items.
2987 if (!mInLoad) {
2988 mInLoad = true;
2989 updateInLoadMenuItems();
2990 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002991 }
2992 }
2993
2994 @Override
2995 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04002996 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002997
2998 // here, if url is null, we want to reset the title
Leon Scroggins1f005d32009-08-10 17:36:42 -04002999 setUrlTitle(url, title, view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003000
3001 if (url == null ||
3002 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3003 return;
3004 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003005 // See if we can find the current url in our history database and
3006 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003007 if (url.startsWith("http://www.")) {
3008 url = url.substring(11);
3009 } else if (url.startsWith("http://")) {
3010 url = url.substring(4);
3011 }
3012 try {
3013 url = "%" + url;
3014 String [] selArgs = new String[] { url };
3015
3016 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3017 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3018 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3019 Browser.HISTORY_PROJECTION, where, selArgs, null);
3020 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003021 // Current implementation of database only has one entry per
3022 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003023 ContentValues map = new ContentValues();
3024 map.put(Browser.BookmarkColumns.TITLE, title);
3025 mResolver.update(Browser.BOOKMARKS_URI, map,
3026 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003027 }
3028 c.close();
3029 } catch (IllegalStateException e) {
3030 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3031 } catch (SQLiteException ex) {
3032 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3033 }
3034 }
3035
3036 @Override
3037 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003038 updateIcon(view, icon);
3039 }
3040
3041 @Override
3042 public void onReceivedTouchIconUrl(WebView view, String url) {
3043 final ContentResolver cr = getContentResolver();
3044 final Cursor c =
3045 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003046 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003047 if (c != null) {
3048 if (c.getCount() > 0) {
3049 new DownloadTouchIcon(cr, c, view).execute(url);
3050 } else {
3051 c.close();
3052 }
3053 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003054 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003055
Andrei Popescuadc008d2009-06-26 14:11:30 +01003056 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003057 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003058 if (mCustomView != null)
3059 return;
3060
3061 // Add the custom view to its container.
3062 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3063 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003064 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003065 // Save the menu state and set it to empty while the custom
3066 // view is showing.
3067 mOldMenuState = mMenuState;
3068 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003069 // Hide the content view.
3070 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003071 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003072 mCustomViewContainer.setVisibility(View.VISIBLE);
3073 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003074 }
3075
3076 @Override
3077 public void onHideCustomView() {
3078 if (mCustomView == null)
3079 return;
3080
Andrei Popescuc9b55562009-07-07 10:51:15 +01003081 // Hide the custom view.
3082 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003083 // Remove the custom view from its container.
3084 mCustomViewContainer.removeView(mCustomView);
3085 mCustomView = null;
3086 // Reset the old menu state.
3087 mMenuState = mOldMenuState;
3088 mOldMenuState = EMPTY_MENU;
3089 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003090 mCustomViewCallback.onCustomViewHidden();
3091 // Show the content view.
3092 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003093 }
3094
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003095 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003096 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003097 * @param url the URL that exceeded the quota
3098 * @param databaseIdentifier the identifier of the database on
3099 * which the transaction that caused the quota overflow was run
3100 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003101 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003102 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003103 * @param quotaUpdater The callback to run when a decision to allow or
3104 * deny quota has been made. Don't forget to call this!
3105 */
3106 @Override
3107 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003108 String databaseIdentifier, long currentQuota, long estimatedSize,
3109 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003110 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003111 url, databaseIdentifier, currentQuota, estimatedSize,
3112 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003113 }
3114
3115 /**
3116 * The Application Cache has exceeded its max size.
3117 * @param spaceNeeded is the amount of disk space that would be needed
3118 * in order for the last appcache operation to succeed.
3119 * @param totalUsedQuota is the sum of all origins' quota.
3120 * @param quotaUpdater A callback to inform the WebCore thread that a new
3121 * app cache size is available. This callback must always be executed at
3122 * some point to ensure that the sleeping WebCore thread is woken up.
3123 */
3124 @Override
3125 public void onReachedMaxAppCacheSize(long spaceNeeded,
3126 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3127 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3128 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003129 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003130
Steve Block2bc69912009-07-30 14:45:13 +01003131 /**
3132 * Instructs the browser to show a prompt to ask the user to set the
3133 * Geolocation permission state for the specified origin.
3134 * @param origin The origin for which Geolocation permissions are
3135 * requested.
3136 * @param callback The callback to call once the user has set the
3137 * Geolocation permission state.
3138 */
3139 @Override
3140 public void onGeolocationPermissionsShowPrompt(String origin,
3141 GeolocationPermissions.Callback callback) {
3142 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3143 origin, callback);
3144 }
3145
3146 /**
3147 * Instructs the browser to hide the Geolocation permissions prompt.
3148 */
3149 @Override
3150 public void onGeolocationPermissionsHidePrompt() {
3151 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3152 }
3153
Ben Murdoch7db26342009-06-03 18:21:19 +01003154 /* Adds a JavaScript error message to the system log.
3155 * @param message The error message to report.
3156 * @param lineNumber The line number of the error.
3157 * @param sourceID The name of the source file that caused the error.
3158 */
3159 @Override
3160 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003161 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3162 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3163 if (mShouldShowErrorConsole &&
3164 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3165 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3166 }
3167 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003168 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003169 };
3170
3171 /**
3172 * Notify the host application a download should be done, or that
3173 * the data should be streamed if a streaming viewer is available.
3174 * @param url The full url to the content that should be downloaded
3175 * @param contentDisposition Content-disposition http header, if
3176 * present.
3177 * @param mimetype The mimetype of the content reported by the server
3178 * @param contentLength The file size reported by the server
3179 */
3180 public void onDownloadStart(String url, String userAgent,
3181 String contentDisposition, String mimetype, long contentLength) {
3182 // if we're dealing wih A/V content that's not explicitly marked
3183 // for download, check if it's streamable.
3184 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003185 || !contentDisposition.regionMatches(
3186 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003187 // query the package manager to see if there's a registered handler
3188 // that matches.
3189 Intent intent = new Intent(Intent.ACTION_VIEW);
3190 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003191 ResolveInfo info = getPackageManager().resolveActivity(intent,
3192 PackageManager.MATCH_DEFAULT_ONLY);
3193 if (info != null) {
3194 ComponentName myName = getComponentName();
3195 // If we resolved to ourselves, we don't want to attempt to
3196 // load the url only to try and download it again.
3197 if (!myName.getPackageName().equals(
3198 info.activityInfo.packageName)
3199 || !myName.getClassName().equals(
3200 info.activityInfo.name)) {
3201 // someone (other than us) knows how to handle this mime
3202 // type with this scheme, don't download.
3203 try {
3204 startActivity(intent);
3205 return;
3206 } catch (ActivityNotFoundException ex) {
3207 if (LOGD_ENABLED) {
3208 Log.d(LOGTAG, "activity not found for " + mimetype
3209 + " over " + Uri.parse(url).getScheme(),
3210 ex);
3211 }
3212 // Best behavior is to fall back to a download in this
3213 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003214 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003215 }
3216 }
3217 }
3218 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3219 }
3220
3221 /**
3222 * Notify the host application a download should be done, even if there
3223 * is a streaming viewer available for thise type.
3224 * @param url The full url to the content that should be downloaded
3225 * @param contentDisposition Content-disposition http header, if
3226 * present.
3227 * @param mimetype The mimetype of the content reported by the server
3228 * @param contentLength The file size reported by the server
3229 */
3230 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3231 String contentDisposition, String mimetype, long contentLength) {
3232
3233 String filename = URLUtil.guessFileName(url,
3234 contentDisposition, mimetype);
3235
3236 // Check to see if we have an SDCard
3237 String status = Environment.getExternalStorageState();
3238 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3239 int title;
3240 String msg;
3241
3242 // Check to see if the SDCard is busy, same as the music app
3243 if (status.equals(Environment.MEDIA_SHARED)) {
3244 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3245 title = R.string.download_sdcard_busy_dlg_title;
3246 } else {
3247 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3248 title = R.string.download_no_sdcard_dlg_title;
3249 }
3250
3251 new AlertDialog.Builder(this)
3252 .setTitle(title)
3253 .setIcon(android.R.drawable.ic_dialog_alert)
3254 .setMessage(msg)
3255 .setPositiveButton(R.string.ok, null)
3256 .show();
3257 return;
3258 }
3259
3260 // java.net.URI is a lot stricter than KURL so we have to undo
3261 // KURL's percent-encoding and redo the encoding using java.net.URI.
3262 URI uri = null;
3263 try {
3264 // Undo the percent-encoding that KURL may have done.
3265 String newUrl = new String(URLUtil.decode(url.getBytes()));
3266 // Parse the url into pieces
3267 WebAddress w = new WebAddress(newUrl);
3268 String frag = null;
3269 String query = null;
3270 String path = w.mPath;
3271 // Break the path into path, query, and fragment
3272 if (path.length() > 0) {
3273 // Strip the fragment
3274 int idx = path.lastIndexOf('#');
3275 if (idx != -1) {
3276 frag = path.substring(idx + 1);
3277 path = path.substring(0, idx);
3278 }
3279 idx = path.lastIndexOf('?');
3280 if (idx != -1) {
3281 query = path.substring(idx + 1);
3282 path = path.substring(0, idx);
3283 }
3284 }
3285 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3286 query, frag);
3287 } catch (Exception e) {
3288 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3289 return;
3290 }
3291
3292 // XXX: Have to use the old url since the cookies were stored using the
3293 // old percent-encoded url.
3294 String cookies = CookieManager.getInstance().getCookie(url);
3295
3296 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003297 values.put(Downloads.COLUMN_URI, uri.toString());
3298 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3299 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3300 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003301 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003302 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003303 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003304 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3305 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3306 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3307 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003308 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003309 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003310 }
3311 if (mimetype == null) {
3312 // We must have long pressed on a link or image to download it. We
3313 // are not sure of the mimetype in this case, so do a head request
3314 new FetchUrlMimeType(this).execute(values);
3315 } else {
3316 final Uri contentUri =
3317 getContentResolver().insert(Downloads.CONTENT_URI, values);
3318 viewDownloads(contentUri);
3319 }
3320
3321 }
3322
3323 /**
3324 * Resets the lock icon. This method is called when we start a new load and
3325 * know the url to be loaded.
3326 */
3327 private void resetLockIcon(String url) {
3328 // Save the lock-icon state (we revert to it if the load gets cancelled)
3329 saveLockIcon();
3330
3331 mLockIconType = LOCK_ICON_UNSECURE;
3332 if (URLUtil.isHttpsUrl(url)) {
3333 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003334 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003335 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3336 " reset lock icon to " + mLockIconType);
3337 }
3338 }
3339
3340 updateLockIconImage(LOCK_ICON_UNSECURE);
3341 }
3342
3343 /**
3344 * Resets the lock icon. This method is called when the icon needs to be
3345 * reset but we do not know whether we are loading a secure or not secure
3346 * page.
3347 */
3348 private void resetLockIcon() {
3349 // Save the lock-icon state (we revert to it if the load gets cancelled)
3350 saveLockIcon();
3351
3352 mLockIconType = LOCK_ICON_UNSECURE;
3353
Dave Bort31a6d1c2009-04-13 15:56:49 -07003354 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003355 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3356 " reset lock icon to " + mLockIconType);
3357 }
3358
3359 updateLockIconImage(LOCK_ICON_UNSECURE);
3360 }
3361
3362 /**
3363 * Updates the lock-icon image in the title-bar.
3364 */
3365 private void updateLockIconImage(int lockIconType) {
3366 Drawable d = null;
3367 if (lockIconType == LOCK_ICON_SECURE) {
3368 d = mSecLockIcon;
3369 } else if (lockIconType == LOCK_ICON_MIXED) {
3370 d = mMixLockIcon;
3371 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04003372 if (CUSTOM_BROWSER_BAR) {
3373 mTitleBar.setLock(d, getTopWindow());
3374 } else {
3375 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003376 }
3377 }
3378
3379 /**
3380 * Displays a page-info dialog.
3381 * @param tab The tab to show info about
3382 * @param fromShowSSLCertificateOnError The flag that indicates whether
3383 * this dialog was opened from the SSL-certificate-on-error dialog or
3384 * not. This is important, since we need to know whether to return to
3385 * the parent dialog or simply dismiss.
3386 */
3387 private void showPageInfo(final TabControl.Tab tab,
3388 final boolean fromShowSSLCertificateOnError) {
3389 final LayoutInflater factory = LayoutInflater
3390 .from(this);
3391
3392 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3393
3394 final WebView view = tab.getWebView();
3395
3396 String url = null;
3397 String title = null;
3398
3399 if (view == null) {
3400 url = tab.getUrl();
3401 title = tab.getTitle();
3402 } else if (view == mTabControl.getCurrentWebView()) {
3403 // Use the cached title and url if this is the current WebView
3404 url = mUrl;
3405 title = mTitle;
3406 } else {
3407 url = view.getUrl();
3408 title = view.getTitle();
3409 }
3410
3411 if (url == null) {
3412 url = "";
3413 }
3414 if (title == null) {
3415 title = "";
3416 }
3417
3418 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3419 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3420
3421 mPageInfoView = tab;
3422 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3423
3424 AlertDialog.Builder alertDialogBuilder =
3425 new AlertDialog.Builder(this)
3426 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3427 .setView(pageInfoView)
3428 .setPositiveButton(
3429 R.string.ok,
3430 new DialogInterface.OnClickListener() {
3431 public void onClick(DialogInterface dialog,
3432 int whichButton) {
3433 mPageInfoDialog = null;
3434 mPageInfoView = null;
3435 mPageInfoFromShowSSLCertificateOnError = null;
3436
3437 // if we came here from the SSL error dialog
3438 if (fromShowSSLCertificateOnError) {
3439 // go back to the SSL error dialog
3440 showSSLCertificateOnError(
3441 mSSLCertificateOnErrorView,
3442 mSSLCertificateOnErrorHandler,
3443 mSSLCertificateOnErrorError);
3444 }
3445 }
3446 })
3447 .setOnCancelListener(
3448 new DialogInterface.OnCancelListener() {
3449 public void onCancel(DialogInterface dialog) {
3450 mPageInfoDialog = null;
3451 mPageInfoView = null;
3452 mPageInfoFromShowSSLCertificateOnError = null;
3453
3454 // if we came here from the SSL error dialog
3455 if (fromShowSSLCertificateOnError) {
3456 // go back to the SSL error dialog
3457 showSSLCertificateOnError(
3458 mSSLCertificateOnErrorView,
3459 mSSLCertificateOnErrorHandler,
3460 mSSLCertificateOnErrorError);
3461 }
3462 }
3463 });
3464
3465 // if we have a main top-level page SSL certificate set or a certificate
3466 // error
3467 if (fromShowSSLCertificateOnError ||
3468 (view != null && view.getCertificate() != null)) {
3469 // add a 'View Certificate' button
3470 alertDialogBuilder.setNeutralButton(
3471 R.string.view_certificate,
3472 new DialogInterface.OnClickListener() {
3473 public void onClick(DialogInterface dialog,
3474 int whichButton) {
3475 mPageInfoDialog = null;
3476 mPageInfoView = null;
3477 mPageInfoFromShowSSLCertificateOnError = null;
3478
3479 // if we came here from the SSL error dialog
3480 if (fromShowSSLCertificateOnError) {
3481 // go back to the SSL error dialog
3482 showSSLCertificateOnError(
3483 mSSLCertificateOnErrorView,
3484 mSSLCertificateOnErrorHandler,
3485 mSSLCertificateOnErrorError);
3486 } else {
3487 // otherwise, display the top-most certificate from
3488 // the chain
3489 if (view.getCertificate() != null) {
3490 showSSLCertificate(tab);
3491 }
3492 }
3493 }
3494 });
3495 }
3496
3497 mPageInfoDialog = alertDialogBuilder.show();
3498 }
3499
3500 /**
3501 * Displays the main top-level page SSL certificate dialog
3502 * (accessible from the Page-Info dialog).
3503 * @param tab The tab to show certificate for.
3504 */
3505 private void showSSLCertificate(final TabControl.Tab tab) {
3506 final View certificateView =
3507 inflateCertificateView(tab.getWebView().getCertificate());
3508 if (certificateView == null) {
3509 return;
3510 }
3511
3512 LayoutInflater factory = LayoutInflater.from(this);
3513
3514 final LinearLayout placeholder =
3515 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3516
3517 LinearLayout ll = (LinearLayout) factory.inflate(
3518 R.layout.ssl_success, placeholder);
3519 ((TextView)ll.findViewById(R.id.success))
3520 .setText(R.string.ssl_certificate_is_valid);
3521
3522 mSSLCertificateView = tab;
3523 mSSLCertificateDialog =
3524 new AlertDialog.Builder(this)
3525 .setTitle(R.string.ssl_certificate).setIcon(
3526 R.drawable.ic_dialog_browser_certificate_secure)
3527 .setView(certificateView)
3528 .setPositiveButton(R.string.ok,
3529 new DialogInterface.OnClickListener() {
3530 public void onClick(DialogInterface dialog,
3531 int whichButton) {
3532 mSSLCertificateDialog = null;
3533 mSSLCertificateView = null;
3534
3535 showPageInfo(tab, false);
3536 }
3537 })
3538 .setOnCancelListener(
3539 new DialogInterface.OnCancelListener() {
3540 public void onCancel(DialogInterface dialog) {
3541 mSSLCertificateDialog = null;
3542 mSSLCertificateView = null;
3543
3544 showPageInfo(tab, false);
3545 }
3546 })
3547 .show();
3548 }
3549
3550 /**
3551 * Displays the SSL error certificate dialog.
3552 * @param view The target web-view.
3553 * @param handler The SSL error handler responsible for cancelling the
3554 * connection that resulted in an SSL error or proceeding per user request.
3555 * @param error The SSL error object.
3556 */
3557 private void showSSLCertificateOnError(
3558 final WebView view, final SslErrorHandler handler, final SslError error) {
3559
3560 final View certificateView =
3561 inflateCertificateView(error.getCertificate());
3562 if (certificateView == null) {
3563 return;
3564 }
3565
3566 LayoutInflater factory = LayoutInflater.from(this);
3567
3568 final LinearLayout placeholder =
3569 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3570
3571 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3572 LinearLayout ll = (LinearLayout)factory
3573 .inflate(R.layout.ssl_warning, placeholder);
3574 ((TextView)ll.findViewById(R.id.warning))
3575 .setText(R.string.ssl_untrusted);
3576 }
3577
3578 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3579 LinearLayout ll = (LinearLayout)factory
3580 .inflate(R.layout.ssl_warning, placeholder);
3581 ((TextView)ll.findViewById(R.id.warning))
3582 .setText(R.string.ssl_mismatch);
3583 }
3584
3585 if (error.hasError(SslError.SSL_EXPIRED)) {
3586 LinearLayout ll = (LinearLayout)factory
3587 .inflate(R.layout.ssl_warning, placeholder);
3588 ((TextView)ll.findViewById(R.id.warning))
3589 .setText(R.string.ssl_expired);
3590 }
3591
3592 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3593 LinearLayout ll = (LinearLayout)factory
3594 .inflate(R.layout.ssl_warning, placeholder);
3595 ((TextView)ll.findViewById(R.id.warning))
3596 .setText(R.string.ssl_not_yet_valid);
3597 }
3598
3599 mSSLCertificateOnErrorHandler = handler;
3600 mSSLCertificateOnErrorView = view;
3601 mSSLCertificateOnErrorError = error;
3602 mSSLCertificateOnErrorDialog =
3603 new AlertDialog.Builder(this)
3604 .setTitle(R.string.ssl_certificate).setIcon(
3605 R.drawable.ic_dialog_browser_certificate_partially_secure)
3606 .setView(certificateView)
3607 .setPositiveButton(R.string.ok,
3608 new DialogInterface.OnClickListener() {
3609 public void onClick(DialogInterface dialog,
3610 int whichButton) {
3611 mSSLCertificateOnErrorDialog = null;
3612 mSSLCertificateOnErrorView = null;
3613 mSSLCertificateOnErrorHandler = null;
3614 mSSLCertificateOnErrorError = null;
3615
3616 mWebViewClient.onReceivedSslError(
3617 view, handler, error);
3618 }
3619 })
3620 .setNeutralButton(R.string.page_info_view,
3621 new DialogInterface.OnClickListener() {
3622 public void onClick(DialogInterface dialog,
3623 int whichButton) {
3624 mSSLCertificateOnErrorDialog = null;
3625
3626 // do not clear the dialog state: we will
3627 // need to show the dialog again once the
3628 // user is done exploring the page-info details
3629
3630 showPageInfo(mTabControl.getTabFromView(view),
3631 true);
3632 }
3633 })
3634 .setOnCancelListener(
3635 new DialogInterface.OnCancelListener() {
3636 public void onCancel(DialogInterface dialog) {
3637 mSSLCertificateOnErrorDialog = null;
3638 mSSLCertificateOnErrorView = null;
3639 mSSLCertificateOnErrorHandler = null;
3640 mSSLCertificateOnErrorError = null;
3641
3642 mWebViewClient.onReceivedSslError(
3643 view, handler, error);
3644 }
3645 })
3646 .show();
3647 }
3648
3649 /**
3650 * Inflates the SSL certificate view (helper method).
3651 * @param certificate The SSL certificate.
3652 * @return The resultant certificate view with issued-to, issued-by,
3653 * issued-on, expires-on, and possibly other fields set.
3654 * If the input certificate is null, returns null.
3655 */
3656 private View inflateCertificateView(SslCertificate certificate) {
3657 if (certificate == null) {
3658 return null;
3659 }
3660
3661 LayoutInflater factory = LayoutInflater.from(this);
3662
3663 View certificateView = factory.inflate(
3664 R.layout.ssl_certificate, null);
3665
3666 // issued to:
3667 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3668 if (issuedTo != null) {
3669 ((TextView) certificateView.findViewById(R.id.to_common))
3670 .setText(issuedTo.getCName());
3671 ((TextView) certificateView.findViewById(R.id.to_org))
3672 .setText(issuedTo.getOName());
3673 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3674 .setText(issuedTo.getUName());
3675 }
3676
3677 // issued by:
3678 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3679 if (issuedBy != null) {
3680 ((TextView) certificateView.findViewById(R.id.by_common))
3681 .setText(issuedBy.getCName());
3682 ((TextView) certificateView.findViewById(R.id.by_org))
3683 .setText(issuedBy.getOName());
3684 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3685 .setText(issuedBy.getUName());
3686 }
3687
3688 // issued on:
3689 String issuedOn = reformatCertificateDate(
3690 certificate.getValidNotBefore());
3691 ((TextView) certificateView.findViewById(R.id.issued_on))
3692 .setText(issuedOn);
3693
3694 // expires on:
3695 String expiresOn = reformatCertificateDate(
3696 certificate.getValidNotAfter());
3697 ((TextView) certificateView.findViewById(R.id.expires_on))
3698 .setText(expiresOn);
3699
3700 return certificateView;
3701 }
3702
3703 /**
3704 * Re-formats the certificate date (Date.toString()) string to
3705 * a properly localized date string.
3706 * @return Properly localized version of the certificate date string and
3707 * the original certificate date string if fails to localize.
3708 * If the original string is null, returns an empty string "".
3709 */
3710 private String reformatCertificateDate(String certificateDate) {
3711 String reformattedDate = null;
3712
3713 if (certificateDate != null) {
3714 Date date = null;
3715 try {
3716 date = java.text.DateFormat.getInstance().parse(certificateDate);
3717 } catch (ParseException e) {
3718 date = null;
3719 }
3720
3721 if (date != null) {
3722 reformattedDate =
3723 DateFormat.getDateFormat(this).format(date);
3724 }
3725 }
3726
3727 return reformattedDate != null ? reformattedDate :
3728 (certificateDate != null ? certificateDate : "");
3729 }
3730
3731 /**
3732 * Displays an http-authentication dialog.
3733 */
3734 private void showHttpAuthentication(final HttpAuthHandler handler,
3735 final String host, final String realm, final String title,
3736 final String name, final String password, int focusId) {
3737 LayoutInflater factory = LayoutInflater.from(this);
3738 final View v = factory
3739 .inflate(R.layout.http_authentication, null);
3740 if (name != null) {
3741 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3742 }
3743 if (password != null) {
3744 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3745 }
3746
3747 String titleText = title;
3748 if (titleText == null) {
3749 titleText = getText(R.string.sign_in_to).toString().replace(
3750 "%s1", host).replace("%s2", realm);
3751 }
3752
3753 mHttpAuthHandler = handler;
3754 AlertDialog dialog = new AlertDialog.Builder(this)
3755 .setTitle(titleText)
3756 .setIcon(android.R.drawable.ic_dialog_alert)
3757 .setView(v)
3758 .setPositiveButton(R.string.action,
3759 new DialogInterface.OnClickListener() {
3760 public void onClick(DialogInterface dialog,
3761 int whichButton) {
3762 String nm = ((EditText) v
3763 .findViewById(R.id.username_edit))
3764 .getText().toString();
3765 String pw = ((EditText) v
3766 .findViewById(R.id.password_edit))
3767 .getText().toString();
3768 BrowserActivity.this.setHttpAuthUsernamePassword
3769 (host, realm, nm, pw);
3770 handler.proceed(nm, pw);
3771 mHttpAuthenticationDialog = null;
3772 mHttpAuthHandler = null;
3773 }})
3774 .setNegativeButton(R.string.cancel,
3775 new DialogInterface.OnClickListener() {
3776 public void onClick(DialogInterface dialog,
3777 int whichButton) {
3778 handler.cancel();
3779 BrowserActivity.this.resetTitleAndRevertLockIcon();
3780 mHttpAuthenticationDialog = null;
3781 mHttpAuthHandler = null;
3782 }})
3783 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3784 public void onCancel(DialogInterface dialog) {
3785 handler.cancel();
3786 BrowserActivity.this.resetTitleAndRevertLockIcon();
3787 mHttpAuthenticationDialog = null;
3788 mHttpAuthHandler = null;
3789 }})
3790 .create();
3791 // Make the IME appear when the dialog is displayed if applicable.
3792 dialog.getWindow().setSoftInputMode(
3793 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3794 dialog.show();
3795 if (focusId != 0) {
3796 dialog.findViewById(focusId).requestFocus();
3797 } else {
3798 v.findViewById(R.id.username_edit).requestFocus();
3799 }
3800 mHttpAuthenticationDialog = dialog;
3801 }
3802
3803 public int getProgress() {
3804 WebView w = mTabControl.getCurrentWebView();
3805 if (w != null) {
3806 return w.getProgress();
3807 } else {
3808 return 100;
3809 }
3810 }
3811
3812 /**
3813 * Set HTTP authentication password.
3814 *
3815 * @param host The host for the password
3816 * @param realm The realm for the password
3817 * @param username The username for the password. If it is null, it means
3818 * password can't be saved.
3819 * @param password The password
3820 */
3821 public void setHttpAuthUsernamePassword(String host, String realm,
3822 String username,
3823 String password) {
3824 WebView w = mTabControl.getCurrentWebView();
3825 if (w != null) {
3826 w.setHttpAuthUsernamePassword(host, realm, username, password);
3827 }
3828 }
3829
3830 /**
3831 * connectivity manager says net has come or gone... inform the user
3832 * @param up true if net has come up, false if net has gone down
3833 */
3834 public void onNetworkToggle(boolean up) {
3835 if (up == mIsNetworkUp) {
3836 return;
3837 } else if (up) {
3838 mIsNetworkUp = true;
3839 if (mAlertDialog != null) {
3840 mAlertDialog.cancel();
3841 mAlertDialog = null;
3842 }
3843 } else {
3844 mIsNetworkUp = false;
3845 if (mInLoad && mAlertDialog == null) {
3846 mAlertDialog = new AlertDialog.Builder(this)
3847 .setTitle(R.string.loadSuspendedTitle)
3848 .setMessage(R.string.loadSuspended)
3849 .setPositiveButton(R.string.ok, null)
3850 .show();
3851 }
3852 }
3853 WebView w = mTabControl.getCurrentWebView();
3854 if (w != null) {
3855 w.setNetworkAvailable(up);
3856 }
3857 }
3858
3859 @Override
3860 protected void onActivityResult(int requestCode, int resultCode,
3861 Intent intent) {
3862 switch (requestCode) {
3863 case COMBO_PAGE:
3864 if (resultCode == RESULT_OK && intent != null) {
3865 String data = intent.getAction();
3866 Bundle extras = intent.getExtras();
3867 if (extras != null && extras.getBoolean("new_window", false)) {
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003868 final TabControl.Tab newTab = openTab(data);
3869 if (mSettings.openInBackground() &&
Leon Scroggins1f005d32009-08-10 17:36:42 -04003870 newTab != null) {
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003871 mTabControl.populatePickerData(newTab);
3872 mTabControl.setCurrentTab(newTab);
Leon Scroggins1f005d32009-08-10 17:36:42 -04003873 int newIndex = mTabControl.getCurrentIndex();
3874 if (CUSTOM_BROWSER_BAR) {
3875 mTitleBar.setCurrentTab(newIndex);
3876 }
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003877 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003878 } else {
3879 final TabControl.Tab currentTab =
3880 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003881 dismissSubWindow(currentTab);
3882 if (data != null && data.length() != 0) {
3883 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003884 }
3885 }
3886 }
3887 break;
3888 default:
3889 break;
3890 }
Leon Scroggins30444232009-09-04 18:36:20 -04003891 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003892 }
3893
3894 /*
3895 * This method is called as a result of the user selecting the options
3896 * menu to see the download window, or when a download changes state. It
3897 * shows the download window ontop of the current window.
3898 */
3899 /* package */ void viewDownloads(Uri downloadRecord) {
3900 Intent intent = new Intent(this,
3901 BrowserDownloadPage.class);
3902 intent.setData(downloadRecord);
3903 startActivityForResult(intent, this.DOWNLOAD_PAGE);
3904
3905 }
3906
Leon Scroggins160a7e72009-08-14 18:28:01 -04003907 /**
3908 * Open the Go page.
3909 * @param startWithHistory If true, open starting on the history tab.
3910 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003911 */
Leon Scroggins30444232009-09-04 18:36:20 -04003912 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003913 WebView current = mTabControl.getCurrentWebView();
3914 if (current == null) {
3915 return;
3916 }
3917 Intent intent = new Intent(this,
3918 CombinedBookmarkHistoryActivity.class);
3919 String title = current.getTitle();
3920 String url = current.getUrl();
3921 // Just in case the user opens bookmarks before a page finishes loading
3922 // so the current history item, and therefore the page, is null.
3923 if (null == url) {
3924 url = mLastEnteredUrl;
3925 // This can happen.
3926 if (null == url) {
3927 url = mSettings.getHomePage();
3928 }
3929 }
3930 // In case the web page has not yet received its associated title.
3931 if (title == null) {
3932 title = url;
3933 }
3934 intent.putExtra("title", title);
3935 intent.putExtra("url", url);
Leon Scroggins30444232009-09-04 18:36:20 -04003936 // Disable opening in a new window if we have maxed out the windows
3937 intent.putExtra("disable_new_window", mTabControl.getTabCount()
3938 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04003939 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003940 if (startWithHistory) {
3941 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3942 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3943 }
3944 startActivityForResult(intent, COMBO_PAGE);
3945 }
3946
3947 // Called when loading from context menu or LOAD_URL message
3948 private void loadURL(WebView view, String url) {
3949 // In case the user enters nothing.
3950 if (url != null && url.length() != 0 && view != null) {
3951 url = smartUrlFilter(url);
3952 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
3953 view.loadUrl(url);
3954 }
3955 }
3956 }
3957
The Android Open Source Project0c908882009-03-03 19:32:16 -08003958 private String smartUrlFilter(Uri inUri) {
3959 if (inUri != null) {
3960 return smartUrlFilter(inUri.toString());
3961 }
3962 return null;
3963 }
3964
3965
3966 // get window count
3967
3968 int getWindowCount(){
3969 if(mTabControl != null){
3970 return mTabControl.getTabCount();
3971 }
3972 return 0;
3973 }
3974
Feng Qianb34f87a2009-03-24 21:27:26 -07003975 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003976 "(?i)" + // switch on case insensitive matching
3977 "(" + // begin group for schema
3978 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003979 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003980 ")" +
3981 "(.*)" );
3982
3983 /**
3984 * Attempts to determine whether user input is a URL or search
3985 * terms. Anything with a space is passed to search.
3986 *
3987 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3988 * "Http://" converts to "http://"
3989 *
3990 * @return Original or modified URL
3991 *
3992 */
3993 String smartUrlFilter(String url) {
3994
3995 String inUrl = url.trim();
3996 boolean hasSpace = inUrl.indexOf(' ') != -1;
3997
3998 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3999 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004000 // force scheme to lowercase
4001 String scheme = matcher.group(1);
4002 String lcScheme = scheme.toLowerCase();
4003 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004004 inUrl = lcScheme + matcher.group(2);
4005 }
4006 if (hasSpace) {
4007 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004008 }
4009 return inUrl;
4010 }
4011 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004012 // FIXME: Is this the correct place to add to searches?
4013 // what if someone else calls this function?
4014 int shortcut = parseUrlShortcut(inUrl);
4015 if (shortcut != SHORTCUT_INVALID) {
4016 Browser.addSearchUrl(mResolver, inUrl);
4017 String query = inUrl.substring(2);
4018 switch (shortcut) {
4019 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004020 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004021 case SHORTCUT_WIKIPEDIA_SEARCH:
4022 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4023 case SHORTCUT_DICTIONARY_SEARCH:
4024 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4025 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004026 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004027 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004028 }
4029 }
4030 } else {
4031 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4032 return URLUtil.guessUrl(inUrl);
4033 }
4034 }
4035
4036 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004037 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004038 }
4039
Ben Murdochbff2d602009-07-01 20:19:05 +01004040 /* package */ void setShouldShowErrorConsole(boolean flag) {
4041 if (flag == mShouldShowErrorConsole) {
4042 // Nothing to do.
4043 return;
4044 }
4045
4046 mShouldShowErrorConsole = flag;
4047
4048 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4049
4050 if (flag) {
4051 // Setting the show state of the console will cause it's the layout to be inflated.
4052 if (errorConsole.numberOfErrors() > 0) {
4053 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4054 } else {
4055 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4056 }
4057
4058 // Now we can add it to the main view.
4059 mErrorConsoleContainer.addView(errorConsole,
4060 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4061 ViewGroup.LayoutParams.WRAP_CONTENT));
4062 } else {
4063 mErrorConsoleContainer.removeView(errorConsole);
4064 }
4065
4066 }
4067
The Android Open Source Project0c908882009-03-03 19:32:16 -08004068 private final static int LOCK_ICON_UNSECURE = 0;
4069 private final static int LOCK_ICON_SECURE = 1;
4070 private final static int LOCK_ICON_MIXED = 2;
4071
4072 private int mLockIconType = LOCK_ICON_UNSECURE;
4073 private int mPrevLockType = LOCK_ICON_UNSECURE;
4074
4075 private BrowserSettings mSettings;
4076 private TabControl mTabControl;
4077 private ContentResolver mResolver;
4078 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004079 private View mCustomView;
4080 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004081 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004082
4083 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4084 // view, we should rewrite this.
4085 private int mCurrentMenuState = 0;
4086 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004087 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004088 private static final int EMPTY_MENU = -1;
4089 private Menu mMenu;
4090
4091 private FindDialog mFindDialog;
4092 // Used to prevent chording to result in firing two shortcuts immediately
4093 // one after another. Fixes bug 1211714.
4094 boolean mCanChord;
4095
4096 private boolean mInLoad;
4097 private boolean mIsNetworkUp;
4098
4099 private boolean mPageStarted;
4100 private boolean mActivityInPause = true;
4101
4102 private boolean mMenuIsDown;
4103
4104 private final KeyTracker mKeyTracker = new KeyTracker(this);
4105
4106 // As trackball doesn't send repeat down, we have to track it ourselves
4107 private boolean mTrackTrackball;
4108
4109 private static boolean mInTrace;
4110
4111 // Performance probe
4112 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4113 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4114 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4115 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4116 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4117 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4118 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4119 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4120 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4121 };
4122
4123 private long mStart;
4124 private long mProcessStart;
4125 private long mUserStart;
4126 private long mSystemStart;
4127 private long mIdleStart;
4128 private long mIrqStart;
4129
4130 private long mUiStart;
4131
4132 private Drawable mMixLockIcon;
4133 private Drawable mSecLockIcon;
4134 private Drawable mGenericFavicon;
4135
4136 /* hold a ref so we can auto-cancel if necessary */
4137 private AlertDialog mAlertDialog;
4138
4139 // Wait for credentials before loading google.com
4140 private ProgressDialog mCredsDlg;
4141
4142 // The up-to-date URL and title (these can be different from those stored
4143 // in WebView, since it takes some time for the information in WebView to
4144 // get updated)
4145 private String mUrl;
4146 private String mTitle;
4147
4148 // As PageInfo has different style for landscape / portrait, we have
4149 // to re-open it when configuration changed
4150 private AlertDialog mPageInfoDialog;
4151 private TabControl.Tab mPageInfoView;
4152 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4153 // dialog, we should not just dismiss it, but should get back to the
4154 // SSL-certificate-on-error dialog. This flag is used to store this state
4155 private Boolean mPageInfoFromShowSSLCertificateOnError;
4156
4157 // as SSLCertificateOnError has different style for landscape / portrait,
4158 // we have to re-open it when configuration changed
4159 private AlertDialog mSSLCertificateOnErrorDialog;
4160 private WebView mSSLCertificateOnErrorView;
4161 private SslErrorHandler mSSLCertificateOnErrorHandler;
4162 private SslError mSSLCertificateOnErrorError;
4163
4164 // as SSLCertificate has different style for landscape / portrait, we
4165 // have to re-open it when configuration changed
4166 private AlertDialog mSSLCertificateDialog;
4167 private TabControl.Tab mSSLCertificateView;
4168
4169 // as HttpAuthentication has different style for landscape / portrait, we
4170 // have to re-open it when configuration changed
4171 private AlertDialog mHttpAuthenticationDialog;
4172 private HttpAuthHandler mHttpAuthHandler;
4173
4174 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4175 new FrameLayout.LayoutParams(
4176 ViewGroup.LayoutParams.FILL_PARENT,
4177 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004178 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4179 new FrameLayout.LayoutParams(
4180 ViewGroup.LayoutParams.FILL_PARENT,
4181 ViewGroup.LayoutParams.FILL_PARENT,
4182 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004183 // Google search
4184 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004185 // Wikipedia search
4186 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4187 // Dictionary search
4188 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4189 // Google Mobile Local search
4190 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4191
4192 final static String QUERY_PLACE_HOLDER = "%s";
4193
4194 // "source" parameter for Google search through search key
4195 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4196 // "source" parameter for Google search through goto menu
4197 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4198 // "source" parameter for Google search through simplily type
4199 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4200 // "source" parameter for Google search suggested by the browser
4201 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4202 // "source" parameter for Google search from unknown source
4203 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4204
4205 private final static String LOGTAG = "browser";
4206
The Android Open Source Project0c908882009-03-03 19:32:16 -08004207 private String mLastEnteredUrl;
4208
4209 private PowerManager.WakeLock mWakeLock;
4210 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4211
4212 private Toast mStopToast;
4213
Leon Scroggins1f005d32009-08-10 17:36:42 -04004214 private TitleBarSet mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004215
Ben Murdochbff2d602009-07-01 20:19:05 +01004216 private LinearLayout mErrorConsoleContainer = null;
4217 private boolean mShouldShowErrorConsole = false;
4218
The Android Open Source Project0c908882009-03-03 19:32:16 -08004219 // As the ids are dynamically created, we can't guarantee that they will
4220 // be in sequence, so this static array maps ids to a window number.
4221 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4222 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4223 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4224 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4225
4226 // monitor platform changes
4227 private IntentFilter mNetworkStateChangedFilter;
4228 private BroadcastReceiver mNetworkStateIntentReceiver;
4229
Grace Klobab4da0ad2009-05-14 14:45:40 -07004230 private BroadcastReceiver mPackageInstallationReceiver;
4231
The Android Open Source Project0c908882009-03-03 19:32:16 -08004232 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004233 final static int COMBO_PAGE = 1;
4234 final static int DOWNLOAD_PAGE = 2;
4235 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004236
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004237 /**
4238 * A UrlData class to abstract how the content will be set to WebView.
4239 * This base class uses loadUrl to show the content.
4240 */
4241 private static class UrlData {
4242 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004243 byte[] mPostData;
4244
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004245 UrlData(String url) {
4246 this.mUrl = url;
4247 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004248
4249 void setPostData(byte[] postData) {
4250 mPostData = postData;
4251 }
4252
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004253 boolean isEmpty() {
4254 return mUrl == null || mUrl.length() == 0;
4255 }
4256
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004257 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004258 if (mPostData != null) {
4259 webView.postUrl(mUrl, mPostData);
4260 } else {
4261 webView.loadUrl(mUrl);
4262 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004263 }
4264 };
4265
4266 /**
4267 * A subclass of UrlData class that can display inlined content using
4268 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4269 */
4270 private static class InlinedUrlData extends UrlData {
4271 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4272 super(failUrl);
4273 mInlined = inlined;
4274 mMimeType = mimeType;
4275 mEncoding = encoding;
4276 }
4277 String mMimeType;
4278 String mInlined;
4279 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004280 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004281 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004282 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004283 }
4284
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004285 @Override
4286 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004287 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4288 }
4289 }
4290
Leon Scroggins1f005d32009-08-10 17:36:42 -04004291 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004292}