blob: 7e0db5668607632d11ce654e69de479a66a32a46 [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
963 cancelStopToast();
964
965 // unregister network state listener
966 unregisterReceiver(mNetworkStateIntentReceiver);
967 WebView.disablePlatformNotifications();
968
969 if (mSensorManager != null) {
970 mSensorManager.unregisterListener(mSensorListener);
971 }
972 }
973
974 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700975 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800976 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
977 }
978 super.onDestroy();
979 // Remove the current tab and sub window
980 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700981 if (t != null) {
982 dismissSubWindow(t);
983 removeTabFromContentView(t);
984 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800985 // Destroy all the tabs
986 mTabControl.destroy();
987 WebIconDatabase.getInstance().close();
988 if (mGlsConnection != null) {
989 unbindService(mGlsConnection);
990 mGlsConnection = null;
991 }
992
993 //
994 // stop MASF proxy service
995 //
996 //Intent proxyServiceIntent = new Intent();
997 //proxyServiceIntent.setComponent
998 // (new ComponentName(
999 // "com.android.masfproxyservice",
1000 // "com.android.masfproxyservice.MasfProxyService"));
1001 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001002
1003 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001004 }
1005
1006 @Override
1007 public void onConfigurationChanged(Configuration newConfig) {
1008 super.onConfigurationChanged(newConfig);
1009
1010 if (mPageInfoDialog != null) {
1011 mPageInfoDialog.dismiss();
1012 showPageInfo(
1013 mPageInfoView,
1014 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1015 }
1016 if (mSSLCertificateDialog != null) {
1017 mSSLCertificateDialog.dismiss();
1018 showSSLCertificate(
1019 mSSLCertificateView);
1020 }
1021 if (mSSLCertificateOnErrorDialog != null) {
1022 mSSLCertificateOnErrorDialog.dismiss();
1023 showSSLCertificateOnError(
1024 mSSLCertificateOnErrorView,
1025 mSSLCertificateOnErrorHandler,
1026 mSSLCertificateOnErrorError);
1027 }
1028 if (mHttpAuthenticationDialog != null) {
1029 String title = ((TextView) mHttpAuthenticationDialog
1030 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1031 .toString();
1032 String name = ((TextView) mHttpAuthenticationDialog
1033 .findViewById(R.id.username_edit)).getText().toString();
1034 String password = ((TextView) mHttpAuthenticationDialog
1035 .findViewById(R.id.password_edit)).getText().toString();
1036 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1037 .getId();
1038 mHttpAuthenticationDialog.dismiss();
1039 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1040 name, password, focusId);
1041 }
1042 if (mFindDialog != null && mFindDialog.isShowing()) {
1043 mFindDialog.onConfigurationChanged(newConfig);
1044 }
1045 }
1046
1047 @Override public void onLowMemory() {
1048 super.onLowMemory();
1049 mTabControl.freeMemory();
1050 }
1051
Mike Reed7bfa63b2009-05-28 11:08:32 -04001052 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001053 if ((!mActivityInPause && !mPageStarted) ||
1054 (mActivityInPause && mPageStarted)) {
1055 CookieSyncManager.getInstance().startSync();
1056 WebView w = mTabControl.getCurrentWebView();
1057 if (w != null) {
1058 w.resumeTimers();
1059 }
1060 return true;
1061 } else {
1062 return false;
1063 }
1064 }
1065
Mike Reed7bfa63b2009-05-28 11:08:32 -04001066 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001067 if (mActivityInPause && !mPageStarted) {
1068 CookieSyncManager.getInstance().stopSync();
1069 WebView w = mTabControl.getCurrentWebView();
1070 if (w != null) {
1071 w.pauseTimers();
1072 }
1073 return true;
1074 } else {
1075 return false;
1076 }
1077 }
1078
Leon Scroggins1f005d32009-08-10 17:36:42 -04001079 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001080 /*
1081 * This function is called when we are launching for the first time. We
1082 * are waiting for the login credentials before loading Google home
1083 * pages. This way the user will be logged in straight away.
1084 */
1085 private void waitForCredentials() {
1086 // Show a toast
1087 mCredsDlg = new ProgressDialog(this);
1088 mCredsDlg.setIndeterminate(true);
1089 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1090 // If the user cancels the operation, then cancel the Google
1091 // Credentials request.
1092 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1093 mCredsDlg.show();
1094
1095 // We set a timeout for the retrieval of credentials in onResume()
1096 // as that is when we have freed up some CPU time to get
1097 // the login credentials.
1098 }
1099
1100 /*
1101 * If we have received the credentials or we have timed out and we are
1102 * showing the credentials dialog, then it is time to move on.
1103 */
1104 private void resumeAfterCredentials() {
1105 if (mCredsDlg == null) {
1106 return;
1107 }
1108
1109 // Clear the toast
1110 if (mCredsDlg.isShowing()) {
1111 mCredsDlg.dismiss();
1112 }
1113 mCredsDlg = null;
1114
1115 // Clear any pending timeout
1116 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1117
1118 // Load the page
1119 WebView w = mTabControl.getCurrentWebView();
1120 if (w != null) {
1121 w.loadUrl(mSettings.getHomePage());
1122 }
1123
1124 // Update the settings, need to do this last as it can take a moment
1125 // to persist the settings. In the mean time we could be loading
1126 // content.
1127 mSettings.setLoginInitialized(this);
1128 }
1129
1130 // Open the icon database and retain all the icons for visited sites.
1131 private void retainIconsOnStartup() {
1132 final WebIconDatabase db = WebIconDatabase.getInstance();
1133 db.open(getDir("icons", 0).getPath());
1134 try {
1135 Cursor c = Browser.getAllBookmarks(mResolver);
1136 if (!c.moveToFirst()) {
1137 c.deactivate();
1138 return;
1139 }
1140 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1141 do {
1142 String url = c.getString(urlIndex);
1143 db.retainIconForPageUrl(url);
1144 } while (c.moveToNext());
1145 c.deactivate();
1146 } catch (IllegalStateException e) {
1147 Log.e(LOGTAG, "retainIconsOnStartup", e);
1148 }
1149 }
1150
1151 // Helper method for getting the top window.
1152 WebView getTopWindow() {
1153 return mTabControl.getCurrentTopWebView();
1154 }
1155
1156 @Override
1157 public boolean onCreateOptionsMenu(Menu menu) {
1158 super.onCreateOptionsMenu(menu);
1159
1160 MenuInflater inflater = getMenuInflater();
1161 inflater.inflate(R.menu.browser, menu);
1162 mMenu = menu;
1163 updateInLoadMenuItems();
1164 return true;
1165 }
1166
1167 /**
1168 * As the menu can be open when loading state changes
1169 * we must manually update the state of the stop/reload menu
1170 * item
1171 */
1172 private void updateInLoadMenuItems() {
1173 if (mMenu == null) {
1174 return;
1175 }
1176 MenuItem src = mInLoad ?
1177 mMenu.findItem(R.id.stop_menu_id):
1178 mMenu.findItem(R.id.reload_menu_id);
1179 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1180 dest.setIcon(src.getIcon());
1181 dest.setTitle(src.getTitle());
1182 }
1183
1184 @Override
1185 public boolean onContextItemSelected(MenuItem item) {
1186 // chording is not an issue with context menus, but we use the same
1187 // options selector, so set mCanChord to true so we can access them.
1188 mCanChord = true;
1189 int id = item.getItemId();
1190 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001191 if (null == webView) {
1192 return false;
1193 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001194 final HashMap hrefMap = new HashMap();
1195 hrefMap.put("webview", webView);
1196 final Message msg = mHandler.obtainMessage(
1197 FOCUS_NODE_HREF, id, 0, hrefMap);
1198 switch (id) {
1199 // -- Browser context menu
1200 case R.id.open_context_menu_id:
1201 case R.id.open_newtab_context_menu_id:
1202 case R.id.bookmark_context_menu_id:
1203 case R.id.save_link_context_menu_id:
1204 case R.id.share_link_context_menu_id:
1205 case R.id.copy_link_context_menu_id:
1206 webView.requestFocusNodeHref(msg);
1207 break;
1208
1209 default:
1210 // For other context menus
1211 return onOptionsItemSelected(item);
1212 }
1213 mCanChord = false;
1214 return true;
1215 }
1216
1217 private Bundle createGoogleSearchSourceBundle(String source) {
1218 Bundle bundle = new Bundle();
1219 bundle.putString(SearchManager.SOURCE, source);
1220 return bundle;
1221 }
1222
1223 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001224 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001225 */
1226 @Override
1227 public boolean onSearchRequested() {
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001228 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001229 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001230 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001231 return true;
1232 }
1233
1234 @Override
1235 public void startSearch(String initialQuery, boolean selectInitialQuery,
1236 Bundle appSearchData, boolean globalSearch) {
1237 if (appSearchData == null) {
1238 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1239 }
1240 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1241 }
1242
Leon Scroggins1f005d32009-08-10 17:36:42 -04001243 /**
1244 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1245 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001246 * @param index Index of the tab to change to, as defined by
1247 * mTabControl.getTabIndex(Tab t).
1248 * @return boolean True if we successfully switched to a different tab. If
1249 * the indexth tab is null, or if that tab is the same as
1250 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001251 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001252 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001253 TabControl.Tab tab = mTabControl.getTab(index);
1254 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1255 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001256 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001257 }
1258 if (currentTab != null) {
1259 // currentTab may be null if it was just removed. In that case,
1260 // we do not need to remove it
1261 removeTabFromContentView(currentTab);
1262 }
1263 removeTabFromContentView(tab);
1264 mTabControl.setCurrentTab(tab);
1265 attachTabToContentView(tab);
Leon Scrogginsa11b75a2009-08-18 10:22:05 -04001266 if (CUSTOM_BROWSER_BAR) {
1267 mTitleBar.setCurrentTab(index);
1268 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001269 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001270 }
1271
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001272 /* package */ TabControl.Tab openTabToHomePage() {
1273 return openTabAndShow(mSettings.getHomePage(), false, null);
1274 }
1275
Leon Scroggins1f005d32009-08-10 17:36:42 -04001276 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001277 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001278 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001279 // This is the last tab. Open a new one, with the home
1280 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001281 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001282 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001283 return;
1284 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001285 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001286 int indexToShow = -1;
1287 if (parent != null) {
1288 indexToShow = mTabControl.getTabIndex(parent);
1289 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001290 final int currentIndex = mTabControl.getCurrentIndex();
1291 // Try to move to the tab to the right
1292 indexToShow = currentIndex + 1;
1293 if (indexToShow > mTabControl.getTabCount() - 1) {
1294 // Try to move to the tab to the left
1295 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001296 }
1297 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001298 if (switchToTab(indexToShow)) {
1299 // Close window
1300 closeTab(current);
1301 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001302 }
1303
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001304 private ActiveTabsPage mActiveTabsPage;
1305
1306 /**
1307 * Remove the active tabs page.
1308 * @param needToAttach If true, the active tabs page did not attach a tab
1309 * to the content view, so we need to do that here.
1310 */
1311 /* package */ void removeActiveTabPage(boolean needToAttach) {
1312 mContentView.removeView(mActiveTabsPage);
1313 mActiveTabsPage = null;
1314 mMenuState = R.id.MAIN_MENU;
1315 if (needToAttach) {
1316 attachTabToContentView(mTabControl.getCurrentTab());
1317 }
1318 getTopWindow().requestFocus();
1319 }
1320
The Android Open Source Project0c908882009-03-03 19:32:16 -08001321 @Override
1322 public boolean onOptionsItemSelected(MenuItem item) {
1323 if (!mCanChord) {
1324 // The user has already fired a shortcut with this hold down of the
1325 // menu key.
1326 return false;
1327 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001328 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001329 return false;
1330 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001331 if (mMenuIsDown) {
1332 // The shortcut action consumes the MENU. Even if it is still down,
1333 // it won't trigger the next shortcut action. In the case of the
1334 // shortcut action triggering a new activity, like Bookmarks, we
1335 // won't get onKeyUp for MENU. So it is important to reset it here.
1336 mMenuIsDown = false;
1337 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001338 switch (item.getItemId()) {
1339 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001340 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001341 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001342 break;
1343
Leon Scroggins64b80f32009-08-07 12:03:34 -04001344 case R.id.goto_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001345 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001346 break;
1347
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001348 case R.id.active_tabs_menu_id:
1349 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1350 removeTabFromContentView(mTabControl.getCurrentTab());
1351 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1352 mActiveTabsPage.requestFocus();
1353 mMenuState = EMPTY_MENU;
1354 break;
1355
Leon Scroggins1f005d32009-08-10 17:36:42 -04001356 case R.id.add_bookmark_menu_id:
1357 Intent i = new Intent(BrowserActivity.this,
1358 AddBookmarkPage.class);
1359 WebView w = getTopWindow();
1360 i.putExtra("url", w.getUrl());
1361 i.putExtra("title", w.getTitle());
1362 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001363 break;
1364
1365 case R.id.stop_reload_menu_id:
1366 if (mInLoad) {
1367 stopLoading();
1368 } else {
1369 getTopWindow().reload();
1370 }
1371 break;
1372
1373 case R.id.back_menu_id:
1374 getTopWindow().goBack();
1375 break;
1376
1377 case R.id.forward_menu_id:
1378 getTopWindow().goForward();
1379 break;
1380
1381 case R.id.close_menu_id:
1382 // Close the subwindow if it exists.
1383 if (mTabControl.getCurrentSubWindow() != null) {
1384 dismissSubWindow(mTabControl.getCurrentTab());
1385 break;
1386 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001387 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001388 break;
1389
1390 case R.id.homepage_menu_id:
1391 TabControl.Tab current = mTabControl.getCurrentTab();
1392 if (current != null) {
1393 dismissSubWindow(current);
1394 current.getWebView().loadUrl(mSettings.getHomePage());
1395 }
1396 break;
1397
1398 case R.id.preferences_menu_id:
1399 Intent intent = new Intent(this,
1400 BrowserPreferencesPage.class);
1401 startActivityForResult(intent, PREFERENCES_PAGE);
1402 break;
1403
1404 case R.id.find_menu_id:
1405 if (null == mFindDialog) {
1406 mFindDialog = new FindDialog(this);
1407 }
1408 mFindDialog.setWebView(getTopWindow());
1409 mFindDialog.show();
1410 mMenuState = EMPTY_MENU;
1411 break;
1412
1413 case R.id.select_text_id:
1414 getTopWindow().emulateShiftHeld();
1415 break;
1416 case R.id.page_info_menu_id:
1417 showPageInfo(mTabControl.getCurrentTab(), false);
1418 break;
1419
1420 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001421 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001422 break;
1423
1424 case R.id.share_page_menu_id:
1425 Browser.sendString(this, getTopWindow().getUrl());
1426 break;
1427
1428 case R.id.dump_nav_menu_id:
1429 getTopWindow().debugDump();
1430 break;
1431
1432 case R.id.zoom_in_menu_id:
1433 getTopWindow().zoomIn();
1434 break;
1435
1436 case R.id.zoom_out_menu_id:
1437 getTopWindow().zoomOut();
1438 break;
1439
1440 case R.id.view_downloads_menu_id:
1441 viewDownloads(null);
1442 break;
1443
The Android Open Source Project0c908882009-03-03 19:32:16 -08001444 case R.id.window_one_menu_id:
1445 case R.id.window_two_menu_id:
1446 case R.id.window_three_menu_id:
1447 case R.id.window_four_menu_id:
1448 case R.id.window_five_menu_id:
1449 case R.id.window_six_menu_id:
1450 case R.id.window_seven_menu_id:
1451 case R.id.window_eight_menu_id:
1452 {
1453 int menuid = item.getItemId();
1454 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1455 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1456 TabControl.Tab desiredTab = mTabControl.getTab(id);
1457 if (desiredTab != null &&
1458 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001459 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001460 }
1461 break;
1462 }
1463 }
1464 }
1465 break;
1466
1467 default:
1468 if (!super.onOptionsItemSelected(item)) {
1469 return false;
1470 }
1471 // Otherwise fall through.
1472 }
1473 mCanChord = false;
1474 return true;
1475 }
1476
1477 public void closeFind() {
1478 mMenuState = R.id.MAIN_MENU;
1479 }
1480
1481 @Override public boolean onPrepareOptionsMenu(Menu menu)
1482 {
1483 // This happens when the user begins to hold down the menu key, so
1484 // allow them to chord to get a shortcut.
1485 mCanChord = true;
1486 // Note: setVisible will decide whether an item is visible; while
1487 // setEnabled() will decide whether an item is enabled, which also means
1488 // whether the matching shortcut key will function.
1489 super.onPrepareOptionsMenu(menu);
1490 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001491 case EMPTY_MENU:
1492 if (mCurrentMenuState != mMenuState) {
1493 menu.setGroupVisible(R.id.MAIN_MENU, false);
1494 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1495 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001496 }
1497 break;
1498 default:
1499 if (mCurrentMenuState != mMenuState) {
1500 menu.setGroupVisible(R.id.MAIN_MENU, true);
1501 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1502 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001503 }
1504 final WebView w = getTopWindow();
1505 boolean canGoBack = false;
1506 boolean canGoForward = false;
1507 boolean isHome = false;
1508 if (w != null) {
1509 canGoBack = w.canGoBack();
1510 canGoForward = w.canGoForward();
1511 isHome = mSettings.getHomePage().equals(w.getUrl());
1512 }
1513 final MenuItem back = menu.findItem(R.id.back_menu_id);
1514 back.setEnabled(canGoBack);
1515
1516 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1517 home.setEnabled(!isHome);
1518
1519 menu.findItem(R.id.forward_menu_id)
1520 .setEnabled(canGoForward);
1521
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001522 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1523 mTabControl.getTabCount() < TabControl.MAX_TABS);
1524
The Android Open Source Project0c908882009-03-03 19:32:16 -08001525 // decide whether to show the share link option
1526 PackageManager pm = getPackageManager();
1527 Intent send = new Intent(Intent.ACTION_SEND);
1528 send.setType("text/plain");
1529 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1530 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1531
The Android Open Source Project0c908882009-03-03 19:32:16 -08001532 boolean isNavDump = mSettings.isNavDump();
1533 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1534 nav.setVisible(isNavDump);
1535 nav.setEnabled(isNavDump);
1536 break;
1537 }
1538 mCurrentMenuState = mMenuState;
1539 return true;
1540 }
1541
1542 @Override
1543 public void onCreateContextMenu(ContextMenu menu, View v,
1544 ContextMenuInfo menuInfo) {
1545 WebView webview = (WebView) v;
1546 WebView.HitTestResult result = webview.getHitTestResult();
1547 if (result == null) {
1548 return;
1549 }
1550
1551 int type = result.getType();
1552 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1553 Log.w(LOGTAG,
1554 "We should not show context menu when nothing is touched");
1555 return;
1556 }
1557 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1558 // let TextView handles context menu
1559 return;
1560 }
1561
1562 // Note, http://b/issue?id=1106666 is requesting that
1563 // an inflated menu can be used again. This is not available
1564 // yet, so inflate each time (yuk!)
1565 MenuInflater inflater = getMenuInflater();
1566 inflater.inflate(R.menu.browsercontext, menu);
1567
1568 // Show the correct menu group
1569 String extra = result.getExtra();
1570 menu.setGroupVisible(R.id.PHONE_MENU,
1571 type == WebView.HitTestResult.PHONE_TYPE);
1572 menu.setGroupVisible(R.id.EMAIL_MENU,
1573 type == WebView.HitTestResult.EMAIL_TYPE);
1574 menu.setGroupVisible(R.id.GEO_MENU,
1575 type == WebView.HitTestResult.GEO_TYPE);
1576 menu.setGroupVisible(R.id.IMAGE_MENU,
1577 type == WebView.HitTestResult.IMAGE_TYPE
1578 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1579 menu.setGroupVisible(R.id.ANCHOR_MENU,
1580 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1581 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1582
1583 // Setup custom handling depending on the type
1584 switch (type) {
1585 case WebView.HitTestResult.PHONE_TYPE:
1586 menu.setHeaderTitle(Uri.decode(extra));
1587 menu.findItem(R.id.dial_context_menu_id).setIntent(
1588 new Intent(Intent.ACTION_VIEW, Uri
1589 .parse(WebView.SCHEME_TEL + extra)));
1590 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1591 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1592 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1593 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1594 addIntent);
1595 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1596 new Copy(extra));
1597 break;
1598
1599 case WebView.HitTestResult.EMAIL_TYPE:
1600 menu.setHeaderTitle(extra);
1601 menu.findItem(R.id.email_context_menu_id).setIntent(
1602 new Intent(Intent.ACTION_VIEW, Uri
1603 .parse(WebView.SCHEME_MAILTO + extra)));
1604 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1605 new Copy(extra));
1606 break;
1607
1608 case WebView.HitTestResult.GEO_TYPE:
1609 menu.setHeaderTitle(extra);
1610 menu.findItem(R.id.map_context_menu_id).setIntent(
1611 new Intent(Intent.ACTION_VIEW, Uri
1612 .parse(WebView.SCHEME_GEO
1613 + URLEncoder.encode(extra))));
1614 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1615 new Copy(extra));
1616 break;
1617
1618 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1619 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1620 TextView titleView = (TextView) LayoutInflater.from(this)
1621 .inflate(android.R.layout.browser_link_context_header,
1622 null);
1623 titleView.setText(extra);
1624 menu.setHeaderView(titleView);
1625 // decide whether to show the open link in new tab option
1626 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1627 mTabControl.getTabCount() < TabControl.MAX_TABS);
1628 PackageManager pm = getPackageManager();
1629 Intent send = new Intent(Intent.ACTION_SEND);
1630 send.setType("text/plain");
1631 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1632 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1633 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1634 break;
1635 }
1636 // otherwise fall through to handle image part
1637 case WebView.HitTestResult.IMAGE_TYPE:
1638 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1639 menu.setHeaderTitle(extra);
1640 }
1641 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1642 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1643 menu.findItem(R.id.download_context_menu_id).
1644 setOnMenuItemClickListener(new Download(extra));
1645 break;
1646
1647 default:
1648 Log.w(LOGTAG, "We should not get here.");
1649 break;
1650 }
1651 }
1652
The Android Open Source Project0c908882009-03-03 19:32:16 -08001653 // Attach the given tab to the content view.
1654 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001655 // Attach the container that contains the main WebView and any other UI
1656 // associated with the tab.
1657 mContentView.addView(t.getContainer(), COVER_SCREEN_PARAMS);
Ben Murdochbff2d602009-07-01 20:19:05 +01001658
1659 if (mShouldShowErrorConsole) {
1660 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1661 if (errorConsole.numberOfErrors() == 0) {
1662 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1663 } else {
1664 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1665 }
1666
1667 mErrorConsoleContainer.addView(errorConsole,
1668 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1669 ViewGroup.LayoutParams.WRAP_CONTENT));
1670 }
1671
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001672 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001673 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001674 // Attach the sub window if necessary
1675 attachSubWindow(t);
1676 // Request focus on the top window.
1677 t.getTopWindow().requestFocus();
1678 }
1679
1680 // Attach a sub window to the main WebView of the given tab.
1681 private void attachSubWindow(TabControl.Tab t) {
1682 // If a sub window exists, attach it to the content view.
1683 final WebView subView = t.getSubWebView();
1684 if (subView != null) {
1685 final View container = t.getSubWebViewContainer();
1686 mContentView.addView(container, COVER_SCREEN_PARAMS);
1687 subView.requestFocus();
1688 }
1689 }
1690
1691 // Remove the given tab from the content view.
1692 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001693 // Remove the container that contains the main WebView.
1694 mContentView.removeView(t.getContainer());
Ben Murdochbff2d602009-07-01 20:19:05 +01001695
1696 if (mTabControl.getCurrentErrorConsole(false) != null) {
1697 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1698 }
1699
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001700 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001701 view.setEmbeddedTitleBar(null);
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001702
The Android Open Source Project0c908882009-03-03 19:32:16 -08001703 // Remove the sub window if it exists.
1704 if (t.getSubWebView() != null) {
1705 mContentView.removeView(t.getSubWebViewContainer());
1706 }
1707 }
1708
1709 // Remove the sub window if it exists. Also called by TabControl when the
1710 // user clicks the 'X' to dismiss a sub window.
1711 /* package */ void dismissSubWindow(TabControl.Tab t) {
1712 final WebView mainView = t.getWebView();
1713 if (t.getSubWebView() != null) {
1714 // Remove the container view and request focus on the main WebView.
1715 mContentView.removeView(t.getSubWebViewContainer());
1716 mainView.requestFocus();
1717 // Tell the TabControl to dismiss the subwindow. This will destroy
1718 // the WebView.
1719 mTabControl.dismissSubWindow(t);
1720 }
1721 }
1722
Leon Scroggins1f005d32009-08-10 17:36:42 -04001723 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001724 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001725 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1726 String appId) {
1727 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001728 }
1729
1730 // This method does a ton of stuff. It will attempt to create a new tab
1731 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001732 // url isn't null, it will load the given url.
1733 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001734 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001735 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1736 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1737 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001738 final TabControl.Tab tab = mTabControl.createNewTab(
1739 closeOnExit, appId, urlData.mUrl);
1740 WebView webview = tab.getWebView();
1741 if (CUSTOM_BROWSER_BAR) {
1742 mTitleBar.addTab(webview, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001743 }
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001744 // If the last tab was removed from the active tabs page, currentTab
1745 // will be null.
1746 if (currentTab != null) {
1747 removeTabFromContentView(currentTab);
1748 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001749 attachTabToContentView(tab);
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001750 // We must set the new tab as the current tab to reflect the old
1751 // animation behavior.
1752 mTabControl.setCurrentTab(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001753 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001754 urlData.loadIn(webview);
1755 }
1756 return tab;
1757 } else {
1758 // Get rid of the subwindow if it exists
1759 dismissSubWindow(currentTab);
1760 if (!urlData.isEmpty()) {
1761 // Load the given url.
1762 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001763 }
1764 }
Grace Klobac9181842009-04-14 08:53:22 -07001765 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001766 }
1767
Grace Klobac9181842009-04-14 08:53:22 -07001768 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001769 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001770 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001771 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001772 WebView view = t.getWebView();
1773 if (CUSTOM_BROWSER_BAR) {
1774 mTitleBar.addTab(view, false);
1775 }
1776 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001777 }
Grace Klobac9181842009-04-14 08:53:22 -07001778 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001779 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001780 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001781 }
1782 }
1783
1784 private class Copy implements OnMenuItemClickListener {
1785 private CharSequence mText;
1786
1787 public boolean onMenuItemClick(MenuItem item) {
1788 copy(mText);
1789 return true;
1790 }
1791
1792 public Copy(CharSequence toCopy) {
1793 mText = toCopy;
1794 }
1795 }
1796
1797 private class Download implements OnMenuItemClickListener {
1798 private String mText;
1799
1800 public boolean onMenuItemClick(MenuItem item) {
1801 onDownloadStartNoStream(mText, null, null, null, -1);
1802 return true;
1803 }
1804
1805 public Download(String toDownload) {
1806 mText = toDownload;
1807 }
1808 }
1809
1810 private void copy(CharSequence text) {
1811 try {
1812 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1813 if (clip != null) {
1814 clip.setClipboardText(text);
1815 }
1816 } catch (android.os.RemoteException e) {
1817 Log.e(LOGTAG, "Copy failed", e);
1818 }
1819 }
1820
1821 /**
1822 * Resets the browser title-view to whatever it must be (for example, if we
1823 * load a page from history).
1824 */
1825 private void resetTitle() {
1826 resetLockIcon();
1827 resetTitleIconAndProgress();
1828 }
1829
1830 /**
1831 * Resets the browser title-view to whatever it must be
1832 * (for example, if we had a loading error)
1833 * When we have a new page, we call resetTitle, when we
1834 * have to reset the titlebar to whatever it used to be
1835 * (for example, if the user chose to stop loading), we
1836 * call resetTitleAndRevertLockIcon.
1837 */
1838 /* package */ void resetTitleAndRevertLockIcon() {
1839 revertLockIcon();
1840 resetTitleIconAndProgress();
1841 }
1842
1843 /**
1844 * Reset the title, favicon, and progress.
1845 */
1846 private void resetTitleIconAndProgress() {
1847 WebView current = mTabControl.getCurrentWebView();
1848 if (current == null) {
1849 return;
1850 }
1851 resetTitleAndIcon(current);
1852 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001853 mWebChromeClient.onProgressChanged(current, progress);
1854 }
1855
1856 // Reset the title and the icon based on the given item.
1857 private void resetTitleAndIcon(WebView view) {
1858 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1859 if (item != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001860 setUrlTitle(item.getUrl(), item.getTitle(), view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001861 setFavicon(item.getFavicon());
1862 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001863 setUrlTitle(null, null, view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001864 setFavicon(null);
1865 }
1866 }
1867
1868 /**
1869 * Sets a title composed of the URL and the title string.
1870 * @param url The URL of the site being loaded.
1871 * @param title The title of the site being loaded.
1872 */
Leon Scroggins1f005d32009-08-10 17:36:42 -04001873 private void setUrlTitle(String url, String title, WebView view) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001874 mUrl = url;
1875 mTitle = title;
1876
Leon Scroggins1f005d32009-08-10 17:36:42 -04001877 if (CUSTOM_BROWSER_BAR) {
1878 mTitleBar.setTitleAndUrl(title, url, view);
1879 } else {
1880 setTitle(buildUrlTitle(url, title));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001881 }
1882 }
1883
1884 /**
1885 * Builds and returns the page title, which is some
1886 * combination of the page URL and title.
1887 * @param url The URL of the site being loaded.
1888 * @param title The title of the site being loaded.
1889 * @return The page title.
1890 */
1891 private String buildUrlTitle(String url, String title) {
1892 String urlTitle = "";
1893
1894 if (url != null) {
1895 String titleUrl = buildTitleUrl(url);
1896
1897 if (title != null && 0 < title.length()) {
1898 if (titleUrl != null && 0 < titleUrl.length()) {
1899 urlTitle = titleUrl + ": " + title;
1900 } else {
1901 urlTitle = title;
1902 }
1903 } else {
1904 if (titleUrl != null) {
1905 urlTitle = titleUrl;
1906 }
1907 }
1908 }
1909
1910 return urlTitle;
1911 }
1912
1913 /**
1914 * @param url The URL to build a title version of the URL from.
1915 * @return The title version of the URL or null if fails.
1916 * The title version of the URL can be either the URL hostname,
1917 * or the hostname with an "https://" prefix (for secure URLs),
1918 * or an empty string if, for example, the URL in question is a
1919 * file:// URL with no hostname.
1920 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001921 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001922 String titleUrl = null;
1923
1924 if (url != null) {
1925 try {
1926 // parse the url string
1927 URL urlObj = new URL(url);
1928 if (urlObj != null) {
1929 titleUrl = "";
1930
1931 String protocol = urlObj.getProtocol();
1932 String host = urlObj.getHost();
1933
1934 if (host != null && 0 < host.length()) {
1935 titleUrl = host;
1936 if (protocol != null) {
1937 // if a secure site, add an "https://" prefix!
1938 if (protocol.equalsIgnoreCase("https")) {
1939 titleUrl = protocol + "://" + host;
1940 }
1941 }
1942 }
1943 }
1944 } catch (MalformedURLException e) {}
1945 }
1946
1947 return titleUrl;
1948 }
1949
1950 // Set the favicon in the title bar.
1951 private void setFavicon(Bitmap icon) {
Leon Scroggins81db3662009-06-04 17:45:11 -04001952 if (CUSTOM_BROWSER_BAR) {
1953 Drawable[] array = new Drawable[3];
1954 array[0] = new PaintDrawable(Color.BLACK);
1955 PaintDrawable p = new PaintDrawable(Color.WHITE);
1956 array[1] = p;
1957 if (icon == null) {
1958 array[2] = mGenericFavicon;
1959 } else {
1960 array[2] = new BitmapDrawable(icon);
1961 }
1962 LayerDrawable d = new LayerDrawable(array);
1963 d.setLayerInset(1, 1, 1, 1, 1);
1964 d.setLayerInset(2, 2, 2, 2, 2);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001965 mTitleBar.setFavicon(d, getTopWindow());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001966 } else {
Leon Scroggins81db3662009-06-04 17:45:11 -04001967 Drawable[] array = new Drawable[2];
1968 PaintDrawable p = new PaintDrawable(Color.WHITE);
1969 p.setCornerRadius(3f);
1970 array[0] = p;
1971 if (icon == null) {
1972 array[1] = mGenericFavicon;
1973 } else {
1974 array[1] = new BitmapDrawable(icon);
1975 }
1976 LayerDrawable d = new LayerDrawable(array);
1977 d.setLayerInset(1, 2, 2, 2, 2);
1978 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001979 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001980 }
1981
1982 /**
1983 * Saves the current lock-icon state before resetting
1984 * the lock icon. If we have an error, we may need to
1985 * roll back to the previous state.
1986 */
1987 private void saveLockIcon() {
1988 mPrevLockType = mLockIconType;
1989 }
1990
1991 /**
1992 * Reverts the lock-icon state to the last saved state,
1993 * for example, if we had an error, and need to cancel
1994 * the load.
1995 */
1996 private void revertLockIcon() {
1997 mLockIconType = mPrevLockType;
1998
Dave Bort31a6d1c2009-04-13 15:56:49 -07001999 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002000 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2001 " revert lock icon to " + mLockIconType);
2002 }
2003
2004 updateLockIconImage(mLockIconType);
2005 }
2006
Leon Scroggins1f005d32009-08-10 17:36:42 -04002007 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002008 * Close the tab, remove its associated title bar, and adjust mTabControl's
2009 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002010 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002011 /* package */ void closeTab(TabControl.Tab t) {
2012 int currentIndex = mTabControl.getCurrentIndex();
2013 int removeIndex = mTabControl.getTabIndex(t);
Leon Scrogginsa11b75a2009-08-18 10:22:05 -04002014 if (CUSTOM_BROWSER_BAR) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002015 mTitleBar.removeTab(removeIndex);
Leon Scrogginsa11b75a2009-08-18 10:22:05 -04002016 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04002017 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002018 if (currentIndex >= removeIndex && currentIndex != 0) {
2019 currentIndex--;
2020 }
2021 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
The Android Open Source Project0c908882009-03-03 19:32:16 -08002022 }
2023
2024 private void goBackOnePageOrQuit() {
2025 TabControl.Tab current = mTabControl.getCurrentTab();
2026 if (current == null) {
2027 /*
2028 * Instead of finishing the activity, simply push this to the back
2029 * of the stack and let ActivityManager to choose the foreground
2030 * activity. As BrowserActivity is singleTask, it will be always the
2031 * root of the task. So we can use either true or false for
2032 * moveTaskToBack().
2033 */
2034 moveTaskToBack(true);
2035 }
2036 WebView w = current.getWebView();
2037 if (w.canGoBack()) {
2038 w.goBack();
2039 } else {
2040 // Check to see if we are closing a window that was created by
2041 // another window. If so, we switch back to that window.
2042 TabControl.Tab parent = current.getParentTab();
2043 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002044 switchToTab(mTabControl.getTabIndex(parent));
2045 // Now we close the other tab
2046 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002047 } else {
2048 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002049 // force mPageStarted to be false as we are going to either
2050 // finish the activity or remove the tab. This will ensure
2051 // pauseWebView() taking action.
2052 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002053 if (mTabControl.getTabCount() == 1) {
2054 finish();
2055 return;
2056 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002057 // call pauseWebViewTimers() now, we won't be able to call
2058 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002059 // Temporarily change mActivityInPause to be true as
2060 // pauseWebViewTimers() will do nothing if mActivityInPause
2061 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002062 boolean savedState = mActivityInPause;
2063 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002064 Log.e(LOGTAG, "BrowserActivity is already paused "
2065 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002066 }
2067 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002068 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002069 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002070 removeTabFromContentView(current);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002071 if (CUSTOM_BROWSER_BAR) {
2072 mTitleBar.removeTab(mTabControl.getTabIndex(current));
2073 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002074 mTabControl.removeTab(current);
2075 }
2076 /*
2077 * Instead of finishing the activity, simply push this to the back
2078 * of the stack and let ActivityManager to choose the foreground
2079 * activity. As BrowserActivity is singleTask, it will be always the
2080 * root of the task. So we can use either true or false for
2081 * moveTaskToBack().
2082 */
2083 moveTaskToBack(true);
2084 }
2085 }
2086 }
2087
2088 public KeyTracker.State onKeyTracker(int keyCode,
2089 KeyEvent event,
2090 KeyTracker.Stage stage,
2091 int duration) {
2092 // if onKeyTracker() is called after activity onStop()
2093 // because of accumulated key events,
2094 // we should ignore it as browser is not active any more.
2095 WebView topWindow = getTopWindow();
Andrei Popescuadc008d2009-06-26 14:11:30 +01002096 if (topWindow == null && mCustomView == null)
The Android Open Source Project0c908882009-03-03 19:32:16 -08002097 return KeyTracker.State.NOT_TRACKING;
2098
2099 if (keyCode == KeyEvent.KEYCODE_BACK) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01002100 // Check if a custom view is currently showing and, if it is, hide it.
2101 if (mCustomView != null) {
2102 mWebChromeClient.onHideCustomView();
2103 return KeyTracker.State.DONE_TRACKING;
2104 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002105 if (stage == KeyTracker.Stage.LONG_REPEAT) {
Leon Scroggins30444232009-09-04 18:36:20 -04002106 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002107 return KeyTracker.State.DONE_TRACKING;
2108 } else if (stage == KeyTracker.Stage.UP) {
2109 // FIXME: Currently, we do not have a notion of the
2110 // history picker for the subwindow, but maybe we
2111 // should?
2112 WebView subwindow = mTabControl.getCurrentSubWindow();
2113 if (subwindow != null) {
2114 if (subwindow.canGoBack()) {
2115 subwindow.goBack();
2116 } else {
2117 dismissSubWindow(mTabControl.getCurrentTab());
2118 }
2119 } else {
2120 goBackOnePageOrQuit();
2121 }
2122 return KeyTracker.State.DONE_TRACKING;
2123 }
2124 return KeyTracker.State.KEEP_TRACKING;
2125 }
2126 return KeyTracker.State.NOT_TRACKING;
2127 }
2128
2129 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2130 if (keyCode == KeyEvent.KEYCODE_MENU) {
2131 mMenuIsDown = true;
Grace Kloba6ee9c492009-07-13 10:04:34 -07002132 } else if (mMenuIsDown) {
2133 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2134 // still down, we don't want to trigger the search. Pretend to
2135 // consume the key and do nothing.
2136 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002137 }
2138 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2139 if (!handled) {
2140 switch (keyCode) {
2141 case KeyEvent.KEYCODE_SPACE:
2142 if (event.isShiftPressed()) {
2143 getTopWindow().pageUp(false);
2144 } else {
2145 getTopWindow().pageDown(false);
2146 }
2147 handled = true;
2148 break;
2149
2150 default:
2151 break;
2152 }
2153 }
2154 return handled || super.onKeyDown(keyCode, event);
2155 }
2156
2157 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2158 if (keyCode == KeyEvent.KEYCODE_MENU) {
2159 mMenuIsDown = false;
2160 }
2161 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2162 }
2163
2164 private void stopLoading() {
2165 resetTitleAndRevertLockIcon();
2166 WebView w = getTopWindow();
2167 w.stopLoading();
2168 mWebViewClient.onPageFinished(w, w.getUrl());
2169
2170 cancelStopToast();
2171 mStopToast = Toast
2172 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2173 mStopToast.show();
2174 }
2175
2176 private void cancelStopToast() {
2177 if (mStopToast != null) {
2178 mStopToast.cancel();
2179 mStopToast = null;
2180 }
2181 }
2182
2183 // called by a non-UI thread to post the message
2184 public void postMessage(int what, int arg1, int arg2, Object obj) {
2185 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2186 }
2187
2188 // public message ids
2189 public final static int LOAD_URL = 1001;
2190 public final static int STOP_LOAD = 1002;
2191
2192 // Message Ids
2193 private static final int FOCUS_NODE_HREF = 102;
2194 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002195 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002196
2197 // Private handler for handling javascript and saving passwords
2198 private Handler mHandler = new Handler() {
2199
2200 public void handleMessage(Message msg) {
2201 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002202 case FOCUS_NODE_HREF:
2203 String url = (String) msg.getData().get("url");
2204 if (url == null || url.length() == 0) {
2205 break;
2206 }
2207 HashMap focusNodeMap = (HashMap) msg.obj;
2208 WebView view = (WebView) focusNodeMap.get("webview");
2209 // Only apply the action if the top window did not change.
2210 if (getTopWindow() != view) {
2211 break;
2212 }
2213 switch (msg.arg1) {
2214 case R.id.open_context_menu_id:
2215 case R.id.view_image_context_menu_id:
2216 loadURL(getTopWindow(), url);
2217 break;
2218 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002219 final TabControl.Tab parent = mTabControl
2220 .getCurrentTab();
2221 final TabControl.Tab newTab = openTab(url);
2222 if (newTab != parent) {
2223 parent.addChildTab(newTab);
2224 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002225 break;
2226 case R.id.bookmark_context_menu_id:
2227 Intent intent = new Intent(BrowserActivity.this,
2228 AddBookmarkPage.class);
2229 intent.putExtra("url", url);
2230 startActivity(intent);
2231 break;
2232 case R.id.share_link_context_menu_id:
2233 Browser.sendString(BrowserActivity.this, url);
2234 break;
2235 case R.id.copy_link_context_menu_id:
2236 copy(url);
2237 break;
2238 case R.id.save_link_context_menu_id:
2239 case R.id.download_context_menu_id:
2240 onDownloadStartNoStream(url, null, null, null, -1);
2241 break;
2242 }
2243 break;
2244
2245 case LOAD_URL:
2246 loadURL(getTopWindow(), (String) msg.obj);
2247 break;
2248
2249 case STOP_LOAD:
2250 stopLoading();
2251 break;
2252
2253 case CANCEL_CREDS_REQUEST:
2254 resumeAfterCredentials();
2255 break;
2256
The Android Open Source Project0c908882009-03-03 19:32:16 -08002257 case RELEASE_WAKELOCK:
2258 if (mWakeLock.isHeld()) {
2259 mWakeLock.release();
2260 }
2261 break;
2262 }
2263 }
2264 };
2265
Leon Scroggins89c6d362009-07-15 16:54:37 -04002266 private void updateScreenshot(WebView view) {
2267 // If this is a bookmarked site, add a screenshot to the database.
2268 // FIXME: When should we update? Every time?
2269 // FIXME: Would like to make sure there is actually something to
2270 // draw, but the API for that (WebViewCore.pictureReady()) is not
2271 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002272 ContentResolver cr = getContentResolver();
2273 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002274 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002275 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002276 boolean succeed = c.moveToFirst();
2277 ContentValues values = null;
2278 while (succeed) {
2279 if (values == null) {
2280 final ByteArrayOutputStream os
2281 = new ByteArrayOutputStream();
2282 Picture thumbnail = view.capturePicture();
2283 // Keep width and height in sync with BrowserBookmarksPage
2284 // and bookmark_thumb
2285 Bitmap bm = Bitmap.createBitmap(100, 80,
2286 Bitmap.Config.ARGB_4444);
2287 Canvas canvas = new Canvas(bm);
2288 // May need to tweak these values to determine what is the
2289 // best scale factor
2290 canvas.scale(.5f, .5f);
2291 thumbnail.draw(canvas);
2292 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2293 values = new ContentValues();
2294 values.put(Browser.BookmarkColumns.THUMBNAIL,
2295 os.toByteArray());
2296 }
2297 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2298 c.getInt(0)), values, null, null);
2299 succeed = c.moveToNext();
2300 }
2301 c.close();
2302 }
2303 }
2304
The Android Open Source Project0c908882009-03-03 19:32:16 -08002305 // -------------------------------------------------------------------------
2306 // WebViewClient implementation.
2307 //-------------------------------------------------------------------------
2308
2309 // Use in overrideUrlLoading
2310 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2311 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2312 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2313 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2314
2315 /* package */ WebViewClient getWebViewClient() {
2316 return mWebViewClient;
2317 }
2318
Patrick Scott3918d442009-08-04 13:22:29 -04002319 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002320 if (icon != null) {
2321 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott3918d442009-08-04 13:22:29 -04002322 view, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002323 }
2324 setFavicon(icon);
2325 }
2326
2327 private final WebViewClient mWebViewClient = new WebViewClient() {
2328 @Override
2329 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2330 resetLockIcon(url);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002331 setUrlTitle(url, null, view);
Ben Murdochbff2d602009-07-01 20:19:05 +01002332
2333 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2334 if (errorConsole != null) {
2335 errorConsole.clearErrorMessages();
2336 if (mShouldShowErrorConsole) {
2337 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2338 }
2339 }
2340
The Android Open Source Project0c908882009-03-03 19:32:16 -08002341 // Call updateIcon instead of setFavicon so the bookmark
2342 // database can be updated.
Patrick Scott3918d442009-08-04 13:22:29 -04002343 updateIcon(view, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002344
Grace Kloba4d7880f2009-08-12 09:35:42 -07002345 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002346 String host;
2347 try {
2348 WebAddress uri = new WebAddress(url);
2349 host = uri.mHost;
2350 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002351 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002352 }
2353 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002354 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002355 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002356 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002357 }
2358
2359 // Performance probe
2360 if (false) {
2361 mStart = SystemClock.uptimeMillis();
2362 mProcessStart = Process.getElapsedCpuTime();
2363 long[] sysCpu = new long[7];
2364 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2365 sysCpu, null)) {
2366 mUserStart = sysCpu[0] + sysCpu[1];
2367 mSystemStart = sysCpu[2];
2368 mIdleStart = sysCpu[3];
2369 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2370 }
2371 mUiStart = SystemClock.currentThreadTimeMillis();
2372 }
2373
2374 if (!mPageStarted) {
2375 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002376 // if onResume() has been called, resumeWebViewTimers() does
2377 // nothing.
2378 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002379 }
2380
2381 // reset sync timer to avoid sync starts during loading a page
2382 CookieSyncManager.getInstance().resetSync();
2383
2384 mInLoad = true;
2385 updateInLoadMenuItems();
2386 if (!mIsNetworkUp) {
2387 if ( mAlertDialog == null) {
2388 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2389 .setTitle(R.string.loadSuspendedTitle)
2390 .setMessage(R.string.loadSuspended)
2391 .setPositiveButton(R.string.ok, null)
2392 .show();
2393 }
2394 if (view != null) {
2395 view.setNetworkAvailable(false);
2396 }
2397 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002398 }
2399
2400 @Override
2401 public void onPageFinished(WebView view, String url) {
2402 // Reset the title and icon in case we stopped a provisional
2403 // load.
2404 resetTitleAndIcon(view);
2405
2406 // Update the lock icon image only once we are done loading
2407 updateLockIconImage(mLockIconType);
Leon Scroggins89c6d362009-07-15 16:54:37 -04002408 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002409
The Android Open Source Project0c908882009-03-03 19:32:16 -08002410 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002411 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002412 long[] sysCpu = new long[7];
2413 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2414 sysCpu, null)) {
2415 String uiInfo = "UI thread used "
2416 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2417 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002418 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002419 Log.d(LOGTAG, uiInfo);
2420 }
2421 //The string that gets written to the log
2422 String performanceString = "It took total "
2423 + (SystemClock.uptimeMillis() - mStart)
2424 + " ms clock time to load the page."
2425 + "\nbrowser process used "
2426 + (Process.getElapsedCpuTime() - mProcessStart)
2427 + " ms, user processes used "
2428 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2429 + " ms, kernel used "
2430 + (sysCpu[2] - mSystemStart) * 10
2431 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2432 + " ms and irq took "
2433 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2434 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002435 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002436 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2437 }
2438 if (url != null) {
2439 // strip the url to maintain consistency
2440 String newUrl = new String(url);
2441 if (newUrl.startsWith("http://www.")) {
2442 newUrl = newUrl.substring(11);
2443 } else if (newUrl.startsWith("http://")) {
2444 newUrl = newUrl.substring(7);
2445 } else if (newUrl.startsWith("https://www.")) {
2446 newUrl = newUrl.substring(12);
2447 } else if (newUrl.startsWith("https://")) {
2448 newUrl = newUrl.substring(8);
2449 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002450 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002451 Log.d(LOGTAG, newUrl + " loaded");
2452 }
2453 /*
2454 if (sWhiteList.contains(newUrl)) {
2455 // The string that gets pushed to the statistcs
2456 // service
2457 performanceString = performanceString
2458 + "\nWebpage: "
2459 + newUrl
2460 + "\nCarrier: "
2461 + android.os.SystemProperties
2462 .get("gsm.sim.operator.alpha");
2463 if (mWebView != null
2464 && mWebView.getContext() != null
2465 && mWebView.getContext().getSystemService(
2466 Context.CONNECTIVITY_SERVICE) != null) {
2467 ConnectivityManager cManager =
2468 (ConnectivityManager) mWebView
2469 .getContext().getSystemService(
2470 Context.CONNECTIVITY_SERVICE);
2471 NetworkInfo nInfo = cManager
2472 .getActiveNetworkInfo();
2473 if (nInfo != null) {
2474 performanceString = performanceString
2475 + "\nNetwork Type: "
2476 + nInfo.getType().toString();
2477 }
2478 }
2479 Checkin.logEvent(mResolver,
2480 Checkin.Events.Tag.WEBPAGE_LOAD,
2481 performanceString);
2482 Log.w(LOGTAG, "pushed to the statistics service");
2483 }
2484 */
2485 }
2486 }
2487 }
2488
2489 if (mInTrace) {
2490 mInTrace = false;
2491 Debug.stopMethodTracing();
2492 }
2493
2494 if (mPageStarted) {
2495 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002496 // pauseWebViewTimers() will do nothing and return false if
2497 // onPause() is not called yet.
2498 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002499 if (mWakeLock.isHeld()) {
2500 mHandler.removeMessages(RELEASE_WAKELOCK);
2501 mWakeLock.release();
2502 }
2503 }
2504 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002505 }
2506
2507 // return true if want to hijack the url to let another app to handle it
2508 @Override
2509 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2510 if (url.startsWith(SCHEME_WTAI)) {
2511 // wtai://wp/mc;number
2512 // number=string(phone-number)
2513 if (url.startsWith(SCHEME_WTAI_MC)) {
2514 Intent intent = new Intent(Intent.ACTION_VIEW,
2515 Uri.parse(WebView.SCHEME_TEL +
2516 url.substring(SCHEME_WTAI_MC.length())));
2517 startActivity(intent);
2518 return true;
2519 }
2520 // wtai://wp/sd;dtmf
2521 // dtmf=string(dialstring)
2522 if (url.startsWith(SCHEME_WTAI_SD)) {
2523 // TODO
2524 // only send when there is active voice connection
2525 return false;
2526 }
2527 // wtai://wp/ap;number;name
2528 // number=string(phone-number)
2529 // name=string
2530 if (url.startsWith(SCHEME_WTAI_AP)) {
2531 // TODO
2532 return false;
2533 }
2534 }
2535
Dianne Hackborn99189432009-06-17 18:06:18 -07002536 // The "about:" schemes are internal to the browser; don't
2537 // want these to be dispatched to other apps.
2538 if (url.startsWith("about:")) {
2539 return false;
2540 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002541
Dianne Hackborn99189432009-06-17 18:06:18 -07002542 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002543
Dianne Hackborn99189432009-06-17 18:06:18 -07002544 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002545 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002546 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2547 } catch (URISyntaxException ex) {
2548 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002549 return false;
2550 }
2551
Grace Kloba5b078b52009-06-24 20:23:41 -07002552 // check whether the intent can be resolved. If not, we will see
2553 // whether we can download it from the Market.
2554 if (getPackageManager().resolveActivity(intent, 0) == null) {
2555 String packagename = intent.getPackage();
2556 if (packagename != null) {
2557 intent = new Intent(Intent.ACTION_VIEW, Uri
2558 .parse("market://search?q=pname:" + packagename));
2559 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2560 startActivity(intent);
2561 return true;
2562 } else {
2563 return false;
2564 }
2565 }
2566
Dianne Hackborn99189432009-06-17 18:06:18 -07002567 // sanitize the Intent, ensuring web pages can not bypass browser
2568 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002569 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002570 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002571 try {
2572 if (startActivityIfNeeded(intent, -1)) {
2573 return true;
2574 }
2575 } catch (ActivityNotFoundException ex) {
2576 // ignore the error. If no application can handle the URL,
2577 // eg about:blank, assume the browser can handle it.
2578 }
2579
2580 if (mMenuIsDown) {
2581 openTab(url);
2582 closeOptionsMenu();
2583 return true;
2584 }
2585
2586 return false;
2587 }
2588
2589 /**
2590 * Updates the lock icon. This method is called when we discover another
2591 * resource to be loaded for this page (for example, javascript). While
2592 * we update the icon type, we do not update the lock icon itself until
2593 * we are done loading, it is slightly more secure this way.
2594 */
2595 @Override
2596 public void onLoadResource(WebView view, String url) {
2597 if (url != null && url.length() > 0) {
2598 // It is only if the page claims to be secure
2599 // that we may have to update the lock:
2600 if (mLockIconType == LOCK_ICON_SECURE) {
2601 // If NOT a 'safe' url, change the lock to mixed content!
2602 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2603 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002604 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002605 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2606 " updated lock icon to " + mLockIconType + " due to " + url);
2607 }
2608 }
2609 }
2610 }
2611 }
2612
2613 /**
2614 * Show the dialog, asking the user if they would like to continue after
2615 * an excessive number of HTTP redirects.
2616 */
2617 @Override
2618 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2619 final Message continueMsg) {
2620 new AlertDialog.Builder(BrowserActivity.this)
2621 .setTitle(R.string.browserFrameRedirect)
2622 .setMessage(R.string.browserFrame307Post)
2623 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2624 public void onClick(DialogInterface dialog, int which) {
2625 continueMsg.sendToTarget();
2626 }})
2627 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2628 public void onClick(DialogInterface dialog, int which) {
2629 cancelMsg.sendToTarget();
2630 }})
2631 .setOnCancelListener(new OnCancelListener() {
2632 public void onCancel(DialogInterface dialog) {
2633 cancelMsg.sendToTarget();
2634 }})
2635 .show();
2636 }
2637
Patrick Scott37911c72009-03-24 18:02:58 -07002638 // Container class for the next error dialog that needs to be
2639 // displayed.
2640 class ErrorDialog {
2641 public final int mTitle;
2642 public final String mDescription;
2643 public final int mError;
2644 ErrorDialog(int title, String desc, int error) {
2645 mTitle = title;
2646 mDescription = desc;
2647 mError = error;
2648 }
2649 };
2650
2651 private void processNextError() {
2652 if (mQueuedErrors == null) {
2653 return;
2654 }
2655 // The first one is currently displayed so just remove it.
2656 mQueuedErrors.removeFirst();
2657 if (mQueuedErrors.size() == 0) {
2658 mQueuedErrors = null;
2659 return;
2660 }
2661 showError(mQueuedErrors.getFirst());
2662 }
2663
2664 private DialogInterface.OnDismissListener mDialogListener =
2665 new DialogInterface.OnDismissListener() {
2666 public void onDismiss(DialogInterface d) {
2667 processNextError();
2668 }
2669 };
2670 private LinkedList<ErrorDialog> mQueuedErrors;
2671
2672 private void queueError(int err, String desc) {
2673 if (mQueuedErrors == null) {
2674 mQueuedErrors = new LinkedList<ErrorDialog>();
2675 }
2676 for (ErrorDialog d : mQueuedErrors) {
2677 if (d.mError == err) {
2678 // Already saw a similar error, ignore the new one.
2679 return;
2680 }
2681 }
2682 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002683 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002684 R.string.browserFrameFileErrorLabel :
2685 R.string.browserFrameNetworkErrorLabel,
2686 desc, err);
2687 mQueuedErrors.addLast(errDialog);
2688
2689 // Show the dialog now if the queue was empty.
2690 if (mQueuedErrors.size() == 1) {
2691 showError(errDialog);
2692 }
2693 }
2694
2695 private void showError(ErrorDialog errDialog) {
2696 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2697 .setTitle(errDialog.mTitle)
2698 .setMessage(errDialog.mDescription)
2699 .setPositiveButton(R.string.ok, null)
2700 .create();
2701 d.setOnDismissListener(mDialogListener);
2702 d.show();
2703 }
2704
The Android Open Source Project0c908882009-03-03 19:32:16 -08002705 /**
2706 * Show a dialog informing the user of the network error reported by
2707 * WebCore.
2708 */
2709 @Override
2710 public void onReceivedError(WebView view, int errorCode,
2711 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002712 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2713 errorCode != WebViewClient.ERROR_CONNECT &&
2714 errorCode != WebViewClient.ERROR_BAD_URL &&
2715 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2716 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002717 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002718 }
Patrick Scott37911c72009-03-24 18:02:58 -07002719 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2720 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002721
2722 // We need to reset the title after an error.
2723 resetTitleAndRevertLockIcon();
2724 }
2725
2726 /**
2727 * Check with the user if it is ok to resend POST data as the page they
2728 * are trying to navigate to is the result of a POST.
2729 */
2730 @Override
2731 public void onFormResubmission(WebView view, final Message dontResend,
2732 final Message resend) {
2733 new AlertDialog.Builder(BrowserActivity.this)
2734 .setTitle(R.string.browserFrameFormResubmitLabel)
2735 .setMessage(R.string.browserFrameFormResubmitMessage)
2736 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2737 public void onClick(DialogInterface dialog, int which) {
2738 resend.sendToTarget();
2739 }})
2740 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2741 public void onClick(DialogInterface dialog, int which) {
2742 dontResend.sendToTarget();
2743 }})
2744 .setOnCancelListener(new OnCancelListener() {
2745 public void onCancel(DialogInterface dialog) {
2746 dontResend.sendToTarget();
2747 }})
2748 .show();
2749 }
2750
2751 /**
2752 * Insert the url into the visited history database.
2753 * @param url The url to be inserted.
2754 * @param isReload True if this url is being reloaded.
2755 * FIXME: Not sure what to do when reloading the page.
2756 */
2757 @Override
2758 public void doUpdateVisitedHistory(WebView view, String url,
2759 boolean isReload) {
2760 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2761 return;
2762 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002763 // remove "client" before updating it to the history so that it wont
2764 // show up in the auto-complete list.
2765 int index = url.indexOf("client=ms-");
2766 if (index > 0 && url.contains(".google.")) {
2767 int end = url.indexOf('&', index);
2768 if (end > 0) {
2769 url = url.substring(0, index-1).concat(url.substring(end));
2770 } else {
2771 url = url.substring(0, index-1);
2772 }
2773 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002774 Browser.updateVisitedHistory(mResolver, url, true);
2775 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2776 }
2777
2778 /**
2779 * Displays SSL error(s) dialog to the user.
2780 */
2781 @Override
2782 public void onReceivedSslError(
2783 final WebView view, final SslErrorHandler handler, final SslError error) {
2784
2785 if (mSettings.showSecurityWarnings()) {
2786 final LayoutInflater factory =
2787 LayoutInflater.from(BrowserActivity.this);
2788 final View warningsView =
2789 factory.inflate(R.layout.ssl_warnings, null);
2790 final LinearLayout placeholder =
2791 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2792
2793 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2794 LinearLayout ll = (LinearLayout)factory
2795 .inflate(R.layout.ssl_warning, null);
2796 ((TextView)ll.findViewById(R.id.warning))
2797 .setText(R.string.ssl_untrusted);
2798 placeholder.addView(ll);
2799 }
2800
2801 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2802 LinearLayout ll = (LinearLayout)factory
2803 .inflate(R.layout.ssl_warning, null);
2804 ((TextView)ll.findViewById(R.id.warning))
2805 .setText(R.string.ssl_mismatch);
2806 placeholder.addView(ll);
2807 }
2808
2809 if (error.hasError(SslError.SSL_EXPIRED)) {
2810 LinearLayout ll = (LinearLayout)factory
2811 .inflate(R.layout.ssl_warning, null);
2812 ((TextView)ll.findViewById(R.id.warning))
2813 .setText(R.string.ssl_expired);
2814 placeholder.addView(ll);
2815 }
2816
2817 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2818 LinearLayout ll = (LinearLayout)factory
2819 .inflate(R.layout.ssl_warning, null);
2820 ((TextView)ll.findViewById(R.id.warning))
2821 .setText(R.string.ssl_not_yet_valid);
2822 placeholder.addView(ll);
2823 }
2824
2825 new AlertDialog.Builder(BrowserActivity.this)
2826 .setTitle(R.string.security_warning)
2827 .setIcon(android.R.drawable.ic_dialog_alert)
2828 .setView(warningsView)
2829 .setPositiveButton(R.string.ssl_continue,
2830 new DialogInterface.OnClickListener() {
2831 public void onClick(DialogInterface dialog, int whichButton) {
2832 handler.proceed();
2833 }
2834 })
2835 .setNeutralButton(R.string.view_certificate,
2836 new DialogInterface.OnClickListener() {
2837 public void onClick(DialogInterface dialog, int whichButton) {
2838 showSSLCertificateOnError(view, handler, error);
2839 }
2840 })
2841 .setNegativeButton(R.string.cancel,
2842 new DialogInterface.OnClickListener() {
2843 public void onClick(DialogInterface dialog, int whichButton) {
2844 handler.cancel();
2845 BrowserActivity.this.resetTitleAndRevertLockIcon();
2846 }
2847 })
2848 .setOnCancelListener(
2849 new DialogInterface.OnCancelListener() {
2850 public void onCancel(DialogInterface dialog) {
2851 handler.cancel();
2852 BrowserActivity.this.resetTitleAndRevertLockIcon();
2853 }
2854 })
2855 .show();
2856 } else {
2857 handler.proceed();
2858 }
2859 }
2860
2861 /**
2862 * Handles an HTTP authentication request.
2863 *
2864 * @param handler The authentication handler
2865 * @param host The host
2866 * @param realm The realm
2867 */
2868 @Override
2869 public void onReceivedHttpAuthRequest(WebView view,
2870 final HttpAuthHandler handler, final String host, final String realm) {
2871 String username = null;
2872 String password = null;
2873
2874 boolean reuseHttpAuthUsernamePassword =
2875 handler.useHttpAuthUsernamePassword();
2876
2877 if (reuseHttpAuthUsernamePassword &&
2878 (mTabControl.getCurrentWebView() != null)) {
2879 String[] credentials =
2880 mTabControl.getCurrentWebView()
2881 .getHttpAuthUsernamePassword(host, realm);
2882 if (credentials != null && credentials.length == 2) {
2883 username = credentials[0];
2884 password = credentials[1];
2885 }
2886 }
2887
2888 if (username != null && password != null) {
2889 handler.proceed(username, password);
2890 } else {
2891 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2892 }
2893 }
2894
2895 @Override
2896 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2897 if (mMenuIsDown) {
2898 // only check shortcut key when MENU is held
2899 return getWindow().isShortcutKey(event.getKeyCode(), event);
2900 } else {
2901 return false;
2902 }
2903 }
2904
2905 @Override
2906 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2907 if (view != mTabControl.getCurrentTopWebView()) {
2908 return;
2909 }
2910 if (event.isDown()) {
2911 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2912 } else {
2913 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2914 }
2915 }
2916 };
2917
2918 //--------------------------------------------------------------------------
2919 // WebChromeClient implementation
2920 //--------------------------------------------------------------------------
2921
2922 /* package */ WebChromeClient getWebChromeClient() {
2923 return mWebChromeClient;
2924 }
2925
2926 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2927 // Helper method to create a new tab or sub window.
2928 private void createWindow(final boolean dialog, final Message msg) {
2929 if (dialog) {
2930 mTabControl.createSubWindow();
2931 final TabControl.Tab t = mTabControl.getCurrentTab();
2932 attachSubWindow(t);
2933 WebView.WebViewTransport transport =
2934 (WebView.WebViewTransport) msg.obj;
2935 transport.setWebView(t.getSubWebView());
2936 msg.sendToTarget();
2937 } else {
2938 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04002939 final TabControl.Tab newTab
2940 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07002941 if (newTab != parent) {
2942 parent.addChildTab(newTab);
2943 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002944 WebView.WebViewTransport transport =
2945 (WebView.WebViewTransport) msg.obj;
2946 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04002947 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002948 }
2949 }
2950
2951 @Override
2952 public boolean onCreateWindow(WebView view, final boolean dialog,
2953 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002954 // Short-circuit if we can't create any more tabs or sub windows.
2955 if (dialog && mTabControl.getCurrentSubWindow() != null) {
2956 new AlertDialog.Builder(BrowserActivity.this)
2957 .setTitle(R.string.too_many_subwindows_dialog_title)
2958 .setIcon(android.R.drawable.ic_dialog_alert)
2959 .setMessage(R.string.too_many_subwindows_dialog_message)
2960 .setPositiveButton(R.string.ok, null)
2961 .show();
2962 return false;
2963 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
2964 new AlertDialog.Builder(BrowserActivity.this)
2965 .setTitle(R.string.too_many_windows_dialog_title)
2966 .setIcon(android.R.drawable.ic_dialog_alert)
2967 .setMessage(R.string.too_many_windows_dialog_message)
2968 .setPositiveButton(R.string.ok, null)
2969 .show();
2970 return false;
2971 }
2972
2973 // Short-circuit if this was a user gesture.
2974 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002975 createWindow(dialog, resultMsg);
2976 return true;
2977 }
2978
2979 // Allow the popup and create the appropriate window.
2980 final AlertDialog.OnClickListener allowListener =
2981 new AlertDialog.OnClickListener() {
2982 public void onClick(DialogInterface d,
2983 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002984 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002985 }
2986 };
2987
2988 // Block the popup by returning a null WebView.
2989 final AlertDialog.OnClickListener blockListener =
2990 new AlertDialog.OnClickListener() {
2991 public void onClick(DialogInterface d, int which) {
2992 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002993 }
2994 };
2995
2996 // Build a confirmation dialog to display to the user.
2997 final AlertDialog d =
2998 new AlertDialog.Builder(BrowserActivity.this)
2999 .setTitle(R.string.attention)
3000 .setIcon(android.R.drawable.ic_dialog_alert)
3001 .setMessage(R.string.popup_window_attempt)
3002 .setPositiveButton(R.string.allow, allowListener)
3003 .setNegativeButton(R.string.block, blockListener)
3004 .setCancelable(false)
3005 .create();
3006
3007 // Show the confirmation dialog.
3008 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003009 return true;
3010 }
3011
3012 @Override
3013 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003014 final TabControl.Tab current = mTabControl.getCurrentTab();
3015 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003016 if (parent != null) {
3017 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003018 switchToTab(mTabControl.getTabIndex(parent));
3019 // Now we need to close the window
3020 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003021 }
3022 }
3023
3024 @Override
3025 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003026 if (CUSTOM_BROWSER_BAR) {
3027 mTitleBar.setProgress(newProgress, view);
3028 } else {
3029 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3030 newProgress * 100);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003031 }
3032
3033 if (newProgress == 100) {
3034 // onProgressChanged() is called for sub-frame too while
3035 // onPageFinished() is only called for the main frame. sync
3036 // cookie and cache promptly here.
3037 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003038 if (mInLoad) {
3039 mInLoad = false;
3040 updateInLoadMenuItems();
3041 }
3042 } else {
3043 // onPageFinished may have already been called but a subframe
3044 // is still loading and updating the progress. Reset mInLoad
3045 // and update the menu items.
3046 if (!mInLoad) {
3047 mInLoad = true;
3048 updateInLoadMenuItems();
3049 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003050 }
3051 }
3052
3053 @Override
3054 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003055 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003056
3057 // here, if url is null, we want to reset the title
Leon Scroggins1f005d32009-08-10 17:36:42 -04003058 setUrlTitle(url, title, view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003059
3060 if (url == null ||
3061 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3062 return;
3063 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003064 // See if we can find the current url in our history database and
3065 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003066 if (url.startsWith("http://www.")) {
3067 url = url.substring(11);
3068 } else if (url.startsWith("http://")) {
3069 url = url.substring(4);
3070 }
3071 try {
3072 url = "%" + url;
3073 String [] selArgs = new String[] { url };
3074
3075 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3076 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3077 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3078 Browser.HISTORY_PROJECTION, where, selArgs, null);
3079 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003080 // Current implementation of database only has one entry per
3081 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003082 ContentValues map = new ContentValues();
3083 map.put(Browser.BookmarkColumns.TITLE, title);
3084 mResolver.update(Browser.BOOKMARKS_URI, map,
3085 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003086 }
3087 c.close();
3088 } catch (IllegalStateException e) {
3089 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3090 } catch (SQLiteException ex) {
3091 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3092 }
3093 }
3094
3095 @Override
3096 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003097 updateIcon(view, icon);
3098 }
3099
3100 @Override
3101 public void onReceivedTouchIconUrl(WebView view, String url) {
3102 final ContentResolver cr = getContentResolver();
3103 final Cursor c =
3104 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003105 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003106 if (c != null) {
3107 if (c.getCount() > 0) {
3108 new DownloadTouchIcon(cr, c, view).execute(url);
3109 } else {
3110 c.close();
3111 }
3112 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003113 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003114
Andrei Popescuadc008d2009-06-26 14:11:30 +01003115 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003116 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003117 if (mCustomView != null)
3118 return;
3119
3120 // Add the custom view to its container.
3121 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3122 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003123 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003124 // Save the menu state and set it to empty while the custom
3125 // view is showing.
3126 mOldMenuState = mMenuState;
3127 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003128 // Hide the content view.
3129 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003130 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003131 mCustomViewContainer.setVisibility(View.VISIBLE);
3132 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003133 }
3134
3135 @Override
3136 public void onHideCustomView() {
3137 if (mCustomView == null)
3138 return;
3139
Andrei Popescuc9b55562009-07-07 10:51:15 +01003140 // Hide the custom view.
3141 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003142 // Remove the custom view from its container.
3143 mCustomViewContainer.removeView(mCustomView);
3144 mCustomView = null;
3145 // Reset the old menu state.
3146 mMenuState = mOldMenuState;
3147 mOldMenuState = EMPTY_MENU;
3148 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003149 mCustomViewCallback.onCustomViewHidden();
3150 // Show the content view.
3151 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003152 }
3153
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003154 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003155 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003156 * @param url the URL that exceeded the quota
3157 * @param databaseIdentifier the identifier of the database on
3158 * which the transaction that caused the quota overflow was run
3159 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003160 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003161 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003162 * @param quotaUpdater The callback to run when a decision to allow or
3163 * deny quota has been made. Don't forget to call this!
3164 */
3165 @Override
3166 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003167 String databaseIdentifier, long currentQuota, long estimatedSize,
3168 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003169 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003170 url, databaseIdentifier, currentQuota, estimatedSize,
3171 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003172 }
3173
3174 /**
3175 * The Application Cache has exceeded its max size.
3176 * @param spaceNeeded is the amount of disk space that would be needed
3177 * in order for the last appcache operation to succeed.
3178 * @param totalUsedQuota is the sum of all origins' quota.
3179 * @param quotaUpdater A callback to inform the WebCore thread that a new
3180 * app cache size is available. This callback must always be executed at
3181 * some point to ensure that the sleeping WebCore thread is woken up.
3182 */
3183 @Override
3184 public void onReachedMaxAppCacheSize(long spaceNeeded,
3185 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3186 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3187 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003188 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003189
Steve Block2bc69912009-07-30 14:45:13 +01003190 /**
3191 * Instructs the browser to show a prompt to ask the user to set the
3192 * Geolocation permission state for the specified origin.
3193 * @param origin The origin for which Geolocation permissions are
3194 * requested.
3195 * @param callback The callback to call once the user has set the
3196 * Geolocation permission state.
3197 */
3198 @Override
3199 public void onGeolocationPermissionsShowPrompt(String origin,
3200 GeolocationPermissions.Callback callback) {
3201 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3202 origin, callback);
3203 }
3204
3205 /**
3206 * Instructs the browser to hide the Geolocation permissions prompt.
3207 */
3208 @Override
3209 public void onGeolocationPermissionsHidePrompt() {
3210 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3211 }
3212
Ben Murdoch7db26342009-06-03 18:21:19 +01003213 /* Adds a JavaScript error message to the system log.
3214 * @param message The error message to report.
3215 * @param lineNumber The line number of the error.
3216 * @param sourceID The name of the source file that caused the error.
3217 */
3218 @Override
3219 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003220 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3221 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3222 if (mShouldShowErrorConsole &&
3223 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3224 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3225 }
3226 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003227 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003228 };
3229
3230 /**
3231 * Notify the host application a download should be done, or that
3232 * the data should be streamed if a streaming viewer is available.
3233 * @param url The full url to the content that should be downloaded
3234 * @param contentDisposition Content-disposition http header, if
3235 * present.
3236 * @param mimetype The mimetype of the content reported by the server
3237 * @param contentLength The file size reported by the server
3238 */
3239 public void onDownloadStart(String url, String userAgent,
3240 String contentDisposition, String mimetype, long contentLength) {
3241 // if we're dealing wih A/V content that's not explicitly marked
3242 // for download, check if it's streamable.
3243 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003244 || !contentDisposition.regionMatches(
3245 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003246 // query the package manager to see if there's a registered handler
3247 // that matches.
3248 Intent intent = new Intent(Intent.ACTION_VIEW);
3249 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003250 ResolveInfo info = getPackageManager().resolveActivity(intent,
3251 PackageManager.MATCH_DEFAULT_ONLY);
3252 if (info != null) {
3253 ComponentName myName = getComponentName();
3254 // If we resolved to ourselves, we don't want to attempt to
3255 // load the url only to try and download it again.
3256 if (!myName.getPackageName().equals(
3257 info.activityInfo.packageName)
3258 || !myName.getClassName().equals(
3259 info.activityInfo.name)) {
3260 // someone (other than us) knows how to handle this mime
3261 // type with this scheme, don't download.
3262 try {
3263 startActivity(intent);
3264 return;
3265 } catch (ActivityNotFoundException ex) {
3266 if (LOGD_ENABLED) {
3267 Log.d(LOGTAG, "activity not found for " + mimetype
3268 + " over " + Uri.parse(url).getScheme(),
3269 ex);
3270 }
3271 // Best behavior is to fall back to a download in this
3272 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003273 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003274 }
3275 }
3276 }
3277 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3278 }
3279
3280 /**
3281 * Notify the host application a download should be done, even if there
3282 * is a streaming viewer available for thise type.
3283 * @param url The full url to the content that should be downloaded
3284 * @param contentDisposition Content-disposition http header, if
3285 * present.
3286 * @param mimetype The mimetype of the content reported by the server
3287 * @param contentLength The file size reported by the server
3288 */
3289 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3290 String contentDisposition, String mimetype, long contentLength) {
3291
3292 String filename = URLUtil.guessFileName(url,
3293 contentDisposition, mimetype);
3294
3295 // Check to see if we have an SDCard
3296 String status = Environment.getExternalStorageState();
3297 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3298 int title;
3299 String msg;
3300
3301 // Check to see if the SDCard is busy, same as the music app
3302 if (status.equals(Environment.MEDIA_SHARED)) {
3303 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3304 title = R.string.download_sdcard_busy_dlg_title;
3305 } else {
3306 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3307 title = R.string.download_no_sdcard_dlg_title;
3308 }
3309
3310 new AlertDialog.Builder(this)
3311 .setTitle(title)
3312 .setIcon(android.R.drawable.ic_dialog_alert)
3313 .setMessage(msg)
3314 .setPositiveButton(R.string.ok, null)
3315 .show();
3316 return;
3317 }
3318
3319 // java.net.URI is a lot stricter than KURL so we have to undo
3320 // KURL's percent-encoding and redo the encoding using java.net.URI.
3321 URI uri = null;
3322 try {
3323 // Undo the percent-encoding that KURL may have done.
3324 String newUrl = new String(URLUtil.decode(url.getBytes()));
3325 // Parse the url into pieces
3326 WebAddress w = new WebAddress(newUrl);
3327 String frag = null;
3328 String query = null;
3329 String path = w.mPath;
3330 // Break the path into path, query, and fragment
3331 if (path.length() > 0) {
3332 // Strip the fragment
3333 int idx = path.lastIndexOf('#');
3334 if (idx != -1) {
3335 frag = path.substring(idx + 1);
3336 path = path.substring(0, idx);
3337 }
3338 idx = path.lastIndexOf('?');
3339 if (idx != -1) {
3340 query = path.substring(idx + 1);
3341 path = path.substring(0, idx);
3342 }
3343 }
3344 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3345 query, frag);
3346 } catch (Exception e) {
3347 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3348 return;
3349 }
3350
3351 // XXX: Have to use the old url since the cookies were stored using the
3352 // old percent-encoded url.
3353 String cookies = CookieManager.getInstance().getCookie(url);
3354
3355 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003356 values.put(Downloads.COLUMN_URI, uri.toString());
3357 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3358 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3359 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003360 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003361 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003362 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003363 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3364 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3365 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3366 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003367 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003368 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003369 }
3370 if (mimetype == null) {
3371 // We must have long pressed on a link or image to download it. We
3372 // are not sure of the mimetype in this case, so do a head request
3373 new FetchUrlMimeType(this).execute(values);
3374 } else {
3375 final Uri contentUri =
3376 getContentResolver().insert(Downloads.CONTENT_URI, values);
3377 viewDownloads(contentUri);
3378 }
3379
3380 }
3381
3382 /**
3383 * Resets the lock icon. This method is called when we start a new load and
3384 * know the url to be loaded.
3385 */
3386 private void resetLockIcon(String url) {
3387 // Save the lock-icon state (we revert to it if the load gets cancelled)
3388 saveLockIcon();
3389
3390 mLockIconType = LOCK_ICON_UNSECURE;
3391 if (URLUtil.isHttpsUrl(url)) {
3392 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003393 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003394 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3395 " reset lock icon to " + mLockIconType);
3396 }
3397 }
3398
3399 updateLockIconImage(LOCK_ICON_UNSECURE);
3400 }
3401
3402 /**
3403 * Resets the lock icon. This method is called when the icon needs to be
3404 * reset but we do not know whether we are loading a secure or not secure
3405 * page.
3406 */
3407 private void resetLockIcon() {
3408 // Save the lock-icon state (we revert to it if the load gets cancelled)
3409 saveLockIcon();
3410
3411 mLockIconType = LOCK_ICON_UNSECURE;
3412
Dave Bort31a6d1c2009-04-13 15:56:49 -07003413 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003414 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3415 " reset lock icon to " + mLockIconType);
3416 }
3417
3418 updateLockIconImage(LOCK_ICON_UNSECURE);
3419 }
3420
3421 /**
3422 * Updates the lock-icon image in the title-bar.
3423 */
3424 private void updateLockIconImage(int lockIconType) {
3425 Drawable d = null;
3426 if (lockIconType == LOCK_ICON_SECURE) {
3427 d = mSecLockIcon;
3428 } else if (lockIconType == LOCK_ICON_MIXED) {
3429 d = mMixLockIcon;
3430 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04003431 if (CUSTOM_BROWSER_BAR) {
3432 mTitleBar.setLock(d, getTopWindow());
3433 } else {
3434 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003435 }
3436 }
3437
3438 /**
3439 * Displays a page-info dialog.
3440 * @param tab The tab to show info about
3441 * @param fromShowSSLCertificateOnError The flag that indicates whether
3442 * this dialog was opened from the SSL-certificate-on-error dialog or
3443 * not. This is important, since we need to know whether to return to
3444 * the parent dialog or simply dismiss.
3445 */
3446 private void showPageInfo(final TabControl.Tab tab,
3447 final boolean fromShowSSLCertificateOnError) {
3448 final LayoutInflater factory = LayoutInflater
3449 .from(this);
3450
3451 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3452
3453 final WebView view = tab.getWebView();
3454
3455 String url = null;
3456 String title = null;
3457
3458 if (view == null) {
3459 url = tab.getUrl();
3460 title = tab.getTitle();
3461 } else if (view == mTabControl.getCurrentWebView()) {
3462 // Use the cached title and url if this is the current WebView
3463 url = mUrl;
3464 title = mTitle;
3465 } else {
3466 url = view.getUrl();
3467 title = view.getTitle();
3468 }
3469
3470 if (url == null) {
3471 url = "";
3472 }
3473 if (title == null) {
3474 title = "";
3475 }
3476
3477 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3478 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3479
3480 mPageInfoView = tab;
3481 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3482
3483 AlertDialog.Builder alertDialogBuilder =
3484 new AlertDialog.Builder(this)
3485 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3486 .setView(pageInfoView)
3487 .setPositiveButton(
3488 R.string.ok,
3489 new DialogInterface.OnClickListener() {
3490 public void onClick(DialogInterface dialog,
3491 int whichButton) {
3492 mPageInfoDialog = null;
3493 mPageInfoView = null;
3494 mPageInfoFromShowSSLCertificateOnError = null;
3495
3496 // if we came here from the SSL error dialog
3497 if (fromShowSSLCertificateOnError) {
3498 // go back to the SSL error dialog
3499 showSSLCertificateOnError(
3500 mSSLCertificateOnErrorView,
3501 mSSLCertificateOnErrorHandler,
3502 mSSLCertificateOnErrorError);
3503 }
3504 }
3505 })
3506 .setOnCancelListener(
3507 new DialogInterface.OnCancelListener() {
3508 public void onCancel(DialogInterface dialog) {
3509 mPageInfoDialog = null;
3510 mPageInfoView = null;
3511 mPageInfoFromShowSSLCertificateOnError = null;
3512
3513 // if we came here from the SSL error dialog
3514 if (fromShowSSLCertificateOnError) {
3515 // go back to the SSL error dialog
3516 showSSLCertificateOnError(
3517 mSSLCertificateOnErrorView,
3518 mSSLCertificateOnErrorHandler,
3519 mSSLCertificateOnErrorError);
3520 }
3521 }
3522 });
3523
3524 // if we have a main top-level page SSL certificate set or a certificate
3525 // error
3526 if (fromShowSSLCertificateOnError ||
3527 (view != null && view.getCertificate() != null)) {
3528 // add a 'View Certificate' button
3529 alertDialogBuilder.setNeutralButton(
3530 R.string.view_certificate,
3531 new DialogInterface.OnClickListener() {
3532 public void onClick(DialogInterface dialog,
3533 int whichButton) {
3534 mPageInfoDialog = null;
3535 mPageInfoView = null;
3536 mPageInfoFromShowSSLCertificateOnError = null;
3537
3538 // if we came here from the SSL error dialog
3539 if (fromShowSSLCertificateOnError) {
3540 // go back to the SSL error dialog
3541 showSSLCertificateOnError(
3542 mSSLCertificateOnErrorView,
3543 mSSLCertificateOnErrorHandler,
3544 mSSLCertificateOnErrorError);
3545 } else {
3546 // otherwise, display the top-most certificate from
3547 // the chain
3548 if (view.getCertificate() != null) {
3549 showSSLCertificate(tab);
3550 }
3551 }
3552 }
3553 });
3554 }
3555
3556 mPageInfoDialog = alertDialogBuilder.show();
3557 }
3558
3559 /**
3560 * Displays the main top-level page SSL certificate dialog
3561 * (accessible from the Page-Info dialog).
3562 * @param tab The tab to show certificate for.
3563 */
3564 private void showSSLCertificate(final TabControl.Tab tab) {
3565 final View certificateView =
3566 inflateCertificateView(tab.getWebView().getCertificate());
3567 if (certificateView == null) {
3568 return;
3569 }
3570
3571 LayoutInflater factory = LayoutInflater.from(this);
3572
3573 final LinearLayout placeholder =
3574 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3575
3576 LinearLayout ll = (LinearLayout) factory.inflate(
3577 R.layout.ssl_success, placeholder);
3578 ((TextView)ll.findViewById(R.id.success))
3579 .setText(R.string.ssl_certificate_is_valid);
3580
3581 mSSLCertificateView = tab;
3582 mSSLCertificateDialog =
3583 new AlertDialog.Builder(this)
3584 .setTitle(R.string.ssl_certificate).setIcon(
3585 R.drawable.ic_dialog_browser_certificate_secure)
3586 .setView(certificateView)
3587 .setPositiveButton(R.string.ok,
3588 new DialogInterface.OnClickListener() {
3589 public void onClick(DialogInterface dialog,
3590 int whichButton) {
3591 mSSLCertificateDialog = null;
3592 mSSLCertificateView = null;
3593
3594 showPageInfo(tab, false);
3595 }
3596 })
3597 .setOnCancelListener(
3598 new DialogInterface.OnCancelListener() {
3599 public void onCancel(DialogInterface dialog) {
3600 mSSLCertificateDialog = null;
3601 mSSLCertificateView = null;
3602
3603 showPageInfo(tab, false);
3604 }
3605 })
3606 .show();
3607 }
3608
3609 /**
3610 * Displays the SSL error certificate dialog.
3611 * @param view The target web-view.
3612 * @param handler The SSL error handler responsible for cancelling the
3613 * connection that resulted in an SSL error or proceeding per user request.
3614 * @param error The SSL error object.
3615 */
3616 private void showSSLCertificateOnError(
3617 final WebView view, final SslErrorHandler handler, final SslError error) {
3618
3619 final View certificateView =
3620 inflateCertificateView(error.getCertificate());
3621 if (certificateView == null) {
3622 return;
3623 }
3624
3625 LayoutInflater factory = LayoutInflater.from(this);
3626
3627 final LinearLayout placeholder =
3628 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3629
3630 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3631 LinearLayout ll = (LinearLayout)factory
3632 .inflate(R.layout.ssl_warning, placeholder);
3633 ((TextView)ll.findViewById(R.id.warning))
3634 .setText(R.string.ssl_untrusted);
3635 }
3636
3637 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3638 LinearLayout ll = (LinearLayout)factory
3639 .inflate(R.layout.ssl_warning, placeholder);
3640 ((TextView)ll.findViewById(R.id.warning))
3641 .setText(R.string.ssl_mismatch);
3642 }
3643
3644 if (error.hasError(SslError.SSL_EXPIRED)) {
3645 LinearLayout ll = (LinearLayout)factory
3646 .inflate(R.layout.ssl_warning, placeholder);
3647 ((TextView)ll.findViewById(R.id.warning))
3648 .setText(R.string.ssl_expired);
3649 }
3650
3651 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3652 LinearLayout ll = (LinearLayout)factory
3653 .inflate(R.layout.ssl_warning, placeholder);
3654 ((TextView)ll.findViewById(R.id.warning))
3655 .setText(R.string.ssl_not_yet_valid);
3656 }
3657
3658 mSSLCertificateOnErrorHandler = handler;
3659 mSSLCertificateOnErrorView = view;
3660 mSSLCertificateOnErrorError = error;
3661 mSSLCertificateOnErrorDialog =
3662 new AlertDialog.Builder(this)
3663 .setTitle(R.string.ssl_certificate).setIcon(
3664 R.drawable.ic_dialog_browser_certificate_partially_secure)
3665 .setView(certificateView)
3666 .setPositiveButton(R.string.ok,
3667 new DialogInterface.OnClickListener() {
3668 public void onClick(DialogInterface dialog,
3669 int whichButton) {
3670 mSSLCertificateOnErrorDialog = null;
3671 mSSLCertificateOnErrorView = null;
3672 mSSLCertificateOnErrorHandler = null;
3673 mSSLCertificateOnErrorError = null;
3674
3675 mWebViewClient.onReceivedSslError(
3676 view, handler, error);
3677 }
3678 })
3679 .setNeutralButton(R.string.page_info_view,
3680 new DialogInterface.OnClickListener() {
3681 public void onClick(DialogInterface dialog,
3682 int whichButton) {
3683 mSSLCertificateOnErrorDialog = null;
3684
3685 // do not clear the dialog state: we will
3686 // need to show the dialog again once the
3687 // user is done exploring the page-info details
3688
3689 showPageInfo(mTabControl.getTabFromView(view),
3690 true);
3691 }
3692 })
3693 .setOnCancelListener(
3694 new DialogInterface.OnCancelListener() {
3695 public void onCancel(DialogInterface dialog) {
3696 mSSLCertificateOnErrorDialog = null;
3697 mSSLCertificateOnErrorView = null;
3698 mSSLCertificateOnErrorHandler = null;
3699 mSSLCertificateOnErrorError = null;
3700
3701 mWebViewClient.onReceivedSslError(
3702 view, handler, error);
3703 }
3704 })
3705 .show();
3706 }
3707
3708 /**
3709 * Inflates the SSL certificate view (helper method).
3710 * @param certificate The SSL certificate.
3711 * @return The resultant certificate view with issued-to, issued-by,
3712 * issued-on, expires-on, and possibly other fields set.
3713 * If the input certificate is null, returns null.
3714 */
3715 private View inflateCertificateView(SslCertificate certificate) {
3716 if (certificate == null) {
3717 return null;
3718 }
3719
3720 LayoutInflater factory = LayoutInflater.from(this);
3721
3722 View certificateView = factory.inflate(
3723 R.layout.ssl_certificate, null);
3724
3725 // issued to:
3726 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3727 if (issuedTo != null) {
3728 ((TextView) certificateView.findViewById(R.id.to_common))
3729 .setText(issuedTo.getCName());
3730 ((TextView) certificateView.findViewById(R.id.to_org))
3731 .setText(issuedTo.getOName());
3732 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3733 .setText(issuedTo.getUName());
3734 }
3735
3736 // issued by:
3737 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3738 if (issuedBy != null) {
3739 ((TextView) certificateView.findViewById(R.id.by_common))
3740 .setText(issuedBy.getCName());
3741 ((TextView) certificateView.findViewById(R.id.by_org))
3742 .setText(issuedBy.getOName());
3743 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3744 .setText(issuedBy.getUName());
3745 }
3746
3747 // issued on:
3748 String issuedOn = reformatCertificateDate(
3749 certificate.getValidNotBefore());
3750 ((TextView) certificateView.findViewById(R.id.issued_on))
3751 .setText(issuedOn);
3752
3753 // expires on:
3754 String expiresOn = reformatCertificateDate(
3755 certificate.getValidNotAfter());
3756 ((TextView) certificateView.findViewById(R.id.expires_on))
3757 .setText(expiresOn);
3758
3759 return certificateView;
3760 }
3761
3762 /**
3763 * Re-formats the certificate date (Date.toString()) string to
3764 * a properly localized date string.
3765 * @return Properly localized version of the certificate date string and
3766 * the original certificate date string if fails to localize.
3767 * If the original string is null, returns an empty string "".
3768 */
3769 private String reformatCertificateDate(String certificateDate) {
3770 String reformattedDate = null;
3771
3772 if (certificateDate != null) {
3773 Date date = null;
3774 try {
3775 date = java.text.DateFormat.getInstance().parse(certificateDate);
3776 } catch (ParseException e) {
3777 date = null;
3778 }
3779
3780 if (date != null) {
3781 reformattedDate =
3782 DateFormat.getDateFormat(this).format(date);
3783 }
3784 }
3785
3786 return reformattedDate != null ? reformattedDate :
3787 (certificateDate != null ? certificateDate : "");
3788 }
3789
3790 /**
3791 * Displays an http-authentication dialog.
3792 */
3793 private void showHttpAuthentication(final HttpAuthHandler handler,
3794 final String host, final String realm, final String title,
3795 final String name, final String password, int focusId) {
3796 LayoutInflater factory = LayoutInflater.from(this);
3797 final View v = factory
3798 .inflate(R.layout.http_authentication, null);
3799 if (name != null) {
3800 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3801 }
3802 if (password != null) {
3803 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3804 }
3805
3806 String titleText = title;
3807 if (titleText == null) {
3808 titleText = getText(R.string.sign_in_to).toString().replace(
3809 "%s1", host).replace("%s2", realm);
3810 }
3811
3812 mHttpAuthHandler = handler;
3813 AlertDialog dialog = new AlertDialog.Builder(this)
3814 .setTitle(titleText)
3815 .setIcon(android.R.drawable.ic_dialog_alert)
3816 .setView(v)
3817 .setPositiveButton(R.string.action,
3818 new DialogInterface.OnClickListener() {
3819 public void onClick(DialogInterface dialog,
3820 int whichButton) {
3821 String nm = ((EditText) v
3822 .findViewById(R.id.username_edit))
3823 .getText().toString();
3824 String pw = ((EditText) v
3825 .findViewById(R.id.password_edit))
3826 .getText().toString();
3827 BrowserActivity.this.setHttpAuthUsernamePassword
3828 (host, realm, nm, pw);
3829 handler.proceed(nm, pw);
3830 mHttpAuthenticationDialog = null;
3831 mHttpAuthHandler = null;
3832 }})
3833 .setNegativeButton(R.string.cancel,
3834 new DialogInterface.OnClickListener() {
3835 public void onClick(DialogInterface dialog,
3836 int whichButton) {
3837 handler.cancel();
3838 BrowserActivity.this.resetTitleAndRevertLockIcon();
3839 mHttpAuthenticationDialog = null;
3840 mHttpAuthHandler = null;
3841 }})
3842 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3843 public void onCancel(DialogInterface dialog) {
3844 handler.cancel();
3845 BrowserActivity.this.resetTitleAndRevertLockIcon();
3846 mHttpAuthenticationDialog = null;
3847 mHttpAuthHandler = null;
3848 }})
3849 .create();
3850 // Make the IME appear when the dialog is displayed if applicable.
3851 dialog.getWindow().setSoftInputMode(
3852 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3853 dialog.show();
3854 if (focusId != 0) {
3855 dialog.findViewById(focusId).requestFocus();
3856 } else {
3857 v.findViewById(R.id.username_edit).requestFocus();
3858 }
3859 mHttpAuthenticationDialog = dialog;
3860 }
3861
3862 public int getProgress() {
3863 WebView w = mTabControl.getCurrentWebView();
3864 if (w != null) {
3865 return w.getProgress();
3866 } else {
3867 return 100;
3868 }
3869 }
3870
3871 /**
3872 * Set HTTP authentication password.
3873 *
3874 * @param host The host for the password
3875 * @param realm The realm for the password
3876 * @param username The username for the password. If it is null, it means
3877 * password can't be saved.
3878 * @param password The password
3879 */
3880 public void setHttpAuthUsernamePassword(String host, String realm,
3881 String username,
3882 String password) {
3883 WebView w = mTabControl.getCurrentWebView();
3884 if (w != null) {
3885 w.setHttpAuthUsernamePassword(host, realm, username, password);
3886 }
3887 }
3888
3889 /**
3890 * connectivity manager says net has come or gone... inform the user
3891 * @param up true if net has come up, false if net has gone down
3892 */
3893 public void onNetworkToggle(boolean up) {
3894 if (up == mIsNetworkUp) {
3895 return;
3896 } else if (up) {
3897 mIsNetworkUp = true;
3898 if (mAlertDialog != null) {
3899 mAlertDialog.cancel();
3900 mAlertDialog = null;
3901 }
3902 } else {
3903 mIsNetworkUp = false;
3904 if (mInLoad && mAlertDialog == null) {
3905 mAlertDialog = new AlertDialog.Builder(this)
3906 .setTitle(R.string.loadSuspendedTitle)
3907 .setMessage(R.string.loadSuspended)
3908 .setPositiveButton(R.string.ok, null)
3909 .show();
3910 }
3911 }
3912 WebView w = mTabControl.getCurrentWebView();
3913 if (w != null) {
3914 w.setNetworkAvailable(up);
3915 }
3916 }
3917
3918 @Override
3919 protected void onActivityResult(int requestCode, int resultCode,
3920 Intent intent) {
3921 switch (requestCode) {
3922 case COMBO_PAGE:
3923 if (resultCode == RESULT_OK && intent != null) {
3924 String data = intent.getAction();
3925 Bundle extras = intent.getExtras();
3926 if (extras != null && extras.getBoolean("new_window", false)) {
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003927 final TabControl.Tab newTab = openTab(data);
3928 if (mSettings.openInBackground() &&
Leon Scroggins1f005d32009-08-10 17:36:42 -04003929 newTab != null) {
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003930 mTabControl.populatePickerData(newTab);
3931 mTabControl.setCurrentTab(newTab);
Leon Scroggins1f005d32009-08-10 17:36:42 -04003932 int newIndex = mTabControl.getCurrentIndex();
3933 if (CUSTOM_BROWSER_BAR) {
3934 mTitleBar.setCurrentTab(newIndex);
3935 }
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003936 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003937 } else {
3938 final TabControl.Tab currentTab =
3939 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003940 dismissSubWindow(currentTab);
3941 if (data != null && data.length() != 0) {
3942 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003943 }
3944 }
3945 }
3946 break;
3947 default:
3948 break;
3949 }
Leon Scroggins30444232009-09-04 18:36:20 -04003950 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003951 }
3952
3953 /*
3954 * This method is called as a result of the user selecting the options
3955 * menu to see the download window, or when a download changes state. It
3956 * shows the download window ontop of the current window.
3957 */
3958 /* package */ void viewDownloads(Uri downloadRecord) {
3959 Intent intent = new Intent(this,
3960 BrowserDownloadPage.class);
3961 intent.setData(downloadRecord);
3962 startActivityForResult(intent, this.DOWNLOAD_PAGE);
3963
3964 }
3965
Leon Scroggins160a7e72009-08-14 18:28:01 -04003966 /**
3967 * Open the Go page.
3968 * @param startWithHistory If true, open starting on the history tab.
3969 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003970 */
Leon Scroggins30444232009-09-04 18:36:20 -04003971 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003972 WebView current = mTabControl.getCurrentWebView();
3973 if (current == null) {
3974 return;
3975 }
3976 Intent intent = new Intent(this,
3977 CombinedBookmarkHistoryActivity.class);
3978 String title = current.getTitle();
3979 String url = current.getUrl();
3980 // Just in case the user opens bookmarks before a page finishes loading
3981 // so the current history item, and therefore the page, is null.
3982 if (null == url) {
3983 url = mLastEnteredUrl;
3984 // This can happen.
3985 if (null == url) {
3986 url = mSettings.getHomePage();
3987 }
3988 }
3989 // In case the web page has not yet received its associated title.
3990 if (title == null) {
3991 title = url;
3992 }
3993 intent.putExtra("title", title);
3994 intent.putExtra("url", url);
Leon Scroggins30444232009-09-04 18:36:20 -04003995 // Disable opening in a new window if we have maxed out the windows
3996 intent.putExtra("disable_new_window", mTabControl.getTabCount()
3997 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04003998 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003999 if (startWithHistory) {
4000 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4001 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4002 }
4003 startActivityForResult(intent, COMBO_PAGE);
4004 }
4005
4006 // Called when loading from context menu or LOAD_URL message
4007 private void loadURL(WebView view, String url) {
4008 // In case the user enters nothing.
4009 if (url != null && url.length() != 0 && view != null) {
4010 url = smartUrlFilter(url);
4011 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4012 view.loadUrl(url);
4013 }
4014 }
4015 }
4016
The Android Open Source Project0c908882009-03-03 19:32:16 -08004017 private String smartUrlFilter(Uri inUri) {
4018 if (inUri != null) {
4019 return smartUrlFilter(inUri.toString());
4020 }
4021 return null;
4022 }
4023
4024
4025 // get window count
4026
4027 int getWindowCount(){
4028 if(mTabControl != null){
4029 return mTabControl.getTabCount();
4030 }
4031 return 0;
4032 }
4033
Feng Qianb34f87a2009-03-24 21:27:26 -07004034 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004035 "(?i)" + // switch on case insensitive matching
4036 "(" + // begin group for schema
4037 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004038 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004039 ")" +
4040 "(.*)" );
4041
4042 /**
4043 * Attempts to determine whether user input is a URL or search
4044 * terms. Anything with a space is passed to search.
4045 *
4046 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4047 * "Http://" converts to "http://"
4048 *
4049 * @return Original or modified URL
4050 *
4051 */
4052 String smartUrlFilter(String url) {
4053
4054 String inUrl = url.trim();
4055 boolean hasSpace = inUrl.indexOf(' ') != -1;
4056
4057 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4058 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004059 // force scheme to lowercase
4060 String scheme = matcher.group(1);
4061 String lcScheme = scheme.toLowerCase();
4062 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004063 inUrl = lcScheme + matcher.group(2);
4064 }
4065 if (hasSpace) {
4066 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004067 }
4068 return inUrl;
4069 }
4070 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004071 // FIXME: Is this the correct place to add to searches?
4072 // what if someone else calls this function?
4073 int shortcut = parseUrlShortcut(inUrl);
4074 if (shortcut != SHORTCUT_INVALID) {
4075 Browser.addSearchUrl(mResolver, inUrl);
4076 String query = inUrl.substring(2);
4077 switch (shortcut) {
4078 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004079 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004080 case SHORTCUT_WIKIPEDIA_SEARCH:
4081 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4082 case SHORTCUT_DICTIONARY_SEARCH:
4083 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4084 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004085 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004086 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004087 }
4088 }
4089 } else {
4090 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4091 return URLUtil.guessUrl(inUrl);
4092 }
4093 }
4094
4095 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004096 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004097 }
4098
Ben Murdochbff2d602009-07-01 20:19:05 +01004099 /* package */ void setShouldShowErrorConsole(boolean flag) {
4100 if (flag == mShouldShowErrorConsole) {
4101 // Nothing to do.
4102 return;
4103 }
4104
4105 mShouldShowErrorConsole = flag;
4106
4107 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4108
4109 if (flag) {
4110 // Setting the show state of the console will cause it's the layout to be inflated.
4111 if (errorConsole.numberOfErrors() > 0) {
4112 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4113 } else {
4114 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4115 }
4116
4117 // Now we can add it to the main view.
4118 mErrorConsoleContainer.addView(errorConsole,
4119 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4120 ViewGroup.LayoutParams.WRAP_CONTENT));
4121 } else {
4122 mErrorConsoleContainer.removeView(errorConsole);
4123 }
4124
4125 }
4126
The Android Open Source Project0c908882009-03-03 19:32:16 -08004127 private final static int LOCK_ICON_UNSECURE = 0;
4128 private final static int LOCK_ICON_SECURE = 1;
4129 private final static int LOCK_ICON_MIXED = 2;
4130
4131 private int mLockIconType = LOCK_ICON_UNSECURE;
4132 private int mPrevLockType = LOCK_ICON_UNSECURE;
4133
4134 private BrowserSettings mSettings;
4135 private TabControl mTabControl;
4136 private ContentResolver mResolver;
4137 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004138 private View mCustomView;
4139 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004140 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004141
4142 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4143 // view, we should rewrite this.
4144 private int mCurrentMenuState = 0;
4145 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004146 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004147 private static final int EMPTY_MENU = -1;
4148 private Menu mMenu;
4149
4150 private FindDialog mFindDialog;
4151 // Used to prevent chording to result in firing two shortcuts immediately
4152 // one after another. Fixes bug 1211714.
4153 boolean mCanChord;
4154
4155 private boolean mInLoad;
4156 private boolean mIsNetworkUp;
4157
4158 private boolean mPageStarted;
4159 private boolean mActivityInPause = true;
4160
4161 private boolean mMenuIsDown;
4162
4163 private final KeyTracker mKeyTracker = new KeyTracker(this);
4164
4165 // As trackball doesn't send repeat down, we have to track it ourselves
4166 private boolean mTrackTrackball;
4167
4168 private static boolean mInTrace;
4169
4170 // Performance probe
4171 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4172 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4173 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4174 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4175 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4176 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4177 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4178 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4179 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4180 };
4181
4182 private long mStart;
4183 private long mProcessStart;
4184 private long mUserStart;
4185 private long mSystemStart;
4186 private long mIdleStart;
4187 private long mIrqStart;
4188
4189 private long mUiStart;
4190
4191 private Drawable mMixLockIcon;
4192 private Drawable mSecLockIcon;
4193 private Drawable mGenericFavicon;
4194
4195 /* hold a ref so we can auto-cancel if necessary */
4196 private AlertDialog mAlertDialog;
4197
4198 // Wait for credentials before loading google.com
4199 private ProgressDialog mCredsDlg;
4200
4201 // The up-to-date URL and title (these can be different from those stored
4202 // in WebView, since it takes some time for the information in WebView to
4203 // get updated)
4204 private String mUrl;
4205 private String mTitle;
4206
4207 // As PageInfo has different style for landscape / portrait, we have
4208 // to re-open it when configuration changed
4209 private AlertDialog mPageInfoDialog;
4210 private TabControl.Tab mPageInfoView;
4211 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4212 // dialog, we should not just dismiss it, but should get back to the
4213 // SSL-certificate-on-error dialog. This flag is used to store this state
4214 private Boolean mPageInfoFromShowSSLCertificateOnError;
4215
4216 // as SSLCertificateOnError has different style for landscape / portrait,
4217 // we have to re-open it when configuration changed
4218 private AlertDialog mSSLCertificateOnErrorDialog;
4219 private WebView mSSLCertificateOnErrorView;
4220 private SslErrorHandler mSSLCertificateOnErrorHandler;
4221 private SslError mSSLCertificateOnErrorError;
4222
4223 // as SSLCertificate has different style for landscape / portrait, we
4224 // have to re-open it when configuration changed
4225 private AlertDialog mSSLCertificateDialog;
4226 private TabControl.Tab mSSLCertificateView;
4227
4228 // as HttpAuthentication has different style for landscape / portrait, we
4229 // have to re-open it when configuration changed
4230 private AlertDialog mHttpAuthenticationDialog;
4231 private HttpAuthHandler mHttpAuthHandler;
4232
4233 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4234 new FrameLayout.LayoutParams(
4235 ViewGroup.LayoutParams.FILL_PARENT,
4236 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004237 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4238 new FrameLayout.LayoutParams(
4239 ViewGroup.LayoutParams.FILL_PARENT,
4240 ViewGroup.LayoutParams.FILL_PARENT,
4241 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004242 // Google search
4243 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004244 // Wikipedia search
4245 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4246 // Dictionary search
4247 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4248 // Google Mobile Local search
4249 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4250
4251 final static String QUERY_PLACE_HOLDER = "%s";
4252
4253 // "source" parameter for Google search through search key
4254 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4255 // "source" parameter for Google search through goto menu
4256 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4257 // "source" parameter for Google search through simplily type
4258 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4259 // "source" parameter for Google search suggested by the browser
4260 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4261 // "source" parameter for Google search from unknown source
4262 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4263
4264 private final static String LOGTAG = "browser";
4265
The Android Open Source Project0c908882009-03-03 19:32:16 -08004266 private String mLastEnteredUrl;
4267
4268 private PowerManager.WakeLock mWakeLock;
4269 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4270
4271 private Toast mStopToast;
4272
Leon Scroggins1f005d32009-08-10 17:36:42 -04004273 private TitleBarSet mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004274
Ben Murdochbff2d602009-07-01 20:19:05 +01004275 private LinearLayout mErrorConsoleContainer = null;
4276 private boolean mShouldShowErrorConsole = false;
4277
The Android Open Source Project0c908882009-03-03 19:32:16 -08004278 // As the ids are dynamically created, we can't guarantee that they will
4279 // be in sequence, so this static array maps ids to a window number.
4280 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4281 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4282 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4283 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4284
4285 // monitor platform changes
4286 private IntentFilter mNetworkStateChangedFilter;
4287 private BroadcastReceiver mNetworkStateIntentReceiver;
4288
Grace Klobab4da0ad2009-05-14 14:45:40 -07004289 private BroadcastReceiver mPackageInstallationReceiver;
4290
The Android Open Source Project0c908882009-03-03 19:32:16 -08004291 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004292 final static int COMBO_PAGE = 1;
4293 final static int DOWNLOAD_PAGE = 2;
4294 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004295
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004296 /**
4297 * A UrlData class to abstract how the content will be set to WebView.
4298 * This base class uses loadUrl to show the content.
4299 */
4300 private static class UrlData {
4301 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004302 byte[] mPostData;
4303
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004304 UrlData(String url) {
4305 this.mUrl = url;
4306 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004307
4308 void setPostData(byte[] postData) {
4309 mPostData = postData;
4310 }
4311
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004312 boolean isEmpty() {
4313 return mUrl == null || mUrl.length() == 0;
4314 }
4315
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004316 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004317 if (mPostData != null) {
4318 webView.postUrl(mUrl, mPostData);
4319 } else {
4320 webView.loadUrl(mUrl);
4321 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004322 }
4323 };
4324
4325 /**
4326 * A subclass of UrlData class that can display inlined content using
4327 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4328 */
4329 private static class InlinedUrlData extends UrlData {
4330 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4331 super(failUrl);
4332 mInlined = inlined;
4333 mMimeType = mimeType;
4334 mEncoding = encoding;
4335 }
4336 String mMimeType;
4337 String mInlined;
4338 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004339 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004340 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004341 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004342 }
4343
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004344 @Override
4345 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004346 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4347 }
4348 }
4349
Leon Scroggins1f005d32009-08-10 17:36:42 -04004350 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004351}