blob: 7e0f93d6de51b2492523f06a3577c59019edd942 [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) {
Cary Clark652ff872009-09-10 13:34:44 -0400750 // FIXME: Converting the url to lower case
751 // duplicates functionality in smartUrlFilter().
752 // However, changing all current callers of fixUrl to
753 // call smartUrlFilter in addition may have unwanted
754 // consequences, and is deferred for now.
755 int colon = inUrl.indexOf(':');
756 boolean allLower = true;
757 for (int index = 0; index < colon; index++) {
758 char ch = inUrl.charAt(index);
759 if (!Character.isLetter(ch)) {
760 break;
761 }
762 allLower &= Character.isLowerCase(ch);
763 if (index == colon - 1 && !allLower) {
764 inUrl = inUrl.substring(0, colon).toLowerCase()
765 + inUrl.substring(colon);
766 }
767 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800768 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
769 return inUrl;
770 if (inUrl.startsWith("http:") ||
771 inUrl.startsWith("https:")) {
772 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
773 inUrl = inUrl.replaceFirst("/", "//");
774 } else inUrl = inUrl.replaceFirst(":", "://");
775 }
776 return inUrl;
777 }
778
779 /**
780 * Looking for the pattern like this
781 *
782 * *
783 * * *
784 * *** * *******
785 * * *
786 * * *
787 * *
788 */
789 private final SensorListener mSensorListener = new SensorListener() {
790 private long mLastGestureTime;
791 private float[] mPrev = new float[3];
792 private float[] mPrevDiff = new float[3];
793 private float[] mDiff = new float[3];
794 private float[] mRevertDiff = new float[3];
795
796 public void onSensorChanged(int sensor, float[] values) {
797 boolean show = false;
798 float[] diff = new float[3];
799
800 for (int i = 0; i < 3; i++) {
801 diff[i] = values[i] - mPrev[i];
802 if (Math.abs(diff[i]) > 1) {
803 show = true;
804 }
805 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
806 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
807 // start track when there is a big move, or revert
808 mRevertDiff[i] = mDiff[i];
809 mDiff[i] = 0;
810 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
811 // reset when it is flat
812 mDiff[i] = mRevertDiff[i] = 0;
813 }
814 mDiff[i] += diff[i];
815 mPrevDiff[i] = diff[i];
816 mPrev[i] = values[i];
817 }
818
819 if (false) {
820 // only shows if we think the delta is big enough, in an attempt
821 // to detect "serious" moves left/right or up/down
822 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
823 + values[0] + ", " + values[1] + ", " + values[2] + ")"
824 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
825 + ")");
826 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
827 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
828 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
829 + mRevertDiff[2] + ")");
830 }
831
832 long now = android.os.SystemClock.uptimeMillis();
833 if (now - mLastGestureTime > 1000) {
834 mLastGestureTime = 0;
835
836 float y = mDiff[1];
837 float z = mDiff[2];
838 float ay = Math.abs(y);
839 float az = Math.abs(z);
840 float ry = mRevertDiff[1];
841 float rz = mRevertDiff[2];
842 float ary = Math.abs(ry);
843 float arz = Math.abs(rz);
844 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
845 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
846
847 if ((gestY || gestZ) && !(gestY && gestZ)) {
848 WebView view = mTabControl.getCurrentWebView();
849
850 if (view != null) {
851 if (gestZ) {
852 if (z < 0) {
853 view.zoomOut();
854 } else {
855 view.zoomIn();
856 }
857 } else {
858 view.flingScroll(0, Math.round(y * 100));
859 }
860 }
861 mLastGestureTime = now;
862 }
863 }
864 }
865
866 public void onAccuracyChanged(int sensor, int accuracy) {
867 // TODO Auto-generated method stub
868
869 }
870 };
871
872 @Override protected void onResume() {
873 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700874 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800875 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
876 }
877
878 if (!mActivityInPause) {
879 Log.e(LOGTAG, "BrowserActivity is already resumed.");
880 return;
881 }
882
Mike Reed7bfa63b2009-05-28 11:08:32 -0400883 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800884 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400885 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800886
887 if (mWakeLock.isHeld()) {
888 mHandler.removeMessages(RELEASE_WAKELOCK);
889 mWakeLock.release();
890 }
891
892 if (mCredsDlg != null) {
893 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
894 // In case credential request never comes back
895 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
896 }
897 }
898
899 registerReceiver(mNetworkStateIntentReceiver,
900 mNetworkStateChangedFilter);
901 WebView.enablePlatformNotifications();
902
903 if (mSettings.doFlick()) {
904 if (mSensorManager == null) {
905 mSensorManager = (SensorManager) getSystemService(
906 Context.SENSOR_SERVICE);
907 }
908 mSensorManager.registerListener(mSensorListener,
909 SensorManager.SENSOR_ACCELEROMETER,
910 SensorManager.SENSOR_DELAY_FASTEST);
911 } else {
912 mSensorManager = null;
913 }
914 }
915
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400916 @Override
917 public boolean onMenuOpened(int featureId, Menu menu) {
918 mTitleBar.setVisibility(View.VISIBLE);
919 return true;
920 }
921
The Android Open Source Project0c908882009-03-03 19:32:16 -0800922 /**
923 * onSaveInstanceState(Bundle map)
924 * onSaveInstanceState is called right before onStop(). The map contains
925 * the saved state.
926 */
927 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700928 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800929 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
930 }
931 // the default implementation requires each view to have an id. As the
932 // browser handles the state itself and it doesn't use id for the views,
933 // don't call the default implementation. Otherwise it will trigger the
934 // warning like this, "couldn't save which view has focus because the
935 // focused view XXX has no id".
936
937 // Save all the tabs
938 mTabControl.saveState(outState);
939 }
940
941 @Override protected void onPause() {
942 super.onPause();
943
944 if (mActivityInPause) {
945 Log.e(LOGTAG, "BrowserActivity is already paused.");
946 return;
947 }
948
Mike Reed7bfa63b2009-05-28 11:08:32 -0400949 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800950 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400951 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800952 mWakeLock.acquire();
953 mHandler.sendMessageDelayed(mHandler
954 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
955 }
956
957 // Clear the credentials toast if it is up
958 if (mCredsDlg != null && mCredsDlg.isShowing()) {
959 mCredsDlg.dismiss();
960 }
961 mCredsDlg = null;
962
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400963 // FIXME: This removes the active tabs page and resets the menu to
964 // MAIN_MENU. A better solution might be to do this work in onNewIntent
965 // but then we would need to save it in onSaveInstanceState and restore
966 // it in onCreate/onRestoreInstanceState
967 if (mActiveTabsPage != null) {
968 removeActiveTabPage(true);
969 }
970
The Android Open Source Project0c908882009-03-03 19:32:16 -0800971 cancelStopToast();
972
973 // unregister network state listener
974 unregisterReceiver(mNetworkStateIntentReceiver);
975 WebView.disablePlatformNotifications();
976
977 if (mSensorManager != null) {
978 mSensorManager.unregisterListener(mSensorListener);
979 }
980 }
981
982 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700983 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800984 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
985 }
986 super.onDestroy();
987 // Remove the current tab and sub window
988 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700989 if (t != null) {
990 dismissSubWindow(t);
991 removeTabFromContentView(t);
992 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800993 // Destroy all the tabs
994 mTabControl.destroy();
995 WebIconDatabase.getInstance().close();
996 if (mGlsConnection != null) {
997 unbindService(mGlsConnection);
998 mGlsConnection = null;
999 }
1000
1001 //
1002 // stop MASF proxy service
1003 //
1004 //Intent proxyServiceIntent = new Intent();
1005 //proxyServiceIntent.setComponent
1006 // (new ComponentName(
1007 // "com.android.masfproxyservice",
1008 // "com.android.masfproxyservice.MasfProxyService"));
1009 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001010
1011 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001012 }
1013
1014 @Override
1015 public void onConfigurationChanged(Configuration newConfig) {
1016 super.onConfigurationChanged(newConfig);
1017
1018 if (mPageInfoDialog != null) {
1019 mPageInfoDialog.dismiss();
1020 showPageInfo(
1021 mPageInfoView,
1022 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1023 }
1024 if (mSSLCertificateDialog != null) {
1025 mSSLCertificateDialog.dismiss();
1026 showSSLCertificate(
1027 mSSLCertificateView);
1028 }
1029 if (mSSLCertificateOnErrorDialog != null) {
1030 mSSLCertificateOnErrorDialog.dismiss();
1031 showSSLCertificateOnError(
1032 mSSLCertificateOnErrorView,
1033 mSSLCertificateOnErrorHandler,
1034 mSSLCertificateOnErrorError);
1035 }
1036 if (mHttpAuthenticationDialog != null) {
1037 String title = ((TextView) mHttpAuthenticationDialog
1038 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1039 .toString();
1040 String name = ((TextView) mHttpAuthenticationDialog
1041 .findViewById(R.id.username_edit)).getText().toString();
1042 String password = ((TextView) mHttpAuthenticationDialog
1043 .findViewById(R.id.password_edit)).getText().toString();
1044 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1045 .getId();
1046 mHttpAuthenticationDialog.dismiss();
1047 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1048 name, password, focusId);
1049 }
1050 if (mFindDialog != null && mFindDialog.isShowing()) {
1051 mFindDialog.onConfigurationChanged(newConfig);
1052 }
1053 }
1054
1055 @Override public void onLowMemory() {
1056 super.onLowMemory();
1057 mTabControl.freeMemory();
1058 }
1059
Mike Reed7bfa63b2009-05-28 11:08:32 -04001060 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001061 if ((!mActivityInPause && !mPageStarted) ||
1062 (mActivityInPause && mPageStarted)) {
1063 CookieSyncManager.getInstance().startSync();
1064 WebView w = mTabControl.getCurrentWebView();
1065 if (w != null) {
1066 w.resumeTimers();
1067 }
1068 return true;
1069 } else {
1070 return false;
1071 }
1072 }
1073
Mike Reed7bfa63b2009-05-28 11:08:32 -04001074 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001075 if (mActivityInPause && !mPageStarted) {
1076 CookieSyncManager.getInstance().stopSync();
1077 WebView w = mTabControl.getCurrentWebView();
1078 if (w != null) {
1079 w.pauseTimers();
1080 }
1081 return true;
1082 } else {
1083 return false;
1084 }
1085 }
1086
Leon Scroggins1f005d32009-08-10 17:36:42 -04001087 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001088 /*
1089 * This function is called when we are launching for the first time. We
1090 * are waiting for the login credentials before loading Google home
1091 * pages. This way the user will be logged in straight away.
1092 */
1093 private void waitForCredentials() {
1094 // Show a toast
1095 mCredsDlg = new ProgressDialog(this);
1096 mCredsDlg.setIndeterminate(true);
1097 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1098 // If the user cancels the operation, then cancel the Google
1099 // Credentials request.
1100 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1101 mCredsDlg.show();
1102
1103 // We set a timeout for the retrieval of credentials in onResume()
1104 // as that is when we have freed up some CPU time to get
1105 // the login credentials.
1106 }
1107
1108 /*
1109 * If we have received the credentials or we have timed out and we are
1110 * showing the credentials dialog, then it is time to move on.
1111 */
1112 private void resumeAfterCredentials() {
1113 if (mCredsDlg == null) {
1114 return;
1115 }
1116
1117 // Clear the toast
1118 if (mCredsDlg.isShowing()) {
1119 mCredsDlg.dismiss();
1120 }
1121 mCredsDlg = null;
1122
1123 // Clear any pending timeout
1124 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1125
1126 // Load the page
1127 WebView w = mTabControl.getCurrentWebView();
1128 if (w != null) {
1129 w.loadUrl(mSettings.getHomePage());
1130 }
1131
1132 // Update the settings, need to do this last as it can take a moment
1133 // to persist the settings. In the mean time we could be loading
1134 // content.
1135 mSettings.setLoginInitialized(this);
1136 }
1137
1138 // Open the icon database and retain all the icons for visited sites.
1139 private void retainIconsOnStartup() {
1140 final WebIconDatabase db = WebIconDatabase.getInstance();
1141 db.open(getDir("icons", 0).getPath());
1142 try {
1143 Cursor c = Browser.getAllBookmarks(mResolver);
1144 if (!c.moveToFirst()) {
1145 c.deactivate();
1146 return;
1147 }
1148 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1149 do {
1150 String url = c.getString(urlIndex);
1151 db.retainIconForPageUrl(url);
1152 } while (c.moveToNext());
1153 c.deactivate();
1154 } catch (IllegalStateException e) {
1155 Log.e(LOGTAG, "retainIconsOnStartup", e);
1156 }
1157 }
1158
1159 // Helper method for getting the top window.
1160 WebView getTopWindow() {
1161 return mTabControl.getCurrentTopWebView();
1162 }
1163
1164 @Override
1165 public boolean onCreateOptionsMenu(Menu menu) {
1166 super.onCreateOptionsMenu(menu);
1167
1168 MenuInflater inflater = getMenuInflater();
1169 inflater.inflate(R.menu.browser, menu);
1170 mMenu = menu;
1171 updateInLoadMenuItems();
1172 return true;
1173 }
1174
1175 /**
1176 * As the menu can be open when loading state changes
1177 * we must manually update the state of the stop/reload menu
1178 * item
1179 */
1180 private void updateInLoadMenuItems() {
1181 if (mMenu == null) {
1182 return;
1183 }
1184 MenuItem src = mInLoad ?
1185 mMenu.findItem(R.id.stop_menu_id):
1186 mMenu.findItem(R.id.reload_menu_id);
1187 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1188 dest.setIcon(src.getIcon());
1189 dest.setTitle(src.getTitle());
1190 }
1191
1192 @Override
1193 public boolean onContextItemSelected(MenuItem item) {
1194 // chording is not an issue with context menus, but we use the same
1195 // options selector, so set mCanChord to true so we can access them.
1196 mCanChord = true;
1197 int id = item.getItemId();
1198 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001199 if (null == webView) {
1200 return false;
1201 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001202 final HashMap hrefMap = new HashMap();
1203 hrefMap.put("webview", webView);
1204 final Message msg = mHandler.obtainMessage(
1205 FOCUS_NODE_HREF, id, 0, hrefMap);
1206 switch (id) {
1207 // -- Browser context menu
1208 case R.id.open_context_menu_id:
1209 case R.id.open_newtab_context_menu_id:
1210 case R.id.bookmark_context_menu_id:
1211 case R.id.save_link_context_menu_id:
1212 case R.id.share_link_context_menu_id:
1213 case R.id.copy_link_context_menu_id:
1214 webView.requestFocusNodeHref(msg);
1215 break;
1216
1217 default:
1218 // For other context menus
1219 return onOptionsItemSelected(item);
1220 }
1221 mCanChord = false;
1222 return true;
1223 }
1224
1225 private Bundle createGoogleSearchSourceBundle(String source) {
1226 Bundle bundle = new Bundle();
1227 bundle.putString(SearchManager.SOURCE, source);
1228 return bundle;
1229 }
1230
1231 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001232 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001233 */
1234 @Override
1235 public boolean onSearchRequested() {
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001236 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001237 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001238 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001239 return true;
1240 }
1241
1242 @Override
1243 public void startSearch(String initialQuery, boolean selectInitialQuery,
1244 Bundle appSearchData, boolean globalSearch) {
1245 if (appSearchData == null) {
1246 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1247 }
1248 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1249 }
1250
Leon Scroggins1f005d32009-08-10 17:36:42 -04001251 /**
1252 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1253 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001254 * @param index Index of the tab to change to, as defined by
1255 * mTabControl.getTabIndex(Tab t).
1256 * @return boolean True if we successfully switched to a different tab. If
1257 * the indexth tab is null, or if that tab is the same as
1258 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001259 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001260 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001261 TabControl.Tab tab = mTabControl.getTab(index);
1262 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1263 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001264 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001265 }
1266 if (currentTab != null) {
1267 // currentTab may be null if it was just removed. In that case,
1268 // we do not need to remove it
1269 removeTabFromContentView(currentTab);
1270 }
1271 removeTabFromContentView(tab);
1272 mTabControl.setCurrentTab(tab);
1273 attachTabToContentView(tab);
Leon Scrogginsa11b75a2009-08-18 10:22:05 -04001274 if (CUSTOM_BROWSER_BAR) {
1275 mTitleBar.setCurrentTab(index);
1276 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001277 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001278 }
1279
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001280 /* package */ TabControl.Tab openTabToHomePage() {
1281 return openTabAndShow(mSettings.getHomePage(), false, null);
1282 }
1283
Leon Scroggins1f005d32009-08-10 17:36:42 -04001284 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001285 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001286 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001287 // This is the last tab. Open a new one, with the home
1288 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001289 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001290 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001291 return;
1292 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001293 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001294 int indexToShow = -1;
1295 if (parent != null) {
1296 indexToShow = mTabControl.getTabIndex(parent);
1297 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001298 final int currentIndex = mTabControl.getCurrentIndex();
1299 // Try to move to the tab to the right
1300 indexToShow = currentIndex + 1;
1301 if (indexToShow > mTabControl.getTabCount() - 1) {
1302 // Try to move to the tab to the left
1303 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001304 }
1305 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001306 if (switchToTab(indexToShow)) {
1307 // Close window
1308 closeTab(current);
1309 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001310 }
1311
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001312 private ActiveTabsPage mActiveTabsPage;
1313
1314 /**
1315 * Remove the active tabs page.
1316 * @param needToAttach If true, the active tabs page did not attach a tab
1317 * to the content view, so we need to do that here.
1318 */
1319 /* package */ void removeActiveTabPage(boolean needToAttach) {
1320 mContentView.removeView(mActiveTabsPage);
1321 mActiveTabsPage = null;
1322 mMenuState = R.id.MAIN_MENU;
1323 if (needToAttach) {
1324 attachTabToContentView(mTabControl.getCurrentTab());
1325 }
1326 getTopWindow().requestFocus();
1327 }
1328
The Android Open Source Project0c908882009-03-03 19:32:16 -08001329 @Override
1330 public boolean onOptionsItemSelected(MenuItem item) {
1331 if (!mCanChord) {
1332 // The user has already fired a shortcut with this hold down of the
1333 // menu key.
1334 return false;
1335 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001336 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001337 return false;
1338 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001339 if (mMenuIsDown) {
1340 // The shortcut action consumes the MENU. Even if it is still down,
1341 // it won't trigger the next shortcut action. In the case of the
1342 // shortcut action triggering a new activity, like Bookmarks, we
1343 // won't get onKeyUp for MENU. So it is important to reset it here.
1344 mMenuIsDown = false;
1345 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001346 switch (item.getItemId()) {
1347 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001348 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001349 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001350 break;
1351
Leon Scroggins64b80f32009-08-07 12:03:34 -04001352 case R.id.goto_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001353 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001354 break;
1355
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001356 case R.id.active_tabs_menu_id:
1357 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1358 removeTabFromContentView(mTabControl.getCurrentTab());
1359 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1360 mActiveTabsPage.requestFocus();
1361 mMenuState = EMPTY_MENU;
1362 break;
1363
Leon Scroggins1f005d32009-08-10 17:36:42 -04001364 case R.id.add_bookmark_menu_id:
1365 Intent i = new Intent(BrowserActivity.this,
1366 AddBookmarkPage.class);
1367 WebView w = getTopWindow();
1368 i.putExtra("url", w.getUrl());
1369 i.putExtra("title", w.getTitle());
1370 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001371 break;
1372
1373 case R.id.stop_reload_menu_id:
1374 if (mInLoad) {
1375 stopLoading();
1376 } else {
1377 getTopWindow().reload();
1378 }
1379 break;
1380
1381 case R.id.back_menu_id:
1382 getTopWindow().goBack();
1383 break;
1384
1385 case R.id.forward_menu_id:
1386 getTopWindow().goForward();
1387 break;
1388
1389 case R.id.close_menu_id:
1390 // Close the subwindow if it exists.
1391 if (mTabControl.getCurrentSubWindow() != null) {
1392 dismissSubWindow(mTabControl.getCurrentTab());
1393 break;
1394 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001395 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001396 break;
1397
1398 case R.id.homepage_menu_id:
1399 TabControl.Tab current = mTabControl.getCurrentTab();
1400 if (current != null) {
1401 dismissSubWindow(current);
1402 current.getWebView().loadUrl(mSettings.getHomePage());
1403 }
1404 break;
1405
1406 case R.id.preferences_menu_id:
1407 Intent intent = new Intent(this,
1408 BrowserPreferencesPage.class);
1409 startActivityForResult(intent, PREFERENCES_PAGE);
1410 break;
1411
1412 case R.id.find_menu_id:
1413 if (null == mFindDialog) {
1414 mFindDialog = new FindDialog(this);
1415 }
1416 mFindDialog.setWebView(getTopWindow());
1417 mFindDialog.show();
1418 mMenuState = EMPTY_MENU;
1419 break;
1420
1421 case R.id.select_text_id:
1422 getTopWindow().emulateShiftHeld();
1423 break;
1424 case R.id.page_info_menu_id:
1425 showPageInfo(mTabControl.getCurrentTab(), false);
1426 break;
1427
1428 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001429 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001430 break;
1431
1432 case R.id.share_page_menu_id:
1433 Browser.sendString(this, getTopWindow().getUrl());
1434 break;
1435
1436 case R.id.dump_nav_menu_id:
1437 getTopWindow().debugDump();
1438 break;
1439
1440 case R.id.zoom_in_menu_id:
1441 getTopWindow().zoomIn();
1442 break;
1443
1444 case R.id.zoom_out_menu_id:
1445 getTopWindow().zoomOut();
1446 break;
1447
1448 case R.id.view_downloads_menu_id:
1449 viewDownloads(null);
1450 break;
1451
The Android Open Source Project0c908882009-03-03 19:32:16 -08001452 case R.id.window_one_menu_id:
1453 case R.id.window_two_menu_id:
1454 case R.id.window_three_menu_id:
1455 case R.id.window_four_menu_id:
1456 case R.id.window_five_menu_id:
1457 case R.id.window_six_menu_id:
1458 case R.id.window_seven_menu_id:
1459 case R.id.window_eight_menu_id:
1460 {
1461 int menuid = item.getItemId();
1462 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1463 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1464 TabControl.Tab desiredTab = mTabControl.getTab(id);
1465 if (desiredTab != null &&
1466 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001467 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001468 }
1469 break;
1470 }
1471 }
1472 }
1473 break;
1474
1475 default:
1476 if (!super.onOptionsItemSelected(item)) {
1477 return false;
1478 }
1479 // Otherwise fall through.
1480 }
1481 mCanChord = false;
1482 return true;
1483 }
1484
1485 public void closeFind() {
1486 mMenuState = R.id.MAIN_MENU;
1487 }
1488
1489 @Override public boolean onPrepareOptionsMenu(Menu menu)
1490 {
1491 // This happens when the user begins to hold down the menu key, so
1492 // allow them to chord to get a shortcut.
1493 mCanChord = true;
1494 // Note: setVisible will decide whether an item is visible; while
1495 // setEnabled() will decide whether an item is enabled, which also means
1496 // whether the matching shortcut key will function.
1497 super.onPrepareOptionsMenu(menu);
1498 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001499 case EMPTY_MENU:
1500 if (mCurrentMenuState != mMenuState) {
1501 menu.setGroupVisible(R.id.MAIN_MENU, false);
1502 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1503 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001504 }
1505 break;
1506 default:
1507 if (mCurrentMenuState != mMenuState) {
1508 menu.setGroupVisible(R.id.MAIN_MENU, true);
1509 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1510 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001511 }
1512 final WebView w = getTopWindow();
1513 boolean canGoBack = false;
1514 boolean canGoForward = false;
1515 boolean isHome = false;
1516 if (w != null) {
1517 canGoBack = w.canGoBack();
1518 canGoForward = w.canGoForward();
1519 isHome = mSettings.getHomePage().equals(w.getUrl());
1520 }
1521 final MenuItem back = menu.findItem(R.id.back_menu_id);
1522 back.setEnabled(canGoBack);
1523
1524 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1525 home.setEnabled(!isHome);
1526
1527 menu.findItem(R.id.forward_menu_id)
1528 .setEnabled(canGoForward);
1529
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001530 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1531 mTabControl.getTabCount() < TabControl.MAX_TABS);
1532
The Android Open Source Project0c908882009-03-03 19:32:16 -08001533 // decide whether to show the share link option
1534 PackageManager pm = getPackageManager();
1535 Intent send = new Intent(Intent.ACTION_SEND);
1536 send.setType("text/plain");
1537 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1538 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1539
The Android Open Source Project0c908882009-03-03 19:32:16 -08001540 boolean isNavDump = mSettings.isNavDump();
1541 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1542 nav.setVisible(isNavDump);
1543 nav.setEnabled(isNavDump);
1544 break;
1545 }
1546 mCurrentMenuState = mMenuState;
1547 return true;
1548 }
1549
1550 @Override
1551 public void onCreateContextMenu(ContextMenu menu, View v,
1552 ContextMenuInfo menuInfo) {
1553 WebView webview = (WebView) v;
1554 WebView.HitTestResult result = webview.getHitTestResult();
1555 if (result == null) {
1556 return;
1557 }
1558
1559 int type = result.getType();
1560 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1561 Log.w(LOGTAG,
1562 "We should not show context menu when nothing is touched");
1563 return;
1564 }
1565 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1566 // let TextView handles context menu
1567 return;
1568 }
1569
1570 // Note, http://b/issue?id=1106666 is requesting that
1571 // an inflated menu can be used again. This is not available
1572 // yet, so inflate each time (yuk!)
1573 MenuInflater inflater = getMenuInflater();
1574 inflater.inflate(R.menu.browsercontext, menu);
1575
1576 // Show the correct menu group
1577 String extra = result.getExtra();
1578 menu.setGroupVisible(R.id.PHONE_MENU,
1579 type == WebView.HitTestResult.PHONE_TYPE);
1580 menu.setGroupVisible(R.id.EMAIL_MENU,
1581 type == WebView.HitTestResult.EMAIL_TYPE);
1582 menu.setGroupVisible(R.id.GEO_MENU,
1583 type == WebView.HitTestResult.GEO_TYPE);
1584 menu.setGroupVisible(R.id.IMAGE_MENU,
1585 type == WebView.HitTestResult.IMAGE_TYPE
1586 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1587 menu.setGroupVisible(R.id.ANCHOR_MENU,
1588 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1589 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1590
1591 // Setup custom handling depending on the type
1592 switch (type) {
1593 case WebView.HitTestResult.PHONE_TYPE:
1594 menu.setHeaderTitle(Uri.decode(extra));
1595 menu.findItem(R.id.dial_context_menu_id).setIntent(
1596 new Intent(Intent.ACTION_VIEW, Uri
1597 .parse(WebView.SCHEME_TEL + extra)));
1598 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1599 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1600 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1601 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1602 addIntent);
1603 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1604 new Copy(extra));
1605 break;
1606
1607 case WebView.HitTestResult.EMAIL_TYPE:
1608 menu.setHeaderTitle(extra);
1609 menu.findItem(R.id.email_context_menu_id).setIntent(
1610 new Intent(Intent.ACTION_VIEW, Uri
1611 .parse(WebView.SCHEME_MAILTO + extra)));
1612 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1613 new Copy(extra));
1614 break;
1615
1616 case WebView.HitTestResult.GEO_TYPE:
1617 menu.setHeaderTitle(extra);
1618 menu.findItem(R.id.map_context_menu_id).setIntent(
1619 new Intent(Intent.ACTION_VIEW, Uri
1620 .parse(WebView.SCHEME_GEO
1621 + URLEncoder.encode(extra))));
1622 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1623 new Copy(extra));
1624 break;
1625
1626 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1627 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1628 TextView titleView = (TextView) LayoutInflater.from(this)
1629 .inflate(android.R.layout.browser_link_context_header,
1630 null);
1631 titleView.setText(extra);
1632 menu.setHeaderView(titleView);
1633 // decide whether to show the open link in new tab option
1634 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1635 mTabControl.getTabCount() < TabControl.MAX_TABS);
1636 PackageManager pm = getPackageManager();
1637 Intent send = new Intent(Intent.ACTION_SEND);
1638 send.setType("text/plain");
1639 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1640 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1641 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1642 break;
1643 }
1644 // otherwise fall through to handle image part
1645 case WebView.HitTestResult.IMAGE_TYPE:
1646 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1647 menu.setHeaderTitle(extra);
1648 }
1649 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1650 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1651 menu.findItem(R.id.download_context_menu_id).
1652 setOnMenuItemClickListener(new Download(extra));
1653 break;
1654
1655 default:
1656 Log.w(LOGTAG, "We should not get here.");
1657 break;
1658 }
1659 }
1660
The Android Open Source Project0c908882009-03-03 19:32:16 -08001661 // Attach the given tab to the content view.
1662 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001663 // Attach the container that contains the main WebView and any other UI
1664 // associated with the tab.
1665 mContentView.addView(t.getContainer(), COVER_SCREEN_PARAMS);
Ben Murdochbff2d602009-07-01 20:19:05 +01001666
1667 if (mShouldShowErrorConsole) {
1668 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1669 if (errorConsole.numberOfErrors() == 0) {
1670 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1671 } else {
1672 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1673 }
1674
1675 mErrorConsoleContainer.addView(errorConsole,
1676 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1677 ViewGroup.LayoutParams.WRAP_CONTENT));
1678 }
1679
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001680 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001681 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001682 // Attach the sub window if necessary
1683 attachSubWindow(t);
1684 // Request focus on the top window.
1685 t.getTopWindow().requestFocus();
1686 }
1687
1688 // Attach a sub window to the main WebView of the given tab.
1689 private void attachSubWindow(TabControl.Tab t) {
1690 // If a sub window exists, attach it to the content view.
1691 final WebView subView = t.getSubWebView();
1692 if (subView != null) {
1693 final View container = t.getSubWebViewContainer();
1694 mContentView.addView(container, COVER_SCREEN_PARAMS);
1695 subView.requestFocus();
1696 }
1697 }
1698
1699 // Remove the given tab from the content view.
1700 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001701 // Remove the container that contains the main WebView.
1702 mContentView.removeView(t.getContainer());
Ben Murdochbff2d602009-07-01 20:19:05 +01001703
1704 if (mTabControl.getCurrentErrorConsole(false) != null) {
1705 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1706 }
1707
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001708 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001709 view.setEmbeddedTitleBar(null);
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001710
The Android Open Source Project0c908882009-03-03 19:32:16 -08001711 // Remove the sub window if it exists.
1712 if (t.getSubWebView() != null) {
1713 mContentView.removeView(t.getSubWebViewContainer());
1714 }
1715 }
1716
1717 // Remove the sub window if it exists. Also called by TabControl when the
1718 // user clicks the 'X' to dismiss a sub window.
1719 /* package */ void dismissSubWindow(TabControl.Tab t) {
1720 final WebView mainView = t.getWebView();
1721 if (t.getSubWebView() != null) {
1722 // Remove the container view and request focus on the main WebView.
1723 mContentView.removeView(t.getSubWebViewContainer());
1724 mainView.requestFocus();
1725 // Tell the TabControl to dismiss the subwindow. This will destroy
1726 // the WebView.
1727 mTabControl.dismissSubWindow(t);
1728 }
1729 }
1730
Leon Scroggins1f005d32009-08-10 17:36:42 -04001731 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001732 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001733 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1734 String appId) {
1735 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001736 }
1737
1738 // This method does a ton of stuff. It will attempt to create a new tab
1739 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001740 // url isn't null, it will load the given url.
1741 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001742 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001743 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1744 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1745 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001746 final TabControl.Tab tab = mTabControl.createNewTab(
1747 closeOnExit, appId, urlData.mUrl);
1748 WebView webview = tab.getWebView();
1749 if (CUSTOM_BROWSER_BAR) {
1750 mTitleBar.addTab(webview, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001751 }
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001752 // If the last tab was removed from the active tabs page, currentTab
1753 // will be null.
1754 if (currentTab != null) {
1755 removeTabFromContentView(currentTab);
1756 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001757 attachTabToContentView(tab);
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001758 // We must set the new tab as the current tab to reflect the old
1759 // animation behavior.
1760 mTabControl.setCurrentTab(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001761 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001762 urlData.loadIn(webview);
1763 }
1764 return tab;
1765 } else {
1766 // Get rid of the subwindow if it exists
1767 dismissSubWindow(currentTab);
1768 if (!urlData.isEmpty()) {
1769 // Load the given url.
1770 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001771 }
1772 }
Grace Klobac9181842009-04-14 08:53:22 -07001773 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001774 }
1775
Grace Klobac9181842009-04-14 08:53:22 -07001776 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001777 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001778 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001779 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001780 WebView view = t.getWebView();
1781 if (CUSTOM_BROWSER_BAR) {
1782 mTitleBar.addTab(view, false);
1783 }
1784 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001785 }
Grace Klobac9181842009-04-14 08:53:22 -07001786 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001787 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001788 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001789 }
1790 }
1791
1792 private class Copy implements OnMenuItemClickListener {
1793 private CharSequence mText;
1794
1795 public boolean onMenuItemClick(MenuItem item) {
1796 copy(mText);
1797 return true;
1798 }
1799
1800 public Copy(CharSequence toCopy) {
1801 mText = toCopy;
1802 }
1803 }
1804
1805 private class Download implements OnMenuItemClickListener {
1806 private String mText;
1807
1808 public boolean onMenuItemClick(MenuItem item) {
1809 onDownloadStartNoStream(mText, null, null, null, -1);
1810 return true;
1811 }
1812
1813 public Download(String toDownload) {
1814 mText = toDownload;
1815 }
1816 }
1817
1818 private void copy(CharSequence text) {
1819 try {
1820 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1821 if (clip != null) {
1822 clip.setClipboardText(text);
1823 }
1824 } catch (android.os.RemoteException e) {
1825 Log.e(LOGTAG, "Copy failed", e);
1826 }
1827 }
1828
1829 /**
1830 * Resets the browser title-view to whatever it must be (for example, if we
1831 * load a page from history).
1832 */
1833 private void resetTitle() {
1834 resetLockIcon();
1835 resetTitleIconAndProgress();
1836 }
1837
1838 /**
1839 * Resets the browser title-view to whatever it must be
1840 * (for example, if we had a loading error)
1841 * When we have a new page, we call resetTitle, when we
1842 * have to reset the titlebar to whatever it used to be
1843 * (for example, if the user chose to stop loading), we
1844 * call resetTitleAndRevertLockIcon.
1845 */
1846 /* package */ void resetTitleAndRevertLockIcon() {
1847 revertLockIcon();
1848 resetTitleIconAndProgress();
1849 }
1850
1851 /**
1852 * Reset the title, favicon, and progress.
1853 */
1854 private void resetTitleIconAndProgress() {
1855 WebView current = mTabControl.getCurrentWebView();
1856 if (current == null) {
1857 return;
1858 }
1859 resetTitleAndIcon(current);
1860 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001861 mWebChromeClient.onProgressChanged(current, progress);
1862 }
1863
1864 // Reset the title and the icon based on the given item.
1865 private void resetTitleAndIcon(WebView view) {
1866 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1867 if (item != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001868 setUrlTitle(item.getUrl(), item.getTitle(), view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001869 setFavicon(item.getFavicon());
1870 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001871 setUrlTitle(null, null, view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001872 setFavicon(null);
1873 }
1874 }
1875
1876 /**
1877 * Sets a title composed of the URL and the title string.
1878 * @param url The URL of the site being loaded.
1879 * @param title The title of the site being loaded.
1880 */
Leon Scroggins1f005d32009-08-10 17:36:42 -04001881 private void setUrlTitle(String url, String title, WebView view) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001882 mUrl = url;
1883 mTitle = title;
1884
Leon Scroggins1f005d32009-08-10 17:36:42 -04001885 if (CUSTOM_BROWSER_BAR) {
1886 mTitleBar.setTitleAndUrl(title, url, view);
1887 } else {
1888 setTitle(buildUrlTitle(url, title));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001889 }
1890 }
1891
1892 /**
1893 * Builds and returns the page title, which is some
1894 * combination of the page URL and title.
1895 * @param url The URL of the site being loaded.
1896 * @param title The title of the site being loaded.
1897 * @return The page title.
1898 */
1899 private String buildUrlTitle(String url, String title) {
1900 String urlTitle = "";
1901
1902 if (url != null) {
1903 String titleUrl = buildTitleUrl(url);
1904
1905 if (title != null && 0 < title.length()) {
1906 if (titleUrl != null && 0 < titleUrl.length()) {
1907 urlTitle = titleUrl + ": " + title;
1908 } else {
1909 urlTitle = title;
1910 }
1911 } else {
1912 if (titleUrl != null) {
1913 urlTitle = titleUrl;
1914 }
1915 }
1916 }
1917
1918 return urlTitle;
1919 }
1920
1921 /**
1922 * @param url The URL to build a title version of the URL from.
1923 * @return The title version of the URL or null if fails.
1924 * The title version of the URL can be either the URL hostname,
1925 * or the hostname with an "https://" prefix (for secure URLs),
1926 * or an empty string if, for example, the URL in question is a
1927 * file:// URL with no hostname.
1928 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001929 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001930 String titleUrl = null;
1931
1932 if (url != null) {
1933 try {
1934 // parse the url string
1935 URL urlObj = new URL(url);
1936 if (urlObj != null) {
1937 titleUrl = "";
1938
1939 String protocol = urlObj.getProtocol();
1940 String host = urlObj.getHost();
1941
1942 if (host != null && 0 < host.length()) {
1943 titleUrl = host;
1944 if (protocol != null) {
1945 // if a secure site, add an "https://" prefix!
1946 if (protocol.equalsIgnoreCase("https")) {
1947 titleUrl = protocol + "://" + host;
1948 }
1949 }
1950 }
1951 }
1952 } catch (MalformedURLException e) {}
1953 }
1954
1955 return titleUrl;
1956 }
1957
1958 // Set the favicon in the title bar.
1959 private void setFavicon(Bitmap icon) {
Leon Scroggins81db3662009-06-04 17:45:11 -04001960 if (CUSTOM_BROWSER_BAR) {
1961 Drawable[] array = new Drawable[3];
1962 array[0] = new PaintDrawable(Color.BLACK);
1963 PaintDrawable p = new PaintDrawable(Color.WHITE);
1964 array[1] = p;
1965 if (icon == null) {
1966 array[2] = mGenericFavicon;
1967 } else {
1968 array[2] = new BitmapDrawable(icon);
1969 }
1970 LayerDrawable d = new LayerDrawable(array);
1971 d.setLayerInset(1, 1, 1, 1, 1);
1972 d.setLayerInset(2, 2, 2, 2, 2);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001973 mTitleBar.setFavicon(d, getTopWindow());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001974 } else {
Leon Scroggins81db3662009-06-04 17:45:11 -04001975 Drawable[] array = new Drawable[2];
1976 PaintDrawable p = new PaintDrawable(Color.WHITE);
1977 p.setCornerRadius(3f);
1978 array[0] = p;
1979 if (icon == null) {
1980 array[1] = mGenericFavicon;
1981 } else {
1982 array[1] = new BitmapDrawable(icon);
1983 }
1984 LayerDrawable d = new LayerDrawable(array);
1985 d.setLayerInset(1, 2, 2, 2, 2);
1986 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001987 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001988 }
1989
1990 /**
1991 * Saves the current lock-icon state before resetting
1992 * the lock icon. If we have an error, we may need to
1993 * roll back to the previous state.
1994 */
1995 private void saveLockIcon() {
1996 mPrevLockType = mLockIconType;
1997 }
1998
1999 /**
2000 * Reverts the lock-icon state to the last saved state,
2001 * for example, if we had an error, and need to cancel
2002 * the load.
2003 */
2004 private void revertLockIcon() {
2005 mLockIconType = mPrevLockType;
2006
Dave Bort31a6d1c2009-04-13 15:56:49 -07002007 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002008 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2009 " revert lock icon to " + mLockIconType);
2010 }
2011
2012 updateLockIconImage(mLockIconType);
2013 }
2014
Leon Scroggins1f005d32009-08-10 17:36:42 -04002015 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002016 * Close the tab, remove its associated title bar, and adjust mTabControl's
2017 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002018 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002019 /* package */ void closeTab(TabControl.Tab t) {
2020 int currentIndex = mTabControl.getCurrentIndex();
2021 int removeIndex = mTabControl.getTabIndex(t);
Leon Scrogginsa11b75a2009-08-18 10:22:05 -04002022 if (CUSTOM_BROWSER_BAR) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002023 mTitleBar.removeTab(removeIndex);
Leon Scrogginsa11b75a2009-08-18 10:22:05 -04002024 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04002025 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002026 if (currentIndex >= removeIndex && currentIndex != 0) {
2027 currentIndex--;
2028 }
2029 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
The Android Open Source Project0c908882009-03-03 19:32:16 -08002030 }
2031
2032 private void goBackOnePageOrQuit() {
2033 TabControl.Tab current = mTabControl.getCurrentTab();
2034 if (current == null) {
2035 /*
2036 * Instead of finishing the activity, simply push this to the back
2037 * of the stack and let ActivityManager to choose the foreground
2038 * activity. As BrowserActivity is singleTask, it will be always the
2039 * root of the task. So we can use either true or false for
2040 * moveTaskToBack().
2041 */
2042 moveTaskToBack(true);
2043 }
2044 WebView w = current.getWebView();
2045 if (w.canGoBack()) {
2046 w.goBack();
2047 } else {
2048 // Check to see if we are closing a window that was created by
2049 // another window. If so, we switch back to that window.
2050 TabControl.Tab parent = current.getParentTab();
2051 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002052 switchToTab(mTabControl.getTabIndex(parent));
2053 // Now we close the other tab
2054 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002055 } else {
2056 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002057 // force mPageStarted to be false as we are going to either
2058 // finish the activity or remove the tab. This will ensure
2059 // pauseWebView() taking action.
2060 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002061 if (mTabControl.getTabCount() == 1) {
2062 finish();
2063 return;
2064 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002065 // call pauseWebViewTimers() now, we won't be able to call
2066 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002067 // Temporarily change mActivityInPause to be true as
2068 // pauseWebViewTimers() will do nothing if mActivityInPause
2069 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002070 boolean savedState = mActivityInPause;
2071 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002072 Log.e(LOGTAG, "BrowserActivity is already paused "
2073 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002074 }
2075 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002076 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002077 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002078 removeTabFromContentView(current);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002079 if (CUSTOM_BROWSER_BAR) {
2080 mTitleBar.removeTab(mTabControl.getTabIndex(current));
2081 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002082 mTabControl.removeTab(current);
2083 }
2084 /*
2085 * Instead of finishing the activity, simply push this to the back
2086 * of the stack and let ActivityManager to choose the foreground
2087 * activity. As BrowserActivity is singleTask, it will be always the
2088 * root of the task. So we can use either true or false for
2089 * moveTaskToBack().
2090 */
2091 moveTaskToBack(true);
2092 }
2093 }
2094 }
2095
2096 public KeyTracker.State onKeyTracker(int keyCode,
2097 KeyEvent event,
2098 KeyTracker.Stage stage,
2099 int duration) {
2100 // if onKeyTracker() is called after activity onStop()
2101 // because of accumulated key events,
2102 // we should ignore it as browser is not active any more.
2103 WebView topWindow = getTopWindow();
Andrei Popescuadc008d2009-06-26 14:11:30 +01002104 if (topWindow == null && mCustomView == null)
The Android Open Source Project0c908882009-03-03 19:32:16 -08002105 return KeyTracker.State.NOT_TRACKING;
2106
2107 if (keyCode == KeyEvent.KEYCODE_BACK) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01002108 // Check if a custom view is currently showing and, if it is, hide it.
2109 if (mCustomView != null) {
2110 mWebChromeClient.onHideCustomView();
2111 return KeyTracker.State.DONE_TRACKING;
2112 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002113 if (stage == KeyTracker.Stage.LONG_REPEAT) {
Leon Scroggins30444232009-09-04 18:36:20 -04002114 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002115 return KeyTracker.State.DONE_TRACKING;
2116 } else if (stage == KeyTracker.Stage.UP) {
2117 // FIXME: Currently, we do not have a notion of the
2118 // history picker for the subwindow, but maybe we
2119 // should?
2120 WebView subwindow = mTabControl.getCurrentSubWindow();
2121 if (subwindow != null) {
2122 if (subwindow.canGoBack()) {
2123 subwindow.goBack();
2124 } else {
2125 dismissSubWindow(mTabControl.getCurrentTab());
2126 }
2127 } else {
2128 goBackOnePageOrQuit();
2129 }
2130 return KeyTracker.State.DONE_TRACKING;
2131 }
2132 return KeyTracker.State.KEEP_TRACKING;
2133 }
2134 return KeyTracker.State.NOT_TRACKING;
2135 }
2136
2137 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2138 if (keyCode == KeyEvent.KEYCODE_MENU) {
2139 mMenuIsDown = true;
Grace Kloba6ee9c492009-07-13 10:04:34 -07002140 } else if (mMenuIsDown) {
2141 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2142 // still down, we don't want to trigger the search. Pretend to
2143 // consume the key and do nothing.
2144 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002145 }
2146 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2147 if (!handled) {
2148 switch (keyCode) {
2149 case KeyEvent.KEYCODE_SPACE:
2150 if (event.isShiftPressed()) {
2151 getTopWindow().pageUp(false);
2152 } else {
2153 getTopWindow().pageDown(false);
2154 }
2155 handled = true;
2156 break;
2157
2158 default:
2159 break;
2160 }
2161 }
2162 return handled || super.onKeyDown(keyCode, event);
2163 }
2164
2165 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2166 if (keyCode == KeyEvent.KEYCODE_MENU) {
2167 mMenuIsDown = false;
2168 }
2169 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2170 }
2171
2172 private void stopLoading() {
2173 resetTitleAndRevertLockIcon();
2174 WebView w = getTopWindow();
2175 w.stopLoading();
2176 mWebViewClient.onPageFinished(w, w.getUrl());
2177
2178 cancelStopToast();
2179 mStopToast = Toast
2180 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2181 mStopToast.show();
2182 }
2183
2184 private void cancelStopToast() {
2185 if (mStopToast != null) {
2186 mStopToast.cancel();
2187 mStopToast = null;
2188 }
2189 }
2190
2191 // called by a non-UI thread to post the message
2192 public void postMessage(int what, int arg1, int arg2, Object obj) {
2193 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2194 }
2195
2196 // public message ids
2197 public final static int LOAD_URL = 1001;
2198 public final static int STOP_LOAD = 1002;
2199
2200 // Message Ids
2201 private static final int FOCUS_NODE_HREF = 102;
2202 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002203 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002204
2205 // Private handler for handling javascript and saving passwords
2206 private Handler mHandler = new Handler() {
2207
2208 public void handleMessage(Message msg) {
2209 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002210 case FOCUS_NODE_HREF:
2211 String url = (String) msg.getData().get("url");
2212 if (url == null || url.length() == 0) {
2213 break;
2214 }
2215 HashMap focusNodeMap = (HashMap) msg.obj;
2216 WebView view = (WebView) focusNodeMap.get("webview");
2217 // Only apply the action if the top window did not change.
2218 if (getTopWindow() != view) {
2219 break;
2220 }
2221 switch (msg.arg1) {
2222 case R.id.open_context_menu_id:
2223 case R.id.view_image_context_menu_id:
2224 loadURL(getTopWindow(), url);
2225 break;
2226 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002227 final TabControl.Tab parent = mTabControl
2228 .getCurrentTab();
2229 final TabControl.Tab newTab = openTab(url);
2230 if (newTab != parent) {
2231 parent.addChildTab(newTab);
2232 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002233 break;
2234 case R.id.bookmark_context_menu_id:
2235 Intent intent = new Intent(BrowserActivity.this,
2236 AddBookmarkPage.class);
2237 intent.putExtra("url", url);
2238 startActivity(intent);
2239 break;
2240 case R.id.share_link_context_menu_id:
2241 Browser.sendString(BrowserActivity.this, url);
2242 break;
2243 case R.id.copy_link_context_menu_id:
2244 copy(url);
2245 break;
2246 case R.id.save_link_context_menu_id:
2247 case R.id.download_context_menu_id:
2248 onDownloadStartNoStream(url, null, null, null, -1);
2249 break;
2250 }
2251 break;
2252
2253 case LOAD_URL:
2254 loadURL(getTopWindow(), (String) msg.obj);
2255 break;
2256
2257 case STOP_LOAD:
2258 stopLoading();
2259 break;
2260
2261 case CANCEL_CREDS_REQUEST:
2262 resumeAfterCredentials();
2263 break;
2264
The Android Open Source Project0c908882009-03-03 19:32:16 -08002265 case RELEASE_WAKELOCK:
2266 if (mWakeLock.isHeld()) {
2267 mWakeLock.release();
2268 }
2269 break;
2270 }
2271 }
2272 };
2273
Leon Scroggins89c6d362009-07-15 16:54:37 -04002274 private void updateScreenshot(WebView view) {
2275 // If this is a bookmarked site, add a screenshot to the database.
2276 // FIXME: When should we update? Every time?
2277 // FIXME: Would like to make sure there is actually something to
2278 // draw, but the API for that (WebViewCore.pictureReady()) is not
2279 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002280 ContentResolver cr = getContentResolver();
2281 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002282 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002283 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002284 boolean succeed = c.moveToFirst();
2285 ContentValues values = null;
2286 while (succeed) {
2287 if (values == null) {
2288 final ByteArrayOutputStream os
2289 = new ByteArrayOutputStream();
2290 Picture thumbnail = view.capturePicture();
2291 // Keep width and height in sync with BrowserBookmarksPage
2292 // and bookmark_thumb
2293 Bitmap bm = Bitmap.createBitmap(100, 80,
2294 Bitmap.Config.ARGB_4444);
2295 Canvas canvas = new Canvas(bm);
2296 // May need to tweak these values to determine what is the
2297 // best scale factor
2298 canvas.scale(.5f, .5f);
2299 thumbnail.draw(canvas);
2300 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2301 values = new ContentValues();
2302 values.put(Browser.BookmarkColumns.THUMBNAIL,
2303 os.toByteArray());
2304 }
2305 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2306 c.getInt(0)), values, null, null);
2307 succeed = c.moveToNext();
2308 }
2309 c.close();
2310 }
2311 }
2312
The Android Open Source Project0c908882009-03-03 19:32:16 -08002313 // -------------------------------------------------------------------------
2314 // WebViewClient implementation.
2315 //-------------------------------------------------------------------------
2316
2317 // Use in overrideUrlLoading
2318 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2319 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2320 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2321 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2322
2323 /* package */ WebViewClient getWebViewClient() {
2324 return mWebViewClient;
2325 }
2326
Patrick Scott3918d442009-08-04 13:22:29 -04002327 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002328 if (icon != null) {
2329 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott3918d442009-08-04 13:22:29 -04002330 view, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002331 }
2332 setFavicon(icon);
2333 }
2334
2335 private final WebViewClient mWebViewClient = new WebViewClient() {
2336 @Override
2337 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2338 resetLockIcon(url);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002339 setUrlTitle(url, null, view);
Ben Murdochbff2d602009-07-01 20:19:05 +01002340
2341 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2342 if (errorConsole != null) {
2343 errorConsole.clearErrorMessages();
2344 if (mShouldShowErrorConsole) {
2345 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2346 }
2347 }
2348
The Android Open Source Project0c908882009-03-03 19:32:16 -08002349 // Call updateIcon instead of setFavicon so the bookmark
2350 // database can be updated.
Patrick Scott3918d442009-08-04 13:22:29 -04002351 updateIcon(view, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002352
Grace Kloba4d7880f2009-08-12 09:35:42 -07002353 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002354 String host;
2355 try {
2356 WebAddress uri = new WebAddress(url);
2357 host = uri.mHost;
2358 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002359 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002360 }
2361 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002362 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002363 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002364 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002365 }
2366
2367 // Performance probe
2368 if (false) {
2369 mStart = SystemClock.uptimeMillis();
2370 mProcessStart = Process.getElapsedCpuTime();
2371 long[] sysCpu = new long[7];
2372 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2373 sysCpu, null)) {
2374 mUserStart = sysCpu[0] + sysCpu[1];
2375 mSystemStart = sysCpu[2];
2376 mIdleStart = sysCpu[3];
2377 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2378 }
2379 mUiStart = SystemClock.currentThreadTimeMillis();
2380 }
2381
2382 if (!mPageStarted) {
2383 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002384 // if onResume() has been called, resumeWebViewTimers() does
2385 // nothing.
2386 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002387 }
2388
2389 // reset sync timer to avoid sync starts during loading a page
2390 CookieSyncManager.getInstance().resetSync();
2391
2392 mInLoad = true;
2393 updateInLoadMenuItems();
2394 if (!mIsNetworkUp) {
2395 if ( mAlertDialog == null) {
2396 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2397 .setTitle(R.string.loadSuspendedTitle)
2398 .setMessage(R.string.loadSuspended)
2399 .setPositiveButton(R.string.ok, null)
2400 .show();
2401 }
2402 if (view != null) {
2403 view.setNetworkAvailable(false);
2404 }
2405 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002406 }
2407
2408 @Override
2409 public void onPageFinished(WebView view, String url) {
2410 // Reset the title and icon in case we stopped a provisional
2411 // load.
2412 resetTitleAndIcon(view);
2413
2414 // Update the lock icon image only once we are done loading
2415 updateLockIconImage(mLockIconType);
Leon Scroggins89c6d362009-07-15 16:54:37 -04002416 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002417
The Android Open Source Project0c908882009-03-03 19:32:16 -08002418 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002419 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002420 long[] sysCpu = new long[7];
2421 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2422 sysCpu, null)) {
2423 String uiInfo = "UI thread used "
2424 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2425 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002426 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002427 Log.d(LOGTAG, uiInfo);
2428 }
2429 //The string that gets written to the log
2430 String performanceString = "It took total "
2431 + (SystemClock.uptimeMillis() - mStart)
2432 + " ms clock time to load the page."
2433 + "\nbrowser process used "
2434 + (Process.getElapsedCpuTime() - mProcessStart)
2435 + " ms, user processes used "
2436 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2437 + " ms, kernel used "
2438 + (sysCpu[2] - mSystemStart) * 10
2439 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2440 + " ms and irq took "
2441 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2442 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002443 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002444 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2445 }
2446 if (url != null) {
2447 // strip the url to maintain consistency
2448 String newUrl = new String(url);
2449 if (newUrl.startsWith("http://www.")) {
2450 newUrl = newUrl.substring(11);
2451 } else if (newUrl.startsWith("http://")) {
2452 newUrl = newUrl.substring(7);
2453 } else if (newUrl.startsWith("https://www.")) {
2454 newUrl = newUrl.substring(12);
2455 } else if (newUrl.startsWith("https://")) {
2456 newUrl = newUrl.substring(8);
2457 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002458 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002459 Log.d(LOGTAG, newUrl + " loaded");
2460 }
2461 /*
2462 if (sWhiteList.contains(newUrl)) {
2463 // The string that gets pushed to the statistcs
2464 // service
2465 performanceString = performanceString
2466 + "\nWebpage: "
2467 + newUrl
2468 + "\nCarrier: "
2469 + android.os.SystemProperties
2470 .get("gsm.sim.operator.alpha");
2471 if (mWebView != null
2472 && mWebView.getContext() != null
2473 && mWebView.getContext().getSystemService(
2474 Context.CONNECTIVITY_SERVICE) != null) {
2475 ConnectivityManager cManager =
2476 (ConnectivityManager) mWebView
2477 .getContext().getSystemService(
2478 Context.CONNECTIVITY_SERVICE);
2479 NetworkInfo nInfo = cManager
2480 .getActiveNetworkInfo();
2481 if (nInfo != null) {
2482 performanceString = performanceString
2483 + "\nNetwork Type: "
2484 + nInfo.getType().toString();
2485 }
2486 }
2487 Checkin.logEvent(mResolver,
2488 Checkin.Events.Tag.WEBPAGE_LOAD,
2489 performanceString);
2490 Log.w(LOGTAG, "pushed to the statistics service");
2491 }
2492 */
2493 }
2494 }
2495 }
2496
2497 if (mInTrace) {
2498 mInTrace = false;
2499 Debug.stopMethodTracing();
2500 }
2501
2502 if (mPageStarted) {
2503 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002504 // pauseWebViewTimers() will do nothing and return false if
2505 // onPause() is not called yet.
2506 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002507 if (mWakeLock.isHeld()) {
2508 mHandler.removeMessages(RELEASE_WAKELOCK);
2509 mWakeLock.release();
2510 }
2511 }
2512 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002513 }
2514
2515 // return true if want to hijack the url to let another app to handle it
2516 @Override
2517 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2518 if (url.startsWith(SCHEME_WTAI)) {
2519 // wtai://wp/mc;number
2520 // number=string(phone-number)
2521 if (url.startsWith(SCHEME_WTAI_MC)) {
2522 Intent intent = new Intent(Intent.ACTION_VIEW,
2523 Uri.parse(WebView.SCHEME_TEL +
2524 url.substring(SCHEME_WTAI_MC.length())));
2525 startActivity(intent);
2526 return true;
2527 }
2528 // wtai://wp/sd;dtmf
2529 // dtmf=string(dialstring)
2530 if (url.startsWith(SCHEME_WTAI_SD)) {
2531 // TODO
2532 // only send when there is active voice connection
2533 return false;
2534 }
2535 // wtai://wp/ap;number;name
2536 // number=string(phone-number)
2537 // name=string
2538 if (url.startsWith(SCHEME_WTAI_AP)) {
2539 // TODO
2540 return false;
2541 }
2542 }
2543
Dianne Hackborn99189432009-06-17 18:06:18 -07002544 // The "about:" schemes are internal to the browser; don't
2545 // want these to be dispatched to other apps.
2546 if (url.startsWith("about:")) {
2547 return false;
2548 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002549
Dianne Hackborn99189432009-06-17 18:06:18 -07002550 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002551
Dianne Hackborn99189432009-06-17 18:06:18 -07002552 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002553 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002554 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2555 } catch (URISyntaxException ex) {
2556 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002557 return false;
2558 }
2559
Grace Kloba5b078b52009-06-24 20:23:41 -07002560 // check whether the intent can be resolved. If not, we will see
2561 // whether we can download it from the Market.
2562 if (getPackageManager().resolveActivity(intent, 0) == null) {
2563 String packagename = intent.getPackage();
2564 if (packagename != null) {
2565 intent = new Intent(Intent.ACTION_VIEW, Uri
2566 .parse("market://search?q=pname:" + packagename));
2567 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2568 startActivity(intent);
2569 return true;
2570 } else {
2571 return false;
2572 }
2573 }
2574
Dianne Hackborn99189432009-06-17 18:06:18 -07002575 // sanitize the Intent, ensuring web pages can not bypass browser
2576 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002577 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002578 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002579 try {
2580 if (startActivityIfNeeded(intent, -1)) {
2581 return true;
2582 }
2583 } catch (ActivityNotFoundException ex) {
2584 // ignore the error. If no application can handle the URL,
2585 // eg about:blank, assume the browser can handle it.
2586 }
2587
2588 if (mMenuIsDown) {
2589 openTab(url);
2590 closeOptionsMenu();
2591 return true;
2592 }
2593
2594 return false;
2595 }
2596
2597 /**
2598 * Updates the lock icon. This method is called when we discover another
2599 * resource to be loaded for this page (for example, javascript). While
2600 * we update the icon type, we do not update the lock icon itself until
2601 * we are done loading, it is slightly more secure this way.
2602 */
2603 @Override
2604 public void onLoadResource(WebView view, String url) {
2605 if (url != null && url.length() > 0) {
2606 // It is only if the page claims to be secure
2607 // that we may have to update the lock:
2608 if (mLockIconType == LOCK_ICON_SECURE) {
2609 // If NOT a 'safe' url, change the lock to mixed content!
2610 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2611 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002612 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002613 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2614 " updated lock icon to " + mLockIconType + " due to " + url);
2615 }
2616 }
2617 }
2618 }
2619 }
2620
2621 /**
2622 * Show the dialog, asking the user if they would like to continue after
2623 * an excessive number of HTTP redirects.
2624 */
2625 @Override
2626 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2627 final Message continueMsg) {
2628 new AlertDialog.Builder(BrowserActivity.this)
2629 .setTitle(R.string.browserFrameRedirect)
2630 .setMessage(R.string.browserFrame307Post)
2631 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2632 public void onClick(DialogInterface dialog, int which) {
2633 continueMsg.sendToTarget();
2634 }})
2635 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2636 public void onClick(DialogInterface dialog, int which) {
2637 cancelMsg.sendToTarget();
2638 }})
2639 .setOnCancelListener(new OnCancelListener() {
2640 public void onCancel(DialogInterface dialog) {
2641 cancelMsg.sendToTarget();
2642 }})
2643 .show();
2644 }
2645
Patrick Scott37911c72009-03-24 18:02:58 -07002646 // Container class for the next error dialog that needs to be
2647 // displayed.
2648 class ErrorDialog {
2649 public final int mTitle;
2650 public final String mDescription;
2651 public final int mError;
2652 ErrorDialog(int title, String desc, int error) {
2653 mTitle = title;
2654 mDescription = desc;
2655 mError = error;
2656 }
2657 };
2658
2659 private void processNextError() {
2660 if (mQueuedErrors == null) {
2661 return;
2662 }
2663 // The first one is currently displayed so just remove it.
2664 mQueuedErrors.removeFirst();
2665 if (mQueuedErrors.size() == 0) {
2666 mQueuedErrors = null;
2667 return;
2668 }
2669 showError(mQueuedErrors.getFirst());
2670 }
2671
2672 private DialogInterface.OnDismissListener mDialogListener =
2673 new DialogInterface.OnDismissListener() {
2674 public void onDismiss(DialogInterface d) {
2675 processNextError();
2676 }
2677 };
2678 private LinkedList<ErrorDialog> mQueuedErrors;
2679
2680 private void queueError(int err, String desc) {
2681 if (mQueuedErrors == null) {
2682 mQueuedErrors = new LinkedList<ErrorDialog>();
2683 }
2684 for (ErrorDialog d : mQueuedErrors) {
2685 if (d.mError == err) {
2686 // Already saw a similar error, ignore the new one.
2687 return;
2688 }
2689 }
2690 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002691 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002692 R.string.browserFrameFileErrorLabel :
2693 R.string.browserFrameNetworkErrorLabel,
2694 desc, err);
2695 mQueuedErrors.addLast(errDialog);
2696
2697 // Show the dialog now if the queue was empty.
2698 if (mQueuedErrors.size() == 1) {
2699 showError(errDialog);
2700 }
2701 }
2702
2703 private void showError(ErrorDialog errDialog) {
2704 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2705 .setTitle(errDialog.mTitle)
2706 .setMessage(errDialog.mDescription)
2707 .setPositiveButton(R.string.ok, null)
2708 .create();
2709 d.setOnDismissListener(mDialogListener);
2710 d.show();
2711 }
2712
The Android Open Source Project0c908882009-03-03 19:32:16 -08002713 /**
2714 * Show a dialog informing the user of the network error reported by
2715 * WebCore.
2716 */
2717 @Override
2718 public void onReceivedError(WebView view, int errorCode,
2719 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002720 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2721 errorCode != WebViewClient.ERROR_CONNECT &&
2722 errorCode != WebViewClient.ERROR_BAD_URL &&
2723 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2724 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002725 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002726 }
Patrick Scott37911c72009-03-24 18:02:58 -07002727 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2728 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002729
2730 // We need to reset the title after an error.
2731 resetTitleAndRevertLockIcon();
2732 }
2733
2734 /**
2735 * Check with the user if it is ok to resend POST data as the page they
2736 * are trying to navigate to is the result of a POST.
2737 */
2738 @Override
2739 public void onFormResubmission(WebView view, final Message dontResend,
2740 final Message resend) {
2741 new AlertDialog.Builder(BrowserActivity.this)
2742 .setTitle(R.string.browserFrameFormResubmitLabel)
2743 .setMessage(R.string.browserFrameFormResubmitMessage)
2744 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2745 public void onClick(DialogInterface dialog, int which) {
2746 resend.sendToTarget();
2747 }})
2748 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2749 public void onClick(DialogInterface dialog, int which) {
2750 dontResend.sendToTarget();
2751 }})
2752 .setOnCancelListener(new OnCancelListener() {
2753 public void onCancel(DialogInterface dialog) {
2754 dontResend.sendToTarget();
2755 }})
2756 .show();
2757 }
2758
2759 /**
2760 * Insert the url into the visited history database.
2761 * @param url The url to be inserted.
2762 * @param isReload True if this url is being reloaded.
2763 * FIXME: Not sure what to do when reloading the page.
2764 */
2765 @Override
2766 public void doUpdateVisitedHistory(WebView view, String url,
2767 boolean isReload) {
2768 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2769 return;
2770 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002771 // remove "client" before updating it to the history so that it wont
2772 // show up in the auto-complete list.
2773 int index = url.indexOf("client=ms-");
2774 if (index > 0 && url.contains(".google.")) {
2775 int end = url.indexOf('&', index);
2776 if (end > 0) {
2777 url = url.substring(0, index-1).concat(url.substring(end));
2778 } else {
2779 url = url.substring(0, index-1);
2780 }
2781 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002782 Browser.updateVisitedHistory(mResolver, url, true);
2783 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2784 }
2785
2786 /**
2787 * Displays SSL error(s) dialog to the user.
2788 */
2789 @Override
2790 public void onReceivedSslError(
2791 final WebView view, final SslErrorHandler handler, final SslError error) {
2792
2793 if (mSettings.showSecurityWarnings()) {
2794 final LayoutInflater factory =
2795 LayoutInflater.from(BrowserActivity.this);
2796 final View warningsView =
2797 factory.inflate(R.layout.ssl_warnings, null);
2798 final LinearLayout placeholder =
2799 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2800
2801 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2802 LinearLayout ll = (LinearLayout)factory
2803 .inflate(R.layout.ssl_warning, null);
2804 ((TextView)ll.findViewById(R.id.warning))
2805 .setText(R.string.ssl_untrusted);
2806 placeholder.addView(ll);
2807 }
2808
2809 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2810 LinearLayout ll = (LinearLayout)factory
2811 .inflate(R.layout.ssl_warning, null);
2812 ((TextView)ll.findViewById(R.id.warning))
2813 .setText(R.string.ssl_mismatch);
2814 placeholder.addView(ll);
2815 }
2816
2817 if (error.hasError(SslError.SSL_EXPIRED)) {
2818 LinearLayout ll = (LinearLayout)factory
2819 .inflate(R.layout.ssl_warning, null);
2820 ((TextView)ll.findViewById(R.id.warning))
2821 .setText(R.string.ssl_expired);
2822 placeholder.addView(ll);
2823 }
2824
2825 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2826 LinearLayout ll = (LinearLayout)factory
2827 .inflate(R.layout.ssl_warning, null);
2828 ((TextView)ll.findViewById(R.id.warning))
2829 .setText(R.string.ssl_not_yet_valid);
2830 placeholder.addView(ll);
2831 }
2832
2833 new AlertDialog.Builder(BrowserActivity.this)
2834 .setTitle(R.string.security_warning)
2835 .setIcon(android.R.drawable.ic_dialog_alert)
2836 .setView(warningsView)
2837 .setPositiveButton(R.string.ssl_continue,
2838 new DialogInterface.OnClickListener() {
2839 public void onClick(DialogInterface dialog, int whichButton) {
2840 handler.proceed();
2841 }
2842 })
2843 .setNeutralButton(R.string.view_certificate,
2844 new DialogInterface.OnClickListener() {
2845 public void onClick(DialogInterface dialog, int whichButton) {
2846 showSSLCertificateOnError(view, handler, error);
2847 }
2848 })
2849 .setNegativeButton(R.string.cancel,
2850 new DialogInterface.OnClickListener() {
2851 public void onClick(DialogInterface dialog, int whichButton) {
2852 handler.cancel();
2853 BrowserActivity.this.resetTitleAndRevertLockIcon();
2854 }
2855 })
2856 .setOnCancelListener(
2857 new DialogInterface.OnCancelListener() {
2858 public void onCancel(DialogInterface dialog) {
2859 handler.cancel();
2860 BrowserActivity.this.resetTitleAndRevertLockIcon();
2861 }
2862 })
2863 .show();
2864 } else {
2865 handler.proceed();
2866 }
2867 }
2868
2869 /**
2870 * Handles an HTTP authentication request.
2871 *
2872 * @param handler The authentication handler
2873 * @param host The host
2874 * @param realm The realm
2875 */
2876 @Override
2877 public void onReceivedHttpAuthRequest(WebView view,
2878 final HttpAuthHandler handler, final String host, final String realm) {
2879 String username = null;
2880 String password = null;
2881
2882 boolean reuseHttpAuthUsernamePassword =
2883 handler.useHttpAuthUsernamePassword();
2884
2885 if (reuseHttpAuthUsernamePassword &&
2886 (mTabControl.getCurrentWebView() != null)) {
2887 String[] credentials =
2888 mTabControl.getCurrentWebView()
2889 .getHttpAuthUsernamePassword(host, realm);
2890 if (credentials != null && credentials.length == 2) {
2891 username = credentials[0];
2892 password = credentials[1];
2893 }
2894 }
2895
2896 if (username != null && password != null) {
2897 handler.proceed(username, password);
2898 } else {
2899 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2900 }
2901 }
2902
2903 @Override
2904 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2905 if (mMenuIsDown) {
2906 // only check shortcut key when MENU is held
2907 return getWindow().isShortcutKey(event.getKeyCode(), event);
2908 } else {
2909 return false;
2910 }
2911 }
2912
2913 @Override
2914 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2915 if (view != mTabControl.getCurrentTopWebView()) {
2916 return;
2917 }
2918 if (event.isDown()) {
2919 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2920 } else {
2921 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2922 }
2923 }
2924 };
2925
2926 //--------------------------------------------------------------------------
2927 // WebChromeClient implementation
2928 //--------------------------------------------------------------------------
2929
2930 /* package */ WebChromeClient getWebChromeClient() {
2931 return mWebChromeClient;
2932 }
2933
2934 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2935 // Helper method to create a new tab or sub window.
2936 private void createWindow(final boolean dialog, final Message msg) {
2937 if (dialog) {
2938 mTabControl.createSubWindow();
2939 final TabControl.Tab t = mTabControl.getCurrentTab();
2940 attachSubWindow(t);
2941 WebView.WebViewTransport transport =
2942 (WebView.WebViewTransport) msg.obj;
2943 transport.setWebView(t.getSubWebView());
2944 msg.sendToTarget();
2945 } else {
2946 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04002947 final TabControl.Tab newTab
2948 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07002949 if (newTab != parent) {
2950 parent.addChildTab(newTab);
2951 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002952 WebView.WebViewTransport transport =
2953 (WebView.WebViewTransport) msg.obj;
2954 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04002955 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002956 }
2957 }
2958
2959 @Override
2960 public boolean onCreateWindow(WebView view, final boolean dialog,
2961 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002962 // Short-circuit if we can't create any more tabs or sub windows.
2963 if (dialog && mTabControl.getCurrentSubWindow() != null) {
2964 new AlertDialog.Builder(BrowserActivity.this)
2965 .setTitle(R.string.too_many_subwindows_dialog_title)
2966 .setIcon(android.R.drawable.ic_dialog_alert)
2967 .setMessage(R.string.too_many_subwindows_dialog_message)
2968 .setPositiveButton(R.string.ok, null)
2969 .show();
2970 return false;
2971 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
2972 new AlertDialog.Builder(BrowserActivity.this)
2973 .setTitle(R.string.too_many_windows_dialog_title)
2974 .setIcon(android.R.drawable.ic_dialog_alert)
2975 .setMessage(R.string.too_many_windows_dialog_message)
2976 .setPositiveButton(R.string.ok, null)
2977 .show();
2978 return false;
2979 }
2980
2981 // Short-circuit if this was a user gesture.
2982 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002983 createWindow(dialog, resultMsg);
2984 return true;
2985 }
2986
2987 // Allow the popup and create the appropriate window.
2988 final AlertDialog.OnClickListener allowListener =
2989 new AlertDialog.OnClickListener() {
2990 public void onClick(DialogInterface d,
2991 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002992 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002993 }
2994 };
2995
2996 // Block the popup by returning a null WebView.
2997 final AlertDialog.OnClickListener blockListener =
2998 new AlertDialog.OnClickListener() {
2999 public void onClick(DialogInterface d, int which) {
3000 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003001 }
3002 };
3003
3004 // Build a confirmation dialog to display to the user.
3005 final AlertDialog d =
3006 new AlertDialog.Builder(BrowserActivity.this)
3007 .setTitle(R.string.attention)
3008 .setIcon(android.R.drawable.ic_dialog_alert)
3009 .setMessage(R.string.popup_window_attempt)
3010 .setPositiveButton(R.string.allow, allowListener)
3011 .setNegativeButton(R.string.block, blockListener)
3012 .setCancelable(false)
3013 .create();
3014
3015 // Show the confirmation dialog.
3016 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003017 return true;
3018 }
3019
3020 @Override
3021 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003022 final TabControl.Tab current = mTabControl.getCurrentTab();
3023 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003024 if (parent != null) {
3025 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003026 switchToTab(mTabControl.getTabIndex(parent));
3027 // Now we need to close the window
3028 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003029 }
3030 }
3031
3032 @Override
3033 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003034 if (CUSTOM_BROWSER_BAR) {
3035 mTitleBar.setProgress(newProgress, view);
3036 } else {
3037 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3038 newProgress * 100);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003039 }
3040
3041 if (newProgress == 100) {
3042 // onProgressChanged() is called for sub-frame too while
3043 // onPageFinished() is only called for the main frame. sync
3044 // cookie and cache promptly here.
3045 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003046 if (mInLoad) {
3047 mInLoad = false;
3048 updateInLoadMenuItems();
3049 }
3050 } else {
3051 // onPageFinished may have already been called but a subframe
3052 // is still loading and updating the progress. Reset mInLoad
3053 // and update the menu items.
3054 if (!mInLoad) {
3055 mInLoad = true;
3056 updateInLoadMenuItems();
3057 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003058 }
3059 }
3060
3061 @Override
3062 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003063 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003064
3065 // here, if url is null, we want to reset the title
Leon Scroggins1f005d32009-08-10 17:36:42 -04003066 setUrlTitle(url, title, view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003067
3068 if (url == null ||
3069 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3070 return;
3071 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003072 // See if we can find the current url in our history database and
3073 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003074 if (url.startsWith("http://www.")) {
3075 url = url.substring(11);
3076 } else if (url.startsWith("http://")) {
3077 url = url.substring(4);
3078 }
3079 try {
3080 url = "%" + url;
3081 String [] selArgs = new String[] { url };
3082
3083 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3084 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3085 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3086 Browser.HISTORY_PROJECTION, where, selArgs, null);
3087 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003088 // Current implementation of database only has one entry per
3089 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003090 ContentValues map = new ContentValues();
3091 map.put(Browser.BookmarkColumns.TITLE, title);
3092 mResolver.update(Browser.BOOKMARKS_URI, map,
3093 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003094 }
3095 c.close();
3096 } catch (IllegalStateException e) {
3097 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3098 } catch (SQLiteException ex) {
3099 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3100 }
3101 }
3102
3103 @Override
3104 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003105 updateIcon(view, icon);
3106 }
3107
3108 @Override
3109 public void onReceivedTouchIconUrl(WebView view, String url) {
3110 final ContentResolver cr = getContentResolver();
3111 final Cursor c =
3112 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003113 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003114 if (c != null) {
3115 if (c.getCount() > 0) {
3116 new DownloadTouchIcon(cr, c, view).execute(url);
3117 } else {
3118 c.close();
3119 }
3120 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003121 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003122
Andrei Popescuadc008d2009-06-26 14:11:30 +01003123 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003124 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003125 if (mCustomView != null)
3126 return;
3127
3128 // Add the custom view to its container.
3129 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3130 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003131 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003132 // Save the menu state and set it to empty while the custom
3133 // view is showing.
3134 mOldMenuState = mMenuState;
3135 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003136 // Hide the content view.
3137 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003138 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003139 mCustomViewContainer.setVisibility(View.VISIBLE);
3140 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003141 }
3142
3143 @Override
3144 public void onHideCustomView() {
3145 if (mCustomView == null)
3146 return;
3147
Andrei Popescuc9b55562009-07-07 10:51:15 +01003148 // Hide the custom view.
3149 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003150 // Remove the custom view from its container.
3151 mCustomViewContainer.removeView(mCustomView);
3152 mCustomView = null;
3153 // Reset the old menu state.
3154 mMenuState = mOldMenuState;
3155 mOldMenuState = EMPTY_MENU;
3156 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003157 mCustomViewCallback.onCustomViewHidden();
3158 // Show the content view.
3159 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003160 }
3161
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003162 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003163 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003164 * @param url the URL that exceeded the quota
3165 * @param databaseIdentifier the identifier of the database on
3166 * which the transaction that caused the quota overflow was run
3167 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003168 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003169 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003170 * @param quotaUpdater The callback to run when a decision to allow or
3171 * deny quota has been made. Don't forget to call this!
3172 */
3173 @Override
3174 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003175 String databaseIdentifier, long currentQuota, long estimatedSize,
3176 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003177 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003178 url, databaseIdentifier, currentQuota, estimatedSize,
3179 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003180 }
3181
3182 /**
3183 * The Application Cache has exceeded its max size.
3184 * @param spaceNeeded is the amount of disk space that would be needed
3185 * in order for the last appcache operation to succeed.
3186 * @param totalUsedQuota is the sum of all origins' quota.
3187 * @param quotaUpdater A callback to inform the WebCore thread that a new
3188 * app cache size is available. This callback must always be executed at
3189 * some point to ensure that the sleeping WebCore thread is woken up.
3190 */
3191 @Override
3192 public void onReachedMaxAppCacheSize(long spaceNeeded,
3193 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3194 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3195 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003196 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003197
Steve Block2bc69912009-07-30 14:45:13 +01003198 /**
3199 * Instructs the browser to show a prompt to ask the user to set the
3200 * Geolocation permission state for the specified origin.
3201 * @param origin The origin for which Geolocation permissions are
3202 * requested.
3203 * @param callback The callback to call once the user has set the
3204 * Geolocation permission state.
3205 */
3206 @Override
3207 public void onGeolocationPermissionsShowPrompt(String origin,
3208 GeolocationPermissions.Callback callback) {
3209 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3210 origin, callback);
3211 }
3212
3213 /**
3214 * Instructs the browser to hide the Geolocation permissions prompt.
3215 */
3216 @Override
3217 public void onGeolocationPermissionsHidePrompt() {
3218 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3219 }
3220
Ben Murdoch7db26342009-06-03 18:21:19 +01003221 /* Adds a JavaScript error message to the system log.
3222 * @param message The error message to report.
3223 * @param lineNumber The line number of the error.
3224 * @param sourceID The name of the source file that caused the error.
3225 */
3226 @Override
3227 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003228 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3229 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3230 if (mShouldShowErrorConsole &&
3231 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3232 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3233 }
3234 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003235 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003236 };
3237
3238 /**
3239 * Notify the host application a download should be done, or that
3240 * the data should be streamed if a streaming viewer is available.
3241 * @param url The full url to the content that should be downloaded
3242 * @param contentDisposition Content-disposition http header, if
3243 * present.
3244 * @param mimetype The mimetype of the content reported by the server
3245 * @param contentLength The file size reported by the server
3246 */
3247 public void onDownloadStart(String url, String userAgent,
3248 String contentDisposition, String mimetype, long contentLength) {
3249 // if we're dealing wih A/V content that's not explicitly marked
3250 // for download, check if it's streamable.
3251 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003252 || !contentDisposition.regionMatches(
3253 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003254 // query the package manager to see if there's a registered handler
3255 // that matches.
3256 Intent intent = new Intent(Intent.ACTION_VIEW);
3257 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003258 ResolveInfo info = getPackageManager().resolveActivity(intent,
3259 PackageManager.MATCH_DEFAULT_ONLY);
3260 if (info != null) {
3261 ComponentName myName = getComponentName();
3262 // If we resolved to ourselves, we don't want to attempt to
3263 // load the url only to try and download it again.
3264 if (!myName.getPackageName().equals(
3265 info.activityInfo.packageName)
3266 || !myName.getClassName().equals(
3267 info.activityInfo.name)) {
3268 // someone (other than us) knows how to handle this mime
3269 // type with this scheme, don't download.
3270 try {
3271 startActivity(intent);
3272 return;
3273 } catch (ActivityNotFoundException ex) {
3274 if (LOGD_ENABLED) {
3275 Log.d(LOGTAG, "activity not found for " + mimetype
3276 + " over " + Uri.parse(url).getScheme(),
3277 ex);
3278 }
3279 // Best behavior is to fall back to a download in this
3280 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003281 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003282 }
3283 }
3284 }
3285 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3286 }
3287
3288 /**
3289 * Notify the host application a download should be done, even if there
3290 * is a streaming viewer available for thise type.
3291 * @param url The full url to the content that should be downloaded
3292 * @param contentDisposition Content-disposition http header, if
3293 * present.
3294 * @param mimetype The mimetype of the content reported by the server
3295 * @param contentLength The file size reported by the server
3296 */
3297 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3298 String contentDisposition, String mimetype, long contentLength) {
3299
3300 String filename = URLUtil.guessFileName(url,
3301 contentDisposition, mimetype);
3302
3303 // Check to see if we have an SDCard
3304 String status = Environment.getExternalStorageState();
3305 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3306 int title;
3307 String msg;
3308
3309 // Check to see if the SDCard is busy, same as the music app
3310 if (status.equals(Environment.MEDIA_SHARED)) {
3311 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3312 title = R.string.download_sdcard_busy_dlg_title;
3313 } else {
3314 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3315 title = R.string.download_no_sdcard_dlg_title;
3316 }
3317
3318 new AlertDialog.Builder(this)
3319 .setTitle(title)
3320 .setIcon(android.R.drawable.ic_dialog_alert)
3321 .setMessage(msg)
3322 .setPositiveButton(R.string.ok, null)
3323 .show();
3324 return;
3325 }
3326
3327 // java.net.URI is a lot stricter than KURL so we have to undo
3328 // KURL's percent-encoding and redo the encoding using java.net.URI.
3329 URI uri = null;
3330 try {
3331 // Undo the percent-encoding that KURL may have done.
3332 String newUrl = new String(URLUtil.decode(url.getBytes()));
3333 // Parse the url into pieces
3334 WebAddress w = new WebAddress(newUrl);
3335 String frag = null;
3336 String query = null;
3337 String path = w.mPath;
3338 // Break the path into path, query, and fragment
3339 if (path.length() > 0) {
3340 // Strip the fragment
3341 int idx = path.lastIndexOf('#');
3342 if (idx != -1) {
3343 frag = path.substring(idx + 1);
3344 path = path.substring(0, idx);
3345 }
3346 idx = path.lastIndexOf('?');
3347 if (idx != -1) {
3348 query = path.substring(idx + 1);
3349 path = path.substring(0, idx);
3350 }
3351 }
3352 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3353 query, frag);
3354 } catch (Exception e) {
3355 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3356 return;
3357 }
3358
3359 // XXX: Have to use the old url since the cookies were stored using the
3360 // old percent-encoded url.
3361 String cookies = CookieManager.getInstance().getCookie(url);
3362
3363 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003364 values.put(Downloads.COLUMN_URI, uri.toString());
3365 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3366 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3367 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003368 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003369 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003370 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003371 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3372 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3373 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3374 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003375 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003376 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003377 }
3378 if (mimetype == null) {
3379 // We must have long pressed on a link or image to download it. We
3380 // are not sure of the mimetype in this case, so do a head request
3381 new FetchUrlMimeType(this).execute(values);
3382 } else {
3383 final Uri contentUri =
3384 getContentResolver().insert(Downloads.CONTENT_URI, values);
3385 viewDownloads(contentUri);
3386 }
3387
3388 }
3389
3390 /**
3391 * Resets the lock icon. This method is called when we start a new load and
3392 * know the url to be loaded.
3393 */
3394 private void resetLockIcon(String url) {
3395 // Save the lock-icon state (we revert to it if the load gets cancelled)
3396 saveLockIcon();
3397
3398 mLockIconType = LOCK_ICON_UNSECURE;
3399 if (URLUtil.isHttpsUrl(url)) {
3400 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003401 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003402 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3403 " reset lock icon to " + mLockIconType);
3404 }
3405 }
3406
3407 updateLockIconImage(LOCK_ICON_UNSECURE);
3408 }
3409
3410 /**
3411 * Resets the lock icon. This method is called when the icon needs to be
3412 * reset but we do not know whether we are loading a secure or not secure
3413 * page.
3414 */
3415 private void resetLockIcon() {
3416 // Save the lock-icon state (we revert to it if the load gets cancelled)
3417 saveLockIcon();
3418
3419 mLockIconType = LOCK_ICON_UNSECURE;
3420
Dave Bort31a6d1c2009-04-13 15:56:49 -07003421 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003422 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3423 " reset lock icon to " + mLockIconType);
3424 }
3425
3426 updateLockIconImage(LOCK_ICON_UNSECURE);
3427 }
3428
3429 /**
3430 * Updates the lock-icon image in the title-bar.
3431 */
3432 private void updateLockIconImage(int lockIconType) {
3433 Drawable d = null;
3434 if (lockIconType == LOCK_ICON_SECURE) {
3435 d = mSecLockIcon;
3436 } else if (lockIconType == LOCK_ICON_MIXED) {
3437 d = mMixLockIcon;
3438 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04003439 if (CUSTOM_BROWSER_BAR) {
3440 mTitleBar.setLock(d, getTopWindow());
3441 } else {
3442 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003443 }
3444 }
3445
3446 /**
3447 * Displays a page-info dialog.
3448 * @param tab The tab to show info about
3449 * @param fromShowSSLCertificateOnError The flag that indicates whether
3450 * this dialog was opened from the SSL-certificate-on-error dialog or
3451 * not. This is important, since we need to know whether to return to
3452 * the parent dialog or simply dismiss.
3453 */
3454 private void showPageInfo(final TabControl.Tab tab,
3455 final boolean fromShowSSLCertificateOnError) {
3456 final LayoutInflater factory = LayoutInflater
3457 .from(this);
3458
3459 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3460
3461 final WebView view = tab.getWebView();
3462
3463 String url = null;
3464 String title = null;
3465
3466 if (view == null) {
3467 url = tab.getUrl();
3468 title = tab.getTitle();
3469 } else if (view == mTabControl.getCurrentWebView()) {
3470 // Use the cached title and url if this is the current WebView
3471 url = mUrl;
3472 title = mTitle;
3473 } else {
3474 url = view.getUrl();
3475 title = view.getTitle();
3476 }
3477
3478 if (url == null) {
3479 url = "";
3480 }
3481 if (title == null) {
3482 title = "";
3483 }
3484
3485 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3486 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3487
3488 mPageInfoView = tab;
3489 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3490
3491 AlertDialog.Builder alertDialogBuilder =
3492 new AlertDialog.Builder(this)
3493 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3494 .setView(pageInfoView)
3495 .setPositiveButton(
3496 R.string.ok,
3497 new DialogInterface.OnClickListener() {
3498 public void onClick(DialogInterface dialog,
3499 int whichButton) {
3500 mPageInfoDialog = null;
3501 mPageInfoView = null;
3502 mPageInfoFromShowSSLCertificateOnError = null;
3503
3504 // if we came here from the SSL error dialog
3505 if (fromShowSSLCertificateOnError) {
3506 // go back to the SSL error dialog
3507 showSSLCertificateOnError(
3508 mSSLCertificateOnErrorView,
3509 mSSLCertificateOnErrorHandler,
3510 mSSLCertificateOnErrorError);
3511 }
3512 }
3513 })
3514 .setOnCancelListener(
3515 new DialogInterface.OnCancelListener() {
3516 public void onCancel(DialogInterface dialog) {
3517 mPageInfoDialog = null;
3518 mPageInfoView = null;
3519 mPageInfoFromShowSSLCertificateOnError = null;
3520
3521 // if we came here from the SSL error dialog
3522 if (fromShowSSLCertificateOnError) {
3523 // go back to the SSL error dialog
3524 showSSLCertificateOnError(
3525 mSSLCertificateOnErrorView,
3526 mSSLCertificateOnErrorHandler,
3527 mSSLCertificateOnErrorError);
3528 }
3529 }
3530 });
3531
3532 // if we have a main top-level page SSL certificate set or a certificate
3533 // error
3534 if (fromShowSSLCertificateOnError ||
3535 (view != null && view.getCertificate() != null)) {
3536 // add a 'View Certificate' button
3537 alertDialogBuilder.setNeutralButton(
3538 R.string.view_certificate,
3539 new DialogInterface.OnClickListener() {
3540 public void onClick(DialogInterface dialog,
3541 int whichButton) {
3542 mPageInfoDialog = null;
3543 mPageInfoView = null;
3544 mPageInfoFromShowSSLCertificateOnError = null;
3545
3546 // if we came here from the SSL error dialog
3547 if (fromShowSSLCertificateOnError) {
3548 // go back to the SSL error dialog
3549 showSSLCertificateOnError(
3550 mSSLCertificateOnErrorView,
3551 mSSLCertificateOnErrorHandler,
3552 mSSLCertificateOnErrorError);
3553 } else {
3554 // otherwise, display the top-most certificate from
3555 // the chain
3556 if (view.getCertificate() != null) {
3557 showSSLCertificate(tab);
3558 }
3559 }
3560 }
3561 });
3562 }
3563
3564 mPageInfoDialog = alertDialogBuilder.show();
3565 }
3566
3567 /**
3568 * Displays the main top-level page SSL certificate dialog
3569 * (accessible from the Page-Info dialog).
3570 * @param tab The tab to show certificate for.
3571 */
3572 private void showSSLCertificate(final TabControl.Tab tab) {
3573 final View certificateView =
3574 inflateCertificateView(tab.getWebView().getCertificate());
3575 if (certificateView == null) {
3576 return;
3577 }
3578
3579 LayoutInflater factory = LayoutInflater.from(this);
3580
3581 final LinearLayout placeholder =
3582 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3583
3584 LinearLayout ll = (LinearLayout) factory.inflate(
3585 R.layout.ssl_success, placeholder);
3586 ((TextView)ll.findViewById(R.id.success))
3587 .setText(R.string.ssl_certificate_is_valid);
3588
3589 mSSLCertificateView = tab;
3590 mSSLCertificateDialog =
3591 new AlertDialog.Builder(this)
3592 .setTitle(R.string.ssl_certificate).setIcon(
3593 R.drawable.ic_dialog_browser_certificate_secure)
3594 .setView(certificateView)
3595 .setPositiveButton(R.string.ok,
3596 new DialogInterface.OnClickListener() {
3597 public void onClick(DialogInterface dialog,
3598 int whichButton) {
3599 mSSLCertificateDialog = null;
3600 mSSLCertificateView = null;
3601
3602 showPageInfo(tab, false);
3603 }
3604 })
3605 .setOnCancelListener(
3606 new DialogInterface.OnCancelListener() {
3607 public void onCancel(DialogInterface dialog) {
3608 mSSLCertificateDialog = null;
3609 mSSLCertificateView = null;
3610
3611 showPageInfo(tab, false);
3612 }
3613 })
3614 .show();
3615 }
3616
3617 /**
3618 * Displays the SSL error certificate dialog.
3619 * @param view The target web-view.
3620 * @param handler The SSL error handler responsible for cancelling the
3621 * connection that resulted in an SSL error or proceeding per user request.
3622 * @param error The SSL error object.
3623 */
3624 private void showSSLCertificateOnError(
3625 final WebView view, final SslErrorHandler handler, final SslError error) {
3626
3627 final View certificateView =
3628 inflateCertificateView(error.getCertificate());
3629 if (certificateView == null) {
3630 return;
3631 }
3632
3633 LayoutInflater factory = LayoutInflater.from(this);
3634
3635 final LinearLayout placeholder =
3636 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3637
3638 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3639 LinearLayout ll = (LinearLayout)factory
3640 .inflate(R.layout.ssl_warning, placeholder);
3641 ((TextView)ll.findViewById(R.id.warning))
3642 .setText(R.string.ssl_untrusted);
3643 }
3644
3645 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3646 LinearLayout ll = (LinearLayout)factory
3647 .inflate(R.layout.ssl_warning, placeholder);
3648 ((TextView)ll.findViewById(R.id.warning))
3649 .setText(R.string.ssl_mismatch);
3650 }
3651
3652 if (error.hasError(SslError.SSL_EXPIRED)) {
3653 LinearLayout ll = (LinearLayout)factory
3654 .inflate(R.layout.ssl_warning, placeholder);
3655 ((TextView)ll.findViewById(R.id.warning))
3656 .setText(R.string.ssl_expired);
3657 }
3658
3659 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3660 LinearLayout ll = (LinearLayout)factory
3661 .inflate(R.layout.ssl_warning, placeholder);
3662 ((TextView)ll.findViewById(R.id.warning))
3663 .setText(R.string.ssl_not_yet_valid);
3664 }
3665
3666 mSSLCertificateOnErrorHandler = handler;
3667 mSSLCertificateOnErrorView = view;
3668 mSSLCertificateOnErrorError = error;
3669 mSSLCertificateOnErrorDialog =
3670 new AlertDialog.Builder(this)
3671 .setTitle(R.string.ssl_certificate).setIcon(
3672 R.drawable.ic_dialog_browser_certificate_partially_secure)
3673 .setView(certificateView)
3674 .setPositiveButton(R.string.ok,
3675 new DialogInterface.OnClickListener() {
3676 public void onClick(DialogInterface dialog,
3677 int whichButton) {
3678 mSSLCertificateOnErrorDialog = null;
3679 mSSLCertificateOnErrorView = null;
3680 mSSLCertificateOnErrorHandler = null;
3681 mSSLCertificateOnErrorError = null;
3682
3683 mWebViewClient.onReceivedSslError(
3684 view, handler, error);
3685 }
3686 })
3687 .setNeutralButton(R.string.page_info_view,
3688 new DialogInterface.OnClickListener() {
3689 public void onClick(DialogInterface dialog,
3690 int whichButton) {
3691 mSSLCertificateOnErrorDialog = null;
3692
3693 // do not clear the dialog state: we will
3694 // need to show the dialog again once the
3695 // user is done exploring the page-info details
3696
3697 showPageInfo(mTabControl.getTabFromView(view),
3698 true);
3699 }
3700 })
3701 .setOnCancelListener(
3702 new DialogInterface.OnCancelListener() {
3703 public void onCancel(DialogInterface dialog) {
3704 mSSLCertificateOnErrorDialog = null;
3705 mSSLCertificateOnErrorView = null;
3706 mSSLCertificateOnErrorHandler = null;
3707 mSSLCertificateOnErrorError = null;
3708
3709 mWebViewClient.onReceivedSslError(
3710 view, handler, error);
3711 }
3712 })
3713 .show();
3714 }
3715
3716 /**
3717 * Inflates the SSL certificate view (helper method).
3718 * @param certificate The SSL certificate.
3719 * @return The resultant certificate view with issued-to, issued-by,
3720 * issued-on, expires-on, and possibly other fields set.
3721 * If the input certificate is null, returns null.
3722 */
3723 private View inflateCertificateView(SslCertificate certificate) {
3724 if (certificate == null) {
3725 return null;
3726 }
3727
3728 LayoutInflater factory = LayoutInflater.from(this);
3729
3730 View certificateView = factory.inflate(
3731 R.layout.ssl_certificate, null);
3732
3733 // issued to:
3734 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3735 if (issuedTo != null) {
3736 ((TextView) certificateView.findViewById(R.id.to_common))
3737 .setText(issuedTo.getCName());
3738 ((TextView) certificateView.findViewById(R.id.to_org))
3739 .setText(issuedTo.getOName());
3740 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3741 .setText(issuedTo.getUName());
3742 }
3743
3744 // issued by:
3745 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3746 if (issuedBy != null) {
3747 ((TextView) certificateView.findViewById(R.id.by_common))
3748 .setText(issuedBy.getCName());
3749 ((TextView) certificateView.findViewById(R.id.by_org))
3750 .setText(issuedBy.getOName());
3751 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3752 .setText(issuedBy.getUName());
3753 }
3754
3755 // issued on:
3756 String issuedOn = reformatCertificateDate(
3757 certificate.getValidNotBefore());
3758 ((TextView) certificateView.findViewById(R.id.issued_on))
3759 .setText(issuedOn);
3760
3761 // expires on:
3762 String expiresOn = reformatCertificateDate(
3763 certificate.getValidNotAfter());
3764 ((TextView) certificateView.findViewById(R.id.expires_on))
3765 .setText(expiresOn);
3766
3767 return certificateView;
3768 }
3769
3770 /**
3771 * Re-formats the certificate date (Date.toString()) string to
3772 * a properly localized date string.
3773 * @return Properly localized version of the certificate date string and
3774 * the original certificate date string if fails to localize.
3775 * If the original string is null, returns an empty string "".
3776 */
3777 private String reformatCertificateDate(String certificateDate) {
3778 String reformattedDate = null;
3779
3780 if (certificateDate != null) {
3781 Date date = null;
3782 try {
3783 date = java.text.DateFormat.getInstance().parse(certificateDate);
3784 } catch (ParseException e) {
3785 date = null;
3786 }
3787
3788 if (date != null) {
3789 reformattedDate =
3790 DateFormat.getDateFormat(this).format(date);
3791 }
3792 }
3793
3794 return reformattedDate != null ? reformattedDate :
3795 (certificateDate != null ? certificateDate : "");
3796 }
3797
3798 /**
3799 * Displays an http-authentication dialog.
3800 */
3801 private void showHttpAuthentication(final HttpAuthHandler handler,
3802 final String host, final String realm, final String title,
3803 final String name, final String password, int focusId) {
3804 LayoutInflater factory = LayoutInflater.from(this);
3805 final View v = factory
3806 .inflate(R.layout.http_authentication, null);
3807 if (name != null) {
3808 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3809 }
3810 if (password != null) {
3811 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3812 }
3813
3814 String titleText = title;
3815 if (titleText == null) {
3816 titleText = getText(R.string.sign_in_to).toString().replace(
3817 "%s1", host).replace("%s2", realm);
3818 }
3819
3820 mHttpAuthHandler = handler;
3821 AlertDialog dialog = new AlertDialog.Builder(this)
3822 .setTitle(titleText)
3823 .setIcon(android.R.drawable.ic_dialog_alert)
3824 .setView(v)
3825 .setPositiveButton(R.string.action,
3826 new DialogInterface.OnClickListener() {
3827 public void onClick(DialogInterface dialog,
3828 int whichButton) {
3829 String nm = ((EditText) v
3830 .findViewById(R.id.username_edit))
3831 .getText().toString();
3832 String pw = ((EditText) v
3833 .findViewById(R.id.password_edit))
3834 .getText().toString();
3835 BrowserActivity.this.setHttpAuthUsernamePassword
3836 (host, realm, nm, pw);
3837 handler.proceed(nm, pw);
3838 mHttpAuthenticationDialog = null;
3839 mHttpAuthHandler = null;
3840 }})
3841 .setNegativeButton(R.string.cancel,
3842 new DialogInterface.OnClickListener() {
3843 public void onClick(DialogInterface dialog,
3844 int whichButton) {
3845 handler.cancel();
3846 BrowserActivity.this.resetTitleAndRevertLockIcon();
3847 mHttpAuthenticationDialog = null;
3848 mHttpAuthHandler = null;
3849 }})
3850 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3851 public void onCancel(DialogInterface dialog) {
3852 handler.cancel();
3853 BrowserActivity.this.resetTitleAndRevertLockIcon();
3854 mHttpAuthenticationDialog = null;
3855 mHttpAuthHandler = null;
3856 }})
3857 .create();
3858 // Make the IME appear when the dialog is displayed if applicable.
3859 dialog.getWindow().setSoftInputMode(
3860 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3861 dialog.show();
3862 if (focusId != 0) {
3863 dialog.findViewById(focusId).requestFocus();
3864 } else {
3865 v.findViewById(R.id.username_edit).requestFocus();
3866 }
3867 mHttpAuthenticationDialog = dialog;
3868 }
3869
3870 public int getProgress() {
3871 WebView w = mTabControl.getCurrentWebView();
3872 if (w != null) {
3873 return w.getProgress();
3874 } else {
3875 return 100;
3876 }
3877 }
3878
3879 /**
3880 * Set HTTP authentication password.
3881 *
3882 * @param host The host for the password
3883 * @param realm The realm for the password
3884 * @param username The username for the password. If it is null, it means
3885 * password can't be saved.
3886 * @param password The password
3887 */
3888 public void setHttpAuthUsernamePassword(String host, String realm,
3889 String username,
3890 String password) {
3891 WebView w = mTabControl.getCurrentWebView();
3892 if (w != null) {
3893 w.setHttpAuthUsernamePassword(host, realm, username, password);
3894 }
3895 }
3896
3897 /**
3898 * connectivity manager says net has come or gone... inform the user
3899 * @param up true if net has come up, false if net has gone down
3900 */
3901 public void onNetworkToggle(boolean up) {
3902 if (up == mIsNetworkUp) {
3903 return;
3904 } else if (up) {
3905 mIsNetworkUp = true;
3906 if (mAlertDialog != null) {
3907 mAlertDialog.cancel();
3908 mAlertDialog = null;
3909 }
3910 } else {
3911 mIsNetworkUp = false;
3912 if (mInLoad && mAlertDialog == null) {
3913 mAlertDialog = new AlertDialog.Builder(this)
3914 .setTitle(R.string.loadSuspendedTitle)
3915 .setMessage(R.string.loadSuspended)
3916 .setPositiveButton(R.string.ok, null)
3917 .show();
3918 }
3919 }
3920 WebView w = mTabControl.getCurrentWebView();
3921 if (w != null) {
3922 w.setNetworkAvailable(up);
3923 }
3924 }
3925
3926 @Override
3927 protected void onActivityResult(int requestCode, int resultCode,
3928 Intent intent) {
3929 switch (requestCode) {
3930 case COMBO_PAGE:
3931 if (resultCode == RESULT_OK && intent != null) {
3932 String data = intent.getAction();
3933 Bundle extras = intent.getExtras();
3934 if (extras != null && extras.getBoolean("new_window", false)) {
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003935 final TabControl.Tab newTab = openTab(data);
3936 if (mSettings.openInBackground() &&
Leon Scroggins1f005d32009-08-10 17:36:42 -04003937 newTab != null) {
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003938 mTabControl.populatePickerData(newTab);
3939 mTabControl.setCurrentTab(newTab);
Leon Scroggins1f005d32009-08-10 17:36:42 -04003940 int newIndex = mTabControl.getCurrentIndex();
3941 if (CUSTOM_BROWSER_BAR) {
3942 mTitleBar.setCurrentTab(newIndex);
3943 }
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003944 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003945 } else {
3946 final TabControl.Tab currentTab =
3947 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003948 dismissSubWindow(currentTab);
3949 if (data != null && data.length() != 0) {
3950 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003951 }
3952 }
3953 }
3954 break;
3955 default:
3956 break;
3957 }
Leon Scroggins30444232009-09-04 18:36:20 -04003958 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003959 }
3960
3961 /*
3962 * This method is called as a result of the user selecting the options
3963 * menu to see the download window, or when a download changes state. It
3964 * shows the download window ontop of the current window.
3965 */
3966 /* package */ void viewDownloads(Uri downloadRecord) {
3967 Intent intent = new Intent(this,
3968 BrowserDownloadPage.class);
3969 intent.setData(downloadRecord);
3970 startActivityForResult(intent, this.DOWNLOAD_PAGE);
3971
3972 }
3973
Leon Scroggins160a7e72009-08-14 18:28:01 -04003974 /**
3975 * Open the Go page.
3976 * @param startWithHistory If true, open starting on the history tab.
3977 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003978 */
Leon Scroggins30444232009-09-04 18:36:20 -04003979 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003980 WebView current = mTabControl.getCurrentWebView();
3981 if (current == null) {
3982 return;
3983 }
3984 Intent intent = new Intent(this,
3985 CombinedBookmarkHistoryActivity.class);
3986 String title = current.getTitle();
3987 String url = current.getUrl();
3988 // Just in case the user opens bookmarks before a page finishes loading
3989 // so the current history item, and therefore the page, is null.
3990 if (null == url) {
3991 url = mLastEnteredUrl;
3992 // This can happen.
3993 if (null == url) {
3994 url = mSettings.getHomePage();
3995 }
3996 }
3997 // In case the web page has not yet received its associated title.
3998 if (title == null) {
3999 title = url;
4000 }
4001 intent.putExtra("title", title);
4002 intent.putExtra("url", url);
Leon Scroggins30444232009-09-04 18:36:20 -04004003 // Disable opening in a new window if we have maxed out the windows
4004 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4005 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004006 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004007 if (startWithHistory) {
4008 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4009 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4010 }
4011 startActivityForResult(intent, COMBO_PAGE);
4012 }
4013
4014 // Called when loading from context menu or LOAD_URL message
4015 private void loadURL(WebView view, String url) {
4016 // In case the user enters nothing.
4017 if (url != null && url.length() != 0 && view != null) {
4018 url = smartUrlFilter(url);
4019 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4020 view.loadUrl(url);
4021 }
4022 }
4023 }
4024
The Android Open Source Project0c908882009-03-03 19:32:16 -08004025 private String smartUrlFilter(Uri inUri) {
4026 if (inUri != null) {
4027 return smartUrlFilter(inUri.toString());
4028 }
4029 return null;
4030 }
4031
4032
4033 // get window count
4034
4035 int getWindowCount(){
4036 if(mTabControl != null){
4037 return mTabControl.getTabCount();
4038 }
4039 return 0;
4040 }
4041
Feng Qianb34f87a2009-03-24 21:27:26 -07004042 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004043 "(?i)" + // switch on case insensitive matching
4044 "(" + // begin group for schema
4045 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004046 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004047 ")" +
4048 "(.*)" );
4049
4050 /**
4051 * Attempts to determine whether user input is a URL or search
4052 * terms. Anything with a space is passed to search.
4053 *
4054 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4055 * "Http://" converts to "http://"
4056 *
4057 * @return Original or modified URL
4058 *
4059 */
4060 String smartUrlFilter(String url) {
4061
4062 String inUrl = url.trim();
4063 boolean hasSpace = inUrl.indexOf(' ') != -1;
4064
4065 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4066 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004067 // force scheme to lowercase
4068 String scheme = matcher.group(1);
4069 String lcScheme = scheme.toLowerCase();
4070 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004071 inUrl = lcScheme + matcher.group(2);
4072 }
4073 if (hasSpace) {
4074 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004075 }
4076 return inUrl;
4077 }
4078 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004079 // FIXME: Is this the correct place to add to searches?
4080 // what if someone else calls this function?
4081 int shortcut = parseUrlShortcut(inUrl);
4082 if (shortcut != SHORTCUT_INVALID) {
4083 Browser.addSearchUrl(mResolver, inUrl);
4084 String query = inUrl.substring(2);
4085 switch (shortcut) {
4086 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004087 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004088 case SHORTCUT_WIKIPEDIA_SEARCH:
4089 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4090 case SHORTCUT_DICTIONARY_SEARCH:
4091 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4092 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004093 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004094 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004095 }
4096 }
4097 } else {
4098 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4099 return URLUtil.guessUrl(inUrl);
4100 }
4101 }
4102
4103 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004104 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004105 }
4106
Ben Murdochbff2d602009-07-01 20:19:05 +01004107 /* package */ void setShouldShowErrorConsole(boolean flag) {
4108 if (flag == mShouldShowErrorConsole) {
4109 // Nothing to do.
4110 return;
4111 }
4112
4113 mShouldShowErrorConsole = flag;
4114
4115 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4116
4117 if (flag) {
4118 // Setting the show state of the console will cause it's the layout to be inflated.
4119 if (errorConsole.numberOfErrors() > 0) {
4120 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4121 } else {
4122 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4123 }
4124
4125 // Now we can add it to the main view.
4126 mErrorConsoleContainer.addView(errorConsole,
4127 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4128 ViewGroup.LayoutParams.WRAP_CONTENT));
4129 } else {
4130 mErrorConsoleContainer.removeView(errorConsole);
4131 }
4132
4133 }
4134
The Android Open Source Project0c908882009-03-03 19:32:16 -08004135 private final static int LOCK_ICON_UNSECURE = 0;
4136 private final static int LOCK_ICON_SECURE = 1;
4137 private final static int LOCK_ICON_MIXED = 2;
4138
4139 private int mLockIconType = LOCK_ICON_UNSECURE;
4140 private int mPrevLockType = LOCK_ICON_UNSECURE;
4141
4142 private BrowserSettings mSettings;
4143 private TabControl mTabControl;
4144 private ContentResolver mResolver;
4145 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004146 private View mCustomView;
4147 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004148 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004149
4150 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4151 // view, we should rewrite this.
4152 private int mCurrentMenuState = 0;
4153 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004154 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004155 private static final int EMPTY_MENU = -1;
4156 private Menu mMenu;
4157
4158 private FindDialog mFindDialog;
4159 // Used to prevent chording to result in firing two shortcuts immediately
4160 // one after another. Fixes bug 1211714.
4161 boolean mCanChord;
4162
4163 private boolean mInLoad;
4164 private boolean mIsNetworkUp;
4165
4166 private boolean mPageStarted;
4167 private boolean mActivityInPause = true;
4168
4169 private boolean mMenuIsDown;
4170
4171 private final KeyTracker mKeyTracker = new KeyTracker(this);
4172
4173 // As trackball doesn't send repeat down, we have to track it ourselves
4174 private boolean mTrackTrackball;
4175
4176 private static boolean mInTrace;
4177
4178 // Performance probe
4179 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4180 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4181 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4182 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4183 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4184 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4185 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4186 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4187 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4188 };
4189
4190 private long mStart;
4191 private long mProcessStart;
4192 private long mUserStart;
4193 private long mSystemStart;
4194 private long mIdleStart;
4195 private long mIrqStart;
4196
4197 private long mUiStart;
4198
4199 private Drawable mMixLockIcon;
4200 private Drawable mSecLockIcon;
4201 private Drawable mGenericFavicon;
4202
4203 /* hold a ref so we can auto-cancel if necessary */
4204 private AlertDialog mAlertDialog;
4205
4206 // Wait for credentials before loading google.com
4207 private ProgressDialog mCredsDlg;
4208
4209 // The up-to-date URL and title (these can be different from those stored
4210 // in WebView, since it takes some time for the information in WebView to
4211 // get updated)
4212 private String mUrl;
4213 private String mTitle;
4214
4215 // As PageInfo has different style for landscape / portrait, we have
4216 // to re-open it when configuration changed
4217 private AlertDialog mPageInfoDialog;
4218 private TabControl.Tab mPageInfoView;
4219 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4220 // dialog, we should not just dismiss it, but should get back to the
4221 // SSL-certificate-on-error dialog. This flag is used to store this state
4222 private Boolean mPageInfoFromShowSSLCertificateOnError;
4223
4224 // as SSLCertificateOnError has different style for landscape / portrait,
4225 // we have to re-open it when configuration changed
4226 private AlertDialog mSSLCertificateOnErrorDialog;
4227 private WebView mSSLCertificateOnErrorView;
4228 private SslErrorHandler mSSLCertificateOnErrorHandler;
4229 private SslError mSSLCertificateOnErrorError;
4230
4231 // as SSLCertificate has different style for landscape / portrait, we
4232 // have to re-open it when configuration changed
4233 private AlertDialog mSSLCertificateDialog;
4234 private TabControl.Tab mSSLCertificateView;
4235
4236 // as HttpAuthentication has different style for landscape / portrait, we
4237 // have to re-open it when configuration changed
4238 private AlertDialog mHttpAuthenticationDialog;
4239 private HttpAuthHandler mHttpAuthHandler;
4240
4241 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4242 new FrameLayout.LayoutParams(
4243 ViewGroup.LayoutParams.FILL_PARENT,
4244 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004245 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4246 new FrameLayout.LayoutParams(
4247 ViewGroup.LayoutParams.FILL_PARENT,
4248 ViewGroup.LayoutParams.FILL_PARENT,
4249 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004250 // Google search
4251 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004252 // Wikipedia search
4253 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4254 // Dictionary search
4255 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4256 // Google Mobile Local search
4257 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4258
4259 final static String QUERY_PLACE_HOLDER = "%s";
4260
4261 // "source" parameter for Google search through search key
4262 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4263 // "source" parameter for Google search through goto menu
4264 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4265 // "source" parameter for Google search through simplily type
4266 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4267 // "source" parameter for Google search suggested by the browser
4268 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4269 // "source" parameter for Google search from unknown source
4270 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4271
4272 private final static String LOGTAG = "browser";
4273
The Android Open Source Project0c908882009-03-03 19:32:16 -08004274 private String mLastEnteredUrl;
4275
4276 private PowerManager.WakeLock mWakeLock;
4277 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4278
4279 private Toast mStopToast;
4280
Leon Scroggins1f005d32009-08-10 17:36:42 -04004281 private TitleBarSet mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004282
Ben Murdochbff2d602009-07-01 20:19:05 +01004283 private LinearLayout mErrorConsoleContainer = null;
4284 private boolean mShouldShowErrorConsole = false;
4285
The Android Open Source Project0c908882009-03-03 19:32:16 -08004286 // As the ids are dynamically created, we can't guarantee that they will
4287 // be in sequence, so this static array maps ids to a window number.
4288 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4289 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4290 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4291 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4292
4293 // monitor platform changes
4294 private IntentFilter mNetworkStateChangedFilter;
4295 private BroadcastReceiver mNetworkStateIntentReceiver;
4296
Grace Klobab4da0ad2009-05-14 14:45:40 -07004297 private BroadcastReceiver mPackageInstallationReceiver;
4298
The Android Open Source Project0c908882009-03-03 19:32:16 -08004299 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004300 final static int COMBO_PAGE = 1;
4301 final static int DOWNLOAD_PAGE = 2;
4302 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004303
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004304 /**
4305 * A UrlData class to abstract how the content will be set to WebView.
4306 * This base class uses loadUrl to show the content.
4307 */
4308 private static class UrlData {
4309 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004310 byte[] mPostData;
4311
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004312 UrlData(String url) {
4313 this.mUrl = url;
4314 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004315
4316 void setPostData(byte[] postData) {
4317 mPostData = postData;
4318 }
4319
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004320 boolean isEmpty() {
4321 return mUrl == null || mUrl.length() == 0;
4322 }
4323
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004324 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004325 if (mPostData != null) {
4326 webView.postUrl(mUrl, mPostData);
4327 } else {
4328 webView.loadUrl(mUrl);
4329 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004330 }
4331 };
4332
4333 /**
4334 * A subclass of UrlData class that can display inlined content using
4335 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4336 */
4337 private static class InlinedUrlData extends UrlData {
4338 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4339 super(failUrl);
4340 mInlined = inlined;
4341 mMimeType = mimeType;
4342 mEncoding = encoding;
4343 }
4344 String mMimeType;
4345 String mInlined;
4346 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004347 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004348 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004349 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004350 }
4351
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004352 @Override
4353 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004354 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4355 }
4356 }
4357
Leon Scroggins1f005d32009-08-10 17:36:42 -04004358 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004359}