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