blob: 6ea9ebb10a3ead6cbfd645c4274742aa964c0ae6 [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 Scroggins1f005d32009-08-10 17:36:42 -0400484 bookmarksOrHistoryPicker(false);
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.
1215 */
1216 /* package */ void switchToTab(int index) {
1217 TabControl.Tab tab = mTabControl.getTab(index);
1218 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1219 if (tab == null || tab == currentTab) {
1220 return;
1221 }
1222 if (currentTab != null) {
1223 // currentTab may be null if it was just removed. In that case,
1224 // we do not need to remove it
1225 removeTabFromContentView(currentTab);
1226 }
1227 removeTabFromContentView(tab);
1228 mTabControl.setCurrentTab(tab);
1229 attachTabToContentView(tab);
1230 }
1231
1232 /* package */ void closeCurrentWindow() {
1233 final int currentIndex = mTabControl.getCurrentIndex();
1234 final TabControl.Tab current = mTabControl.getCurrentTab();
1235 final TabControl.Tab parent = current.getParentTab();
1236 // FIXME: With the new tabbed title bar, we will want to move to the
1237 // next tab to the right
1238 int indexToShow = -1;
1239 if (parent != null) {
1240 indexToShow = mTabControl.getTabIndex(parent);
1241 } else {
1242 // Get the last tab in the list. If it is the current tab,
1243 // subtract 1 more.
1244 indexToShow = mTabControl.getTabCount() - 1;
1245 if (currentIndex == indexToShow) {
1246 indexToShow--;
1247 }
1248 }
1249 switchToTab(indexToShow);
1250 // Close window
1251 closeTab(current);
1252 }
1253
The Android Open Source Project0c908882009-03-03 19:32:16 -08001254 @Override
1255 public boolean onOptionsItemSelected(MenuItem item) {
1256 if (!mCanChord) {
1257 // The user has already fired a shortcut with this hold down of the
1258 // menu key.
1259 return false;
1260 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001261 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001262 return false;
1263 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001264 if (mMenuIsDown) {
1265 // The shortcut action consumes the MENU. Even if it is still down,
1266 // it won't trigger the next shortcut action. In the case of the
1267 // shortcut action triggering a new activity, like Bookmarks, we
1268 // won't get onKeyUp for MENU. So it is important to reset it here.
1269 mMenuIsDown = false;
1270 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001271 switch (item.getItemId()) {
1272 // -- Main menu
Leon Scroggins64b80f32009-08-07 12:03:34 -04001273 case R.id.goto_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001274 bookmarksOrHistoryPicker(false);
1275 break;
1276
Leon Scroggins1f005d32009-08-10 17:36:42 -04001277 case R.id.add_bookmark_menu_id:
1278 Intent i = new Intent(BrowserActivity.this,
1279 AddBookmarkPage.class);
1280 WebView w = getTopWindow();
1281 i.putExtra("url", w.getUrl());
1282 i.putExtra("title", w.getTitle());
1283 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001284 break;
1285
1286 case R.id.stop_reload_menu_id:
1287 if (mInLoad) {
1288 stopLoading();
1289 } else {
1290 getTopWindow().reload();
1291 }
1292 break;
1293
1294 case R.id.back_menu_id:
1295 getTopWindow().goBack();
1296 break;
1297
1298 case R.id.forward_menu_id:
1299 getTopWindow().goForward();
1300 break;
1301
1302 case R.id.close_menu_id:
1303 // Close the subwindow if it exists.
1304 if (mTabControl.getCurrentSubWindow() != null) {
1305 dismissSubWindow(mTabControl.getCurrentTab());
1306 break;
1307 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001308 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001309 break;
1310
1311 case R.id.homepage_menu_id:
1312 TabControl.Tab current = mTabControl.getCurrentTab();
1313 if (current != null) {
1314 dismissSubWindow(current);
1315 current.getWebView().loadUrl(mSettings.getHomePage());
1316 }
1317 break;
1318
1319 case R.id.preferences_menu_id:
1320 Intent intent = new Intent(this,
1321 BrowserPreferencesPage.class);
1322 startActivityForResult(intent, PREFERENCES_PAGE);
1323 break;
1324
1325 case R.id.find_menu_id:
1326 if (null == mFindDialog) {
1327 mFindDialog = new FindDialog(this);
1328 }
1329 mFindDialog.setWebView(getTopWindow());
1330 mFindDialog.show();
1331 mMenuState = EMPTY_MENU;
1332 break;
1333
1334 case R.id.select_text_id:
1335 getTopWindow().emulateShiftHeld();
1336 break;
1337 case R.id.page_info_menu_id:
1338 showPageInfo(mTabControl.getCurrentTab(), false);
1339 break;
1340
1341 case R.id.classic_history_menu_id:
1342 bookmarksOrHistoryPicker(true);
1343 break;
1344
1345 case R.id.share_page_menu_id:
1346 Browser.sendString(this, getTopWindow().getUrl());
1347 break;
1348
1349 case R.id.dump_nav_menu_id:
1350 getTopWindow().debugDump();
1351 break;
1352
1353 case R.id.zoom_in_menu_id:
1354 getTopWindow().zoomIn();
1355 break;
1356
1357 case R.id.zoom_out_menu_id:
1358 getTopWindow().zoomOut();
1359 break;
1360
1361 case R.id.view_downloads_menu_id:
1362 viewDownloads(null);
1363 break;
1364
The Android Open Source Project0c908882009-03-03 19:32:16 -08001365 case R.id.window_one_menu_id:
1366 case R.id.window_two_menu_id:
1367 case R.id.window_three_menu_id:
1368 case R.id.window_four_menu_id:
1369 case R.id.window_five_menu_id:
1370 case R.id.window_six_menu_id:
1371 case R.id.window_seven_menu_id:
1372 case R.id.window_eight_menu_id:
1373 {
1374 int menuid = item.getItemId();
1375 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1376 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1377 TabControl.Tab desiredTab = mTabControl.getTab(id);
1378 if (desiredTab != null &&
1379 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001380 switchToTab(id);
1381 mTitleBar.setCurrentTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001382 }
1383 break;
1384 }
1385 }
1386 }
1387 break;
1388
1389 default:
1390 if (!super.onOptionsItemSelected(item)) {
1391 return false;
1392 }
1393 // Otherwise fall through.
1394 }
1395 mCanChord = false;
1396 return true;
1397 }
1398
1399 public void closeFind() {
1400 mMenuState = R.id.MAIN_MENU;
1401 }
1402
1403 @Override public boolean onPrepareOptionsMenu(Menu menu)
1404 {
1405 // This happens when the user begins to hold down the menu key, so
1406 // allow them to chord to get a shortcut.
1407 mCanChord = true;
1408 // Note: setVisible will decide whether an item is visible; while
1409 // setEnabled() will decide whether an item is enabled, which also means
1410 // whether the matching shortcut key will function.
1411 super.onPrepareOptionsMenu(menu);
1412 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001413 case EMPTY_MENU:
1414 if (mCurrentMenuState != mMenuState) {
1415 menu.setGroupVisible(R.id.MAIN_MENU, false);
1416 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1417 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001418 }
1419 break;
1420 default:
1421 if (mCurrentMenuState != mMenuState) {
1422 menu.setGroupVisible(R.id.MAIN_MENU, true);
1423 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1424 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001425 }
1426 final WebView w = getTopWindow();
1427 boolean canGoBack = false;
1428 boolean canGoForward = false;
1429 boolean isHome = false;
1430 if (w != null) {
1431 canGoBack = w.canGoBack();
1432 canGoForward = w.canGoForward();
1433 isHome = mSettings.getHomePage().equals(w.getUrl());
1434 }
1435 final MenuItem back = menu.findItem(R.id.back_menu_id);
1436 back.setEnabled(canGoBack);
1437
1438 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1439 home.setEnabled(!isHome);
1440
1441 menu.findItem(R.id.forward_menu_id)
1442 .setEnabled(canGoForward);
1443
1444 // decide whether to show the share link option
1445 PackageManager pm = getPackageManager();
1446 Intent send = new Intent(Intent.ACTION_SEND);
1447 send.setType("text/plain");
1448 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1449 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1450
The Android Open Source Project0c908882009-03-03 19:32:16 -08001451 boolean isNavDump = mSettings.isNavDump();
1452 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1453 nav.setVisible(isNavDump);
1454 nav.setEnabled(isNavDump);
1455 break;
1456 }
1457 mCurrentMenuState = mMenuState;
1458 return true;
1459 }
1460
1461 @Override
1462 public void onCreateContextMenu(ContextMenu menu, View v,
1463 ContextMenuInfo menuInfo) {
1464 WebView webview = (WebView) v;
1465 WebView.HitTestResult result = webview.getHitTestResult();
1466 if (result == null) {
1467 return;
1468 }
1469
1470 int type = result.getType();
1471 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1472 Log.w(LOGTAG,
1473 "We should not show context menu when nothing is touched");
1474 return;
1475 }
1476 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1477 // let TextView handles context menu
1478 return;
1479 }
1480
1481 // Note, http://b/issue?id=1106666 is requesting that
1482 // an inflated menu can be used again. This is not available
1483 // yet, so inflate each time (yuk!)
1484 MenuInflater inflater = getMenuInflater();
1485 inflater.inflate(R.menu.browsercontext, menu);
1486
1487 // Show the correct menu group
1488 String extra = result.getExtra();
1489 menu.setGroupVisible(R.id.PHONE_MENU,
1490 type == WebView.HitTestResult.PHONE_TYPE);
1491 menu.setGroupVisible(R.id.EMAIL_MENU,
1492 type == WebView.HitTestResult.EMAIL_TYPE);
1493 menu.setGroupVisible(R.id.GEO_MENU,
1494 type == WebView.HitTestResult.GEO_TYPE);
1495 menu.setGroupVisible(R.id.IMAGE_MENU,
1496 type == WebView.HitTestResult.IMAGE_TYPE
1497 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1498 menu.setGroupVisible(R.id.ANCHOR_MENU,
1499 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1500 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1501
1502 // Setup custom handling depending on the type
1503 switch (type) {
1504 case WebView.HitTestResult.PHONE_TYPE:
1505 menu.setHeaderTitle(Uri.decode(extra));
1506 menu.findItem(R.id.dial_context_menu_id).setIntent(
1507 new Intent(Intent.ACTION_VIEW, Uri
1508 .parse(WebView.SCHEME_TEL + extra)));
1509 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1510 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1511 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1512 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1513 addIntent);
1514 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1515 new Copy(extra));
1516 break;
1517
1518 case WebView.HitTestResult.EMAIL_TYPE:
1519 menu.setHeaderTitle(extra);
1520 menu.findItem(R.id.email_context_menu_id).setIntent(
1521 new Intent(Intent.ACTION_VIEW, Uri
1522 .parse(WebView.SCHEME_MAILTO + extra)));
1523 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1524 new Copy(extra));
1525 break;
1526
1527 case WebView.HitTestResult.GEO_TYPE:
1528 menu.setHeaderTitle(extra);
1529 menu.findItem(R.id.map_context_menu_id).setIntent(
1530 new Intent(Intent.ACTION_VIEW, Uri
1531 .parse(WebView.SCHEME_GEO
1532 + URLEncoder.encode(extra))));
1533 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1534 new Copy(extra));
1535 break;
1536
1537 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1538 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1539 TextView titleView = (TextView) LayoutInflater.from(this)
1540 .inflate(android.R.layout.browser_link_context_header,
1541 null);
1542 titleView.setText(extra);
1543 menu.setHeaderView(titleView);
1544 // decide whether to show the open link in new tab option
1545 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1546 mTabControl.getTabCount() < TabControl.MAX_TABS);
1547 PackageManager pm = getPackageManager();
1548 Intent send = new Intent(Intent.ACTION_SEND);
1549 send.setType("text/plain");
1550 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1551 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1552 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1553 break;
1554 }
1555 // otherwise fall through to handle image part
1556 case WebView.HitTestResult.IMAGE_TYPE:
1557 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1558 menu.setHeaderTitle(extra);
1559 }
1560 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1561 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1562 menu.findItem(R.id.download_context_menu_id).
1563 setOnMenuItemClickListener(new Download(extra));
1564 break;
1565
1566 default:
1567 Log.w(LOGTAG, "We should not get here.");
1568 break;
1569 }
1570 }
1571
The Android Open Source Project0c908882009-03-03 19:32:16 -08001572 // Attach the given tab to the content view.
1573 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001574 // Attach the container that contains the main WebView and any other UI
1575 // associated with the tab.
1576 mContentView.addView(t.getContainer(), COVER_SCREEN_PARAMS);
Ben Murdochbff2d602009-07-01 20:19:05 +01001577
1578 if (mShouldShowErrorConsole) {
1579 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1580 if (errorConsole.numberOfErrors() == 0) {
1581 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1582 } else {
1583 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1584 }
1585
1586 mErrorConsoleContainer.addView(errorConsole,
1587 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1588 ViewGroup.LayoutParams.WRAP_CONTENT));
1589 }
1590
The Android Open Source Project0c908882009-03-03 19:32:16 -08001591 // Attach the sub window if necessary
1592 attachSubWindow(t);
1593 // Request focus on the top window.
1594 t.getTopWindow().requestFocus();
1595 }
1596
1597 // Attach a sub window to the main WebView of the given tab.
1598 private void attachSubWindow(TabControl.Tab t) {
1599 // If a sub window exists, attach it to the content view.
1600 final WebView subView = t.getSubWebView();
1601 if (subView != null) {
1602 final View container = t.getSubWebViewContainer();
1603 mContentView.addView(container, COVER_SCREEN_PARAMS);
1604 subView.requestFocus();
1605 }
1606 }
1607
1608 // Remove the given tab from the content view.
1609 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001610 // Remove the container that contains the main WebView.
1611 mContentView.removeView(t.getContainer());
Ben Murdochbff2d602009-07-01 20:19:05 +01001612
1613 if (mTabControl.getCurrentErrorConsole(false) != null) {
1614 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1615 }
1616
The Android Open Source Project0c908882009-03-03 19:32:16 -08001617 // Remove the sub window if it exists.
1618 if (t.getSubWebView() != null) {
1619 mContentView.removeView(t.getSubWebViewContainer());
1620 }
1621 }
1622
1623 // Remove the sub window if it exists. Also called by TabControl when the
1624 // user clicks the 'X' to dismiss a sub window.
1625 /* package */ void dismissSubWindow(TabControl.Tab t) {
1626 final WebView mainView = t.getWebView();
1627 if (t.getSubWebView() != null) {
1628 // Remove the container view and request focus on the main WebView.
1629 mContentView.removeView(t.getSubWebViewContainer());
1630 mainView.requestFocus();
1631 // Tell the TabControl to dismiss the subwindow. This will destroy
1632 // the WebView.
1633 mTabControl.dismissSubWindow(t);
1634 }
1635 }
1636
Leon Scroggins1f005d32009-08-10 17:36:42 -04001637 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001638 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001639 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1640 String appId) {
1641 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001642 }
1643
1644 // This method does a ton of stuff. It will attempt to create a new tab
1645 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001646 // url isn't null, it will load the given url.
1647 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001648 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001649 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1650 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1651 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001652 final TabControl.Tab tab = mTabControl.createNewTab(
1653 closeOnExit, appId, urlData.mUrl);
1654 WebView webview = tab.getWebView();
1655 if (CUSTOM_BROWSER_BAR) {
1656 mTitleBar.addTab(webview, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001657 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001658 removeTabFromContentView(currentTab);
1659 attachTabToContentView(tab);
1660 if (urlData.isEmpty()) {
1661 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001662 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001663 urlData.loadIn(webview);
1664 }
1665 return tab;
1666 } else {
1667 // Get rid of the subwindow if it exists
1668 dismissSubWindow(currentTab);
1669 if (!urlData.isEmpty()) {
1670 // Load the given url.
1671 urlData.loadIn(currentTab.getWebView());
1672 } else {
1673 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001674 }
1675 }
Grace Klobac9181842009-04-14 08:53:22 -07001676 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001677 }
1678
Grace Klobac9181842009-04-14 08:53:22 -07001679 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001680 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001681 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001682 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001683 WebView view = t.getWebView();
1684 if (CUSTOM_BROWSER_BAR) {
1685 mTitleBar.addTab(view, false);
1686 }
1687 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001688 }
Grace Klobac9181842009-04-14 08:53:22 -07001689 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001690 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001691 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001692 }
1693 }
1694
1695 private class Copy implements OnMenuItemClickListener {
1696 private CharSequence mText;
1697
1698 public boolean onMenuItemClick(MenuItem item) {
1699 copy(mText);
1700 return true;
1701 }
1702
1703 public Copy(CharSequence toCopy) {
1704 mText = toCopy;
1705 }
1706 }
1707
1708 private class Download implements OnMenuItemClickListener {
1709 private String mText;
1710
1711 public boolean onMenuItemClick(MenuItem item) {
1712 onDownloadStartNoStream(mText, null, null, null, -1);
1713 return true;
1714 }
1715
1716 public Download(String toDownload) {
1717 mText = toDownload;
1718 }
1719 }
1720
1721 private void copy(CharSequence text) {
1722 try {
1723 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1724 if (clip != null) {
1725 clip.setClipboardText(text);
1726 }
1727 } catch (android.os.RemoteException e) {
1728 Log.e(LOGTAG, "Copy failed", e);
1729 }
1730 }
1731
1732 /**
1733 * Resets the browser title-view to whatever it must be (for example, if we
1734 * load a page from history).
1735 */
1736 private void resetTitle() {
1737 resetLockIcon();
1738 resetTitleIconAndProgress();
1739 }
1740
1741 /**
1742 * Resets the browser title-view to whatever it must be
1743 * (for example, if we had a loading error)
1744 * When we have a new page, we call resetTitle, when we
1745 * have to reset the titlebar to whatever it used to be
1746 * (for example, if the user chose to stop loading), we
1747 * call resetTitleAndRevertLockIcon.
1748 */
1749 /* package */ void resetTitleAndRevertLockIcon() {
1750 revertLockIcon();
1751 resetTitleIconAndProgress();
1752 }
1753
1754 /**
1755 * Reset the title, favicon, and progress.
1756 */
1757 private void resetTitleIconAndProgress() {
1758 WebView current = mTabControl.getCurrentWebView();
1759 if (current == null) {
1760 return;
1761 }
1762 resetTitleAndIcon(current);
1763 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001764 mWebChromeClient.onProgressChanged(current, progress);
1765 }
1766
1767 // Reset the title and the icon based on the given item.
1768 private void resetTitleAndIcon(WebView view) {
1769 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1770 if (item != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001771 setUrlTitle(item.getUrl(), item.getTitle(), view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001772 setFavicon(item.getFavicon());
1773 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001774 setUrlTitle(null, null, view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001775 setFavicon(null);
1776 }
1777 }
1778
1779 /**
1780 * Sets a title composed of the URL and the title string.
1781 * @param url The URL of the site being loaded.
1782 * @param title The title of the site being loaded.
1783 */
Leon Scroggins1f005d32009-08-10 17:36:42 -04001784 private void setUrlTitle(String url, String title, WebView view) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001785 mUrl = url;
1786 mTitle = title;
1787
Leon Scroggins1f005d32009-08-10 17:36:42 -04001788 if (CUSTOM_BROWSER_BAR) {
1789 mTitleBar.setTitleAndUrl(title, url, view);
1790 } else {
1791 setTitle(buildUrlTitle(url, title));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001792 }
1793 }
1794
1795 /**
1796 * Builds and returns the page title, which is some
1797 * combination of the page URL and title.
1798 * @param url The URL of the site being loaded.
1799 * @param title The title of the site being loaded.
1800 * @return The page title.
1801 */
1802 private String buildUrlTitle(String url, String title) {
1803 String urlTitle = "";
1804
1805 if (url != null) {
1806 String titleUrl = buildTitleUrl(url);
1807
1808 if (title != null && 0 < title.length()) {
1809 if (titleUrl != null && 0 < titleUrl.length()) {
1810 urlTitle = titleUrl + ": " + title;
1811 } else {
1812 urlTitle = title;
1813 }
1814 } else {
1815 if (titleUrl != null) {
1816 urlTitle = titleUrl;
1817 }
1818 }
1819 }
1820
1821 return urlTitle;
1822 }
1823
1824 /**
1825 * @param url The URL to build a title version of the URL from.
1826 * @return The title version of the URL or null if fails.
1827 * The title version of the URL can be either the URL hostname,
1828 * or the hostname with an "https://" prefix (for secure URLs),
1829 * or an empty string if, for example, the URL in question is a
1830 * file:// URL with no hostname.
1831 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001832 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001833 String titleUrl = null;
1834
1835 if (url != null) {
1836 try {
1837 // parse the url string
1838 URL urlObj = new URL(url);
1839 if (urlObj != null) {
1840 titleUrl = "";
1841
1842 String protocol = urlObj.getProtocol();
1843 String host = urlObj.getHost();
1844
1845 if (host != null && 0 < host.length()) {
1846 titleUrl = host;
1847 if (protocol != null) {
1848 // if a secure site, add an "https://" prefix!
1849 if (protocol.equalsIgnoreCase("https")) {
1850 titleUrl = protocol + "://" + host;
1851 }
1852 }
1853 }
1854 }
1855 } catch (MalformedURLException e) {}
1856 }
1857
1858 return titleUrl;
1859 }
1860
1861 // Set the favicon in the title bar.
1862 private void setFavicon(Bitmap icon) {
Leon Scroggins81db3662009-06-04 17:45:11 -04001863 if (CUSTOM_BROWSER_BAR) {
1864 Drawable[] array = new Drawable[3];
1865 array[0] = new PaintDrawable(Color.BLACK);
1866 PaintDrawable p = new PaintDrawable(Color.WHITE);
1867 array[1] = p;
1868 if (icon == null) {
1869 array[2] = mGenericFavicon;
1870 } else {
1871 array[2] = new BitmapDrawable(icon);
1872 }
1873 LayerDrawable d = new LayerDrawable(array);
1874 d.setLayerInset(1, 1, 1, 1, 1);
1875 d.setLayerInset(2, 2, 2, 2, 2);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001876 mTitleBar.setFavicon(d, getTopWindow());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001877 } else {
Leon Scroggins81db3662009-06-04 17:45:11 -04001878 Drawable[] array = new Drawable[2];
1879 PaintDrawable p = new PaintDrawable(Color.WHITE);
1880 p.setCornerRadius(3f);
1881 array[0] = p;
1882 if (icon == null) {
1883 array[1] = mGenericFavicon;
1884 } else {
1885 array[1] = new BitmapDrawable(icon);
1886 }
1887 LayerDrawable d = new LayerDrawable(array);
1888 d.setLayerInset(1, 2, 2, 2, 2);
1889 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001890 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001891 }
1892
1893 /**
1894 * Saves the current lock-icon state before resetting
1895 * the lock icon. If we have an error, we may need to
1896 * roll back to the previous state.
1897 */
1898 private void saveLockIcon() {
1899 mPrevLockType = mLockIconType;
1900 }
1901
1902 /**
1903 * Reverts the lock-icon state to the last saved state,
1904 * for example, if we had an error, and need to cancel
1905 * the load.
1906 */
1907 private void revertLockIcon() {
1908 mLockIconType = mPrevLockType;
1909
Dave Bort31a6d1c2009-04-13 15:56:49 -07001910 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001911 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
1912 " revert lock icon to " + mLockIconType);
1913 }
1914
1915 updateLockIconImage(mLockIconType);
1916 }
1917
Leon Scroggins1f005d32009-08-10 17:36:42 -04001918 /**
1919 * Close the tab after removing its associated title bar.
1920 */
1921 private void closeTab(TabControl.Tab t) {
1922 mTitleBar.removeTab(mTabControl.getTabIndex(t));
1923 mTabControl.removeTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001924 }
1925
1926 private void goBackOnePageOrQuit() {
1927 TabControl.Tab current = mTabControl.getCurrentTab();
1928 if (current == null) {
1929 /*
1930 * Instead of finishing the activity, simply push this to the back
1931 * of the stack and let ActivityManager to choose the foreground
1932 * activity. As BrowserActivity is singleTask, it will be always the
1933 * root of the task. So we can use either true or false for
1934 * moveTaskToBack().
1935 */
1936 moveTaskToBack(true);
1937 }
1938 WebView w = current.getWebView();
1939 if (w.canGoBack()) {
1940 w.goBack();
1941 } else {
1942 // Check to see if we are closing a window that was created by
1943 // another window. If so, we switch back to that window.
1944 TabControl.Tab parent = current.getParentTab();
1945 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001946 switchToTab(mTabControl.getTabIndex(parent));
1947 // Now we close the other tab
1948 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001949 } else {
1950 if (current.closeOnExit()) {
1951 if (mTabControl.getTabCount() == 1) {
1952 finish();
1953 return;
1954 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04001955 // call pauseWebViewTimers() now, we won't be able to call
1956 // it in onPause() as the WebView won't be valid.
1957 pauseWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001958 removeTabFromContentView(current);
1959 mTabControl.removeTab(current);
1960 }
1961 /*
1962 * Instead of finishing the activity, simply push this to the back
1963 * of the stack and let ActivityManager to choose the foreground
1964 * activity. As BrowserActivity is singleTask, it will be always the
1965 * root of the task. So we can use either true or false for
1966 * moveTaskToBack().
1967 */
1968 moveTaskToBack(true);
1969 }
1970 }
1971 }
1972
1973 public KeyTracker.State onKeyTracker(int keyCode,
1974 KeyEvent event,
1975 KeyTracker.Stage stage,
1976 int duration) {
1977 // if onKeyTracker() is called after activity onStop()
1978 // because of accumulated key events,
1979 // we should ignore it as browser is not active any more.
1980 WebView topWindow = getTopWindow();
Andrei Popescuadc008d2009-06-26 14:11:30 +01001981 if (topWindow == null && mCustomView == null)
The Android Open Source Project0c908882009-03-03 19:32:16 -08001982 return KeyTracker.State.NOT_TRACKING;
1983
1984 if (keyCode == KeyEvent.KEYCODE_BACK) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01001985 // Check if a custom view is currently showing and, if it is, hide it.
1986 if (mCustomView != null) {
1987 mWebChromeClient.onHideCustomView();
1988 return KeyTracker.State.DONE_TRACKING;
1989 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001990 if (stage == KeyTracker.Stage.LONG_REPEAT) {
1991 bookmarksOrHistoryPicker(true);
1992 return KeyTracker.State.DONE_TRACKING;
1993 } else if (stage == KeyTracker.Stage.UP) {
1994 // FIXME: Currently, we do not have a notion of the
1995 // history picker for the subwindow, but maybe we
1996 // should?
1997 WebView subwindow = mTabControl.getCurrentSubWindow();
1998 if (subwindow != null) {
1999 if (subwindow.canGoBack()) {
2000 subwindow.goBack();
2001 } else {
2002 dismissSubWindow(mTabControl.getCurrentTab());
2003 }
2004 } else {
2005 goBackOnePageOrQuit();
2006 }
2007 return KeyTracker.State.DONE_TRACKING;
2008 }
2009 return KeyTracker.State.KEEP_TRACKING;
2010 }
2011 return KeyTracker.State.NOT_TRACKING;
2012 }
2013
2014 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2015 if (keyCode == KeyEvent.KEYCODE_MENU) {
2016 mMenuIsDown = true;
Grace Kloba6ee9c492009-07-13 10:04:34 -07002017 } else if (mMenuIsDown) {
2018 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2019 // still down, we don't want to trigger the search. Pretend to
2020 // consume the key and do nothing.
2021 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002022 }
2023 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2024 if (!handled) {
2025 switch (keyCode) {
2026 case KeyEvent.KEYCODE_SPACE:
2027 if (event.isShiftPressed()) {
2028 getTopWindow().pageUp(false);
2029 } else {
2030 getTopWindow().pageDown(false);
2031 }
2032 handled = true;
2033 break;
2034
2035 default:
2036 break;
2037 }
2038 }
2039 return handled || super.onKeyDown(keyCode, event);
2040 }
2041
2042 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2043 if (keyCode == KeyEvent.KEYCODE_MENU) {
2044 mMenuIsDown = false;
2045 }
2046 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2047 }
2048
2049 private void stopLoading() {
2050 resetTitleAndRevertLockIcon();
2051 WebView w = getTopWindow();
2052 w.stopLoading();
2053 mWebViewClient.onPageFinished(w, w.getUrl());
2054
2055 cancelStopToast();
2056 mStopToast = Toast
2057 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2058 mStopToast.show();
2059 }
2060
2061 private void cancelStopToast() {
2062 if (mStopToast != null) {
2063 mStopToast.cancel();
2064 mStopToast = null;
2065 }
2066 }
2067
2068 // called by a non-UI thread to post the message
2069 public void postMessage(int what, int arg1, int arg2, Object obj) {
2070 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2071 }
2072
2073 // public message ids
2074 public final static int LOAD_URL = 1001;
2075 public final static int STOP_LOAD = 1002;
2076
2077 // Message Ids
2078 private static final int FOCUS_NODE_HREF = 102;
2079 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002080 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002081
2082 // Private handler for handling javascript and saving passwords
2083 private Handler mHandler = new Handler() {
2084
2085 public void handleMessage(Message msg) {
2086 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002087 case FOCUS_NODE_HREF:
2088 String url = (String) msg.getData().get("url");
2089 if (url == null || url.length() == 0) {
2090 break;
2091 }
2092 HashMap focusNodeMap = (HashMap) msg.obj;
2093 WebView view = (WebView) focusNodeMap.get("webview");
2094 // Only apply the action if the top window did not change.
2095 if (getTopWindow() != view) {
2096 break;
2097 }
2098 switch (msg.arg1) {
2099 case R.id.open_context_menu_id:
2100 case R.id.view_image_context_menu_id:
2101 loadURL(getTopWindow(), url);
2102 break;
2103 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002104 final TabControl.Tab parent = mTabControl
2105 .getCurrentTab();
2106 final TabControl.Tab newTab = openTab(url);
2107 if (newTab != parent) {
2108 parent.addChildTab(newTab);
2109 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002110 break;
2111 case R.id.bookmark_context_menu_id:
2112 Intent intent = new Intent(BrowserActivity.this,
2113 AddBookmarkPage.class);
2114 intent.putExtra("url", url);
2115 startActivity(intent);
2116 break;
2117 case R.id.share_link_context_menu_id:
2118 Browser.sendString(BrowserActivity.this, url);
2119 break;
2120 case R.id.copy_link_context_menu_id:
2121 copy(url);
2122 break;
2123 case R.id.save_link_context_menu_id:
2124 case R.id.download_context_menu_id:
2125 onDownloadStartNoStream(url, null, null, null, -1);
2126 break;
2127 }
2128 break;
2129
2130 case LOAD_URL:
2131 loadURL(getTopWindow(), (String) msg.obj);
2132 break;
2133
2134 case STOP_LOAD:
2135 stopLoading();
2136 break;
2137
2138 case CANCEL_CREDS_REQUEST:
2139 resumeAfterCredentials();
2140 break;
2141
The Android Open Source Project0c908882009-03-03 19:32:16 -08002142 case RELEASE_WAKELOCK:
2143 if (mWakeLock.isHeld()) {
2144 mWakeLock.release();
2145 }
2146 break;
2147 }
2148 }
2149 };
2150
Leon Scroggins89c6d362009-07-15 16:54:37 -04002151 private void updateScreenshot(WebView view) {
2152 // If this is a bookmarked site, add a screenshot to the database.
2153 // FIXME: When should we update? Every time?
2154 // FIXME: Would like to make sure there is actually something to
2155 // draw, but the API for that (WebViewCore.pictureReady()) is not
2156 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002157 ContentResolver cr = getContentResolver();
2158 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002159 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002160 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002161 boolean succeed = c.moveToFirst();
2162 ContentValues values = null;
2163 while (succeed) {
2164 if (values == null) {
2165 final ByteArrayOutputStream os
2166 = new ByteArrayOutputStream();
2167 Picture thumbnail = view.capturePicture();
2168 // Keep width and height in sync with BrowserBookmarksPage
2169 // and bookmark_thumb
2170 Bitmap bm = Bitmap.createBitmap(100, 80,
2171 Bitmap.Config.ARGB_4444);
2172 Canvas canvas = new Canvas(bm);
2173 // May need to tweak these values to determine what is the
2174 // best scale factor
2175 canvas.scale(.5f, .5f);
2176 thumbnail.draw(canvas);
2177 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2178 values = new ContentValues();
2179 values.put(Browser.BookmarkColumns.THUMBNAIL,
2180 os.toByteArray());
2181 }
2182 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2183 c.getInt(0)), values, null, null);
2184 succeed = c.moveToNext();
2185 }
2186 c.close();
2187 }
2188 }
2189
The Android Open Source Project0c908882009-03-03 19:32:16 -08002190 // -------------------------------------------------------------------------
2191 // WebViewClient implementation.
2192 //-------------------------------------------------------------------------
2193
2194 // Use in overrideUrlLoading
2195 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2196 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2197 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2198 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2199
2200 /* package */ WebViewClient getWebViewClient() {
2201 return mWebViewClient;
2202 }
2203
Patrick Scott3918d442009-08-04 13:22:29 -04002204 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002205 if (icon != null) {
2206 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott3918d442009-08-04 13:22:29 -04002207 view, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002208 }
2209 setFavicon(icon);
2210 }
2211
2212 private final WebViewClient mWebViewClient = new WebViewClient() {
2213 @Override
2214 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2215 resetLockIcon(url);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002216 setUrlTitle(url, null, view);
Ben Murdochbff2d602009-07-01 20:19:05 +01002217
2218 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2219 if (errorConsole != null) {
2220 errorConsole.clearErrorMessages();
2221 if (mShouldShowErrorConsole) {
2222 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2223 }
2224 }
2225
The Android Open Source Project0c908882009-03-03 19:32:16 -08002226 // Call updateIcon instead of setFavicon so the bookmark
2227 // database can be updated.
Patrick Scott3918d442009-08-04 13:22:29 -04002228 updateIcon(view, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002229
Grace Kloba4d7880f2009-08-12 09:35:42 -07002230 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002231 String host;
2232 try {
2233 WebAddress uri = new WebAddress(url);
2234 host = uri.mHost;
2235 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002236 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002237 }
2238 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002239 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002240 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002241 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002242 }
2243
2244 // Performance probe
2245 if (false) {
2246 mStart = SystemClock.uptimeMillis();
2247 mProcessStart = Process.getElapsedCpuTime();
2248 long[] sysCpu = new long[7];
2249 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2250 sysCpu, null)) {
2251 mUserStart = sysCpu[0] + sysCpu[1];
2252 mSystemStart = sysCpu[2];
2253 mIdleStart = sysCpu[3];
2254 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2255 }
2256 mUiStart = SystemClock.currentThreadTimeMillis();
2257 }
2258
2259 if (!mPageStarted) {
2260 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002261 // if onResume() has been called, resumeWebViewTimers() does
2262 // nothing.
2263 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002264 }
2265
2266 // reset sync timer to avoid sync starts during loading a page
2267 CookieSyncManager.getInstance().resetSync();
2268
2269 mInLoad = true;
2270 updateInLoadMenuItems();
2271 if (!mIsNetworkUp) {
2272 if ( mAlertDialog == null) {
2273 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2274 .setTitle(R.string.loadSuspendedTitle)
2275 .setMessage(R.string.loadSuspended)
2276 .setPositiveButton(R.string.ok, null)
2277 .show();
2278 }
2279 if (view != null) {
2280 view.setNetworkAvailable(false);
2281 }
2282 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002283 }
2284
2285 @Override
2286 public void onPageFinished(WebView view, String url) {
2287 // Reset the title and icon in case we stopped a provisional
2288 // load.
2289 resetTitleAndIcon(view);
2290
2291 // Update the lock icon image only once we are done loading
2292 updateLockIconImage(mLockIconType);
Leon Scroggins89c6d362009-07-15 16:54:37 -04002293 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002294
The Android Open Source Project0c908882009-03-03 19:32:16 -08002295 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002296 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002297 long[] sysCpu = new long[7];
2298 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2299 sysCpu, null)) {
2300 String uiInfo = "UI thread used "
2301 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2302 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002303 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002304 Log.d(LOGTAG, uiInfo);
2305 }
2306 //The string that gets written to the log
2307 String performanceString = "It took total "
2308 + (SystemClock.uptimeMillis() - mStart)
2309 + " ms clock time to load the page."
2310 + "\nbrowser process used "
2311 + (Process.getElapsedCpuTime() - mProcessStart)
2312 + " ms, user processes used "
2313 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2314 + " ms, kernel used "
2315 + (sysCpu[2] - mSystemStart) * 10
2316 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2317 + " ms and irq took "
2318 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2319 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002320 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002321 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2322 }
2323 if (url != null) {
2324 // strip the url to maintain consistency
2325 String newUrl = new String(url);
2326 if (newUrl.startsWith("http://www.")) {
2327 newUrl = newUrl.substring(11);
2328 } else if (newUrl.startsWith("http://")) {
2329 newUrl = newUrl.substring(7);
2330 } else if (newUrl.startsWith("https://www.")) {
2331 newUrl = newUrl.substring(12);
2332 } else if (newUrl.startsWith("https://")) {
2333 newUrl = newUrl.substring(8);
2334 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002335 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002336 Log.d(LOGTAG, newUrl + " loaded");
2337 }
2338 /*
2339 if (sWhiteList.contains(newUrl)) {
2340 // The string that gets pushed to the statistcs
2341 // service
2342 performanceString = performanceString
2343 + "\nWebpage: "
2344 + newUrl
2345 + "\nCarrier: "
2346 + android.os.SystemProperties
2347 .get("gsm.sim.operator.alpha");
2348 if (mWebView != null
2349 && mWebView.getContext() != null
2350 && mWebView.getContext().getSystemService(
2351 Context.CONNECTIVITY_SERVICE) != null) {
2352 ConnectivityManager cManager =
2353 (ConnectivityManager) mWebView
2354 .getContext().getSystemService(
2355 Context.CONNECTIVITY_SERVICE);
2356 NetworkInfo nInfo = cManager
2357 .getActiveNetworkInfo();
2358 if (nInfo != null) {
2359 performanceString = performanceString
2360 + "\nNetwork Type: "
2361 + nInfo.getType().toString();
2362 }
2363 }
2364 Checkin.logEvent(mResolver,
2365 Checkin.Events.Tag.WEBPAGE_LOAD,
2366 performanceString);
2367 Log.w(LOGTAG, "pushed to the statistics service");
2368 }
2369 */
2370 }
2371 }
2372 }
2373
2374 if (mInTrace) {
2375 mInTrace = false;
2376 Debug.stopMethodTracing();
2377 }
2378
2379 if (mPageStarted) {
2380 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002381 // pauseWebViewTimers() will do nothing and return false if
2382 // onPause() is not called yet.
2383 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002384 if (mWakeLock.isHeld()) {
2385 mHandler.removeMessages(RELEASE_WAKELOCK);
2386 mWakeLock.release();
2387 }
2388 }
2389 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002390 }
2391
2392 // return true if want to hijack the url to let another app to handle it
2393 @Override
2394 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2395 if (url.startsWith(SCHEME_WTAI)) {
2396 // wtai://wp/mc;number
2397 // number=string(phone-number)
2398 if (url.startsWith(SCHEME_WTAI_MC)) {
2399 Intent intent = new Intent(Intent.ACTION_VIEW,
2400 Uri.parse(WebView.SCHEME_TEL +
2401 url.substring(SCHEME_WTAI_MC.length())));
2402 startActivity(intent);
2403 return true;
2404 }
2405 // wtai://wp/sd;dtmf
2406 // dtmf=string(dialstring)
2407 if (url.startsWith(SCHEME_WTAI_SD)) {
2408 // TODO
2409 // only send when there is active voice connection
2410 return false;
2411 }
2412 // wtai://wp/ap;number;name
2413 // number=string(phone-number)
2414 // name=string
2415 if (url.startsWith(SCHEME_WTAI_AP)) {
2416 // TODO
2417 return false;
2418 }
2419 }
2420
Dianne Hackborn99189432009-06-17 18:06:18 -07002421 // The "about:" schemes are internal to the browser; don't
2422 // want these to be dispatched to other apps.
2423 if (url.startsWith("about:")) {
2424 return false;
2425 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002426
Dianne Hackborn99189432009-06-17 18:06:18 -07002427 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002428
Dianne Hackborn99189432009-06-17 18:06:18 -07002429 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002430 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002431 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2432 } catch (URISyntaxException ex) {
2433 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002434 return false;
2435 }
2436
Grace Kloba5b078b52009-06-24 20:23:41 -07002437 // check whether the intent can be resolved. If not, we will see
2438 // whether we can download it from the Market.
2439 if (getPackageManager().resolveActivity(intent, 0) == null) {
2440 String packagename = intent.getPackage();
2441 if (packagename != null) {
2442 intent = new Intent(Intent.ACTION_VIEW, Uri
2443 .parse("market://search?q=pname:" + packagename));
2444 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2445 startActivity(intent);
2446 return true;
2447 } else {
2448 return false;
2449 }
2450 }
2451
Dianne Hackborn99189432009-06-17 18:06:18 -07002452 // sanitize the Intent, ensuring web pages can not bypass browser
2453 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002454 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002455 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002456 try {
2457 if (startActivityIfNeeded(intent, -1)) {
2458 return true;
2459 }
2460 } catch (ActivityNotFoundException ex) {
2461 // ignore the error. If no application can handle the URL,
2462 // eg about:blank, assume the browser can handle it.
2463 }
2464
2465 if (mMenuIsDown) {
2466 openTab(url);
2467 closeOptionsMenu();
2468 return true;
2469 }
2470
2471 return false;
2472 }
2473
2474 /**
2475 * Updates the lock icon. This method is called when we discover another
2476 * resource to be loaded for this page (for example, javascript). While
2477 * we update the icon type, we do not update the lock icon itself until
2478 * we are done loading, it is slightly more secure this way.
2479 */
2480 @Override
2481 public void onLoadResource(WebView view, String url) {
2482 if (url != null && url.length() > 0) {
2483 // It is only if the page claims to be secure
2484 // that we may have to update the lock:
2485 if (mLockIconType == LOCK_ICON_SECURE) {
2486 // If NOT a 'safe' url, change the lock to mixed content!
2487 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2488 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002489 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002490 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2491 " updated lock icon to " + mLockIconType + " due to " + url);
2492 }
2493 }
2494 }
2495 }
2496 }
2497
2498 /**
2499 * Show the dialog, asking the user if they would like to continue after
2500 * an excessive number of HTTP redirects.
2501 */
2502 @Override
2503 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2504 final Message continueMsg) {
2505 new AlertDialog.Builder(BrowserActivity.this)
2506 .setTitle(R.string.browserFrameRedirect)
2507 .setMessage(R.string.browserFrame307Post)
2508 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2509 public void onClick(DialogInterface dialog, int which) {
2510 continueMsg.sendToTarget();
2511 }})
2512 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2513 public void onClick(DialogInterface dialog, int which) {
2514 cancelMsg.sendToTarget();
2515 }})
2516 .setOnCancelListener(new OnCancelListener() {
2517 public void onCancel(DialogInterface dialog) {
2518 cancelMsg.sendToTarget();
2519 }})
2520 .show();
2521 }
2522
Patrick Scott37911c72009-03-24 18:02:58 -07002523 // Container class for the next error dialog that needs to be
2524 // displayed.
2525 class ErrorDialog {
2526 public final int mTitle;
2527 public final String mDescription;
2528 public final int mError;
2529 ErrorDialog(int title, String desc, int error) {
2530 mTitle = title;
2531 mDescription = desc;
2532 mError = error;
2533 }
2534 };
2535
2536 private void processNextError() {
2537 if (mQueuedErrors == null) {
2538 return;
2539 }
2540 // The first one is currently displayed so just remove it.
2541 mQueuedErrors.removeFirst();
2542 if (mQueuedErrors.size() == 0) {
2543 mQueuedErrors = null;
2544 return;
2545 }
2546 showError(mQueuedErrors.getFirst());
2547 }
2548
2549 private DialogInterface.OnDismissListener mDialogListener =
2550 new DialogInterface.OnDismissListener() {
2551 public void onDismiss(DialogInterface d) {
2552 processNextError();
2553 }
2554 };
2555 private LinkedList<ErrorDialog> mQueuedErrors;
2556
2557 private void queueError(int err, String desc) {
2558 if (mQueuedErrors == null) {
2559 mQueuedErrors = new LinkedList<ErrorDialog>();
2560 }
2561 for (ErrorDialog d : mQueuedErrors) {
2562 if (d.mError == err) {
2563 // Already saw a similar error, ignore the new one.
2564 return;
2565 }
2566 }
2567 ErrorDialog errDialog = new ErrorDialog(
2568 err == EventHandler.FILE_NOT_FOUND_ERROR ?
2569 R.string.browserFrameFileErrorLabel :
2570 R.string.browserFrameNetworkErrorLabel,
2571 desc, err);
2572 mQueuedErrors.addLast(errDialog);
2573
2574 // Show the dialog now if the queue was empty.
2575 if (mQueuedErrors.size() == 1) {
2576 showError(errDialog);
2577 }
2578 }
2579
2580 private void showError(ErrorDialog errDialog) {
2581 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2582 .setTitle(errDialog.mTitle)
2583 .setMessage(errDialog.mDescription)
2584 .setPositiveButton(R.string.ok, null)
2585 .create();
2586 d.setOnDismissListener(mDialogListener);
2587 d.show();
2588 }
2589
The Android Open Source Project0c908882009-03-03 19:32:16 -08002590 /**
2591 * Show a dialog informing the user of the network error reported by
2592 * WebCore.
2593 */
2594 @Override
2595 public void onReceivedError(WebView view, int errorCode,
2596 String description, String failingUrl) {
2597 if (errorCode != EventHandler.ERROR_LOOKUP &&
2598 errorCode != EventHandler.ERROR_CONNECT &&
2599 errorCode != EventHandler.ERROR_BAD_URL &&
2600 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
2601 errorCode != EventHandler.FILE_ERROR) {
Patrick Scott37911c72009-03-24 18:02:58 -07002602 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002603 }
Patrick Scott37911c72009-03-24 18:02:58 -07002604 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2605 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002606
2607 // We need to reset the title after an error.
2608 resetTitleAndRevertLockIcon();
2609 }
2610
2611 /**
2612 * Check with the user if it is ok to resend POST data as the page they
2613 * are trying to navigate to is the result of a POST.
2614 */
2615 @Override
2616 public void onFormResubmission(WebView view, final Message dontResend,
2617 final Message resend) {
2618 new AlertDialog.Builder(BrowserActivity.this)
2619 .setTitle(R.string.browserFrameFormResubmitLabel)
2620 .setMessage(R.string.browserFrameFormResubmitMessage)
2621 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2622 public void onClick(DialogInterface dialog, int which) {
2623 resend.sendToTarget();
2624 }})
2625 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2626 public void onClick(DialogInterface dialog, int which) {
2627 dontResend.sendToTarget();
2628 }})
2629 .setOnCancelListener(new OnCancelListener() {
2630 public void onCancel(DialogInterface dialog) {
2631 dontResend.sendToTarget();
2632 }})
2633 .show();
2634 }
2635
2636 /**
2637 * Insert the url into the visited history database.
2638 * @param url The url to be inserted.
2639 * @param isReload True if this url is being reloaded.
2640 * FIXME: Not sure what to do when reloading the page.
2641 */
2642 @Override
2643 public void doUpdateVisitedHistory(WebView view, String url,
2644 boolean isReload) {
2645 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2646 return;
2647 }
2648 Browser.updateVisitedHistory(mResolver, url, true);
2649 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2650 }
2651
2652 /**
2653 * Displays SSL error(s) dialog to the user.
2654 */
2655 @Override
2656 public void onReceivedSslError(
2657 final WebView view, final SslErrorHandler handler, final SslError error) {
2658
2659 if (mSettings.showSecurityWarnings()) {
2660 final LayoutInflater factory =
2661 LayoutInflater.from(BrowserActivity.this);
2662 final View warningsView =
2663 factory.inflate(R.layout.ssl_warnings, null);
2664 final LinearLayout placeholder =
2665 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2666
2667 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2668 LinearLayout ll = (LinearLayout)factory
2669 .inflate(R.layout.ssl_warning, null);
2670 ((TextView)ll.findViewById(R.id.warning))
2671 .setText(R.string.ssl_untrusted);
2672 placeholder.addView(ll);
2673 }
2674
2675 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2676 LinearLayout ll = (LinearLayout)factory
2677 .inflate(R.layout.ssl_warning, null);
2678 ((TextView)ll.findViewById(R.id.warning))
2679 .setText(R.string.ssl_mismatch);
2680 placeholder.addView(ll);
2681 }
2682
2683 if (error.hasError(SslError.SSL_EXPIRED)) {
2684 LinearLayout ll = (LinearLayout)factory
2685 .inflate(R.layout.ssl_warning, null);
2686 ((TextView)ll.findViewById(R.id.warning))
2687 .setText(R.string.ssl_expired);
2688 placeholder.addView(ll);
2689 }
2690
2691 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2692 LinearLayout ll = (LinearLayout)factory
2693 .inflate(R.layout.ssl_warning, null);
2694 ((TextView)ll.findViewById(R.id.warning))
2695 .setText(R.string.ssl_not_yet_valid);
2696 placeholder.addView(ll);
2697 }
2698
2699 new AlertDialog.Builder(BrowserActivity.this)
2700 .setTitle(R.string.security_warning)
2701 .setIcon(android.R.drawable.ic_dialog_alert)
2702 .setView(warningsView)
2703 .setPositiveButton(R.string.ssl_continue,
2704 new DialogInterface.OnClickListener() {
2705 public void onClick(DialogInterface dialog, int whichButton) {
2706 handler.proceed();
2707 }
2708 })
2709 .setNeutralButton(R.string.view_certificate,
2710 new DialogInterface.OnClickListener() {
2711 public void onClick(DialogInterface dialog, int whichButton) {
2712 showSSLCertificateOnError(view, handler, error);
2713 }
2714 })
2715 .setNegativeButton(R.string.cancel,
2716 new DialogInterface.OnClickListener() {
2717 public void onClick(DialogInterface dialog, int whichButton) {
2718 handler.cancel();
2719 BrowserActivity.this.resetTitleAndRevertLockIcon();
2720 }
2721 })
2722 .setOnCancelListener(
2723 new DialogInterface.OnCancelListener() {
2724 public void onCancel(DialogInterface dialog) {
2725 handler.cancel();
2726 BrowserActivity.this.resetTitleAndRevertLockIcon();
2727 }
2728 })
2729 .show();
2730 } else {
2731 handler.proceed();
2732 }
2733 }
2734
2735 /**
2736 * Handles an HTTP authentication request.
2737 *
2738 * @param handler The authentication handler
2739 * @param host The host
2740 * @param realm The realm
2741 */
2742 @Override
2743 public void onReceivedHttpAuthRequest(WebView view,
2744 final HttpAuthHandler handler, final String host, final String realm) {
2745 String username = null;
2746 String password = null;
2747
2748 boolean reuseHttpAuthUsernamePassword =
2749 handler.useHttpAuthUsernamePassword();
2750
2751 if (reuseHttpAuthUsernamePassword &&
2752 (mTabControl.getCurrentWebView() != null)) {
2753 String[] credentials =
2754 mTabControl.getCurrentWebView()
2755 .getHttpAuthUsernamePassword(host, realm);
2756 if (credentials != null && credentials.length == 2) {
2757 username = credentials[0];
2758 password = credentials[1];
2759 }
2760 }
2761
2762 if (username != null && password != null) {
2763 handler.proceed(username, password);
2764 } else {
2765 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2766 }
2767 }
2768
2769 @Override
2770 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2771 if (mMenuIsDown) {
2772 // only check shortcut key when MENU is held
2773 return getWindow().isShortcutKey(event.getKeyCode(), event);
2774 } else {
2775 return false;
2776 }
2777 }
2778
2779 @Override
2780 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2781 if (view != mTabControl.getCurrentTopWebView()) {
2782 return;
2783 }
2784 if (event.isDown()) {
2785 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2786 } else {
2787 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2788 }
2789 }
2790 };
2791
2792 //--------------------------------------------------------------------------
2793 // WebChromeClient implementation
2794 //--------------------------------------------------------------------------
2795
2796 /* package */ WebChromeClient getWebChromeClient() {
2797 return mWebChromeClient;
2798 }
2799
2800 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2801 // Helper method to create a new tab or sub window.
2802 private void createWindow(final boolean dialog, final Message msg) {
2803 if (dialog) {
2804 mTabControl.createSubWindow();
2805 final TabControl.Tab t = mTabControl.getCurrentTab();
2806 attachSubWindow(t);
2807 WebView.WebViewTransport transport =
2808 (WebView.WebViewTransport) msg.obj;
2809 transport.setWebView(t.getSubWebView());
2810 msg.sendToTarget();
2811 } else {
2812 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04002813 final TabControl.Tab newTab
2814 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07002815 if (newTab != parent) {
2816 parent.addChildTab(newTab);
2817 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002818 WebView.WebViewTransport transport =
2819 (WebView.WebViewTransport) msg.obj;
2820 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04002821 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002822 }
2823 }
2824
2825 @Override
2826 public boolean onCreateWindow(WebView view, final boolean dialog,
2827 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002828 // Short-circuit if we can't create any more tabs or sub windows.
2829 if (dialog && mTabControl.getCurrentSubWindow() != null) {
2830 new AlertDialog.Builder(BrowserActivity.this)
2831 .setTitle(R.string.too_many_subwindows_dialog_title)
2832 .setIcon(android.R.drawable.ic_dialog_alert)
2833 .setMessage(R.string.too_many_subwindows_dialog_message)
2834 .setPositiveButton(R.string.ok, null)
2835 .show();
2836 return false;
2837 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
2838 new AlertDialog.Builder(BrowserActivity.this)
2839 .setTitle(R.string.too_many_windows_dialog_title)
2840 .setIcon(android.R.drawable.ic_dialog_alert)
2841 .setMessage(R.string.too_many_windows_dialog_message)
2842 .setPositiveButton(R.string.ok, null)
2843 .show();
2844 return false;
2845 }
2846
2847 // Short-circuit if this was a user gesture.
2848 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002849 createWindow(dialog, resultMsg);
2850 return true;
2851 }
2852
2853 // Allow the popup and create the appropriate window.
2854 final AlertDialog.OnClickListener allowListener =
2855 new AlertDialog.OnClickListener() {
2856 public void onClick(DialogInterface d,
2857 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002858 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002859 }
2860 };
2861
2862 // Block the popup by returning a null WebView.
2863 final AlertDialog.OnClickListener blockListener =
2864 new AlertDialog.OnClickListener() {
2865 public void onClick(DialogInterface d, int which) {
2866 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002867 }
2868 };
2869
2870 // Build a confirmation dialog to display to the user.
2871 final AlertDialog d =
2872 new AlertDialog.Builder(BrowserActivity.this)
2873 .setTitle(R.string.attention)
2874 .setIcon(android.R.drawable.ic_dialog_alert)
2875 .setMessage(R.string.popup_window_attempt)
2876 .setPositiveButton(R.string.allow, allowListener)
2877 .setNegativeButton(R.string.block, blockListener)
2878 .setCancelable(false)
2879 .create();
2880
2881 // Show the confirmation dialog.
2882 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002883 return true;
2884 }
2885
2886 @Override
2887 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002888 final TabControl.Tab current = mTabControl.getCurrentTab();
2889 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002890 if (parent != null) {
2891 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002892 switchToTab(mTabControl.getTabIndex(parent));
2893 // Now we need to close the window
2894 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002895 }
2896 }
2897
2898 @Override
2899 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002900 if (CUSTOM_BROWSER_BAR) {
2901 mTitleBar.setProgress(newProgress, view);
2902 } else {
2903 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
2904 newProgress * 100);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002905 }
2906
2907 if (newProgress == 100) {
2908 // onProgressChanged() is called for sub-frame too while
2909 // onPageFinished() is only called for the main frame. sync
2910 // cookie and cache promptly here.
2911 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002912 if (mInLoad) {
2913 mInLoad = false;
2914 updateInLoadMenuItems();
2915 }
2916 } else {
2917 // onPageFinished may have already been called but a subframe
2918 // is still loading and updating the progress. Reset mInLoad
2919 // and update the menu items.
2920 if (!mInLoad) {
2921 mInLoad = true;
2922 updateInLoadMenuItems();
2923 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002924 }
2925 }
2926
2927 @Override
2928 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04002929 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002930
2931 // here, if url is null, we want to reset the title
Leon Scroggins1f005d32009-08-10 17:36:42 -04002932 setUrlTitle(url, title, view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002933
2934 if (url == null ||
2935 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
2936 return;
2937 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04002938 // See if we can find the current url in our history database and
2939 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002940 if (url.startsWith("http://www.")) {
2941 url = url.substring(11);
2942 } else if (url.startsWith("http://")) {
2943 url = url.substring(4);
2944 }
2945 try {
2946 url = "%" + url;
2947 String [] selArgs = new String[] { url };
2948
2949 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
2950 + Browser.BookmarkColumns.BOOKMARK + " = 0";
2951 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2952 Browser.HISTORY_PROJECTION, where, selArgs, null);
2953 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002954 // Current implementation of database only has one entry per
2955 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04002956 ContentValues map = new ContentValues();
2957 map.put(Browser.BookmarkColumns.TITLE, title);
2958 mResolver.update(Browser.BOOKMARKS_URI, map,
2959 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002960 }
2961 c.close();
2962 } catch (IllegalStateException e) {
2963 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
2964 } catch (SQLiteException ex) {
2965 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
2966 }
2967 }
2968
2969 @Override
2970 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04002971 updateIcon(view, icon);
2972 }
2973
2974 @Override
2975 public void onReceivedTouchIconUrl(WebView view, String url) {
2976 final ContentResolver cr = getContentResolver();
2977 final Cursor c =
2978 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002979 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002980 if (c != null) {
2981 if (c.getCount() > 0) {
2982 new DownloadTouchIcon(cr, c, view).execute(url);
2983 } else {
2984 c.close();
2985 }
2986 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002987 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01002988
Andrei Popescuadc008d2009-06-26 14:11:30 +01002989 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01002990 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01002991 if (mCustomView != null)
2992 return;
2993
2994 // Add the custom view to its container.
2995 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2996 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01002997 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01002998 // Save the menu state and set it to empty while the custom
2999 // view is showing.
3000 mOldMenuState = mMenuState;
3001 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003002 // Hide the content view.
3003 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003004 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003005 mCustomViewContainer.setVisibility(View.VISIBLE);
3006 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003007 }
3008
3009 @Override
3010 public void onHideCustomView() {
3011 if (mCustomView == null)
3012 return;
3013
Andrei Popescuc9b55562009-07-07 10:51:15 +01003014 // Hide the custom view.
3015 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003016 // Remove the custom view from its container.
3017 mCustomViewContainer.removeView(mCustomView);
3018 mCustomView = null;
3019 // Reset the old menu state.
3020 mMenuState = mOldMenuState;
3021 mOldMenuState = EMPTY_MENU;
3022 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003023 mCustomViewCallback.onCustomViewHidden();
3024 // Show the content view.
3025 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003026 }
3027
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003028 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003029 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003030 * @param url the URL that exceeded the quota
3031 * @param databaseIdentifier the identifier of the database on
3032 * which the transaction that caused the quota overflow was run
3033 * @param currentQuota the current quota for the origin.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003034 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003035 * @param quotaUpdater The callback to run when a decision to allow or
3036 * deny quota has been made. Don't forget to call this!
3037 */
3038 @Override
3039 public void onExceededDatabaseQuota(String url,
Andrei Popescu79e82b72009-07-27 12:01:59 +01003040 String databaseIdentifier, long currentQuota, long totalUsedQuota,
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003041 WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003042 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
3043 url, databaseIdentifier, currentQuota, totalUsedQuota,
3044 quotaUpdater);
3045 }
3046
3047 /**
3048 * The Application Cache has exceeded its max size.
3049 * @param spaceNeeded is the amount of disk space that would be needed
3050 * in order for the last appcache operation to succeed.
3051 * @param totalUsedQuota is the sum of all origins' quota.
3052 * @param quotaUpdater A callback to inform the WebCore thread that a new
3053 * app cache size is available. This callback must always be executed at
3054 * some point to ensure that the sleeping WebCore thread is woken up.
3055 */
3056 @Override
3057 public void onReachedMaxAppCacheSize(long spaceNeeded,
3058 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3059 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3060 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003061 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003062
Steve Block2bc69912009-07-30 14:45:13 +01003063 /**
3064 * Instructs the browser to show a prompt to ask the user to set the
3065 * Geolocation permission state for the specified origin.
3066 * @param origin The origin for which Geolocation permissions are
3067 * requested.
3068 * @param callback The callback to call once the user has set the
3069 * Geolocation permission state.
3070 */
3071 @Override
3072 public void onGeolocationPermissionsShowPrompt(String origin,
3073 GeolocationPermissions.Callback callback) {
3074 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3075 origin, callback);
3076 }
3077
3078 /**
3079 * Instructs the browser to hide the Geolocation permissions prompt.
3080 */
3081 @Override
3082 public void onGeolocationPermissionsHidePrompt() {
3083 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3084 }
3085
Ben Murdoch7db26342009-06-03 18:21:19 +01003086 /* Adds a JavaScript error message to the system log.
3087 * @param message The error message to report.
3088 * @param lineNumber The line number of the error.
3089 * @param sourceID The name of the source file that caused the error.
3090 */
3091 @Override
3092 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003093 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3094 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3095 if (mShouldShowErrorConsole &&
3096 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3097 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3098 }
3099 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003100 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003101 };
3102
3103 /**
3104 * Notify the host application a download should be done, or that
3105 * the data should be streamed if a streaming viewer is available.
3106 * @param url The full url to the content that should be downloaded
3107 * @param contentDisposition Content-disposition http header, if
3108 * present.
3109 * @param mimetype The mimetype of the content reported by the server
3110 * @param contentLength The file size reported by the server
3111 */
3112 public void onDownloadStart(String url, String userAgent,
3113 String contentDisposition, String mimetype, long contentLength) {
3114 // if we're dealing wih A/V content that's not explicitly marked
3115 // for download, check if it's streamable.
3116 if (contentDisposition == null
3117 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3118 // query the package manager to see if there's a registered handler
3119 // that matches.
3120 Intent intent = new Intent(Intent.ACTION_VIEW);
3121 intent.setDataAndType(Uri.parse(url), mimetype);
3122 if (getPackageManager().resolveActivity(intent,
3123 PackageManager.MATCH_DEFAULT_ONLY) != null) {
3124 // someone knows how to handle this mime type with this scheme, don't download.
3125 try {
3126 startActivity(intent);
3127 return;
3128 } catch (ActivityNotFoundException ex) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07003129 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003130 Log.d(LOGTAG, "activity not found for " + mimetype
3131 + " over " + Uri.parse(url).getScheme(), ex);
3132 }
3133 // Best behavior is to fall back to a download in this case
3134 }
3135 }
3136 }
3137 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3138 }
3139
3140 /**
3141 * Notify the host application a download should be done, even if there
3142 * is a streaming viewer available for thise type.
3143 * @param url The full url to the content that should be downloaded
3144 * @param contentDisposition Content-disposition http header, if
3145 * present.
3146 * @param mimetype The mimetype of the content reported by the server
3147 * @param contentLength The file size reported by the server
3148 */
3149 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3150 String contentDisposition, String mimetype, long contentLength) {
3151
3152 String filename = URLUtil.guessFileName(url,
3153 contentDisposition, mimetype);
3154
3155 // Check to see if we have an SDCard
3156 String status = Environment.getExternalStorageState();
3157 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3158 int title;
3159 String msg;
3160
3161 // Check to see if the SDCard is busy, same as the music app
3162 if (status.equals(Environment.MEDIA_SHARED)) {
3163 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3164 title = R.string.download_sdcard_busy_dlg_title;
3165 } else {
3166 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3167 title = R.string.download_no_sdcard_dlg_title;
3168 }
3169
3170 new AlertDialog.Builder(this)
3171 .setTitle(title)
3172 .setIcon(android.R.drawable.ic_dialog_alert)
3173 .setMessage(msg)
3174 .setPositiveButton(R.string.ok, null)
3175 .show();
3176 return;
3177 }
3178
3179 // java.net.URI is a lot stricter than KURL so we have to undo
3180 // KURL's percent-encoding and redo the encoding using java.net.URI.
3181 URI uri = null;
3182 try {
3183 // Undo the percent-encoding that KURL may have done.
3184 String newUrl = new String(URLUtil.decode(url.getBytes()));
3185 // Parse the url into pieces
3186 WebAddress w = new WebAddress(newUrl);
3187 String frag = null;
3188 String query = null;
3189 String path = w.mPath;
3190 // Break the path into path, query, and fragment
3191 if (path.length() > 0) {
3192 // Strip the fragment
3193 int idx = path.lastIndexOf('#');
3194 if (idx != -1) {
3195 frag = path.substring(idx + 1);
3196 path = path.substring(0, idx);
3197 }
3198 idx = path.lastIndexOf('?');
3199 if (idx != -1) {
3200 query = path.substring(idx + 1);
3201 path = path.substring(0, idx);
3202 }
3203 }
3204 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3205 query, frag);
3206 } catch (Exception e) {
3207 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3208 return;
3209 }
3210
3211 // XXX: Have to use the old url since the cookies were stored using the
3212 // old percent-encoded url.
3213 String cookies = CookieManager.getInstance().getCookie(url);
3214
3215 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003216 values.put(Downloads.COLUMN_URI, uri.toString());
3217 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3218 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3219 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003220 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003221 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003222 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003223 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3224 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3225 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3226 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003227 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003228 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003229 }
3230 if (mimetype == null) {
3231 // We must have long pressed on a link or image to download it. We
3232 // are not sure of the mimetype in this case, so do a head request
3233 new FetchUrlMimeType(this).execute(values);
3234 } else {
3235 final Uri contentUri =
3236 getContentResolver().insert(Downloads.CONTENT_URI, values);
3237 viewDownloads(contentUri);
3238 }
3239
3240 }
3241
3242 /**
3243 * Resets the lock icon. This method is called when we start a new load and
3244 * know the url to be loaded.
3245 */
3246 private void resetLockIcon(String url) {
3247 // Save the lock-icon state (we revert to it if the load gets cancelled)
3248 saveLockIcon();
3249
3250 mLockIconType = LOCK_ICON_UNSECURE;
3251 if (URLUtil.isHttpsUrl(url)) {
3252 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003253 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003254 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3255 " reset lock icon to " + mLockIconType);
3256 }
3257 }
3258
3259 updateLockIconImage(LOCK_ICON_UNSECURE);
3260 }
3261
3262 /**
3263 * Resets the lock icon. This method is called when the icon needs to be
3264 * reset but we do not know whether we are loading a secure or not secure
3265 * page.
3266 */
3267 private void resetLockIcon() {
3268 // Save the lock-icon state (we revert to it if the load gets cancelled)
3269 saveLockIcon();
3270
3271 mLockIconType = LOCK_ICON_UNSECURE;
3272
Dave Bort31a6d1c2009-04-13 15:56:49 -07003273 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003274 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3275 " reset lock icon to " + mLockIconType);
3276 }
3277
3278 updateLockIconImage(LOCK_ICON_UNSECURE);
3279 }
3280
3281 /**
3282 * Updates the lock-icon image in the title-bar.
3283 */
3284 private void updateLockIconImage(int lockIconType) {
3285 Drawable d = null;
3286 if (lockIconType == LOCK_ICON_SECURE) {
3287 d = mSecLockIcon;
3288 } else if (lockIconType == LOCK_ICON_MIXED) {
3289 d = mMixLockIcon;
3290 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04003291 if (CUSTOM_BROWSER_BAR) {
3292 mTitleBar.setLock(d, getTopWindow());
3293 } else {
3294 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003295 }
3296 }
3297
3298 /**
3299 * Displays a page-info dialog.
3300 * @param tab The tab to show info about
3301 * @param fromShowSSLCertificateOnError The flag that indicates whether
3302 * this dialog was opened from the SSL-certificate-on-error dialog or
3303 * not. This is important, since we need to know whether to return to
3304 * the parent dialog or simply dismiss.
3305 */
3306 private void showPageInfo(final TabControl.Tab tab,
3307 final boolean fromShowSSLCertificateOnError) {
3308 final LayoutInflater factory = LayoutInflater
3309 .from(this);
3310
3311 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3312
3313 final WebView view = tab.getWebView();
3314
3315 String url = null;
3316 String title = null;
3317
3318 if (view == null) {
3319 url = tab.getUrl();
3320 title = tab.getTitle();
3321 } else if (view == mTabControl.getCurrentWebView()) {
3322 // Use the cached title and url if this is the current WebView
3323 url = mUrl;
3324 title = mTitle;
3325 } else {
3326 url = view.getUrl();
3327 title = view.getTitle();
3328 }
3329
3330 if (url == null) {
3331 url = "";
3332 }
3333 if (title == null) {
3334 title = "";
3335 }
3336
3337 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3338 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3339
3340 mPageInfoView = tab;
3341 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3342
3343 AlertDialog.Builder alertDialogBuilder =
3344 new AlertDialog.Builder(this)
3345 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3346 .setView(pageInfoView)
3347 .setPositiveButton(
3348 R.string.ok,
3349 new DialogInterface.OnClickListener() {
3350 public void onClick(DialogInterface dialog,
3351 int whichButton) {
3352 mPageInfoDialog = null;
3353 mPageInfoView = null;
3354 mPageInfoFromShowSSLCertificateOnError = null;
3355
3356 // if we came here from the SSL error dialog
3357 if (fromShowSSLCertificateOnError) {
3358 // go back to the SSL error dialog
3359 showSSLCertificateOnError(
3360 mSSLCertificateOnErrorView,
3361 mSSLCertificateOnErrorHandler,
3362 mSSLCertificateOnErrorError);
3363 }
3364 }
3365 })
3366 .setOnCancelListener(
3367 new DialogInterface.OnCancelListener() {
3368 public void onCancel(DialogInterface dialog) {
3369 mPageInfoDialog = null;
3370 mPageInfoView = null;
3371 mPageInfoFromShowSSLCertificateOnError = null;
3372
3373 // if we came here from the SSL error dialog
3374 if (fromShowSSLCertificateOnError) {
3375 // go back to the SSL error dialog
3376 showSSLCertificateOnError(
3377 mSSLCertificateOnErrorView,
3378 mSSLCertificateOnErrorHandler,
3379 mSSLCertificateOnErrorError);
3380 }
3381 }
3382 });
3383
3384 // if we have a main top-level page SSL certificate set or a certificate
3385 // error
3386 if (fromShowSSLCertificateOnError ||
3387 (view != null && view.getCertificate() != null)) {
3388 // add a 'View Certificate' button
3389 alertDialogBuilder.setNeutralButton(
3390 R.string.view_certificate,
3391 new DialogInterface.OnClickListener() {
3392 public void onClick(DialogInterface dialog,
3393 int whichButton) {
3394 mPageInfoDialog = null;
3395 mPageInfoView = null;
3396 mPageInfoFromShowSSLCertificateOnError = null;
3397
3398 // if we came here from the SSL error dialog
3399 if (fromShowSSLCertificateOnError) {
3400 // go back to the SSL error dialog
3401 showSSLCertificateOnError(
3402 mSSLCertificateOnErrorView,
3403 mSSLCertificateOnErrorHandler,
3404 mSSLCertificateOnErrorError);
3405 } else {
3406 // otherwise, display the top-most certificate from
3407 // the chain
3408 if (view.getCertificate() != null) {
3409 showSSLCertificate(tab);
3410 }
3411 }
3412 }
3413 });
3414 }
3415
3416 mPageInfoDialog = alertDialogBuilder.show();
3417 }
3418
3419 /**
3420 * Displays the main top-level page SSL certificate dialog
3421 * (accessible from the Page-Info dialog).
3422 * @param tab The tab to show certificate for.
3423 */
3424 private void showSSLCertificate(final TabControl.Tab tab) {
3425 final View certificateView =
3426 inflateCertificateView(tab.getWebView().getCertificate());
3427 if (certificateView == null) {
3428 return;
3429 }
3430
3431 LayoutInflater factory = LayoutInflater.from(this);
3432
3433 final LinearLayout placeholder =
3434 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3435
3436 LinearLayout ll = (LinearLayout) factory.inflate(
3437 R.layout.ssl_success, placeholder);
3438 ((TextView)ll.findViewById(R.id.success))
3439 .setText(R.string.ssl_certificate_is_valid);
3440
3441 mSSLCertificateView = tab;
3442 mSSLCertificateDialog =
3443 new AlertDialog.Builder(this)
3444 .setTitle(R.string.ssl_certificate).setIcon(
3445 R.drawable.ic_dialog_browser_certificate_secure)
3446 .setView(certificateView)
3447 .setPositiveButton(R.string.ok,
3448 new DialogInterface.OnClickListener() {
3449 public void onClick(DialogInterface dialog,
3450 int whichButton) {
3451 mSSLCertificateDialog = null;
3452 mSSLCertificateView = null;
3453
3454 showPageInfo(tab, false);
3455 }
3456 })
3457 .setOnCancelListener(
3458 new DialogInterface.OnCancelListener() {
3459 public void onCancel(DialogInterface dialog) {
3460 mSSLCertificateDialog = null;
3461 mSSLCertificateView = null;
3462
3463 showPageInfo(tab, false);
3464 }
3465 })
3466 .show();
3467 }
3468
3469 /**
3470 * Displays the SSL error certificate dialog.
3471 * @param view The target web-view.
3472 * @param handler The SSL error handler responsible for cancelling the
3473 * connection that resulted in an SSL error or proceeding per user request.
3474 * @param error The SSL error object.
3475 */
3476 private void showSSLCertificateOnError(
3477 final WebView view, final SslErrorHandler handler, final SslError error) {
3478
3479 final View certificateView =
3480 inflateCertificateView(error.getCertificate());
3481 if (certificateView == null) {
3482 return;
3483 }
3484
3485 LayoutInflater factory = LayoutInflater.from(this);
3486
3487 final LinearLayout placeholder =
3488 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3489
3490 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3491 LinearLayout ll = (LinearLayout)factory
3492 .inflate(R.layout.ssl_warning, placeholder);
3493 ((TextView)ll.findViewById(R.id.warning))
3494 .setText(R.string.ssl_untrusted);
3495 }
3496
3497 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3498 LinearLayout ll = (LinearLayout)factory
3499 .inflate(R.layout.ssl_warning, placeholder);
3500 ((TextView)ll.findViewById(R.id.warning))
3501 .setText(R.string.ssl_mismatch);
3502 }
3503
3504 if (error.hasError(SslError.SSL_EXPIRED)) {
3505 LinearLayout ll = (LinearLayout)factory
3506 .inflate(R.layout.ssl_warning, placeholder);
3507 ((TextView)ll.findViewById(R.id.warning))
3508 .setText(R.string.ssl_expired);
3509 }
3510
3511 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3512 LinearLayout ll = (LinearLayout)factory
3513 .inflate(R.layout.ssl_warning, placeholder);
3514 ((TextView)ll.findViewById(R.id.warning))
3515 .setText(R.string.ssl_not_yet_valid);
3516 }
3517
3518 mSSLCertificateOnErrorHandler = handler;
3519 mSSLCertificateOnErrorView = view;
3520 mSSLCertificateOnErrorError = error;
3521 mSSLCertificateOnErrorDialog =
3522 new AlertDialog.Builder(this)
3523 .setTitle(R.string.ssl_certificate).setIcon(
3524 R.drawable.ic_dialog_browser_certificate_partially_secure)
3525 .setView(certificateView)
3526 .setPositiveButton(R.string.ok,
3527 new DialogInterface.OnClickListener() {
3528 public void onClick(DialogInterface dialog,
3529 int whichButton) {
3530 mSSLCertificateOnErrorDialog = null;
3531 mSSLCertificateOnErrorView = null;
3532 mSSLCertificateOnErrorHandler = null;
3533 mSSLCertificateOnErrorError = null;
3534
3535 mWebViewClient.onReceivedSslError(
3536 view, handler, error);
3537 }
3538 })
3539 .setNeutralButton(R.string.page_info_view,
3540 new DialogInterface.OnClickListener() {
3541 public void onClick(DialogInterface dialog,
3542 int whichButton) {
3543 mSSLCertificateOnErrorDialog = null;
3544
3545 // do not clear the dialog state: we will
3546 // need to show the dialog again once the
3547 // user is done exploring the page-info details
3548
3549 showPageInfo(mTabControl.getTabFromView(view),
3550 true);
3551 }
3552 })
3553 .setOnCancelListener(
3554 new DialogInterface.OnCancelListener() {
3555 public void onCancel(DialogInterface dialog) {
3556 mSSLCertificateOnErrorDialog = null;
3557 mSSLCertificateOnErrorView = null;
3558 mSSLCertificateOnErrorHandler = null;
3559 mSSLCertificateOnErrorError = null;
3560
3561 mWebViewClient.onReceivedSslError(
3562 view, handler, error);
3563 }
3564 })
3565 .show();
3566 }
3567
3568 /**
3569 * Inflates the SSL certificate view (helper method).
3570 * @param certificate The SSL certificate.
3571 * @return The resultant certificate view with issued-to, issued-by,
3572 * issued-on, expires-on, and possibly other fields set.
3573 * If the input certificate is null, returns null.
3574 */
3575 private View inflateCertificateView(SslCertificate certificate) {
3576 if (certificate == null) {
3577 return null;
3578 }
3579
3580 LayoutInflater factory = LayoutInflater.from(this);
3581
3582 View certificateView = factory.inflate(
3583 R.layout.ssl_certificate, null);
3584
3585 // issued to:
3586 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3587 if (issuedTo != null) {
3588 ((TextView) certificateView.findViewById(R.id.to_common))
3589 .setText(issuedTo.getCName());
3590 ((TextView) certificateView.findViewById(R.id.to_org))
3591 .setText(issuedTo.getOName());
3592 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3593 .setText(issuedTo.getUName());
3594 }
3595
3596 // issued by:
3597 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3598 if (issuedBy != null) {
3599 ((TextView) certificateView.findViewById(R.id.by_common))
3600 .setText(issuedBy.getCName());
3601 ((TextView) certificateView.findViewById(R.id.by_org))
3602 .setText(issuedBy.getOName());
3603 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3604 .setText(issuedBy.getUName());
3605 }
3606
3607 // issued on:
3608 String issuedOn = reformatCertificateDate(
3609 certificate.getValidNotBefore());
3610 ((TextView) certificateView.findViewById(R.id.issued_on))
3611 .setText(issuedOn);
3612
3613 // expires on:
3614 String expiresOn = reformatCertificateDate(
3615 certificate.getValidNotAfter());
3616 ((TextView) certificateView.findViewById(R.id.expires_on))
3617 .setText(expiresOn);
3618
3619 return certificateView;
3620 }
3621
3622 /**
3623 * Re-formats the certificate date (Date.toString()) string to
3624 * a properly localized date string.
3625 * @return Properly localized version of the certificate date string and
3626 * the original certificate date string if fails to localize.
3627 * If the original string is null, returns an empty string "".
3628 */
3629 private String reformatCertificateDate(String certificateDate) {
3630 String reformattedDate = null;
3631
3632 if (certificateDate != null) {
3633 Date date = null;
3634 try {
3635 date = java.text.DateFormat.getInstance().parse(certificateDate);
3636 } catch (ParseException e) {
3637 date = null;
3638 }
3639
3640 if (date != null) {
3641 reformattedDate =
3642 DateFormat.getDateFormat(this).format(date);
3643 }
3644 }
3645
3646 return reformattedDate != null ? reformattedDate :
3647 (certificateDate != null ? certificateDate : "");
3648 }
3649
3650 /**
3651 * Displays an http-authentication dialog.
3652 */
3653 private void showHttpAuthentication(final HttpAuthHandler handler,
3654 final String host, final String realm, final String title,
3655 final String name, final String password, int focusId) {
3656 LayoutInflater factory = LayoutInflater.from(this);
3657 final View v = factory
3658 .inflate(R.layout.http_authentication, null);
3659 if (name != null) {
3660 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3661 }
3662 if (password != null) {
3663 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3664 }
3665
3666 String titleText = title;
3667 if (titleText == null) {
3668 titleText = getText(R.string.sign_in_to).toString().replace(
3669 "%s1", host).replace("%s2", realm);
3670 }
3671
3672 mHttpAuthHandler = handler;
3673 AlertDialog dialog = new AlertDialog.Builder(this)
3674 .setTitle(titleText)
3675 .setIcon(android.R.drawable.ic_dialog_alert)
3676 .setView(v)
3677 .setPositiveButton(R.string.action,
3678 new DialogInterface.OnClickListener() {
3679 public void onClick(DialogInterface dialog,
3680 int whichButton) {
3681 String nm = ((EditText) v
3682 .findViewById(R.id.username_edit))
3683 .getText().toString();
3684 String pw = ((EditText) v
3685 .findViewById(R.id.password_edit))
3686 .getText().toString();
3687 BrowserActivity.this.setHttpAuthUsernamePassword
3688 (host, realm, nm, pw);
3689 handler.proceed(nm, pw);
3690 mHttpAuthenticationDialog = null;
3691 mHttpAuthHandler = null;
3692 }})
3693 .setNegativeButton(R.string.cancel,
3694 new DialogInterface.OnClickListener() {
3695 public void onClick(DialogInterface dialog,
3696 int whichButton) {
3697 handler.cancel();
3698 BrowserActivity.this.resetTitleAndRevertLockIcon();
3699 mHttpAuthenticationDialog = null;
3700 mHttpAuthHandler = null;
3701 }})
3702 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3703 public void onCancel(DialogInterface dialog) {
3704 handler.cancel();
3705 BrowserActivity.this.resetTitleAndRevertLockIcon();
3706 mHttpAuthenticationDialog = null;
3707 mHttpAuthHandler = null;
3708 }})
3709 .create();
3710 // Make the IME appear when the dialog is displayed if applicable.
3711 dialog.getWindow().setSoftInputMode(
3712 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3713 dialog.show();
3714 if (focusId != 0) {
3715 dialog.findViewById(focusId).requestFocus();
3716 } else {
3717 v.findViewById(R.id.username_edit).requestFocus();
3718 }
3719 mHttpAuthenticationDialog = dialog;
3720 }
3721
3722 public int getProgress() {
3723 WebView w = mTabControl.getCurrentWebView();
3724 if (w != null) {
3725 return w.getProgress();
3726 } else {
3727 return 100;
3728 }
3729 }
3730
3731 /**
3732 * Set HTTP authentication password.
3733 *
3734 * @param host The host for the password
3735 * @param realm The realm for the password
3736 * @param username The username for the password. If it is null, it means
3737 * password can't be saved.
3738 * @param password The password
3739 */
3740 public void setHttpAuthUsernamePassword(String host, String realm,
3741 String username,
3742 String password) {
3743 WebView w = mTabControl.getCurrentWebView();
3744 if (w != null) {
3745 w.setHttpAuthUsernamePassword(host, realm, username, password);
3746 }
3747 }
3748
3749 /**
3750 * connectivity manager says net has come or gone... inform the user
3751 * @param up true if net has come up, false if net has gone down
3752 */
3753 public void onNetworkToggle(boolean up) {
3754 if (up == mIsNetworkUp) {
3755 return;
3756 } else if (up) {
3757 mIsNetworkUp = true;
3758 if (mAlertDialog != null) {
3759 mAlertDialog.cancel();
3760 mAlertDialog = null;
3761 }
3762 } else {
3763 mIsNetworkUp = false;
3764 if (mInLoad && mAlertDialog == null) {
3765 mAlertDialog = new AlertDialog.Builder(this)
3766 .setTitle(R.string.loadSuspendedTitle)
3767 .setMessage(R.string.loadSuspended)
3768 .setPositiveButton(R.string.ok, null)
3769 .show();
3770 }
3771 }
3772 WebView w = mTabControl.getCurrentWebView();
3773 if (w != null) {
3774 w.setNetworkAvailable(up);
3775 }
3776 }
3777
3778 @Override
3779 protected void onActivityResult(int requestCode, int resultCode,
3780 Intent intent) {
3781 switch (requestCode) {
3782 case COMBO_PAGE:
3783 if (resultCode == RESULT_OK && intent != null) {
3784 String data = intent.getAction();
3785 Bundle extras = intent.getExtras();
3786 if (extras != null && extras.getBoolean("new_window", false)) {
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003787 final TabControl.Tab newTab = openTab(data);
3788 if (mSettings.openInBackground() &&
Leon Scroggins1f005d32009-08-10 17:36:42 -04003789 newTab != null) {
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003790 mTabControl.populatePickerData(newTab);
3791 mTabControl.setCurrentTab(newTab);
Leon Scroggins1f005d32009-08-10 17:36:42 -04003792 int newIndex = mTabControl.getCurrentIndex();
3793 if (CUSTOM_BROWSER_BAR) {
3794 mTitleBar.setCurrentTab(newIndex);
3795 }
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003796 }
Leon Scroggins64b80f32009-08-07 12:03:34 -04003797 } else if (intent.getBooleanExtra("open_search", false)) {
3798 onSearchRequested();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003799 } else {
3800 final TabControl.Tab currentTab =
3801 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003802 dismissSubWindow(currentTab);
3803 if (data != null && data.length() != 0) {
3804 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003805 }
3806 }
3807 }
3808 break;
3809 default:
3810 break;
3811 }
3812 getTopWindow().requestFocus();
3813 }
3814
3815 /*
3816 * This method is called as a result of the user selecting the options
3817 * menu to see the download window, or when a download changes state. It
3818 * shows the download window ontop of the current window.
3819 */
3820 /* package */ void viewDownloads(Uri downloadRecord) {
3821 Intent intent = new Intent(this,
3822 BrowserDownloadPage.class);
3823 intent.setData(downloadRecord);
3824 startActivityForResult(intent, this.DOWNLOAD_PAGE);
3825
3826 }
3827
Leon Scrogginse4b3bda2009-06-09 15:46:41 -04003828 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003829 WebView current = mTabControl.getCurrentWebView();
3830 if (current == null) {
3831 return;
3832 }
3833 Intent intent = new Intent(this,
3834 CombinedBookmarkHistoryActivity.class);
3835 String title = current.getTitle();
3836 String url = current.getUrl();
3837 // Just in case the user opens bookmarks before a page finishes loading
3838 // so the current history item, and therefore the page, is null.
3839 if (null == url) {
3840 url = mLastEnteredUrl;
3841 // This can happen.
3842 if (null == url) {
3843 url = mSettings.getHomePage();
3844 }
3845 }
3846 // In case the web page has not yet received its associated title.
3847 if (title == null) {
3848 title = url;
3849 }
3850 intent.putExtra("title", title);
3851 intent.putExtra("url", url);
3852 intent.putExtra("maxTabsOpen",
3853 mTabControl.getTabCount() >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04003854 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003855 if (startWithHistory) {
3856 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3857 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3858 }
3859 startActivityForResult(intent, COMBO_PAGE);
3860 }
3861
3862 // Called when loading from context menu or LOAD_URL message
3863 private void loadURL(WebView view, String url) {
3864 // In case the user enters nothing.
3865 if (url != null && url.length() != 0 && view != null) {
3866 url = smartUrlFilter(url);
3867 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
3868 view.loadUrl(url);
3869 }
3870 }
3871 }
3872
The Android Open Source Project0c908882009-03-03 19:32:16 -08003873 private String smartUrlFilter(Uri inUri) {
3874 if (inUri != null) {
3875 return smartUrlFilter(inUri.toString());
3876 }
3877 return null;
3878 }
3879
3880
3881 // get window count
3882
3883 int getWindowCount(){
3884 if(mTabControl != null){
3885 return mTabControl.getTabCount();
3886 }
3887 return 0;
3888 }
3889
Feng Qianb34f87a2009-03-24 21:27:26 -07003890 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003891 "(?i)" + // switch on case insensitive matching
3892 "(" + // begin group for schema
3893 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003894 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003895 ")" +
3896 "(.*)" );
3897
3898 /**
3899 * Attempts to determine whether user input is a URL or search
3900 * terms. Anything with a space is passed to search.
3901 *
3902 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3903 * "Http://" converts to "http://"
3904 *
3905 * @return Original or modified URL
3906 *
3907 */
3908 String smartUrlFilter(String url) {
3909
3910 String inUrl = url.trim();
3911 boolean hasSpace = inUrl.indexOf(' ') != -1;
3912
3913 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3914 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003915 // force scheme to lowercase
3916 String scheme = matcher.group(1);
3917 String lcScheme = scheme.toLowerCase();
3918 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003919 inUrl = lcScheme + matcher.group(2);
3920 }
3921 if (hasSpace) {
3922 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003923 }
3924 return inUrl;
3925 }
3926 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003927 // FIXME: Is this the correct place to add to searches?
3928 // what if someone else calls this function?
3929 int shortcut = parseUrlShortcut(inUrl);
3930 if (shortcut != SHORTCUT_INVALID) {
3931 Browser.addSearchUrl(mResolver, inUrl);
3932 String query = inUrl.substring(2);
3933 switch (shortcut) {
3934 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003935 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003936 case SHORTCUT_WIKIPEDIA_SEARCH:
3937 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3938 case SHORTCUT_DICTIONARY_SEARCH:
3939 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3940 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003941 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003942 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003943 }
3944 }
3945 } else {
3946 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
3947 return URLUtil.guessUrl(inUrl);
3948 }
3949 }
3950
3951 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003952 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003953 }
3954
Ben Murdochbff2d602009-07-01 20:19:05 +01003955 /* package */ void setShouldShowErrorConsole(boolean flag) {
3956 if (flag == mShouldShowErrorConsole) {
3957 // Nothing to do.
3958 return;
3959 }
3960
3961 mShouldShowErrorConsole = flag;
3962
3963 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3964
3965 if (flag) {
3966 // Setting the show state of the console will cause it's the layout to be inflated.
3967 if (errorConsole.numberOfErrors() > 0) {
3968 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3969 } else {
3970 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3971 }
3972
3973 // Now we can add it to the main view.
3974 mErrorConsoleContainer.addView(errorConsole,
3975 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
3976 ViewGroup.LayoutParams.WRAP_CONTENT));
3977 } else {
3978 mErrorConsoleContainer.removeView(errorConsole);
3979 }
3980
3981 }
3982
The Android Open Source Project0c908882009-03-03 19:32:16 -08003983 private final static int LOCK_ICON_UNSECURE = 0;
3984 private final static int LOCK_ICON_SECURE = 1;
3985 private final static int LOCK_ICON_MIXED = 2;
3986
3987 private int mLockIconType = LOCK_ICON_UNSECURE;
3988 private int mPrevLockType = LOCK_ICON_UNSECURE;
3989
3990 private BrowserSettings mSettings;
3991 private TabControl mTabControl;
3992 private ContentResolver mResolver;
3993 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003994 private View mCustomView;
3995 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003996 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003997
3998 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3999 // view, we should rewrite this.
4000 private int mCurrentMenuState = 0;
4001 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004002 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004003 private static final int EMPTY_MENU = -1;
4004 private Menu mMenu;
4005
4006 private FindDialog mFindDialog;
4007 // Used to prevent chording to result in firing two shortcuts immediately
4008 // one after another. Fixes bug 1211714.
4009 boolean mCanChord;
4010
4011 private boolean mInLoad;
4012 private boolean mIsNetworkUp;
4013
4014 private boolean mPageStarted;
4015 private boolean mActivityInPause = true;
4016
4017 private boolean mMenuIsDown;
4018
4019 private final KeyTracker mKeyTracker = new KeyTracker(this);
4020
4021 // As trackball doesn't send repeat down, we have to track it ourselves
4022 private boolean mTrackTrackball;
4023
4024 private static boolean mInTrace;
4025
4026 // Performance probe
4027 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4028 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4029 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4030 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4031 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4032 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4033 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4034 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4035 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4036 };
4037
4038 private long mStart;
4039 private long mProcessStart;
4040 private long mUserStart;
4041 private long mSystemStart;
4042 private long mIdleStart;
4043 private long mIrqStart;
4044
4045 private long mUiStart;
4046
4047 private Drawable mMixLockIcon;
4048 private Drawable mSecLockIcon;
4049 private Drawable mGenericFavicon;
4050
4051 /* hold a ref so we can auto-cancel if necessary */
4052 private AlertDialog mAlertDialog;
4053
4054 // Wait for credentials before loading google.com
4055 private ProgressDialog mCredsDlg;
4056
4057 // The up-to-date URL and title (these can be different from those stored
4058 // in WebView, since it takes some time for the information in WebView to
4059 // get updated)
4060 private String mUrl;
4061 private String mTitle;
4062
4063 // As PageInfo has different style for landscape / portrait, we have
4064 // to re-open it when configuration changed
4065 private AlertDialog mPageInfoDialog;
4066 private TabControl.Tab mPageInfoView;
4067 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4068 // dialog, we should not just dismiss it, but should get back to the
4069 // SSL-certificate-on-error dialog. This flag is used to store this state
4070 private Boolean mPageInfoFromShowSSLCertificateOnError;
4071
4072 // as SSLCertificateOnError has different style for landscape / portrait,
4073 // we have to re-open it when configuration changed
4074 private AlertDialog mSSLCertificateOnErrorDialog;
4075 private WebView mSSLCertificateOnErrorView;
4076 private SslErrorHandler mSSLCertificateOnErrorHandler;
4077 private SslError mSSLCertificateOnErrorError;
4078
4079 // as SSLCertificate has different style for landscape / portrait, we
4080 // have to re-open it when configuration changed
4081 private AlertDialog mSSLCertificateDialog;
4082 private TabControl.Tab mSSLCertificateView;
4083
4084 // as HttpAuthentication has different style for landscape / portrait, we
4085 // have to re-open it when configuration changed
4086 private AlertDialog mHttpAuthenticationDialog;
4087 private HttpAuthHandler mHttpAuthHandler;
4088
4089 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4090 new FrameLayout.LayoutParams(
4091 ViewGroup.LayoutParams.FILL_PARENT,
4092 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004093 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4094 new FrameLayout.LayoutParams(
4095 ViewGroup.LayoutParams.FILL_PARENT,
4096 ViewGroup.LayoutParams.FILL_PARENT,
4097 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004098 // Google search
4099 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004100 // Wikipedia search
4101 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4102 // Dictionary search
4103 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4104 // Google Mobile Local search
4105 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4106
4107 final static String QUERY_PLACE_HOLDER = "%s";
4108
4109 // "source" parameter for Google search through search key
4110 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4111 // "source" parameter for Google search through goto menu
4112 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4113 // "source" parameter for Google search through simplily type
4114 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4115 // "source" parameter for Google search suggested by the browser
4116 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4117 // "source" parameter for Google search from unknown source
4118 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4119
4120 private final static String LOGTAG = "browser";
4121
The Android Open Source Project0c908882009-03-03 19:32:16 -08004122 private String mLastEnteredUrl;
4123
4124 private PowerManager.WakeLock mWakeLock;
4125 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4126
4127 private Toast mStopToast;
4128
Leon Scroggins1f005d32009-08-10 17:36:42 -04004129 private TitleBarSet mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004130
Ben Murdochbff2d602009-07-01 20:19:05 +01004131 private LinearLayout mErrorConsoleContainer = null;
4132 private boolean mShouldShowErrorConsole = false;
4133
The Android Open Source Project0c908882009-03-03 19:32:16 -08004134 // As the ids are dynamically created, we can't guarantee that they will
4135 // be in sequence, so this static array maps ids to a window number.
4136 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4137 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4138 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4139 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4140
4141 // monitor platform changes
4142 private IntentFilter mNetworkStateChangedFilter;
4143 private BroadcastReceiver mNetworkStateIntentReceiver;
4144
Grace Klobab4da0ad2009-05-14 14:45:40 -07004145 private BroadcastReceiver mPackageInstallationReceiver;
4146
The Android Open Source Project0c908882009-03-03 19:32:16 -08004147 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004148 final static int COMBO_PAGE = 1;
4149 final static int DOWNLOAD_PAGE = 2;
4150 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004151
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004152 /**
4153 * A UrlData class to abstract how the content will be set to WebView.
4154 * This base class uses loadUrl to show the content.
4155 */
4156 private static class UrlData {
4157 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004158 byte[] mPostData;
4159
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004160 UrlData(String url) {
4161 this.mUrl = url;
4162 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004163
4164 void setPostData(byte[] postData) {
4165 mPostData = postData;
4166 }
4167
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004168 boolean isEmpty() {
4169 return mUrl == null || mUrl.length() == 0;
4170 }
4171
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004172 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004173 if (mPostData != null) {
4174 webView.postUrl(mUrl, mPostData);
4175 } else {
4176 webView.loadUrl(mUrl);
4177 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004178 }
4179 };
4180
4181 /**
4182 * A subclass of UrlData class that can display inlined content using
4183 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4184 */
4185 private static class InlinedUrlData extends UrlData {
4186 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4187 super(failUrl);
4188 mInlined = inlined;
4189 mMimeType = mimeType;
4190 mEncoding = encoding;
4191 }
4192 String mMimeType;
4193 String mInlined;
4194 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004195 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004196 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004197 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004198 }
4199
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004200 @Override
4201 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004202 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4203 }
4204 }
4205
Leon Scroggins1f005d32009-08-10 17:36:42 -04004206 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004207}