blob: 8adba4b55a3af1b4720143717fe2083da43bf9a2 [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);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400339 mTitleBar = (TitleBarSet) browserFrameLayout.findViewById(R.id.title_bar);
Andrei Popescuadc008d2009-06-26 14:11:30 +0100340 mContentView = (FrameLayout) browserFrameLayout.findViewById(
Leon Scrogginse4b3bda2009-06-09 15:46:41 -0400341 R.id.main_content);
Ben Murdochbff2d602009-07-01 20:19:05 +0100342 mErrorConsoleContainer = (LinearLayout) browserFrameLayout.findViewById(
343 R.id.error_console);
Andrei Popescuadc008d2009-06-26 14:11:30 +0100344 mCustomViewContainer = (FrameLayout) browserFrameLayout
345 .findViewById(R.id.fullscreen_custom_content);
346 frameLayout.addView(browserFrameLayout, COVER_SCREEN_PARAMS);
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 Scroggins160a7e72009-08-14 18:28:01 -0400484 bookmarksOrHistoryPicker(false, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800485 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700486 if (extra != null) {
487 urlData.setPostData(extra
488 .getByteArray(Browser.EXTRA_POST_DATA));
489 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700490 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800491 }
492 } else {
493 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400494 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800495 attachTabToContentView(mTabControl.getCurrentTab());
496 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700497
Leon Scroggins1f005d32009-08-10 17:36:42 -0400498 if (CUSTOM_BROWSER_BAR) {
499 // Create title bars for all of the tabs that have been created
500 for (int i = 0; i < mTabControl.getTabCount(); i ++) {
501 WebView view = mTabControl.getTab(i).getWebView();
502 mTitleBar.addTab(view, false);
503 }
504
505 mTitleBar.setBrowserActivity(this);
506 mTitleBar.setCurrentTab(mTabControl.getCurrentIndex());
507 }
508
Feng Qianb3c02da2009-06-29 15:58:08 -0700509 // Read JavaScript flags if it exists.
510 String jsFlags = mSettings.getJsFlags();
511 if (jsFlags.trim().length() != 0) {
512 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
513 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800514 }
515
516 @Override
517 protected void onNewIntent(Intent intent) {
518 TabControl.Tab current = mTabControl.getCurrentTab();
519 // When a tab is closed on exit, the current tab index is set to -1.
520 // Reset before proceed as Browser requires the current tab to be set.
521 if (current == null) {
522 // Try to reset the tab in case the index was incorrect.
523 current = mTabControl.getTab(0);
524 if (current == null) {
525 // No tabs at all so just ignore this intent.
526 return;
527 }
528 mTabControl.setCurrentTab(current);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400529 if (CUSTOM_BROWSER_BAR) {
530 mTitleBar.setCurrentTab(mTabControl.getTabIndex(current));
531 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800532 attachTabToContentView(current);
533 resetTitleAndIcon(current.getWebView());
534 }
535 final String action = intent.getAction();
536 final int flags = intent.getFlags();
537 if (Intent.ACTION_MAIN.equals(action) ||
538 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
539 // just resume the browser
540 return;
541 }
542 if (Intent.ACTION_VIEW.equals(action)
543 || Intent.ACTION_SEARCH.equals(action)
544 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
545 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100546 // If this was a search request (e.g. search query directly typed into the address bar),
547 // pass it on to the default web search provider.
548 if (handleWebSearchIntent(intent)) {
549 return;
550 }
551
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700552 UrlData urlData = getUrlDataFromIntent(intent);
553 if (urlData.isEmpty()) {
554 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800555 }
Grace Kloba81678d92009-06-30 07:09:56 -0700556 urlData.setPostData(intent
557 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700558
Grace Klobacc634032009-07-28 15:58:19 -0700559 final String appId = intent
560 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
561 if (Intent.ACTION_VIEW.equals(action)
562 && !getPackageName().equals(appId)
563 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Patrick Scottcd115892009-07-16 09:42:58 -0400564 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700565 if (appTab != null) {
566 Log.i(LOGTAG, "Reusing tab for " + appId);
567 // Dismiss the subwindow if applicable.
568 dismissSubWindow(appTab);
569 // Since we might kill the WebView, remove it from the
570 // content view first.
571 removeTabFromContentView(appTab);
572 // Recreate the main WebView after destroying the old one.
573 // If the WebView has the same original url and is on that
574 // page, it can be reused.
575 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700576 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100577
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700578 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400579 switchToTab(mTabControl.getTabIndex(appTab));
580 if (needsLoad) {
581 urlData.loadIn(appTab.getWebView());
582 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700583 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400584 // If the tab was the current tab, we have to attach
585 // it to the view system again.
586 attachTabToContentView(appTab);
587 if (needsLoad) {
588 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700589 }
590 }
591 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400592 } else {
593 // No matching application tab, try to find a regular tab
594 // with a matching url.
595 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400596 if (appTab != null && current != appTab) {
597 switchToTab(mTabControl.getTabIndex(appTab));
Patrick Scottcd115892009-07-16 09:42:58 -0400598 } else {
599 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
600 // will be opened in a new tab unless we have reached
601 // MAX_TABS. Then the url will be opened in the current
602 // tab. If a new tab is created, it will have "true" for
603 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400604 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400605 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700606 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800607 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700608 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800609 mSettings.toggleDebugSettings();
610 return;
611 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400612 // Get rid of the subwindow if it exists
613 dismissSubWindow(current);
614 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800615 }
616 }
617 }
618
Satish Sampath565505b2009-05-29 15:37:27 +0100619 private int parseUrlShortcut(String url) {
620 if (url == null) return SHORTCUT_INVALID;
621
622 // FIXME: quick search, need to be customized by setting
623 if (url.length() > 2 && url.charAt(1) == ' ') {
624 switch (url.charAt(0)) {
625 case 'g': return SHORTCUT_GOOGLE_SEARCH;
626 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
627 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
628 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
629 }
630 }
631 return SHORTCUT_INVALID;
632 }
633
634 /**
635 * Launches the default web search activity with the query parameters if the given intent's data
636 * are identified as plain search terms and not URLs/shortcuts.
637 * @return true if the intent was handled and web search activity was launched, false if not.
638 */
639 private boolean handleWebSearchIntent(Intent intent) {
640 if (intent == null) return false;
641
642 String url = null;
643 final String action = intent.getAction();
644 if (Intent.ACTION_VIEW.equals(action)) {
645 url = intent.getData().toString();
646 } else if (Intent.ACTION_SEARCH.equals(action)
647 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
648 || Intent.ACTION_WEB_SEARCH.equals(action)) {
649 url = intent.getStringExtra(SearchManager.QUERY);
650 }
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100651 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA));
Satish Sampath565505b2009-05-29 15:37:27 +0100652 }
653
654 /**
655 * Launches the default web search activity with the query parameters if the given url string
656 * was identified as plain search terms and not URL/shortcut.
657 * @return true if the request was handled and web search activity was launched, false if not.
658 */
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100659 private boolean handleWebSearchRequest(String inUrl, Bundle appData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100660 if (inUrl == null) return false;
661
662 // In general, we shouldn't modify URL from Intent.
663 // But currently, we get the user-typed URL from search box as well.
664 String url = fixUrl(inUrl).trim();
665
666 // URLs and site specific search shortcuts are handled by the regular flow of control, so
667 // return early.
668 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100669 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100670 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
671 return false;
672 }
673
674 Browser.updateVisitedHistory(mResolver, url, false);
675 Browser.addSearchUrl(mResolver, url);
676
677 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
678 intent.addCategory(Intent.CATEGORY_DEFAULT);
679 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100680 if (appData != null) {
681 intent.putExtra(SearchManager.APP_DATA, appData);
682 }
Grace Klobacc634032009-07-28 15:58:19 -0700683 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100684 startActivity(intent);
685
686 return true;
687 }
688
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700689 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800690 String url = null;
691 if (intent != null) {
692 final String action = intent.getAction();
693 if (Intent.ACTION_VIEW.equals(action)) {
694 url = smartUrlFilter(intent.getData());
695 if (url != null && url.startsWith("content:")) {
696 /* Append mimetype so webview knows how to display */
697 String mimeType = intent.resolveType(getContentResolver());
698 if (mimeType != null) {
699 url += "?" + mimeType;
700 }
701 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700702 if ("inline:".equals(url)) {
703 return new InlinedUrlData(
704 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
705 intent.getType(),
706 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
707 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
708 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800709 } else if (Intent.ACTION_SEARCH.equals(action)
710 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
711 || Intent.ACTION_WEB_SEARCH.equals(action)) {
712 url = intent.getStringExtra(SearchManager.QUERY);
713 if (url != null) {
714 mLastEnteredUrl = url;
715 // Don't add Urls, just search terms.
716 // Urls will get added when the page is loaded.
717 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
718 Browser.updateVisitedHistory(mResolver, url, false);
719 }
720 // In general, we shouldn't modify URL from Intent.
721 // But currently, we get the user-typed URL from search box as well.
722 url = fixUrl(url);
723 url = smartUrlFilter(url);
724 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
725 if (url.contains(searchSource)) {
726 String source = null;
727 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
728 if (appData != null) {
729 source = appData.getString(SearchManager.SOURCE);
730 }
731 if (TextUtils.isEmpty(source)) {
732 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
733 }
734 url = url.replace(searchSource, "&source=android-"+source+"&");
735 }
736 }
737 }
738 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700739 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800740 }
741
742 /* package */ static String fixUrl(String inUrl) {
743 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
744 return inUrl;
745 if (inUrl.startsWith("http:") ||
746 inUrl.startsWith("https:")) {
747 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
748 inUrl = inUrl.replaceFirst("/", "//");
749 } else inUrl = inUrl.replaceFirst(":", "://");
750 }
751 return inUrl;
752 }
753
754 /**
755 * Looking for the pattern like this
756 *
757 * *
758 * * *
759 * *** * *******
760 * * *
761 * * *
762 * *
763 */
764 private final SensorListener mSensorListener = new SensorListener() {
765 private long mLastGestureTime;
766 private float[] mPrev = new float[3];
767 private float[] mPrevDiff = new float[3];
768 private float[] mDiff = new float[3];
769 private float[] mRevertDiff = new float[3];
770
771 public void onSensorChanged(int sensor, float[] values) {
772 boolean show = false;
773 float[] diff = new float[3];
774
775 for (int i = 0; i < 3; i++) {
776 diff[i] = values[i] - mPrev[i];
777 if (Math.abs(diff[i]) > 1) {
778 show = true;
779 }
780 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
781 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
782 // start track when there is a big move, or revert
783 mRevertDiff[i] = mDiff[i];
784 mDiff[i] = 0;
785 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
786 // reset when it is flat
787 mDiff[i] = mRevertDiff[i] = 0;
788 }
789 mDiff[i] += diff[i];
790 mPrevDiff[i] = diff[i];
791 mPrev[i] = values[i];
792 }
793
794 if (false) {
795 // only shows if we think the delta is big enough, in an attempt
796 // to detect "serious" moves left/right or up/down
797 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
798 + values[0] + ", " + values[1] + ", " + values[2] + ")"
799 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
800 + ")");
801 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
802 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
803 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
804 + mRevertDiff[2] + ")");
805 }
806
807 long now = android.os.SystemClock.uptimeMillis();
808 if (now - mLastGestureTime > 1000) {
809 mLastGestureTime = 0;
810
811 float y = mDiff[1];
812 float z = mDiff[2];
813 float ay = Math.abs(y);
814 float az = Math.abs(z);
815 float ry = mRevertDiff[1];
816 float rz = mRevertDiff[2];
817 float ary = Math.abs(ry);
818 float arz = Math.abs(rz);
819 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
820 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
821
822 if ((gestY || gestZ) && !(gestY && gestZ)) {
823 WebView view = mTabControl.getCurrentWebView();
824
825 if (view != null) {
826 if (gestZ) {
827 if (z < 0) {
828 view.zoomOut();
829 } else {
830 view.zoomIn();
831 }
832 } else {
833 view.flingScroll(0, Math.round(y * 100));
834 }
835 }
836 mLastGestureTime = now;
837 }
838 }
839 }
840
841 public void onAccuracyChanged(int sensor, int accuracy) {
842 // TODO Auto-generated method stub
843
844 }
845 };
846
847 @Override protected void onResume() {
848 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700849 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800850 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
851 }
852
853 if (!mActivityInPause) {
854 Log.e(LOGTAG, "BrowserActivity is already resumed.");
855 return;
856 }
857
Mike Reed7bfa63b2009-05-28 11:08:32 -0400858 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800859 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400860 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800861
862 if (mWakeLock.isHeld()) {
863 mHandler.removeMessages(RELEASE_WAKELOCK);
864 mWakeLock.release();
865 }
866
867 if (mCredsDlg != null) {
868 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
869 // In case credential request never comes back
870 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
871 }
872 }
873
874 registerReceiver(mNetworkStateIntentReceiver,
875 mNetworkStateChangedFilter);
876 WebView.enablePlatformNotifications();
877
878 if (mSettings.doFlick()) {
879 if (mSensorManager == null) {
880 mSensorManager = (SensorManager) getSystemService(
881 Context.SENSOR_SERVICE);
882 }
883 mSensorManager.registerListener(mSensorListener,
884 SensorManager.SENSOR_ACCELEROMETER,
885 SensorManager.SENSOR_DELAY_FASTEST);
886 } else {
887 mSensorManager = null;
888 }
889 }
890
891 /**
892 * onSaveInstanceState(Bundle map)
893 * onSaveInstanceState is called right before onStop(). The map contains
894 * the saved state.
895 */
896 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700897 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800898 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
899 }
900 // the default implementation requires each view to have an id. As the
901 // browser handles the state itself and it doesn't use id for the views,
902 // don't call the default implementation. Otherwise it will trigger the
903 // warning like this, "couldn't save which view has focus because the
904 // focused view XXX has no id".
905
906 // Save all the tabs
907 mTabControl.saveState(outState);
908 }
909
910 @Override protected void onPause() {
911 super.onPause();
912
913 if (mActivityInPause) {
914 Log.e(LOGTAG, "BrowserActivity is already paused.");
915 return;
916 }
917
Mike Reed7bfa63b2009-05-28 11:08:32 -0400918 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800919 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400920 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800921 mWakeLock.acquire();
922 mHandler.sendMessageDelayed(mHandler
923 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
924 }
925
926 // Clear the credentials toast if it is up
927 if (mCredsDlg != null && mCredsDlg.isShowing()) {
928 mCredsDlg.dismiss();
929 }
930 mCredsDlg = null;
931
932 cancelStopToast();
933
934 // unregister network state listener
935 unregisterReceiver(mNetworkStateIntentReceiver);
936 WebView.disablePlatformNotifications();
937
938 if (mSensorManager != null) {
939 mSensorManager.unregisterListener(mSensorListener);
940 }
941 }
942
943 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700944 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800945 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
946 }
947 super.onDestroy();
948 // Remove the current tab and sub window
949 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700950 if (t != null) {
951 dismissSubWindow(t);
952 removeTabFromContentView(t);
953 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800954 // Destroy all the tabs
955 mTabControl.destroy();
956 WebIconDatabase.getInstance().close();
957 if (mGlsConnection != null) {
958 unbindService(mGlsConnection);
959 mGlsConnection = null;
960 }
961
962 //
963 // stop MASF proxy service
964 //
965 //Intent proxyServiceIntent = new Intent();
966 //proxyServiceIntent.setComponent
967 // (new ComponentName(
968 // "com.android.masfproxyservice",
969 // "com.android.masfproxyservice.MasfProxyService"));
970 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -0700971
972 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800973 }
974
975 @Override
976 public void onConfigurationChanged(Configuration newConfig) {
977 super.onConfigurationChanged(newConfig);
978
979 if (mPageInfoDialog != null) {
980 mPageInfoDialog.dismiss();
981 showPageInfo(
982 mPageInfoView,
983 mPageInfoFromShowSSLCertificateOnError.booleanValue());
984 }
985 if (mSSLCertificateDialog != null) {
986 mSSLCertificateDialog.dismiss();
987 showSSLCertificate(
988 mSSLCertificateView);
989 }
990 if (mSSLCertificateOnErrorDialog != null) {
991 mSSLCertificateOnErrorDialog.dismiss();
992 showSSLCertificateOnError(
993 mSSLCertificateOnErrorView,
994 mSSLCertificateOnErrorHandler,
995 mSSLCertificateOnErrorError);
996 }
997 if (mHttpAuthenticationDialog != null) {
998 String title = ((TextView) mHttpAuthenticationDialog
999 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1000 .toString();
1001 String name = ((TextView) mHttpAuthenticationDialog
1002 .findViewById(R.id.username_edit)).getText().toString();
1003 String password = ((TextView) mHttpAuthenticationDialog
1004 .findViewById(R.id.password_edit)).getText().toString();
1005 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1006 .getId();
1007 mHttpAuthenticationDialog.dismiss();
1008 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1009 name, password, focusId);
1010 }
1011 if (mFindDialog != null && mFindDialog.isShowing()) {
1012 mFindDialog.onConfigurationChanged(newConfig);
1013 }
1014 }
1015
1016 @Override public void onLowMemory() {
1017 super.onLowMemory();
1018 mTabControl.freeMemory();
1019 }
1020
Mike Reed7bfa63b2009-05-28 11:08:32 -04001021 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001022 if ((!mActivityInPause && !mPageStarted) ||
1023 (mActivityInPause && mPageStarted)) {
1024 CookieSyncManager.getInstance().startSync();
1025 WebView w = mTabControl.getCurrentWebView();
1026 if (w != null) {
1027 w.resumeTimers();
1028 }
1029 return true;
1030 } else {
1031 return false;
1032 }
1033 }
1034
Mike Reed7bfa63b2009-05-28 11:08:32 -04001035 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001036 if (mActivityInPause && !mPageStarted) {
1037 CookieSyncManager.getInstance().stopSync();
1038 WebView w = mTabControl.getCurrentWebView();
1039 if (w != null) {
1040 w.pauseTimers();
1041 }
1042 return true;
1043 } else {
1044 return false;
1045 }
1046 }
1047
Leon Scroggins1f005d32009-08-10 17:36:42 -04001048 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001049 /*
1050 * This function is called when we are launching for the first time. We
1051 * are waiting for the login credentials before loading Google home
1052 * pages. This way the user will be logged in straight away.
1053 */
1054 private void waitForCredentials() {
1055 // Show a toast
1056 mCredsDlg = new ProgressDialog(this);
1057 mCredsDlg.setIndeterminate(true);
1058 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1059 // If the user cancels the operation, then cancel the Google
1060 // Credentials request.
1061 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1062 mCredsDlg.show();
1063
1064 // We set a timeout for the retrieval of credentials in onResume()
1065 // as that is when we have freed up some CPU time to get
1066 // the login credentials.
1067 }
1068
1069 /*
1070 * If we have received the credentials or we have timed out and we are
1071 * showing the credentials dialog, then it is time to move on.
1072 */
1073 private void resumeAfterCredentials() {
1074 if (mCredsDlg == null) {
1075 return;
1076 }
1077
1078 // Clear the toast
1079 if (mCredsDlg.isShowing()) {
1080 mCredsDlg.dismiss();
1081 }
1082 mCredsDlg = null;
1083
1084 // Clear any pending timeout
1085 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1086
1087 // Load the page
1088 WebView w = mTabControl.getCurrentWebView();
1089 if (w != null) {
1090 w.loadUrl(mSettings.getHomePage());
1091 }
1092
1093 // Update the settings, need to do this last as it can take a moment
1094 // to persist the settings. In the mean time we could be loading
1095 // content.
1096 mSettings.setLoginInitialized(this);
1097 }
1098
1099 // Open the icon database and retain all the icons for visited sites.
1100 private void retainIconsOnStartup() {
1101 final WebIconDatabase db = WebIconDatabase.getInstance();
1102 db.open(getDir("icons", 0).getPath());
1103 try {
1104 Cursor c = Browser.getAllBookmarks(mResolver);
1105 if (!c.moveToFirst()) {
1106 c.deactivate();
1107 return;
1108 }
1109 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1110 do {
1111 String url = c.getString(urlIndex);
1112 db.retainIconForPageUrl(url);
1113 } while (c.moveToNext());
1114 c.deactivate();
1115 } catch (IllegalStateException e) {
1116 Log.e(LOGTAG, "retainIconsOnStartup", e);
1117 }
1118 }
1119
1120 // Helper method for getting the top window.
1121 WebView getTopWindow() {
1122 return mTabControl.getCurrentTopWebView();
1123 }
1124
1125 @Override
1126 public boolean onCreateOptionsMenu(Menu menu) {
1127 super.onCreateOptionsMenu(menu);
1128
1129 MenuInflater inflater = getMenuInflater();
1130 inflater.inflate(R.menu.browser, menu);
1131 mMenu = menu;
1132 updateInLoadMenuItems();
1133 return true;
1134 }
1135
1136 /**
1137 * As the menu can be open when loading state changes
1138 * we must manually update the state of the stop/reload menu
1139 * item
1140 */
1141 private void updateInLoadMenuItems() {
1142 if (mMenu == null) {
1143 return;
1144 }
1145 MenuItem src = mInLoad ?
1146 mMenu.findItem(R.id.stop_menu_id):
1147 mMenu.findItem(R.id.reload_menu_id);
1148 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1149 dest.setIcon(src.getIcon());
1150 dest.setTitle(src.getTitle());
1151 }
1152
1153 @Override
1154 public boolean onContextItemSelected(MenuItem item) {
1155 // chording is not an issue with context menus, but we use the same
1156 // options selector, so set mCanChord to true so we can access them.
1157 mCanChord = true;
1158 int id = item.getItemId();
1159 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001160 if (null == webView) {
1161 return false;
1162 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001163 final HashMap hrefMap = new HashMap();
1164 hrefMap.put("webview", webView);
1165 final Message msg = mHandler.obtainMessage(
1166 FOCUS_NODE_HREF, id, 0, hrefMap);
1167 switch (id) {
1168 // -- Browser context menu
1169 case R.id.open_context_menu_id:
1170 case R.id.open_newtab_context_menu_id:
1171 case R.id.bookmark_context_menu_id:
1172 case R.id.save_link_context_menu_id:
1173 case R.id.share_link_context_menu_id:
1174 case R.id.copy_link_context_menu_id:
1175 webView.requestFocusNodeHref(msg);
1176 break;
1177
1178 default:
1179 // For other context menus
1180 return onOptionsItemSelected(item);
1181 }
1182 mCanChord = false;
1183 return true;
1184 }
1185
1186 private Bundle createGoogleSearchSourceBundle(String source) {
1187 Bundle bundle = new Bundle();
1188 bundle.putString(SearchManager.SOURCE, source);
1189 return bundle;
1190 }
1191
1192 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001193 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001194 */
1195 @Override
1196 public boolean onSearchRequested() {
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001197 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001198 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001199 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001200 return true;
1201 }
1202
1203 @Override
1204 public void startSearch(String initialQuery, boolean selectInitialQuery,
1205 Bundle appSearchData, boolean globalSearch) {
1206 if (appSearchData == null) {
1207 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1208 }
1209 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1210 }
1211
Leon Scroggins1f005d32009-08-10 17:36:42 -04001212 /**
1213 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1214 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001215 * @param index Index of the tab to change to, as defined by
1216 * mTabControl.getTabIndex(Tab t).
1217 * @return boolean True if we successfully switched to a different tab. If
1218 * the indexth tab is null, or if that tab is the same as
1219 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001220 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001221 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001222 TabControl.Tab tab = mTabControl.getTab(index);
1223 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1224 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001225 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001226 }
1227 if (currentTab != null) {
1228 // currentTab may be null if it was just removed. In that case,
1229 // we do not need to remove it
1230 removeTabFromContentView(currentTab);
1231 }
1232 removeTabFromContentView(tab);
1233 mTabControl.setCurrentTab(tab);
1234 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001235 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001236 }
1237
1238 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001239 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001240 if (mTabControl.getTabCount() == 1) {
1241 // This is the last tab. Open a new one, as well as the history
1242 // picker, and close the current one.
1243 TabControl.Tab newTab = openTabAndShow(
1244 BrowserActivity.EMPTY_URL_DATA, false, null);
1245 bookmarksOrHistoryPicker(false, true);
1246 closeTab(current);
1247 mTabControl.setCurrentTab(newTab);
1248 return;
1249 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001250 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001251 int indexToShow = -1;
1252 if (parent != null) {
1253 indexToShow = mTabControl.getTabIndex(parent);
1254 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001255 final int currentIndex = mTabControl.getCurrentIndex();
1256 // Try to move to the tab to the right
1257 indexToShow = currentIndex + 1;
1258 if (indexToShow > mTabControl.getTabCount() - 1) {
1259 // Try to move to the tab to the left
1260 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001261 }
1262 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001263 if (switchToTab(indexToShow)) {
1264 // Close window
1265 closeTab(current);
1266 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001267 }
1268
The Android Open Source Project0c908882009-03-03 19:32:16 -08001269 @Override
1270 public boolean onOptionsItemSelected(MenuItem item) {
1271 if (!mCanChord) {
1272 // The user has already fired a shortcut with this hold down of the
1273 // menu key.
1274 return false;
1275 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001276 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001277 return false;
1278 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001279 if (mMenuIsDown) {
1280 // The shortcut action consumes the MENU. Even if it is still down,
1281 // it won't trigger the next shortcut action. In the case of the
1282 // shortcut action triggering a new activity, like Bookmarks, we
1283 // won't get onKeyUp for MENU. So it is important to reset it here.
1284 mMenuIsDown = false;
1285 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001286 switch (item.getItemId()) {
1287 // -- Main menu
Leon Scroggins64b80f32009-08-07 12:03:34 -04001288 case R.id.goto_menu_id:
Leon Scroggins160a7e72009-08-14 18:28:01 -04001289 bookmarksOrHistoryPicker(false, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001290 break;
1291
Leon Scroggins1f005d32009-08-10 17:36:42 -04001292 case R.id.add_bookmark_menu_id:
1293 Intent i = new Intent(BrowserActivity.this,
1294 AddBookmarkPage.class);
1295 WebView w = getTopWindow();
1296 i.putExtra("url", w.getUrl());
1297 i.putExtra("title", w.getTitle());
1298 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001299 break;
1300
1301 case R.id.stop_reload_menu_id:
1302 if (mInLoad) {
1303 stopLoading();
1304 } else {
1305 getTopWindow().reload();
1306 }
1307 break;
1308
1309 case R.id.back_menu_id:
1310 getTopWindow().goBack();
1311 break;
1312
1313 case R.id.forward_menu_id:
1314 getTopWindow().goForward();
1315 break;
1316
1317 case R.id.close_menu_id:
1318 // Close the subwindow if it exists.
1319 if (mTabControl.getCurrentSubWindow() != null) {
1320 dismissSubWindow(mTabControl.getCurrentTab());
1321 break;
1322 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001323 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001324 break;
1325
1326 case R.id.homepage_menu_id:
1327 TabControl.Tab current = mTabControl.getCurrentTab();
1328 if (current != null) {
1329 dismissSubWindow(current);
1330 current.getWebView().loadUrl(mSettings.getHomePage());
1331 }
1332 break;
1333
1334 case R.id.preferences_menu_id:
1335 Intent intent = new Intent(this,
1336 BrowserPreferencesPage.class);
1337 startActivityForResult(intent, PREFERENCES_PAGE);
1338 break;
1339
1340 case R.id.find_menu_id:
1341 if (null == mFindDialog) {
1342 mFindDialog = new FindDialog(this);
1343 }
1344 mFindDialog.setWebView(getTopWindow());
1345 mFindDialog.show();
1346 mMenuState = EMPTY_MENU;
1347 break;
1348
1349 case R.id.select_text_id:
1350 getTopWindow().emulateShiftHeld();
1351 break;
1352 case R.id.page_info_menu_id:
1353 showPageInfo(mTabControl.getCurrentTab(), false);
1354 break;
1355
1356 case R.id.classic_history_menu_id:
Leon Scroggins160a7e72009-08-14 18:28:01 -04001357 bookmarksOrHistoryPicker(true, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001358 break;
1359
1360 case R.id.share_page_menu_id:
1361 Browser.sendString(this, getTopWindow().getUrl());
1362 break;
1363
1364 case R.id.dump_nav_menu_id:
1365 getTopWindow().debugDump();
1366 break;
1367
1368 case R.id.zoom_in_menu_id:
1369 getTopWindow().zoomIn();
1370 break;
1371
1372 case R.id.zoom_out_menu_id:
1373 getTopWindow().zoomOut();
1374 break;
1375
1376 case R.id.view_downloads_menu_id:
1377 viewDownloads(null);
1378 break;
1379
The Android Open Source Project0c908882009-03-03 19:32:16 -08001380 case R.id.window_one_menu_id:
1381 case R.id.window_two_menu_id:
1382 case R.id.window_three_menu_id:
1383 case R.id.window_four_menu_id:
1384 case R.id.window_five_menu_id:
1385 case R.id.window_six_menu_id:
1386 case R.id.window_seven_menu_id:
1387 case R.id.window_eight_menu_id:
1388 {
1389 int menuid = item.getItemId();
1390 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1391 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1392 TabControl.Tab desiredTab = mTabControl.getTab(id);
1393 if (desiredTab != null &&
1394 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001395 switchToTab(id);
1396 mTitleBar.setCurrentTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001397 }
1398 break;
1399 }
1400 }
1401 }
1402 break;
1403
1404 default:
1405 if (!super.onOptionsItemSelected(item)) {
1406 return false;
1407 }
1408 // Otherwise fall through.
1409 }
1410 mCanChord = false;
1411 return true;
1412 }
1413
1414 public void closeFind() {
1415 mMenuState = R.id.MAIN_MENU;
1416 }
1417
1418 @Override public boolean onPrepareOptionsMenu(Menu menu)
1419 {
1420 // This happens when the user begins to hold down the menu key, so
1421 // allow them to chord to get a shortcut.
1422 mCanChord = true;
1423 // Note: setVisible will decide whether an item is visible; while
1424 // setEnabled() will decide whether an item is enabled, which also means
1425 // whether the matching shortcut key will function.
1426 super.onPrepareOptionsMenu(menu);
1427 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001428 case EMPTY_MENU:
1429 if (mCurrentMenuState != mMenuState) {
1430 menu.setGroupVisible(R.id.MAIN_MENU, false);
1431 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1432 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001433 }
1434 break;
1435 default:
1436 if (mCurrentMenuState != mMenuState) {
1437 menu.setGroupVisible(R.id.MAIN_MENU, true);
1438 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1439 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001440 }
1441 final WebView w = getTopWindow();
1442 boolean canGoBack = false;
1443 boolean canGoForward = false;
1444 boolean isHome = false;
1445 if (w != null) {
1446 canGoBack = w.canGoBack();
1447 canGoForward = w.canGoForward();
1448 isHome = mSettings.getHomePage().equals(w.getUrl());
1449 }
1450 final MenuItem back = menu.findItem(R.id.back_menu_id);
1451 back.setEnabled(canGoBack);
1452
1453 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1454 home.setEnabled(!isHome);
1455
1456 menu.findItem(R.id.forward_menu_id)
1457 .setEnabled(canGoForward);
1458
1459 // decide whether to show the share link option
1460 PackageManager pm = getPackageManager();
1461 Intent send = new Intent(Intent.ACTION_SEND);
1462 send.setType("text/plain");
1463 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1464 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1465
The Android Open Source Project0c908882009-03-03 19:32:16 -08001466 boolean isNavDump = mSettings.isNavDump();
1467 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1468 nav.setVisible(isNavDump);
1469 nav.setEnabled(isNavDump);
1470 break;
1471 }
1472 mCurrentMenuState = mMenuState;
1473 return true;
1474 }
1475
1476 @Override
1477 public void onCreateContextMenu(ContextMenu menu, View v,
1478 ContextMenuInfo menuInfo) {
1479 WebView webview = (WebView) v;
1480 WebView.HitTestResult result = webview.getHitTestResult();
1481 if (result == null) {
1482 return;
1483 }
1484
1485 int type = result.getType();
1486 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1487 Log.w(LOGTAG,
1488 "We should not show context menu when nothing is touched");
1489 return;
1490 }
1491 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1492 // let TextView handles context menu
1493 return;
1494 }
1495
1496 // Note, http://b/issue?id=1106666 is requesting that
1497 // an inflated menu can be used again. This is not available
1498 // yet, so inflate each time (yuk!)
1499 MenuInflater inflater = getMenuInflater();
1500 inflater.inflate(R.menu.browsercontext, menu);
1501
1502 // Show the correct menu group
1503 String extra = result.getExtra();
1504 menu.setGroupVisible(R.id.PHONE_MENU,
1505 type == WebView.HitTestResult.PHONE_TYPE);
1506 menu.setGroupVisible(R.id.EMAIL_MENU,
1507 type == WebView.HitTestResult.EMAIL_TYPE);
1508 menu.setGroupVisible(R.id.GEO_MENU,
1509 type == WebView.HitTestResult.GEO_TYPE);
1510 menu.setGroupVisible(R.id.IMAGE_MENU,
1511 type == WebView.HitTestResult.IMAGE_TYPE
1512 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1513 menu.setGroupVisible(R.id.ANCHOR_MENU,
1514 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1515 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1516
1517 // Setup custom handling depending on the type
1518 switch (type) {
1519 case WebView.HitTestResult.PHONE_TYPE:
1520 menu.setHeaderTitle(Uri.decode(extra));
1521 menu.findItem(R.id.dial_context_menu_id).setIntent(
1522 new Intent(Intent.ACTION_VIEW, Uri
1523 .parse(WebView.SCHEME_TEL + extra)));
1524 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1525 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1526 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1527 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1528 addIntent);
1529 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1530 new Copy(extra));
1531 break;
1532
1533 case WebView.HitTestResult.EMAIL_TYPE:
1534 menu.setHeaderTitle(extra);
1535 menu.findItem(R.id.email_context_menu_id).setIntent(
1536 new Intent(Intent.ACTION_VIEW, Uri
1537 .parse(WebView.SCHEME_MAILTO + extra)));
1538 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1539 new Copy(extra));
1540 break;
1541
1542 case WebView.HitTestResult.GEO_TYPE:
1543 menu.setHeaderTitle(extra);
1544 menu.findItem(R.id.map_context_menu_id).setIntent(
1545 new Intent(Intent.ACTION_VIEW, Uri
1546 .parse(WebView.SCHEME_GEO
1547 + URLEncoder.encode(extra))));
1548 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1549 new Copy(extra));
1550 break;
1551
1552 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1553 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1554 TextView titleView = (TextView) LayoutInflater.from(this)
1555 .inflate(android.R.layout.browser_link_context_header,
1556 null);
1557 titleView.setText(extra);
1558 menu.setHeaderView(titleView);
1559 // decide whether to show the open link in new tab option
1560 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1561 mTabControl.getTabCount() < TabControl.MAX_TABS);
1562 PackageManager pm = getPackageManager();
1563 Intent send = new Intent(Intent.ACTION_SEND);
1564 send.setType("text/plain");
1565 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1566 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1567 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1568 break;
1569 }
1570 // otherwise fall through to handle image part
1571 case WebView.HitTestResult.IMAGE_TYPE:
1572 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1573 menu.setHeaderTitle(extra);
1574 }
1575 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1576 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1577 menu.findItem(R.id.download_context_menu_id).
1578 setOnMenuItemClickListener(new Download(extra));
1579 break;
1580
1581 default:
1582 Log.w(LOGTAG, "We should not get here.");
1583 break;
1584 }
1585 }
1586
The Android Open Source Project0c908882009-03-03 19:32:16 -08001587 // Attach the given tab to the content view.
1588 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001589 // Attach the container that contains the main WebView and any other UI
1590 // associated with the tab.
1591 mContentView.addView(t.getContainer(), COVER_SCREEN_PARAMS);
Ben Murdochbff2d602009-07-01 20:19:05 +01001592
1593 if (mShouldShowErrorConsole) {
1594 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1595 if (errorConsole.numberOfErrors() == 0) {
1596 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1597 } else {
1598 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1599 }
1600
1601 mErrorConsoleContainer.addView(errorConsole,
1602 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1603 ViewGroup.LayoutParams.WRAP_CONTENT));
1604 }
1605
The Android Open Source Project0c908882009-03-03 19:32:16 -08001606 // Attach the sub window if necessary
1607 attachSubWindow(t);
1608 // Request focus on the top window.
1609 t.getTopWindow().requestFocus();
1610 }
1611
1612 // Attach a sub window to the main WebView of the given tab.
1613 private void attachSubWindow(TabControl.Tab t) {
1614 // If a sub window exists, attach it to the content view.
1615 final WebView subView = t.getSubWebView();
1616 if (subView != null) {
1617 final View container = t.getSubWebViewContainer();
1618 mContentView.addView(container, COVER_SCREEN_PARAMS);
1619 subView.requestFocus();
1620 }
1621 }
1622
1623 // Remove the given tab from the content view.
1624 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001625 // Remove the container that contains the main WebView.
1626 mContentView.removeView(t.getContainer());
Ben Murdochbff2d602009-07-01 20:19:05 +01001627
1628 if (mTabControl.getCurrentErrorConsole(false) != null) {
1629 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1630 }
1631
The Android Open Source Project0c908882009-03-03 19:32:16 -08001632 // Remove the sub window if it exists.
1633 if (t.getSubWebView() != null) {
1634 mContentView.removeView(t.getSubWebViewContainer());
1635 }
1636 }
1637
1638 // Remove the sub window if it exists. Also called by TabControl when the
1639 // user clicks the 'X' to dismiss a sub window.
1640 /* package */ void dismissSubWindow(TabControl.Tab t) {
1641 final WebView mainView = t.getWebView();
1642 if (t.getSubWebView() != null) {
1643 // Remove the container view and request focus on the main WebView.
1644 mContentView.removeView(t.getSubWebViewContainer());
1645 mainView.requestFocus();
1646 // Tell the TabControl to dismiss the subwindow. This will destroy
1647 // the WebView.
1648 mTabControl.dismissSubWindow(t);
1649 }
1650 }
1651
Leon Scroggins1f005d32009-08-10 17:36:42 -04001652 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001653 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001654 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1655 String appId) {
1656 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001657 }
1658
1659 // This method does a ton of stuff. It will attempt to create a new tab
1660 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001661 // url isn't null, it will load the given url.
1662 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001663 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001664 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1665 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1666 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001667 final TabControl.Tab tab = mTabControl.createNewTab(
1668 closeOnExit, appId, urlData.mUrl);
1669 WebView webview = tab.getWebView();
1670 if (CUSTOM_BROWSER_BAR) {
1671 mTitleBar.addTab(webview, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001672 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001673 removeTabFromContentView(currentTab);
1674 attachTabToContentView(tab);
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001675 // We must set the new tab as the current tab to reflect the old
1676 // animation behavior.
1677 mTabControl.setCurrentTab(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001678 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001679 urlData.loadIn(webview);
1680 }
1681 return tab;
1682 } else {
1683 // Get rid of the subwindow if it exists
1684 dismissSubWindow(currentTab);
1685 if (!urlData.isEmpty()) {
1686 // Load the given url.
1687 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001688 }
1689 }
Grace Klobac9181842009-04-14 08:53:22 -07001690 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001691 }
1692
Grace Klobac9181842009-04-14 08:53:22 -07001693 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001694 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001695 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001696 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001697 WebView view = t.getWebView();
1698 if (CUSTOM_BROWSER_BAR) {
1699 mTitleBar.addTab(view, false);
1700 }
1701 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001702 }
Grace Klobac9181842009-04-14 08:53:22 -07001703 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001704 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001705 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001706 }
1707 }
1708
1709 private class Copy implements OnMenuItemClickListener {
1710 private CharSequence mText;
1711
1712 public boolean onMenuItemClick(MenuItem item) {
1713 copy(mText);
1714 return true;
1715 }
1716
1717 public Copy(CharSequence toCopy) {
1718 mText = toCopy;
1719 }
1720 }
1721
1722 private class Download implements OnMenuItemClickListener {
1723 private String mText;
1724
1725 public boolean onMenuItemClick(MenuItem item) {
1726 onDownloadStartNoStream(mText, null, null, null, -1);
1727 return true;
1728 }
1729
1730 public Download(String toDownload) {
1731 mText = toDownload;
1732 }
1733 }
1734
1735 private void copy(CharSequence text) {
1736 try {
1737 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1738 if (clip != null) {
1739 clip.setClipboardText(text);
1740 }
1741 } catch (android.os.RemoteException e) {
1742 Log.e(LOGTAG, "Copy failed", e);
1743 }
1744 }
1745
1746 /**
1747 * Resets the browser title-view to whatever it must be (for example, if we
1748 * load a page from history).
1749 */
1750 private void resetTitle() {
1751 resetLockIcon();
1752 resetTitleIconAndProgress();
1753 }
1754
1755 /**
1756 * Resets the browser title-view to whatever it must be
1757 * (for example, if we had a loading error)
1758 * When we have a new page, we call resetTitle, when we
1759 * have to reset the titlebar to whatever it used to be
1760 * (for example, if the user chose to stop loading), we
1761 * call resetTitleAndRevertLockIcon.
1762 */
1763 /* package */ void resetTitleAndRevertLockIcon() {
1764 revertLockIcon();
1765 resetTitleIconAndProgress();
1766 }
1767
1768 /**
1769 * Reset the title, favicon, and progress.
1770 */
1771 private void resetTitleIconAndProgress() {
1772 WebView current = mTabControl.getCurrentWebView();
1773 if (current == null) {
1774 return;
1775 }
1776 resetTitleAndIcon(current);
1777 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001778 mWebChromeClient.onProgressChanged(current, progress);
1779 }
1780
1781 // Reset the title and the icon based on the given item.
1782 private void resetTitleAndIcon(WebView view) {
1783 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1784 if (item != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001785 setUrlTitle(item.getUrl(), item.getTitle(), view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001786 setFavicon(item.getFavicon());
1787 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001788 setUrlTitle(null, null, view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001789 setFavicon(null);
1790 }
1791 }
1792
1793 /**
1794 * Sets a title composed of the URL and the title string.
1795 * @param url The URL of the site being loaded.
1796 * @param title The title of the site being loaded.
1797 */
Leon Scroggins1f005d32009-08-10 17:36:42 -04001798 private void setUrlTitle(String url, String title, WebView view) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001799 mUrl = url;
1800 mTitle = title;
1801
Leon Scroggins1f005d32009-08-10 17:36:42 -04001802 if (CUSTOM_BROWSER_BAR) {
1803 mTitleBar.setTitleAndUrl(title, url, view);
1804 } else {
1805 setTitle(buildUrlTitle(url, title));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001806 }
1807 }
1808
1809 /**
1810 * Builds and returns the page title, which is some
1811 * combination of the page URL and title.
1812 * @param url The URL of the site being loaded.
1813 * @param title The title of the site being loaded.
1814 * @return The page title.
1815 */
1816 private String buildUrlTitle(String url, String title) {
1817 String urlTitle = "";
1818
1819 if (url != null) {
1820 String titleUrl = buildTitleUrl(url);
1821
1822 if (title != null && 0 < title.length()) {
1823 if (titleUrl != null && 0 < titleUrl.length()) {
1824 urlTitle = titleUrl + ": " + title;
1825 } else {
1826 urlTitle = title;
1827 }
1828 } else {
1829 if (titleUrl != null) {
1830 urlTitle = titleUrl;
1831 }
1832 }
1833 }
1834
1835 return urlTitle;
1836 }
1837
1838 /**
1839 * @param url The URL to build a title version of the URL from.
1840 * @return The title version of the URL or null if fails.
1841 * The title version of the URL can be either the URL hostname,
1842 * or the hostname with an "https://" prefix (for secure URLs),
1843 * or an empty string if, for example, the URL in question is a
1844 * file:// URL with no hostname.
1845 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001846 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001847 String titleUrl = null;
1848
1849 if (url != null) {
1850 try {
1851 // parse the url string
1852 URL urlObj = new URL(url);
1853 if (urlObj != null) {
1854 titleUrl = "";
1855
1856 String protocol = urlObj.getProtocol();
1857 String host = urlObj.getHost();
1858
1859 if (host != null && 0 < host.length()) {
1860 titleUrl = host;
1861 if (protocol != null) {
1862 // if a secure site, add an "https://" prefix!
1863 if (protocol.equalsIgnoreCase("https")) {
1864 titleUrl = protocol + "://" + host;
1865 }
1866 }
1867 }
1868 }
1869 } catch (MalformedURLException e) {}
1870 }
1871
1872 return titleUrl;
1873 }
1874
1875 // Set the favicon in the title bar.
1876 private void setFavicon(Bitmap icon) {
Leon Scroggins81db3662009-06-04 17:45:11 -04001877 if (CUSTOM_BROWSER_BAR) {
1878 Drawable[] array = new Drawable[3];
1879 array[0] = new PaintDrawable(Color.BLACK);
1880 PaintDrawable p = new PaintDrawable(Color.WHITE);
1881 array[1] = p;
1882 if (icon == null) {
1883 array[2] = mGenericFavicon;
1884 } else {
1885 array[2] = new BitmapDrawable(icon);
1886 }
1887 LayerDrawable d = new LayerDrawable(array);
1888 d.setLayerInset(1, 1, 1, 1, 1);
1889 d.setLayerInset(2, 2, 2, 2, 2);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001890 mTitleBar.setFavicon(d, getTopWindow());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001891 } else {
Leon Scroggins81db3662009-06-04 17:45:11 -04001892 Drawable[] array = new Drawable[2];
1893 PaintDrawable p = new PaintDrawable(Color.WHITE);
1894 p.setCornerRadius(3f);
1895 array[0] = p;
1896 if (icon == null) {
1897 array[1] = mGenericFavicon;
1898 } else {
1899 array[1] = new BitmapDrawable(icon);
1900 }
1901 LayerDrawable d = new LayerDrawable(array);
1902 d.setLayerInset(1, 2, 2, 2, 2);
1903 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001904 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001905 }
1906
1907 /**
1908 * Saves the current lock-icon state before resetting
1909 * the lock icon. If we have an error, we may need to
1910 * roll back to the previous state.
1911 */
1912 private void saveLockIcon() {
1913 mPrevLockType = mLockIconType;
1914 }
1915
1916 /**
1917 * Reverts the lock-icon state to the last saved state,
1918 * for example, if we had an error, and need to cancel
1919 * the load.
1920 */
1921 private void revertLockIcon() {
1922 mLockIconType = mPrevLockType;
1923
Dave Bort31a6d1c2009-04-13 15:56:49 -07001924 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001925 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
1926 " revert lock icon to " + mLockIconType);
1927 }
1928
1929 updateLockIconImage(mLockIconType);
1930 }
1931
Leon Scroggins1f005d32009-08-10 17:36:42 -04001932 /**
1933 * Close the tab after removing its associated title bar.
1934 */
1935 private void closeTab(TabControl.Tab t) {
1936 mTitleBar.removeTab(mTabControl.getTabIndex(t));
1937 mTabControl.removeTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001938 }
1939
1940 private void goBackOnePageOrQuit() {
1941 TabControl.Tab current = mTabControl.getCurrentTab();
1942 if (current == null) {
1943 /*
1944 * Instead of finishing the activity, simply push this to the back
1945 * of the stack and let ActivityManager to choose the foreground
1946 * activity. As BrowserActivity is singleTask, it will be always the
1947 * root of the task. So we can use either true or false for
1948 * moveTaskToBack().
1949 */
1950 moveTaskToBack(true);
1951 }
1952 WebView w = current.getWebView();
1953 if (w.canGoBack()) {
1954 w.goBack();
1955 } else {
1956 // Check to see if we are closing a window that was created by
1957 // another window. If so, we switch back to that window.
1958 TabControl.Tab parent = current.getParentTab();
1959 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001960 switchToTab(mTabControl.getTabIndex(parent));
1961 // Now we close the other tab
1962 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001963 } else {
1964 if (current.closeOnExit()) {
1965 if (mTabControl.getTabCount() == 1) {
1966 finish();
1967 return;
1968 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04001969 // call pauseWebViewTimers() now, we won't be able to call
1970 // it in onPause() as the WebView won't be valid.
1971 pauseWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001972 removeTabFromContentView(current);
1973 mTabControl.removeTab(current);
1974 }
1975 /*
1976 * Instead of finishing the activity, simply push this to the back
1977 * of the stack and let ActivityManager to choose the foreground
1978 * activity. As BrowserActivity is singleTask, it will be always the
1979 * root of the task. So we can use either true or false for
1980 * moveTaskToBack().
1981 */
1982 moveTaskToBack(true);
1983 }
1984 }
1985 }
1986
1987 public KeyTracker.State onKeyTracker(int keyCode,
1988 KeyEvent event,
1989 KeyTracker.Stage stage,
1990 int duration) {
1991 // if onKeyTracker() is called after activity onStop()
1992 // because of accumulated key events,
1993 // we should ignore it as browser is not active any more.
1994 WebView topWindow = getTopWindow();
Andrei Popescuadc008d2009-06-26 14:11:30 +01001995 if (topWindow == null && mCustomView == null)
The Android Open Source Project0c908882009-03-03 19:32:16 -08001996 return KeyTracker.State.NOT_TRACKING;
1997
1998 if (keyCode == KeyEvent.KEYCODE_BACK) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01001999 // Check if a custom view is currently showing and, if it is, hide it.
2000 if (mCustomView != null) {
2001 mWebChromeClient.onHideCustomView();
2002 return KeyTracker.State.DONE_TRACKING;
2003 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002004 if (stage == KeyTracker.Stage.LONG_REPEAT) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04002005 bookmarksOrHistoryPicker(true, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002006 return KeyTracker.State.DONE_TRACKING;
2007 } else if (stage == KeyTracker.Stage.UP) {
2008 // FIXME: Currently, we do not have a notion of the
2009 // history picker for the subwindow, but maybe we
2010 // should?
2011 WebView subwindow = mTabControl.getCurrentSubWindow();
2012 if (subwindow != null) {
2013 if (subwindow.canGoBack()) {
2014 subwindow.goBack();
2015 } else {
2016 dismissSubWindow(mTabControl.getCurrentTab());
2017 }
2018 } else {
2019 goBackOnePageOrQuit();
2020 }
2021 return KeyTracker.State.DONE_TRACKING;
2022 }
2023 return KeyTracker.State.KEEP_TRACKING;
2024 }
2025 return KeyTracker.State.NOT_TRACKING;
2026 }
2027
2028 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2029 if (keyCode == KeyEvent.KEYCODE_MENU) {
2030 mMenuIsDown = true;
Grace Kloba6ee9c492009-07-13 10:04:34 -07002031 } else if (mMenuIsDown) {
2032 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2033 // still down, we don't want to trigger the search. Pretend to
2034 // consume the key and do nothing.
2035 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002036 }
2037 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2038 if (!handled) {
2039 switch (keyCode) {
2040 case KeyEvent.KEYCODE_SPACE:
2041 if (event.isShiftPressed()) {
2042 getTopWindow().pageUp(false);
2043 } else {
2044 getTopWindow().pageDown(false);
2045 }
2046 handled = true;
2047 break;
2048
2049 default:
2050 break;
2051 }
2052 }
2053 return handled || super.onKeyDown(keyCode, event);
2054 }
2055
2056 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2057 if (keyCode == KeyEvent.KEYCODE_MENU) {
2058 mMenuIsDown = false;
2059 }
2060 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2061 }
2062
2063 private void stopLoading() {
2064 resetTitleAndRevertLockIcon();
2065 WebView w = getTopWindow();
2066 w.stopLoading();
2067 mWebViewClient.onPageFinished(w, w.getUrl());
2068
2069 cancelStopToast();
2070 mStopToast = Toast
2071 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2072 mStopToast.show();
2073 }
2074
2075 private void cancelStopToast() {
2076 if (mStopToast != null) {
2077 mStopToast.cancel();
2078 mStopToast = null;
2079 }
2080 }
2081
2082 // called by a non-UI thread to post the message
2083 public void postMessage(int what, int arg1, int arg2, Object obj) {
2084 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2085 }
2086
2087 // public message ids
2088 public final static int LOAD_URL = 1001;
2089 public final static int STOP_LOAD = 1002;
2090
2091 // Message Ids
2092 private static final int FOCUS_NODE_HREF = 102;
2093 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002094 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002095
2096 // Private handler for handling javascript and saving passwords
2097 private Handler mHandler = new Handler() {
2098
2099 public void handleMessage(Message msg) {
2100 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002101 case FOCUS_NODE_HREF:
2102 String url = (String) msg.getData().get("url");
2103 if (url == null || url.length() == 0) {
2104 break;
2105 }
2106 HashMap focusNodeMap = (HashMap) msg.obj;
2107 WebView view = (WebView) focusNodeMap.get("webview");
2108 // Only apply the action if the top window did not change.
2109 if (getTopWindow() != view) {
2110 break;
2111 }
2112 switch (msg.arg1) {
2113 case R.id.open_context_menu_id:
2114 case R.id.view_image_context_menu_id:
2115 loadURL(getTopWindow(), url);
2116 break;
2117 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002118 final TabControl.Tab parent = mTabControl
2119 .getCurrentTab();
2120 final TabControl.Tab newTab = openTab(url);
2121 if (newTab != parent) {
2122 parent.addChildTab(newTab);
2123 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002124 break;
2125 case R.id.bookmark_context_menu_id:
2126 Intent intent = new Intent(BrowserActivity.this,
2127 AddBookmarkPage.class);
2128 intent.putExtra("url", url);
2129 startActivity(intent);
2130 break;
2131 case R.id.share_link_context_menu_id:
2132 Browser.sendString(BrowserActivity.this, url);
2133 break;
2134 case R.id.copy_link_context_menu_id:
2135 copy(url);
2136 break;
2137 case R.id.save_link_context_menu_id:
2138 case R.id.download_context_menu_id:
2139 onDownloadStartNoStream(url, null, null, null, -1);
2140 break;
2141 }
2142 break;
2143
2144 case LOAD_URL:
2145 loadURL(getTopWindow(), (String) msg.obj);
2146 break;
2147
2148 case STOP_LOAD:
2149 stopLoading();
2150 break;
2151
2152 case CANCEL_CREDS_REQUEST:
2153 resumeAfterCredentials();
2154 break;
2155
The Android Open Source Project0c908882009-03-03 19:32:16 -08002156 case RELEASE_WAKELOCK:
2157 if (mWakeLock.isHeld()) {
2158 mWakeLock.release();
2159 }
2160 break;
2161 }
2162 }
2163 };
2164
Leon Scroggins89c6d362009-07-15 16:54:37 -04002165 private void updateScreenshot(WebView view) {
2166 // If this is a bookmarked site, add a screenshot to the database.
2167 // FIXME: When should we update? Every time?
2168 // FIXME: Would like to make sure there is actually something to
2169 // draw, but the API for that (WebViewCore.pictureReady()) is not
2170 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002171 ContentResolver cr = getContentResolver();
2172 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002173 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002174 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002175 boolean succeed = c.moveToFirst();
2176 ContentValues values = null;
2177 while (succeed) {
2178 if (values == null) {
2179 final ByteArrayOutputStream os
2180 = new ByteArrayOutputStream();
2181 Picture thumbnail = view.capturePicture();
2182 // Keep width and height in sync with BrowserBookmarksPage
2183 // and bookmark_thumb
2184 Bitmap bm = Bitmap.createBitmap(100, 80,
2185 Bitmap.Config.ARGB_4444);
2186 Canvas canvas = new Canvas(bm);
2187 // May need to tweak these values to determine what is the
2188 // best scale factor
2189 canvas.scale(.5f, .5f);
2190 thumbnail.draw(canvas);
2191 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2192 values = new ContentValues();
2193 values.put(Browser.BookmarkColumns.THUMBNAIL,
2194 os.toByteArray());
2195 }
2196 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2197 c.getInt(0)), values, null, null);
2198 succeed = c.moveToNext();
2199 }
2200 c.close();
2201 }
2202 }
2203
The Android Open Source Project0c908882009-03-03 19:32:16 -08002204 // -------------------------------------------------------------------------
2205 // WebViewClient implementation.
2206 //-------------------------------------------------------------------------
2207
2208 // Use in overrideUrlLoading
2209 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2210 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2211 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2212 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2213
2214 /* package */ WebViewClient getWebViewClient() {
2215 return mWebViewClient;
2216 }
2217
Patrick Scott3918d442009-08-04 13:22:29 -04002218 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002219 if (icon != null) {
2220 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott3918d442009-08-04 13:22:29 -04002221 view, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002222 }
2223 setFavicon(icon);
2224 }
2225
2226 private final WebViewClient mWebViewClient = new WebViewClient() {
2227 @Override
2228 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2229 resetLockIcon(url);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002230 setUrlTitle(url, null, view);
Ben Murdochbff2d602009-07-01 20:19:05 +01002231
2232 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2233 if (errorConsole != null) {
2234 errorConsole.clearErrorMessages();
2235 if (mShouldShowErrorConsole) {
2236 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2237 }
2238 }
2239
The Android Open Source Project0c908882009-03-03 19:32:16 -08002240 // Call updateIcon instead of setFavicon so the bookmark
2241 // database can be updated.
Patrick Scott3918d442009-08-04 13:22:29 -04002242 updateIcon(view, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002243
Grace Kloba4d7880f2009-08-12 09:35:42 -07002244 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002245 String host;
2246 try {
2247 WebAddress uri = new WebAddress(url);
2248 host = uri.mHost;
2249 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002250 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002251 }
2252 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002253 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002254 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002255 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002256 }
2257
2258 // Performance probe
2259 if (false) {
2260 mStart = SystemClock.uptimeMillis();
2261 mProcessStart = Process.getElapsedCpuTime();
2262 long[] sysCpu = new long[7];
2263 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2264 sysCpu, null)) {
2265 mUserStart = sysCpu[0] + sysCpu[1];
2266 mSystemStart = sysCpu[2];
2267 mIdleStart = sysCpu[3];
2268 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2269 }
2270 mUiStart = SystemClock.currentThreadTimeMillis();
2271 }
2272
2273 if (!mPageStarted) {
2274 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002275 // if onResume() has been called, resumeWebViewTimers() does
2276 // nothing.
2277 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002278 }
2279
2280 // reset sync timer to avoid sync starts during loading a page
2281 CookieSyncManager.getInstance().resetSync();
2282
2283 mInLoad = true;
2284 updateInLoadMenuItems();
2285 if (!mIsNetworkUp) {
2286 if ( mAlertDialog == null) {
2287 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2288 .setTitle(R.string.loadSuspendedTitle)
2289 .setMessage(R.string.loadSuspended)
2290 .setPositiveButton(R.string.ok, null)
2291 .show();
2292 }
2293 if (view != null) {
2294 view.setNetworkAvailable(false);
2295 }
2296 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002297 }
2298
2299 @Override
2300 public void onPageFinished(WebView view, String url) {
2301 // Reset the title and icon in case we stopped a provisional
2302 // load.
2303 resetTitleAndIcon(view);
2304
2305 // Update the lock icon image only once we are done loading
2306 updateLockIconImage(mLockIconType);
Leon Scroggins89c6d362009-07-15 16:54:37 -04002307 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002308
The Android Open Source Project0c908882009-03-03 19:32:16 -08002309 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002310 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002311 long[] sysCpu = new long[7];
2312 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2313 sysCpu, null)) {
2314 String uiInfo = "UI thread used "
2315 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2316 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002317 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002318 Log.d(LOGTAG, uiInfo);
2319 }
2320 //The string that gets written to the log
2321 String performanceString = "It took total "
2322 + (SystemClock.uptimeMillis() - mStart)
2323 + " ms clock time to load the page."
2324 + "\nbrowser process used "
2325 + (Process.getElapsedCpuTime() - mProcessStart)
2326 + " ms, user processes used "
2327 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2328 + " ms, kernel used "
2329 + (sysCpu[2] - mSystemStart) * 10
2330 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2331 + " ms and irq took "
2332 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2333 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002334 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002335 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2336 }
2337 if (url != null) {
2338 // strip the url to maintain consistency
2339 String newUrl = new String(url);
2340 if (newUrl.startsWith("http://www.")) {
2341 newUrl = newUrl.substring(11);
2342 } else if (newUrl.startsWith("http://")) {
2343 newUrl = newUrl.substring(7);
2344 } else if (newUrl.startsWith("https://www.")) {
2345 newUrl = newUrl.substring(12);
2346 } else if (newUrl.startsWith("https://")) {
2347 newUrl = newUrl.substring(8);
2348 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002349 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002350 Log.d(LOGTAG, newUrl + " loaded");
2351 }
2352 /*
2353 if (sWhiteList.contains(newUrl)) {
2354 // The string that gets pushed to the statistcs
2355 // service
2356 performanceString = performanceString
2357 + "\nWebpage: "
2358 + newUrl
2359 + "\nCarrier: "
2360 + android.os.SystemProperties
2361 .get("gsm.sim.operator.alpha");
2362 if (mWebView != null
2363 && mWebView.getContext() != null
2364 && mWebView.getContext().getSystemService(
2365 Context.CONNECTIVITY_SERVICE) != null) {
2366 ConnectivityManager cManager =
2367 (ConnectivityManager) mWebView
2368 .getContext().getSystemService(
2369 Context.CONNECTIVITY_SERVICE);
2370 NetworkInfo nInfo = cManager
2371 .getActiveNetworkInfo();
2372 if (nInfo != null) {
2373 performanceString = performanceString
2374 + "\nNetwork Type: "
2375 + nInfo.getType().toString();
2376 }
2377 }
2378 Checkin.logEvent(mResolver,
2379 Checkin.Events.Tag.WEBPAGE_LOAD,
2380 performanceString);
2381 Log.w(LOGTAG, "pushed to the statistics service");
2382 }
2383 */
2384 }
2385 }
2386 }
2387
2388 if (mInTrace) {
2389 mInTrace = false;
2390 Debug.stopMethodTracing();
2391 }
2392
2393 if (mPageStarted) {
2394 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002395 // pauseWebViewTimers() will do nothing and return false if
2396 // onPause() is not called yet.
2397 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002398 if (mWakeLock.isHeld()) {
2399 mHandler.removeMessages(RELEASE_WAKELOCK);
2400 mWakeLock.release();
2401 }
2402 }
2403 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002404 }
2405
2406 // return true if want to hijack the url to let another app to handle it
2407 @Override
2408 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2409 if (url.startsWith(SCHEME_WTAI)) {
2410 // wtai://wp/mc;number
2411 // number=string(phone-number)
2412 if (url.startsWith(SCHEME_WTAI_MC)) {
2413 Intent intent = new Intent(Intent.ACTION_VIEW,
2414 Uri.parse(WebView.SCHEME_TEL +
2415 url.substring(SCHEME_WTAI_MC.length())));
2416 startActivity(intent);
2417 return true;
2418 }
2419 // wtai://wp/sd;dtmf
2420 // dtmf=string(dialstring)
2421 if (url.startsWith(SCHEME_WTAI_SD)) {
2422 // TODO
2423 // only send when there is active voice connection
2424 return false;
2425 }
2426 // wtai://wp/ap;number;name
2427 // number=string(phone-number)
2428 // name=string
2429 if (url.startsWith(SCHEME_WTAI_AP)) {
2430 // TODO
2431 return false;
2432 }
2433 }
2434
Dianne Hackborn99189432009-06-17 18:06:18 -07002435 // The "about:" schemes are internal to the browser; don't
2436 // want these to be dispatched to other apps.
2437 if (url.startsWith("about:")) {
2438 return false;
2439 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002440
Dianne Hackborn99189432009-06-17 18:06:18 -07002441 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002442
Dianne Hackborn99189432009-06-17 18:06:18 -07002443 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002444 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002445 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2446 } catch (URISyntaxException ex) {
2447 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002448 return false;
2449 }
2450
Grace Kloba5b078b52009-06-24 20:23:41 -07002451 // check whether the intent can be resolved. If not, we will see
2452 // whether we can download it from the Market.
2453 if (getPackageManager().resolveActivity(intent, 0) == null) {
2454 String packagename = intent.getPackage();
2455 if (packagename != null) {
2456 intent = new Intent(Intent.ACTION_VIEW, Uri
2457 .parse("market://search?q=pname:" + packagename));
2458 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2459 startActivity(intent);
2460 return true;
2461 } else {
2462 return false;
2463 }
2464 }
2465
Dianne Hackborn99189432009-06-17 18:06:18 -07002466 // sanitize the Intent, ensuring web pages can not bypass browser
2467 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002468 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002469 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002470 try {
2471 if (startActivityIfNeeded(intent, -1)) {
2472 return true;
2473 }
2474 } catch (ActivityNotFoundException ex) {
2475 // ignore the error. If no application can handle the URL,
2476 // eg about:blank, assume the browser can handle it.
2477 }
2478
2479 if (mMenuIsDown) {
2480 openTab(url);
2481 closeOptionsMenu();
2482 return true;
2483 }
2484
2485 return false;
2486 }
2487
2488 /**
2489 * Updates the lock icon. This method is called when we discover another
2490 * resource to be loaded for this page (for example, javascript). While
2491 * we update the icon type, we do not update the lock icon itself until
2492 * we are done loading, it is slightly more secure this way.
2493 */
2494 @Override
2495 public void onLoadResource(WebView view, String url) {
2496 if (url != null && url.length() > 0) {
2497 // It is only if the page claims to be secure
2498 // that we may have to update the lock:
2499 if (mLockIconType == LOCK_ICON_SECURE) {
2500 // If NOT a 'safe' url, change the lock to mixed content!
2501 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2502 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002503 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002504 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2505 " updated lock icon to " + mLockIconType + " due to " + url);
2506 }
2507 }
2508 }
2509 }
2510 }
2511
2512 /**
2513 * Show the dialog, asking the user if they would like to continue after
2514 * an excessive number of HTTP redirects.
2515 */
2516 @Override
2517 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2518 final Message continueMsg) {
2519 new AlertDialog.Builder(BrowserActivity.this)
2520 .setTitle(R.string.browserFrameRedirect)
2521 .setMessage(R.string.browserFrame307Post)
2522 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2523 public void onClick(DialogInterface dialog, int which) {
2524 continueMsg.sendToTarget();
2525 }})
2526 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2527 public void onClick(DialogInterface dialog, int which) {
2528 cancelMsg.sendToTarget();
2529 }})
2530 .setOnCancelListener(new OnCancelListener() {
2531 public void onCancel(DialogInterface dialog) {
2532 cancelMsg.sendToTarget();
2533 }})
2534 .show();
2535 }
2536
Patrick Scott37911c72009-03-24 18:02:58 -07002537 // Container class for the next error dialog that needs to be
2538 // displayed.
2539 class ErrorDialog {
2540 public final int mTitle;
2541 public final String mDescription;
2542 public final int mError;
2543 ErrorDialog(int title, String desc, int error) {
2544 mTitle = title;
2545 mDescription = desc;
2546 mError = error;
2547 }
2548 };
2549
2550 private void processNextError() {
2551 if (mQueuedErrors == null) {
2552 return;
2553 }
2554 // The first one is currently displayed so just remove it.
2555 mQueuedErrors.removeFirst();
2556 if (mQueuedErrors.size() == 0) {
2557 mQueuedErrors = null;
2558 return;
2559 }
2560 showError(mQueuedErrors.getFirst());
2561 }
2562
2563 private DialogInterface.OnDismissListener mDialogListener =
2564 new DialogInterface.OnDismissListener() {
2565 public void onDismiss(DialogInterface d) {
2566 processNextError();
2567 }
2568 };
2569 private LinkedList<ErrorDialog> mQueuedErrors;
2570
2571 private void queueError(int err, String desc) {
2572 if (mQueuedErrors == null) {
2573 mQueuedErrors = new LinkedList<ErrorDialog>();
2574 }
2575 for (ErrorDialog d : mQueuedErrors) {
2576 if (d.mError == err) {
2577 // Already saw a similar error, ignore the new one.
2578 return;
2579 }
2580 }
2581 ErrorDialog errDialog = new ErrorDialog(
2582 err == EventHandler.FILE_NOT_FOUND_ERROR ?
2583 R.string.browserFrameFileErrorLabel :
2584 R.string.browserFrameNetworkErrorLabel,
2585 desc, err);
2586 mQueuedErrors.addLast(errDialog);
2587
2588 // Show the dialog now if the queue was empty.
2589 if (mQueuedErrors.size() == 1) {
2590 showError(errDialog);
2591 }
2592 }
2593
2594 private void showError(ErrorDialog errDialog) {
2595 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2596 .setTitle(errDialog.mTitle)
2597 .setMessage(errDialog.mDescription)
2598 .setPositiveButton(R.string.ok, null)
2599 .create();
2600 d.setOnDismissListener(mDialogListener);
2601 d.show();
2602 }
2603
The Android Open Source Project0c908882009-03-03 19:32:16 -08002604 /**
2605 * Show a dialog informing the user of the network error reported by
2606 * WebCore.
2607 */
2608 @Override
2609 public void onReceivedError(WebView view, int errorCode,
2610 String description, String failingUrl) {
2611 if (errorCode != EventHandler.ERROR_LOOKUP &&
2612 errorCode != EventHandler.ERROR_CONNECT &&
2613 errorCode != EventHandler.ERROR_BAD_URL &&
2614 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
2615 errorCode != EventHandler.FILE_ERROR) {
Patrick Scott37911c72009-03-24 18:02:58 -07002616 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002617 }
Patrick Scott37911c72009-03-24 18:02:58 -07002618 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2619 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002620
2621 // We need to reset the title after an error.
2622 resetTitleAndRevertLockIcon();
2623 }
2624
2625 /**
2626 * Check with the user if it is ok to resend POST data as the page they
2627 * are trying to navigate to is the result of a POST.
2628 */
2629 @Override
2630 public void onFormResubmission(WebView view, final Message dontResend,
2631 final Message resend) {
2632 new AlertDialog.Builder(BrowserActivity.this)
2633 .setTitle(R.string.browserFrameFormResubmitLabel)
2634 .setMessage(R.string.browserFrameFormResubmitMessage)
2635 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2636 public void onClick(DialogInterface dialog, int which) {
2637 resend.sendToTarget();
2638 }})
2639 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2640 public void onClick(DialogInterface dialog, int which) {
2641 dontResend.sendToTarget();
2642 }})
2643 .setOnCancelListener(new OnCancelListener() {
2644 public void onCancel(DialogInterface dialog) {
2645 dontResend.sendToTarget();
2646 }})
2647 .show();
2648 }
2649
2650 /**
2651 * Insert the url into the visited history database.
2652 * @param url The url to be inserted.
2653 * @param isReload True if this url is being reloaded.
2654 * FIXME: Not sure what to do when reloading the page.
2655 */
2656 @Override
2657 public void doUpdateVisitedHistory(WebView view, String url,
2658 boolean isReload) {
2659 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2660 return;
2661 }
2662 Browser.updateVisitedHistory(mResolver, url, true);
2663 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2664 }
2665
2666 /**
2667 * Displays SSL error(s) dialog to the user.
2668 */
2669 @Override
2670 public void onReceivedSslError(
2671 final WebView view, final SslErrorHandler handler, final SslError error) {
2672
2673 if (mSettings.showSecurityWarnings()) {
2674 final LayoutInflater factory =
2675 LayoutInflater.from(BrowserActivity.this);
2676 final View warningsView =
2677 factory.inflate(R.layout.ssl_warnings, null);
2678 final LinearLayout placeholder =
2679 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2680
2681 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2682 LinearLayout ll = (LinearLayout)factory
2683 .inflate(R.layout.ssl_warning, null);
2684 ((TextView)ll.findViewById(R.id.warning))
2685 .setText(R.string.ssl_untrusted);
2686 placeholder.addView(ll);
2687 }
2688
2689 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2690 LinearLayout ll = (LinearLayout)factory
2691 .inflate(R.layout.ssl_warning, null);
2692 ((TextView)ll.findViewById(R.id.warning))
2693 .setText(R.string.ssl_mismatch);
2694 placeholder.addView(ll);
2695 }
2696
2697 if (error.hasError(SslError.SSL_EXPIRED)) {
2698 LinearLayout ll = (LinearLayout)factory
2699 .inflate(R.layout.ssl_warning, null);
2700 ((TextView)ll.findViewById(R.id.warning))
2701 .setText(R.string.ssl_expired);
2702 placeholder.addView(ll);
2703 }
2704
2705 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2706 LinearLayout ll = (LinearLayout)factory
2707 .inflate(R.layout.ssl_warning, null);
2708 ((TextView)ll.findViewById(R.id.warning))
2709 .setText(R.string.ssl_not_yet_valid);
2710 placeholder.addView(ll);
2711 }
2712
2713 new AlertDialog.Builder(BrowserActivity.this)
2714 .setTitle(R.string.security_warning)
2715 .setIcon(android.R.drawable.ic_dialog_alert)
2716 .setView(warningsView)
2717 .setPositiveButton(R.string.ssl_continue,
2718 new DialogInterface.OnClickListener() {
2719 public void onClick(DialogInterface dialog, int whichButton) {
2720 handler.proceed();
2721 }
2722 })
2723 .setNeutralButton(R.string.view_certificate,
2724 new DialogInterface.OnClickListener() {
2725 public void onClick(DialogInterface dialog, int whichButton) {
2726 showSSLCertificateOnError(view, handler, error);
2727 }
2728 })
2729 .setNegativeButton(R.string.cancel,
2730 new DialogInterface.OnClickListener() {
2731 public void onClick(DialogInterface dialog, int whichButton) {
2732 handler.cancel();
2733 BrowserActivity.this.resetTitleAndRevertLockIcon();
2734 }
2735 })
2736 .setOnCancelListener(
2737 new DialogInterface.OnCancelListener() {
2738 public void onCancel(DialogInterface dialog) {
2739 handler.cancel();
2740 BrowserActivity.this.resetTitleAndRevertLockIcon();
2741 }
2742 })
2743 .show();
2744 } else {
2745 handler.proceed();
2746 }
2747 }
2748
2749 /**
2750 * Handles an HTTP authentication request.
2751 *
2752 * @param handler The authentication handler
2753 * @param host The host
2754 * @param realm The realm
2755 */
2756 @Override
2757 public void onReceivedHttpAuthRequest(WebView view,
2758 final HttpAuthHandler handler, final String host, final String realm) {
2759 String username = null;
2760 String password = null;
2761
2762 boolean reuseHttpAuthUsernamePassword =
2763 handler.useHttpAuthUsernamePassword();
2764
2765 if (reuseHttpAuthUsernamePassword &&
2766 (mTabControl.getCurrentWebView() != null)) {
2767 String[] credentials =
2768 mTabControl.getCurrentWebView()
2769 .getHttpAuthUsernamePassword(host, realm);
2770 if (credentials != null && credentials.length == 2) {
2771 username = credentials[0];
2772 password = credentials[1];
2773 }
2774 }
2775
2776 if (username != null && password != null) {
2777 handler.proceed(username, password);
2778 } else {
2779 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2780 }
2781 }
2782
2783 @Override
2784 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2785 if (mMenuIsDown) {
2786 // only check shortcut key when MENU is held
2787 return getWindow().isShortcutKey(event.getKeyCode(), event);
2788 } else {
2789 return false;
2790 }
2791 }
2792
2793 @Override
2794 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2795 if (view != mTabControl.getCurrentTopWebView()) {
2796 return;
2797 }
2798 if (event.isDown()) {
2799 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2800 } else {
2801 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2802 }
2803 }
2804 };
2805
2806 //--------------------------------------------------------------------------
2807 // WebChromeClient implementation
2808 //--------------------------------------------------------------------------
2809
2810 /* package */ WebChromeClient getWebChromeClient() {
2811 return mWebChromeClient;
2812 }
2813
2814 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2815 // Helper method to create a new tab or sub window.
2816 private void createWindow(final boolean dialog, final Message msg) {
2817 if (dialog) {
2818 mTabControl.createSubWindow();
2819 final TabControl.Tab t = mTabControl.getCurrentTab();
2820 attachSubWindow(t);
2821 WebView.WebViewTransport transport =
2822 (WebView.WebViewTransport) msg.obj;
2823 transport.setWebView(t.getSubWebView());
2824 msg.sendToTarget();
2825 } else {
2826 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04002827 final TabControl.Tab newTab
2828 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07002829 if (newTab != parent) {
2830 parent.addChildTab(newTab);
2831 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002832 WebView.WebViewTransport transport =
2833 (WebView.WebViewTransport) msg.obj;
2834 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04002835 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002836 }
2837 }
2838
2839 @Override
Leon Scroggins4943a312009-08-07 16:12:57 -04002840 public void onChangeViewingMode(boolean toZoomedOut) {
2841 if (!CUSTOM_BROWSER_BAR) {
2842 return;
2843 }
2844 if (toZoomedOut) {
2845 // FIXME: animate the title bar into view
2846 mTitleBar.setVisibility(View.VISIBLE);
2847 } else {
2848 // FXIME: animate the title bar out of view
2849 mTitleBar.setVisibility(View.GONE);
2850 }
2851 }
2852
2853 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002854 public boolean onCreateWindow(WebView view, final boolean dialog,
2855 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002856 // Short-circuit if we can't create any more tabs or sub windows.
2857 if (dialog && mTabControl.getCurrentSubWindow() != null) {
2858 new AlertDialog.Builder(BrowserActivity.this)
2859 .setTitle(R.string.too_many_subwindows_dialog_title)
2860 .setIcon(android.R.drawable.ic_dialog_alert)
2861 .setMessage(R.string.too_many_subwindows_dialog_message)
2862 .setPositiveButton(R.string.ok, null)
2863 .show();
2864 return false;
2865 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
2866 new AlertDialog.Builder(BrowserActivity.this)
2867 .setTitle(R.string.too_many_windows_dialog_title)
2868 .setIcon(android.R.drawable.ic_dialog_alert)
2869 .setMessage(R.string.too_many_windows_dialog_message)
2870 .setPositiveButton(R.string.ok, null)
2871 .show();
2872 return false;
2873 }
2874
2875 // Short-circuit if this was a user gesture.
2876 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002877 createWindow(dialog, resultMsg);
2878 return true;
2879 }
2880
2881 // Allow the popup and create the appropriate window.
2882 final AlertDialog.OnClickListener allowListener =
2883 new AlertDialog.OnClickListener() {
2884 public void onClick(DialogInterface d,
2885 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002886 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002887 }
2888 };
2889
2890 // Block the popup by returning a null WebView.
2891 final AlertDialog.OnClickListener blockListener =
2892 new AlertDialog.OnClickListener() {
2893 public void onClick(DialogInterface d, int which) {
2894 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002895 }
2896 };
2897
2898 // Build a confirmation dialog to display to the user.
2899 final AlertDialog d =
2900 new AlertDialog.Builder(BrowserActivity.this)
2901 .setTitle(R.string.attention)
2902 .setIcon(android.R.drawable.ic_dialog_alert)
2903 .setMessage(R.string.popup_window_attempt)
2904 .setPositiveButton(R.string.allow, allowListener)
2905 .setNegativeButton(R.string.block, blockListener)
2906 .setCancelable(false)
2907 .create();
2908
2909 // Show the confirmation dialog.
2910 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002911 return true;
2912 }
2913
2914 @Override
2915 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002916 final TabControl.Tab current = mTabControl.getCurrentTab();
2917 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002918 if (parent != null) {
2919 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002920 switchToTab(mTabControl.getTabIndex(parent));
2921 // Now we need to close the window
2922 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002923 }
2924 }
2925
2926 @Override
2927 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002928 if (CUSTOM_BROWSER_BAR) {
2929 mTitleBar.setProgress(newProgress, view);
2930 } else {
2931 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
2932 newProgress * 100);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002933 }
2934
2935 if (newProgress == 100) {
2936 // onProgressChanged() is called for sub-frame too while
2937 // onPageFinished() is only called for the main frame. sync
2938 // cookie and cache promptly here.
2939 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002940 if (mInLoad) {
2941 mInLoad = false;
2942 updateInLoadMenuItems();
2943 }
2944 } else {
2945 // onPageFinished may have already been called but a subframe
2946 // is still loading and updating the progress. Reset mInLoad
2947 // and update the menu items.
2948 if (!mInLoad) {
2949 mInLoad = true;
2950 updateInLoadMenuItems();
2951 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002952 }
2953 }
2954
2955 @Override
2956 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04002957 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002958
2959 // here, if url is null, we want to reset the title
Leon Scroggins1f005d32009-08-10 17:36:42 -04002960 setUrlTitle(url, title, view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002961
2962 if (url == null ||
2963 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
2964 return;
2965 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04002966 // See if we can find the current url in our history database and
2967 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002968 if (url.startsWith("http://www.")) {
2969 url = url.substring(11);
2970 } else if (url.startsWith("http://")) {
2971 url = url.substring(4);
2972 }
2973 try {
2974 url = "%" + url;
2975 String [] selArgs = new String[] { url };
2976
2977 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
2978 + Browser.BookmarkColumns.BOOKMARK + " = 0";
2979 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2980 Browser.HISTORY_PROJECTION, where, selArgs, null);
2981 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002982 // Current implementation of database only has one entry per
2983 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04002984 ContentValues map = new ContentValues();
2985 map.put(Browser.BookmarkColumns.TITLE, title);
2986 mResolver.update(Browser.BOOKMARKS_URI, map,
2987 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002988 }
2989 c.close();
2990 } catch (IllegalStateException e) {
2991 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
2992 } catch (SQLiteException ex) {
2993 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
2994 }
2995 }
2996
2997 @Override
2998 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04002999 updateIcon(view, icon);
3000 }
3001
3002 @Override
3003 public void onReceivedTouchIconUrl(WebView view, String url) {
3004 final ContentResolver cr = getContentResolver();
3005 final Cursor c =
3006 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003007 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003008 if (c != null) {
3009 if (c.getCount() > 0) {
3010 new DownloadTouchIcon(cr, c, view).execute(url);
3011 } else {
3012 c.close();
3013 }
3014 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003015 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003016
Andrei Popescuadc008d2009-06-26 14:11:30 +01003017 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003018 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003019 if (mCustomView != null)
3020 return;
3021
3022 // Add the custom view to its container.
3023 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3024 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003025 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003026 // Save the menu state and set it to empty while the custom
3027 // view is showing.
3028 mOldMenuState = mMenuState;
3029 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003030 // Hide the content view.
3031 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003032 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003033 mCustomViewContainer.setVisibility(View.VISIBLE);
3034 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003035 }
3036
3037 @Override
3038 public void onHideCustomView() {
3039 if (mCustomView == null)
3040 return;
3041
Andrei Popescuc9b55562009-07-07 10:51:15 +01003042 // Hide the custom view.
3043 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003044 // Remove the custom view from its container.
3045 mCustomViewContainer.removeView(mCustomView);
3046 mCustomView = null;
3047 // Reset the old menu state.
3048 mMenuState = mOldMenuState;
3049 mOldMenuState = EMPTY_MENU;
3050 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003051 mCustomViewCallback.onCustomViewHidden();
3052 // Show the content view.
3053 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003054 }
3055
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003056 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003057 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003058 * @param url the URL that exceeded the quota
3059 * @param databaseIdentifier the identifier of the database on
3060 * which the transaction that caused the quota overflow was run
3061 * @param currentQuota the current quota for the origin.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003062 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003063 * @param quotaUpdater The callback to run when a decision to allow or
3064 * deny quota has been made. Don't forget to call this!
3065 */
3066 @Override
3067 public void onExceededDatabaseQuota(String url,
Andrei Popescu79e82b72009-07-27 12:01:59 +01003068 String databaseIdentifier, long currentQuota, long totalUsedQuota,
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003069 WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003070 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
3071 url, databaseIdentifier, currentQuota, totalUsedQuota,
3072 quotaUpdater);
3073 }
3074
3075 /**
3076 * The Application Cache has exceeded its max size.
3077 * @param spaceNeeded is the amount of disk space that would be needed
3078 * in order for the last appcache operation to succeed.
3079 * @param totalUsedQuota is the sum of all origins' quota.
3080 * @param quotaUpdater A callback to inform the WebCore thread that a new
3081 * app cache size is available. This callback must always be executed at
3082 * some point to ensure that the sleeping WebCore thread is woken up.
3083 */
3084 @Override
3085 public void onReachedMaxAppCacheSize(long spaceNeeded,
3086 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3087 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3088 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003089 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003090
Steve Block2bc69912009-07-30 14:45:13 +01003091 /**
3092 * Instructs the browser to show a prompt to ask the user to set the
3093 * Geolocation permission state for the specified origin.
3094 * @param origin The origin for which Geolocation permissions are
3095 * requested.
3096 * @param callback The callback to call once the user has set the
3097 * Geolocation permission state.
3098 */
3099 @Override
3100 public void onGeolocationPermissionsShowPrompt(String origin,
3101 GeolocationPermissions.Callback callback) {
3102 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3103 origin, callback);
3104 }
3105
3106 /**
3107 * Instructs the browser to hide the Geolocation permissions prompt.
3108 */
3109 @Override
3110 public void onGeolocationPermissionsHidePrompt() {
3111 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3112 }
3113
Ben Murdoch7db26342009-06-03 18:21:19 +01003114 /* Adds a JavaScript error message to the system log.
3115 * @param message The error message to report.
3116 * @param lineNumber The line number of the error.
3117 * @param sourceID The name of the source file that caused the error.
3118 */
3119 @Override
3120 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003121 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3122 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3123 if (mShouldShowErrorConsole &&
3124 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3125 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3126 }
3127 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003128 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003129 };
3130
3131 /**
3132 * Notify the host application a download should be done, or that
3133 * the data should be streamed if a streaming viewer is available.
3134 * @param url The full url to the content that should be downloaded
3135 * @param contentDisposition Content-disposition http header, if
3136 * present.
3137 * @param mimetype The mimetype of the content reported by the server
3138 * @param contentLength The file size reported by the server
3139 */
3140 public void onDownloadStart(String url, String userAgent,
3141 String contentDisposition, String mimetype, long contentLength) {
3142 // if we're dealing wih A/V content that's not explicitly marked
3143 // for download, check if it's streamable.
3144 if (contentDisposition == null
3145 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3146 // query the package manager to see if there's a registered handler
3147 // that matches.
3148 Intent intent = new Intent(Intent.ACTION_VIEW);
3149 intent.setDataAndType(Uri.parse(url), mimetype);
3150 if (getPackageManager().resolveActivity(intent,
3151 PackageManager.MATCH_DEFAULT_ONLY) != null) {
3152 // someone knows how to handle this mime type with this scheme, don't download.
3153 try {
3154 startActivity(intent);
3155 return;
3156 } catch (ActivityNotFoundException ex) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07003157 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003158 Log.d(LOGTAG, "activity not found for " + mimetype
3159 + " over " + Uri.parse(url).getScheme(), ex);
3160 }
3161 // Best behavior is to fall back to a download in this case
3162 }
3163 }
3164 }
3165 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3166 }
3167
3168 /**
3169 * Notify the host application a download should be done, even if there
3170 * is a streaming viewer available for thise type.
3171 * @param url The full url to the content that should be downloaded
3172 * @param contentDisposition Content-disposition http header, if
3173 * present.
3174 * @param mimetype The mimetype of the content reported by the server
3175 * @param contentLength The file size reported by the server
3176 */
3177 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3178 String contentDisposition, String mimetype, long contentLength) {
3179
3180 String filename = URLUtil.guessFileName(url,
3181 contentDisposition, mimetype);
3182
3183 // Check to see if we have an SDCard
3184 String status = Environment.getExternalStorageState();
3185 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3186 int title;
3187 String msg;
3188
3189 // Check to see if the SDCard is busy, same as the music app
3190 if (status.equals(Environment.MEDIA_SHARED)) {
3191 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3192 title = R.string.download_sdcard_busy_dlg_title;
3193 } else {
3194 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3195 title = R.string.download_no_sdcard_dlg_title;
3196 }
3197
3198 new AlertDialog.Builder(this)
3199 .setTitle(title)
3200 .setIcon(android.R.drawable.ic_dialog_alert)
3201 .setMessage(msg)
3202 .setPositiveButton(R.string.ok, null)
3203 .show();
3204 return;
3205 }
3206
3207 // java.net.URI is a lot stricter than KURL so we have to undo
3208 // KURL's percent-encoding and redo the encoding using java.net.URI.
3209 URI uri = null;
3210 try {
3211 // Undo the percent-encoding that KURL may have done.
3212 String newUrl = new String(URLUtil.decode(url.getBytes()));
3213 // Parse the url into pieces
3214 WebAddress w = new WebAddress(newUrl);
3215 String frag = null;
3216 String query = null;
3217 String path = w.mPath;
3218 // Break the path into path, query, and fragment
3219 if (path.length() > 0) {
3220 // Strip the fragment
3221 int idx = path.lastIndexOf('#');
3222 if (idx != -1) {
3223 frag = path.substring(idx + 1);
3224 path = path.substring(0, idx);
3225 }
3226 idx = path.lastIndexOf('?');
3227 if (idx != -1) {
3228 query = path.substring(idx + 1);
3229 path = path.substring(0, idx);
3230 }
3231 }
3232 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3233 query, frag);
3234 } catch (Exception e) {
3235 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3236 return;
3237 }
3238
3239 // XXX: Have to use the old url since the cookies were stored using the
3240 // old percent-encoded url.
3241 String cookies = CookieManager.getInstance().getCookie(url);
3242
3243 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003244 values.put(Downloads.COLUMN_URI, uri.toString());
3245 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3246 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3247 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003248 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003249 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003250 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003251 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3252 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3253 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3254 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003255 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003256 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003257 }
3258 if (mimetype == null) {
3259 // We must have long pressed on a link or image to download it. We
3260 // are not sure of the mimetype in this case, so do a head request
3261 new FetchUrlMimeType(this).execute(values);
3262 } else {
3263 final Uri contentUri =
3264 getContentResolver().insert(Downloads.CONTENT_URI, values);
3265 viewDownloads(contentUri);
3266 }
3267
3268 }
3269
3270 /**
3271 * Resets the lock icon. This method is called when we start a new load and
3272 * know the url to be loaded.
3273 */
3274 private void resetLockIcon(String url) {
3275 // Save the lock-icon state (we revert to it if the load gets cancelled)
3276 saveLockIcon();
3277
3278 mLockIconType = LOCK_ICON_UNSECURE;
3279 if (URLUtil.isHttpsUrl(url)) {
3280 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003281 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003282 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3283 " reset lock icon to " + mLockIconType);
3284 }
3285 }
3286
3287 updateLockIconImage(LOCK_ICON_UNSECURE);
3288 }
3289
3290 /**
3291 * Resets the lock icon. This method is called when the icon needs to be
3292 * reset but we do not know whether we are loading a secure or not secure
3293 * page.
3294 */
3295 private void resetLockIcon() {
3296 // Save the lock-icon state (we revert to it if the load gets cancelled)
3297 saveLockIcon();
3298
3299 mLockIconType = LOCK_ICON_UNSECURE;
3300
Dave Bort31a6d1c2009-04-13 15:56:49 -07003301 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003302 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3303 " reset lock icon to " + mLockIconType);
3304 }
3305
3306 updateLockIconImage(LOCK_ICON_UNSECURE);
3307 }
3308
3309 /**
3310 * Updates the lock-icon image in the title-bar.
3311 */
3312 private void updateLockIconImage(int lockIconType) {
3313 Drawable d = null;
3314 if (lockIconType == LOCK_ICON_SECURE) {
3315 d = mSecLockIcon;
3316 } else if (lockIconType == LOCK_ICON_MIXED) {
3317 d = mMixLockIcon;
3318 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04003319 if (CUSTOM_BROWSER_BAR) {
3320 mTitleBar.setLock(d, getTopWindow());
3321 } else {
3322 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003323 }
3324 }
3325
3326 /**
3327 * Displays a page-info dialog.
3328 * @param tab The tab to show info about
3329 * @param fromShowSSLCertificateOnError The flag that indicates whether
3330 * this dialog was opened from the SSL-certificate-on-error dialog or
3331 * not. This is important, since we need to know whether to return to
3332 * the parent dialog or simply dismiss.
3333 */
3334 private void showPageInfo(final TabControl.Tab tab,
3335 final boolean fromShowSSLCertificateOnError) {
3336 final LayoutInflater factory = LayoutInflater
3337 .from(this);
3338
3339 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3340
3341 final WebView view = tab.getWebView();
3342
3343 String url = null;
3344 String title = null;
3345
3346 if (view == null) {
3347 url = tab.getUrl();
3348 title = tab.getTitle();
3349 } else if (view == mTabControl.getCurrentWebView()) {
3350 // Use the cached title and url if this is the current WebView
3351 url = mUrl;
3352 title = mTitle;
3353 } else {
3354 url = view.getUrl();
3355 title = view.getTitle();
3356 }
3357
3358 if (url == null) {
3359 url = "";
3360 }
3361 if (title == null) {
3362 title = "";
3363 }
3364
3365 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3366 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3367
3368 mPageInfoView = tab;
3369 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3370
3371 AlertDialog.Builder alertDialogBuilder =
3372 new AlertDialog.Builder(this)
3373 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3374 .setView(pageInfoView)
3375 .setPositiveButton(
3376 R.string.ok,
3377 new DialogInterface.OnClickListener() {
3378 public void onClick(DialogInterface dialog,
3379 int whichButton) {
3380 mPageInfoDialog = null;
3381 mPageInfoView = null;
3382 mPageInfoFromShowSSLCertificateOnError = null;
3383
3384 // if we came here from the SSL error dialog
3385 if (fromShowSSLCertificateOnError) {
3386 // go back to the SSL error dialog
3387 showSSLCertificateOnError(
3388 mSSLCertificateOnErrorView,
3389 mSSLCertificateOnErrorHandler,
3390 mSSLCertificateOnErrorError);
3391 }
3392 }
3393 })
3394 .setOnCancelListener(
3395 new DialogInterface.OnCancelListener() {
3396 public void onCancel(DialogInterface dialog) {
3397 mPageInfoDialog = null;
3398 mPageInfoView = null;
3399 mPageInfoFromShowSSLCertificateOnError = null;
3400
3401 // if we came here from the SSL error dialog
3402 if (fromShowSSLCertificateOnError) {
3403 // go back to the SSL error dialog
3404 showSSLCertificateOnError(
3405 mSSLCertificateOnErrorView,
3406 mSSLCertificateOnErrorHandler,
3407 mSSLCertificateOnErrorError);
3408 }
3409 }
3410 });
3411
3412 // if we have a main top-level page SSL certificate set or a certificate
3413 // error
3414 if (fromShowSSLCertificateOnError ||
3415 (view != null && view.getCertificate() != null)) {
3416 // add a 'View Certificate' button
3417 alertDialogBuilder.setNeutralButton(
3418 R.string.view_certificate,
3419 new DialogInterface.OnClickListener() {
3420 public void onClick(DialogInterface dialog,
3421 int whichButton) {
3422 mPageInfoDialog = null;
3423 mPageInfoView = null;
3424 mPageInfoFromShowSSLCertificateOnError = null;
3425
3426 // if we came here from the SSL error dialog
3427 if (fromShowSSLCertificateOnError) {
3428 // go back to the SSL error dialog
3429 showSSLCertificateOnError(
3430 mSSLCertificateOnErrorView,
3431 mSSLCertificateOnErrorHandler,
3432 mSSLCertificateOnErrorError);
3433 } else {
3434 // otherwise, display the top-most certificate from
3435 // the chain
3436 if (view.getCertificate() != null) {
3437 showSSLCertificate(tab);
3438 }
3439 }
3440 }
3441 });
3442 }
3443
3444 mPageInfoDialog = alertDialogBuilder.show();
3445 }
3446
3447 /**
3448 * Displays the main top-level page SSL certificate dialog
3449 * (accessible from the Page-Info dialog).
3450 * @param tab The tab to show certificate for.
3451 */
3452 private void showSSLCertificate(final TabControl.Tab tab) {
3453 final View certificateView =
3454 inflateCertificateView(tab.getWebView().getCertificate());
3455 if (certificateView == null) {
3456 return;
3457 }
3458
3459 LayoutInflater factory = LayoutInflater.from(this);
3460
3461 final LinearLayout placeholder =
3462 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3463
3464 LinearLayout ll = (LinearLayout) factory.inflate(
3465 R.layout.ssl_success, placeholder);
3466 ((TextView)ll.findViewById(R.id.success))
3467 .setText(R.string.ssl_certificate_is_valid);
3468
3469 mSSLCertificateView = tab;
3470 mSSLCertificateDialog =
3471 new AlertDialog.Builder(this)
3472 .setTitle(R.string.ssl_certificate).setIcon(
3473 R.drawable.ic_dialog_browser_certificate_secure)
3474 .setView(certificateView)
3475 .setPositiveButton(R.string.ok,
3476 new DialogInterface.OnClickListener() {
3477 public void onClick(DialogInterface dialog,
3478 int whichButton) {
3479 mSSLCertificateDialog = null;
3480 mSSLCertificateView = null;
3481
3482 showPageInfo(tab, false);
3483 }
3484 })
3485 .setOnCancelListener(
3486 new DialogInterface.OnCancelListener() {
3487 public void onCancel(DialogInterface dialog) {
3488 mSSLCertificateDialog = null;
3489 mSSLCertificateView = null;
3490
3491 showPageInfo(tab, false);
3492 }
3493 })
3494 .show();
3495 }
3496
3497 /**
3498 * Displays the SSL error certificate dialog.
3499 * @param view The target web-view.
3500 * @param handler The SSL error handler responsible for cancelling the
3501 * connection that resulted in an SSL error or proceeding per user request.
3502 * @param error The SSL error object.
3503 */
3504 private void showSSLCertificateOnError(
3505 final WebView view, final SslErrorHandler handler, final SslError error) {
3506
3507 final View certificateView =
3508 inflateCertificateView(error.getCertificate());
3509 if (certificateView == null) {
3510 return;
3511 }
3512
3513 LayoutInflater factory = LayoutInflater.from(this);
3514
3515 final LinearLayout placeholder =
3516 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3517
3518 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3519 LinearLayout ll = (LinearLayout)factory
3520 .inflate(R.layout.ssl_warning, placeholder);
3521 ((TextView)ll.findViewById(R.id.warning))
3522 .setText(R.string.ssl_untrusted);
3523 }
3524
3525 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3526 LinearLayout ll = (LinearLayout)factory
3527 .inflate(R.layout.ssl_warning, placeholder);
3528 ((TextView)ll.findViewById(R.id.warning))
3529 .setText(R.string.ssl_mismatch);
3530 }
3531
3532 if (error.hasError(SslError.SSL_EXPIRED)) {
3533 LinearLayout ll = (LinearLayout)factory
3534 .inflate(R.layout.ssl_warning, placeholder);
3535 ((TextView)ll.findViewById(R.id.warning))
3536 .setText(R.string.ssl_expired);
3537 }
3538
3539 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3540 LinearLayout ll = (LinearLayout)factory
3541 .inflate(R.layout.ssl_warning, placeholder);
3542 ((TextView)ll.findViewById(R.id.warning))
3543 .setText(R.string.ssl_not_yet_valid);
3544 }
3545
3546 mSSLCertificateOnErrorHandler = handler;
3547 mSSLCertificateOnErrorView = view;
3548 mSSLCertificateOnErrorError = error;
3549 mSSLCertificateOnErrorDialog =
3550 new AlertDialog.Builder(this)
3551 .setTitle(R.string.ssl_certificate).setIcon(
3552 R.drawable.ic_dialog_browser_certificate_partially_secure)
3553 .setView(certificateView)
3554 .setPositiveButton(R.string.ok,
3555 new DialogInterface.OnClickListener() {
3556 public void onClick(DialogInterface dialog,
3557 int whichButton) {
3558 mSSLCertificateOnErrorDialog = null;
3559 mSSLCertificateOnErrorView = null;
3560 mSSLCertificateOnErrorHandler = null;
3561 mSSLCertificateOnErrorError = null;
3562
3563 mWebViewClient.onReceivedSslError(
3564 view, handler, error);
3565 }
3566 })
3567 .setNeutralButton(R.string.page_info_view,
3568 new DialogInterface.OnClickListener() {
3569 public void onClick(DialogInterface dialog,
3570 int whichButton) {
3571 mSSLCertificateOnErrorDialog = null;
3572
3573 // do not clear the dialog state: we will
3574 // need to show the dialog again once the
3575 // user is done exploring the page-info details
3576
3577 showPageInfo(mTabControl.getTabFromView(view),
3578 true);
3579 }
3580 })
3581 .setOnCancelListener(
3582 new DialogInterface.OnCancelListener() {
3583 public void onCancel(DialogInterface dialog) {
3584 mSSLCertificateOnErrorDialog = null;
3585 mSSLCertificateOnErrorView = null;
3586 mSSLCertificateOnErrorHandler = null;
3587 mSSLCertificateOnErrorError = null;
3588
3589 mWebViewClient.onReceivedSslError(
3590 view, handler, error);
3591 }
3592 })
3593 .show();
3594 }
3595
3596 /**
3597 * Inflates the SSL certificate view (helper method).
3598 * @param certificate The SSL certificate.
3599 * @return The resultant certificate view with issued-to, issued-by,
3600 * issued-on, expires-on, and possibly other fields set.
3601 * If the input certificate is null, returns null.
3602 */
3603 private View inflateCertificateView(SslCertificate certificate) {
3604 if (certificate == null) {
3605 return null;
3606 }
3607
3608 LayoutInflater factory = LayoutInflater.from(this);
3609
3610 View certificateView = factory.inflate(
3611 R.layout.ssl_certificate, null);
3612
3613 // issued to:
3614 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3615 if (issuedTo != null) {
3616 ((TextView) certificateView.findViewById(R.id.to_common))
3617 .setText(issuedTo.getCName());
3618 ((TextView) certificateView.findViewById(R.id.to_org))
3619 .setText(issuedTo.getOName());
3620 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3621 .setText(issuedTo.getUName());
3622 }
3623
3624 // issued by:
3625 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3626 if (issuedBy != null) {
3627 ((TextView) certificateView.findViewById(R.id.by_common))
3628 .setText(issuedBy.getCName());
3629 ((TextView) certificateView.findViewById(R.id.by_org))
3630 .setText(issuedBy.getOName());
3631 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3632 .setText(issuedBy.getUName());
3633 }
3634
3635 // issued on:
3636 String issuedOn = reformatCertificateDate(
3637 certificate.getValidNotBefore());
3638 ((TextView) certificateView.findViewById(R.id.issued_on))
3639 .setText(issuedOn);
3640
3641 // expires on:
3642 String expiresOn = reformatCertificateDate(
3643 certificate.getValidNotAfter());
3644 ((TextView) certificateView.findViewById(R.id.expires_on))
3645 .setText(expiresOn);
3646
3647 return certificateView;
3648 }
3649
3650 /**
3651 * Re-formats the certificate date (Date.toString()) string to
3652 * a properly localized date string.
3653 * @return Properly localized version of the certificate date string and
3654 * the original certificate date string if fails to localize.
3655 * If the original string is null, returns an empty string "".
3656 */
3657 private String reformatCertificateDate(String certificateDate) {
3658 String reformattedDate = null;
3659
3660 if (certificateDate != null) {
3661 Date date = null;
3662 try {
3663 date = java.text.DateFormat.getInstance().parse(certificateDate);
3664 } catch (ParseException e) {
3665 date = null;
3666 }
3667
3668 if (date != null) {
3669 reformattedDate =
3670 DateFormat.getDateFormat(this).format(date);
3671 }
3672 }
3673
3674 return reformattedDate != null ? reformattedDate :
3675 (certificateDate != null ? certificateDate : "");
3676 }
3677
3678 /**
3679 * Displays an http-authentication dialog.
3680 */
3681 private void showHttpAuthentication(final HttpAuthHandler handler,
3682 final String host, final String realm, final String title,
3683 final String name, final String password, int focusId) {
3684 LayoutInflater factory = LayoutInflater.from(this);
3685 final View v = factory
3686 .inflate(R.layout.http_authentication, null);
3687 if (name != null) {
3688 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3689 }
3690 if (password != null) {
3691 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3692 }
3693
3694 String titleText = title;
3695 if (titleText == null) {
3696 titleText = getText(R.string.sign_in_to).toString().replace(
3697 "%s1", host).replace("%s2", realm);
3698 }
3699
3700 mHttpAuthHandler = handler;
3701 AlertDialog dialog = new AlertDialog.Builder(this)
3702 .setTitle(titleText)
3703 .setIcon(android.R.drawable.ic_dialog_alert)
3704 .setView(v)
3705 .setPositiveButton(R.string.action,
3706 new DialogInterface.OnClickListener() {
3707 public void onClick(DialogInterface dialog,
3708 int whichButton) {
3709 String nm = ((EditText) v
3710 .findViewById(R.id.username_edit))
3711 .getText().toString();
3712 String pw = ((EditText) v
3713 .findViewById(R.id.password_edit))
3714 .getText().toString();
3715 BrowserActivity.this.setHttpAuthUsernamePassword
3716 (host, realm, nm, pw);
3717 handler.proceed(nm, pw);
3718 mHttpAuthenticationDialog = null;
3719 mHttpAuthHandler = null;
3720 }})
3721 .setNegativeButton(R.string.cancel,
3722 new DialogInterface.OnClickListener() {
3723 public void onClick(DialogInterface dialog,
3724 int whichButton) {
3725 handler.cancel();
3726 BrowserActivity.this.resetTitleAndRevertLockIcon();
3727 mHttpAuthenticationDialog = null;
3728 mHttpAuthHandler = null;
3729 }})
3730 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3731 public void onCancel(DialogInterface dialog) {
3732 handler.cancel();
3733 BrowserActivity.this.resetTitleAndRevertLockIcon();
3734 mHttpAuthenticationDialog = null;
3735 mHttpAuthHandler = null;
3736 }})
3737 .create();
3738 // Make the IME appear when the dialog is displayed if applicable.
3739 dialog.getWindow().setSoftInputMode(
3740 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3741 dialog.show();
3742 if (focusId != 0) {
3743 dialog.findViewById(focusId).requestFocus();
3744 } else {
3745 v.findViewById(R.id.username_edit).requestFocus();
3746 }
3747 mHttpAuthenticationDialog = dialog;
3748 }
3749
3750 public int getProgress() {
3751 WebView w = mTabControl.getCurrentWebView();
3752 if (w != null) {
3753 return w.getProgress();
3754 } else {
3755 return 100;
3756 }
3757 }
3758
3759 /**
3760 * Set HTTP authentication password.
3761 *
3762 * @param host The host for the password
3763 * @param realm The realm for the password
3764 * @param username The username for the password. If it is null, it means
3765 * password can't be saved.
3766 * @param password The password
3767 */
3768 public void setHttpAuthUsernamePassword(String host, String realm,
3769 String username,
3770 String password) {
3771 WebView w = mTabControl.getCurrentWebView();
3772 if (w != null) {
3773 w.setHttpAuthUsernamePassword(host, realm, username, password);
3774 }
3775 }
3776
3777 /**
3778 * connectivity manager says net has come or gone... inform the user
3779 * @param up true if net has come up, false if net has gone down
3780 */
3781 public void onNetworkToggle(boolean up) {
3782 if (up == mIsNetworkUp) {
3783 return;
3784 } else if (up) {
3785 mIsNetworkUp = true;
3786 if (mAlertDialog != null) {
3787 mAlertDialog.cancel();
3788 mAlertDialog = null;
3789 }
3790 } else {
3791 mIsNetworkUp = false;
3792 if (mInLoad && mAlertDialog == null) {
3793 mAlertDialog = new AlertDialog.Builder(this)
3794 .setTitle(R.string.loadSuspendedTitle)
3795 .setMessage(R.string.loadSuspended)
3796 .setPositiveButton(R.string.ok, null)
3797 .show();
3798 }
3799 }
3800 WebView w = mTabControl.getCurrentWebView();
3801 if (w != null) {
3802 w.setNetworkAvailable(up);
3803 }
3804 }
3805
3806 @Override
3807 protected void onActivityResult(int requestCode, int resultCode,
3808 Intent intent) {
3809 switch (requestCode) {
3810 case COMBO_PAGE:
3811 if (resultCode == RESULT_OK && intent != null) {
3812 String data = intent.getAction();
3813 Bundle extras = intent.getExtras();
3814 if (extras != null && extras.getBoolean("new_window", false)) {
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003815 final TabControl.Tab newTab = openTab(data);
3816 if (mSettings.openInBackground() &&
Leon Scroggins1f005d32009-08-10 17:36:42 -04003817 newTab != null) {
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003818 mTabControl.populatePickerData(newTab);
3819 mTabControl.setCurrentTab(newTab);
Leon Scroggins1f005d32009-08-10 17:36:42 -04003820 int newIndex = mTabControl.getCurrentIndex();
3821 if (CUSTOM_BROWSER_BAR) {
3822 mTitleBar.setCurrentTab(newIndex);
3823 }
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003824 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003825 } else {
3826 final TabControl.Tab currentTab =
3827 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003828 dismissSubWindow(currentTab);
3829 if (data != null && data.length() != 0) {
3830 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003831 }
3832 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04003833 } else if (resultCode == RESULT_CANCELED
3834 && mCancelGoPageMeansClose) {
3835 if (mTabControl.getTabCount() == 1) {
3836 // finish the Browser. When the Browser opens up again,
3837 // we will go through onCreate and once again open up
3838 // the Go page.
3839 finish();
3840 return;
3841 }
3842 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003843 }
3844 break;
3845 default:
3846 break;
3847 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04003848 mCancelGoPageMeansClose = false;
3849 if (getTopWindow() != null) {
3850 getTopWindow().requestFocus();
3851 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003852 }
3853
3854 /*
3855 * This method is called as a result of the user selecting the options
3856 * menu to see the download window, or when a download changes state. It
3857 * shows the download window ontop of the current window.
3858 */
3859 /* package */ void viewDownloads(Uri downloadRecord) {
3860 Intent intent = new Intent(this,
3861 BrowserDownloadPage.class);
3862 intent.setData(downloadRecord);
3863 startActivityForResult(intent, this.DOWNLOAD_PAGE);
3864
3865 }
3866
Leon Scroggins160a7e72009-08-14 18:28:01 -04003867 // True if canceling the "Go" screen should result in closing the current
3868 // window/browser.
3869 private boolean mCancelGoPageMeansClose;
3870
3871 /**
3872 * Open the Go page.
3873 * @param startWithHistory If true, open starting on the history tab.
3874 * Otherwise, start with the bookmarks tab.
3875 * @param cancelGoPageMeansClose Set to true if this came from a new tab, or
3876 * from the only tab, and canceling means to
3877 * close the tab (and possibly the browser)
3878 */
3879 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory,
3880 boolean cancelGoPageMeansClose) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003881 WebView current = mTabControl.getCurrentWebView();
3882 if (current == null) {
3883 return;
3884 }
3885 Intent intent = new Intent(this,
3886 CombinedBookmarkHistoryActivity.class);
3887 String title = current.getTitle();
3888 String url = current.getUrl();
3889 // Just in case the user opens bookmarks before a page finishes loading
3890 // so the current history item, and therefore the page, is null.
3891 if (null == url) {
3892 url = mLastEnteredUrl;
3893 // This can happen.
3894 if (null == url) {
3895 url = mSettings.getHomePage();
3896 }
3897 }
3898 // In case the web page has not yet received its associated title.
3899 if (title == null) {
3900 title = url;
3901 }
3902 intent.putExtra("title", title);
3903 intent.putExtra("url", url);
3904 intent.putExtra("maxTabsOpen",
3905 mTabControl.getTabCount() >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04003906 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003907 if (startWithHistory) {
3908 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3909 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3910 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04003911 mCancelGoPageMeansClose = cancelGoPageMeansClose;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003912 startActivityForResult(intent, COMBO_PAGE);
3913 }
3914
3915 // Called when loading from context menu or LOAD_URL message
3916 private void loadURL(WebView view, String url) {
3917 // In case the user enters nothing.
3918 if (url != null && url.length() != 0 && view != null) {
3919 url = smartUrlFilter(url);
3920 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
3921 view.loadUrl(url);
3922 }
3923 }
3924 }
3925
The Android Open Source Project0c908882009-03-03 19:32:16 -08003926 private String smartUrlFilter(Uri inUri) {
3927 if (inUri != null) {
3928 return smartUrlFilter(inUri.toString());
3929 }
3930 return null;
3931 }
3932
3933
3934 // get window count
3935
3936 int getWindowCount(){
3937 if(mTabControl != null){
3938 return mTabControl.getTabCount();
3939 }
3940 return 0;
3941 }
3942
Feng Qianb34f87a2009-03-24 21:27:26 -07003943 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003944 "(?i)" + // switch on case insensitive matching
3945 "(" + // begin group for schema
3946 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003947 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003948 ")" +
3949 "(.*)" );
3950
3951 /**
3952 * Attempts to determine whether user input is a URL or search
3953 * terms. Anything with a space is passed to search.
3954 *
3955 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3956 * "Http://" converts to "http://"
3957 *
3958 * @return Original or modified URL
3959 *
3960 */
3961 String smartUrlFilter(String url) {
3962
3963 String inUrl = url.trim();
3964 boolean hasSpace = inUrl.indexOf(' ') != -1;
3965
3966 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3967 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003968 // force scheme to lowercase
3969 String scheme = matcher.group(1);
3970 String lcScheme = scheme.toLowerCase();
3971 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003972 inUrl = lcScheme + matcher.group(2);
3973 }
3974 if (hasSpace) {
3975 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003976 }
3977 return inUrl;
3978 }
3979 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003980 // FIXME: Is this the correct place to add to searches?
3981 // what if someone else calls this function?
3982 int shortcut = parseUrlShortcut(inUrl);
3983 if (shortcut != SHORTCUT_INVALID) {
3984 Browser.addSearchUrl(mResolver, inUrl);
3985 String query = inUrl.substring(2);
3986 switch (shortcut) {
3987 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003988 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003989 case SHORTCUT_WIKIPEDIA_SEARCH:
3990 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3991 case SHORTCUT_DICTIONARY_SEARCH:
3992 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3993 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003994 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003995 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003996 }
3997 }
3998 } else {
3999 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4000 return URLUtil.guessUrl(inUrl);
4001 }
4002 }
4003
4004 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004005 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004006 }
4007
Ben Murdochbff2d602009-07-01 20:19:05 +01004008 /* package */ void setShouldShowErrorConsole(boolean flag) {
4009 if (flag == mShouldShowErrorConsole) {
4010 // Nothing to do.
4011 return;
4012 }
4013
4014 mShouldShowErrorConsole = flag;
4015
4016 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4017
4018 if (flag) {
4019 // Setting the show state of the console will cause it's the layout to be inflated.
4020 if (errorConsole.numberOfErrors() > 0) {
4021 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4022 } else {
4023 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4024 }
4025
4026 // Now we can add it to the main view.
4027 mErrorConsoleContainer.addView(errorConsole,
4028 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4029 ViewGroup.LayoutParams.WRAP_CONTENT));
4030 } else {
4031 mErrorConsoleContainer.removeView(errorConsole);
4032 }
4033
4034 }
4035
The Android Open Source Project0c908882009-03-03 19:32:16 -08004036 private final static int LOCK_ICON_UNSECURE = 0;
4037 private final static int LOCK_ICON_SECURE = 1;
4038 private final static int LOCK_ICON_MIXED = 2;
4039
4040 private int mLockIconType = LOCK_ICON_UNSECURE;
4041 private int mPrevLockType = LOCK_ICON_UNSECURE;
4042
4043 private BrowserSettings mSettings;
4044 private TabControl mTabControl;
4045 private ContentResolver mResolver;
4046 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004047 private View mCustomView;
4048 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004049 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004050
4051 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4052 // view, we should rewrite this.
4053 private int mCurrentMenuState = 0;
4054 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004055 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004056 private static final int EMPTY_MENU = -1;
4057 private Menu mMenu;
4058
4059 private FindDialog mFindDialog;
4060 // Used to prevent chording to result in firing two shortcuts immediately
4061 // one after another. Fixes bug 1211714.
4062 boolean mCanChord;
4063
4064 private boolean mInLoad;
4065 private boolean mIsNetworkUp;
4066
4067 private boolean mPageStarted;
4068 private boolean mActivityInPause = true;
4069
4070 private boolean mMenuIsDown;
4071
4072 private final KeyTracker mKeyTracker = new KeyTracker(this);
4073
4074 // As trackball doesn't send repeat down, we have to track it ourselves
4075 private boolean mTrackTrackball;
4076
4077 private static boolean mInTrace;
4078
4079 // Performance probe
4080 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4081 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4082 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4083 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4084 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4085 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4086 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4087 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4088 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4089 };
4090
4091 private long mStart;
4092 private long mProcessStart;
4093 private long mUserStart;
4094 private long mSystemStart;
4095 private long mIdleStart;
4096 private long mIrqStart;
4097
4098 private long mUiStart;
4099
4100 private Drawable mMixLockIcon;
4101 private Drawable mSecLockIcon;
4102 private Drawable mGenericFavicon;
4103
4104 /* hold a ref so we can auto-cancel if necessary */
4105 private AlertDialog mAlertDialog;
4106
4107 // Wait for credentials before loading google.com
4108 private ProgressDialog mCredsDlg;
4109
4110 // The up-to-date URL and title (these can be different from those stored
4111 // in WebView, since it takes some time for the information in WebView to
4112 // get updated)
4113 private String mUrl;
4114 private String mTitle;
4115
4116 // As PageInfo has different style for landscape / portrait, we have
4117 // to re-open it when configuration changed
4118 private AlertDialog mPageInfoDialog;
4119 private TabControl.Tab mPageInfoView;
4120 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4121 // dialog, we should not just dismiss it, but should get back to the
4122 // SSL-certificate-on-error dialog. This flag is used to store this state
4123 private Boolean mPageInfoFromShowSSLCertificateOnError;
4124
4125 // as SSLCertificateOnError has different style for landscape / portrait,
4126 // we have to re-open it when configuration changed
4127 private AlertDialog mSSLCertificateOnErrorDialog;
4128 private WebView mSSLCertificateOnErrorView;
4129 private SslErrorHandler mSSLCertificateOnErrorHandler;
4130 private SslError mSSLCertificateOnErrorError;
4131
4132 // as SSLCertificate has different style for landscape / portrait, we
4133 // have to re-open it when configuration changed
4134 private AlertDialog mSSLCertificateDialog;
4135 private TabControl.Tab mSSLCertificateView;
4136
4137 // as HttpAuthentication has different style for landscape / portrait, we
4138 // have to re-open it when configuration changed
4139 private AlertDialog mHttpAuthenticationDialog;
4140 private HttpAuthHandler mHttpAuthHandler;
4141
4142 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4143 new FrameLayout.LayoutParams(
4144 ViewGroup.LayoutParams.FILL_PARENT,
4145 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004146 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4147 new FrameLayout.LayoutParams(
4148 ViewGroup.LayoutParams.FILL_PARENT,
4149 ViewGroup.LayoutParams.FILL_PARENT,
4150 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004151 // Google search
4152 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004153 // Wikipedia search
4154 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4155 // Dictionary search
4156 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4157 // Google Mobile Local search
4158 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4159
4160 final static String QUERY_PLACE_HOLDER = "%s";
4161
4162 // "source" parameter for Google search through search key
4163 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4164 // "source" parameter for Google search through goto menu
4165 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4166 // "source" parameter for Google search through simplily type
4167 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4168 // "source" parameter for Google search suggested by the browser
4169 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4170 // "source" parameter for Google search from unknown source
4171 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4172
4173 private final static String LOGTAG = "browser";
4174
The Android Open Source Project0c908882009-03-03 19:32:16 -08004175 private String mLastEnteredUrl;
4176
4177 private PowerManager.WakeLock mWakeLock;
4178 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4179
4180 private Toast mStopToast;
4181
Leon Scroggins1f005d32009-08-10 17:36:42 -04004182 private TitleBarSet mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004183
Ben Murdochbff2d602009-07-01 20:19:05 +01004184 private LinearLayout mErrorConsoleContainer = null;
4185 private boolean mShouldShowErrorConsole = false;
4186
The Android Open Source Project0c908882009-03-03 19:32:16 -08004187 // As the ids are dynamically created, we can't guarantee that they will
4188 // be in sequence, so this static array maps ids to a window number.
4189 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4190 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4191 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4192 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4193
4194 // monitor platform changes
4195 private IntentFilter mNetworkStateChangedFilter;
4196 private BroadcastReceiver mNetworkStateIntentReceiver;
4197
Grace Klobab4da0ad2009-05-14 14:45:40 -07004198 private BroadcastReceiver mPackageInstallationReceiver;
4199
The Android Open Source Project0c908882009-03-03 19:32:16 -08004200 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004201 final static int COMBO_PAGE = 1;
4202 final static int DOWNLOAD_PAGE = 2;
4203 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004204
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004205 /**
4206 * A UrlData class to abstract how the content will be set to WebView.
4207 * This base class uses loadUrl to show the content.
4208 */
4209 private static class UrlData {
4210 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004211 byte[] mPostData;
4212
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004213 UrlData(String url) {
4214 this.mUrl = url;
4215 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004216
4217 void setPostData(byte[] postData) {
4218 mPostData = postData;
4219 }
4220
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004221 boolean isEmpty() {
4222 return mUrl == null || mUrl.length() == 0;
4223 }
4224
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004225 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004226 if (mPostData != null) {
4227 webView.postUrl(mUrl, mPostData);
4228 } else {
4229 webView.loadUrl(mUrl);
4230 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004231 }
4232 };
4233
4234 /**
4235 * A subclass of UrlData class that can display inlined content using
4236 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4237 */
4238 private static class InlinedUrlData extends UrlData {
4239 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4240 super(failUrl);
4241 mInlined = inlined;
4242 mMimeType = mimeType;
4243 mEncoding = encoding;
4244 }
4245 String mMimeType;
4246 String mInlined;
4247 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004248 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004249 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004250 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004251 }
4252
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004253 @Override
4254 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004255 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4256 }
4257 }
4258
Leon Scroggins1f005d32009-08-10 17:36:42 -04004259 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004260}