blob: 444e98dc5759f0f007fe738bd6bb80cb1ae41a61 [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;
Andrei Popescu540035d2009-09-18 18:59:20 +010048import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.graphics.DrawFilter;
51import android.graphics.Paint;
52import android.graphics.PaintFlagsDrawFilter;
53import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040054import android.graphics.PixelFormat;
55import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080056import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080057import android.hardware.SensorListener;
58import android.hardware.SensorManager;
59import android.net.ConnectivityManager;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -040060import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080061import 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;
Cary Clark5e335a32009-09-22 14:53:11 -040079import android.provider.ContactsContract;
80import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080081import android.provider.Downloads;
82import android.provider.MediaStore;
The Android Open Source Project0c908882009-03-03 19:32:16 -080083import 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
Grace Kloba5942df02009-09-18 11:48:29 -0700152 implements View.OnCreateContextMenuListener,
The Android Open Source Project0c908882009-03-03 19:32:16 -0800153 DownloadListener {
154
Dave Bort31a6d1c2009-04-13 15:56:49 -0700155 /* Define some aliases to make these debugging flags easier to refer to.
156 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
157 */
158 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
159 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
160 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
161
The Android Open Source Project0c908882009-03-03 19:32:16 -0800162 private IGoogleLoginService mGls = null;
163 private ServiceConnection mGlsConnection = null;
164
165 private SensorManager mSensorManager = null;
166
Satish Sampath565505b2009-05-29 15:37:27 +0100167 // These are single-character shortcuts for searching popular sources.
168 private static final int SHORTCUT_INVALID = 0;
169 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
170 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
171 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
172 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
173
The Android Open Source Project0c908882009-03-03 19:32:16 -0800174 /* Whitelisted webpages
175 private static HashSet<String> sWhiteList;
176
177 static {
178 sWhiteList = new HashSet<String>();
179 sWhiteList.add("cnn.com/");
180 sWhiteList.add("espn.go.com/");
181 sWhiteList.add("nytimes.com/");
182 sWhiteList.add("engadget.com/");
183 sWhiteList.add("yahoo.com/");
184 sWhiteList.add("msn.com/");
185 sWhiteList.add("amazon.com/");
186 sWhiteList.add("consumerist.com/");
187 sWhiteList.add("google.com/m/news");
188 }
189 */
190
191 private void setupHomePage() {
192 final Runnable getAccount = new Runnable() {
193 public void run() {
194 // Lower priority
195 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
196 // get the default home page
197 String homepage = mSettings.getHomePage();
198
199 try {
200 if (mGls == null) return;
201
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700202 if (!homepage.startsWith("http://www.google.")) return;
203 if (homepage.indexOf('?') == -1) return;
204
The Android Open Source Project0c908882009-03-03 19:32:16 -0800205 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
206 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
207
208 // three cases:
209 //
210 // hostedUser == googleUser
211 // The device has only a google account
212 //
213 // hostedUser != googleUser
214 // The device has a hosted account and a google account
215 //
216 // hostedUser != null, googleUser == null
217 // The device has only a hosted account (so far)
218
219 // developers might have no accounts at all
220 if (hostedUser == null) return;
221
222 if (googleUser == null || !hostedUser.equals(googleUser)) {
223 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700224 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800225 }
226 } catch (RemoteException ignore) {
227 // Login service died; carry on
228 } catch (RuntimeException ignore) {
229 // Login service died; carry on
230 } finally {
231 finish(homepage);
232 }
233 }
234
235 private void finish(final String homepage) {
236 mHandler.post(new Runnable() {
237 public void run() {
238 mSettings.setHomePage(BrowserActivity.this, homepage);
239 resumeAfterCredentials();
240
241 // as this is running in a separate thread,
242 // BrowserActivity's onDestroy() may have been called,
243 // which also calls unbindService().
244 if (mGlsConnection != null) {
245 // we no longer need to keep GLS open
246 unbindService(mGlsConnection);
247 mGlsConnection = null;
248 }
249 } });
250 } };
251
252 final boolean[] done = { false };
253
254 // Open a connection to the Google Login Service. The first
255 // time the connection is established, set up the homepage depending on
256 // the account in a background thread.
257 mGlsConnection = new ServiceConnection() {
258 public void onServiceConnected(ComponentName className, IBinder service) {
259 mGls = IGoogleLoginService.Stub.asInterface(service);
260 if (done[0] == false) {
261 done[0] = true;
262 Thread account = new Thread(getAccount);
263 account.setName("GLSAccount");
264 account.start();
265 }
266 }
267 public void onServiceDisconnected(ComponentName className) {
268 mGls = null;
269 }
270 };
271
272 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
273 mGlsConnection, Context.BIND_AUTO_CREATE);
274 }
275
Cary Clarka9771242009-08-11 16:42:26 -0400276 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800277 @Override
278 public Void doInBackground(File... files) {
279 if (files != null) {
280 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400281 if (!f.delete()) {
282 Log.e(LOGTAG, f.getPath() + " was not deleted");
283 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800284 }
285 }
286 return null;
287 }
288 }
289
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400290 /**
291 * This layout holds everything you see below the status bar, including the
292 * error console, the custom view container, and the webviews.
293 */
294 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400295
The Android Open Source Project0c908882009-03-03 19:32:16 -0800296 @Override public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700297 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800298 Log.v(LOGTAG, this + " onStart");
299 }
300 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800301 // test the browser in OpenGL
302 // requestWindowFeature(Window.FEATURE_OPENGL);
303
304 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
305
306 mResolver = getContentResolver();
307
Grace Kloba0923d692009-09-23 21:37:25 -0700308 // If this was a web search request, pass it on to the default web
309 // search provider and finish this activity.
310 if (handleWebSearchIntent(getIntent())) {
311 finish();
312 return;
313 }
314
The Android Open Source Project0c908882009-03-03 19:32:16 -0800315 //
316 // start MASF proxy service
317 //
318 //Intent proxyServiceIntent = new Intent();
319 //proxyServiceIntent.setComponent
320 // (new ComponentName(
321 // "com.android.masfproxyservice",
322 // "com.android.masfproxyservice.MasfProxyService"));
323 //startService(proxyServiceIntent, null);
324
325 mSecLockIcon = Resources.getSystem().getDrawable(
326 android.R.drawable.ic_secure);
327 mMixLockIcon = Resources.getSystem().getDrawable(
328 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800329
Leon Scroggins81db3662009-06-04 17:45:11 -0400330 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
331 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400332 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
333 .inflate(R.layout.custom_screen, null);
334 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
335 R.id.main_content);
336 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
337 .findViewById(R.id.error_console);
338 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
339 .findViewById(R.id.fullscreen_custom_content);
340 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400341 mTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800342
343 // Create the tab control and our initial tab
344 mTabControl = new TabControl(this);
345
346 // Open the icon database and retain all the bookmark urls for favicons
347 retainIconsOnStartup();
348
349 // Keep a settings instance handy.
350 mSettings = BrowserSettings.getInstance();
351 mSettings.setTabControl(mTabControl);
352 mSettings.loadFromDb(this);
353
354 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
355 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
356
Grace Klobaa34f6862009-07-31 16:28:17 -0700357 /* enables registration for changes in network status from
358 http stack */
359 mNetworkStateChangedFilter = new IntentFilter();
360 mNetworkStateChangedFilter.addAction(
361 ConnectivityManager.CONNECTIVITY_ACTION);
362 mNetworkStateIntentReceiver = new BroadcastReceiver() {
363 @Override
364 public void onReceive(Context context, Intent intent) {
365 if (intent.getAction().equals(
366 ConnectivityManager.CONNECTIVITY_ACTION)) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -0400367 NetworkInfo info =
368 (NetworkInfo) intent.getParcelableExtra(
369 ConnectivityManager.EXTRA_NETWORK_INFO);
370 onNetworkToggle(
371 (info != null) ? info.isConnected() : false);
Grace Klobaa34f6862009-07-31 16:28:17 -0700372 }
373 }
374 };
375
Grace Kloba615c6c92009-08-03 10:22:44 -0700376 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
377 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
378 filter.addDataScheme("package");
379 mPackageInstallationReceiver = new BroadcastReceiver() {
380 @Override
381 public void onReceive(Context context, Intent intent) {
382 final String action = intent.getAction();
383 final String packageName = intent.getData()
384 .getSchemeSpecificPart();
385 final boolean replacing = intent.getBooleanExtra(
386 Intent.EXTRA_REPLACING, false);
387 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
388 // if it is replacing, refreshPlugins() when adding
389 return;
390 }
391 PackageManager pm = BrowserActivity.this.getPackageManager();
392 PackageInfo pkgInfo = null;
393 try {
394 pkgInfo = pm.getPackageInfo(packageName,
395 PackageManager.GET_PERMISSIONS);
396 } catch (PackageManager.NameNotFoundException e) {
397 return;
398 }
399 if (pkgInfo != null) {
400 String permissions[] = pkgInfo.requestedPermissions;
401 if (permissions == null) {
402 return;
403 }
404 boolean permissionOk = false;
405 for (String permit : permissions) {
406 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
407 permissionOk = true;
408 break;
409 }
410 }
411 if (permissionOk) {
412 PluginManager.getInstance(BrowserActivity.this)
413 .refreshPlugins(
414 Intent.ACTION_PACKAGE_ADDED
415 .equals(action));
416 }
417 }
418 }
419 };
420 registerReceiver(mPackageInstallationReceiver, filter);
421
The Android Open Source Project0c908882009-03-03 19:32:16 -0800422 if (!mTabControl.restoreState(icicle)) {
423 // clear up the thumbnail directory if we can't restore the state as
424 // none of the files in the directory are referenced any more.
425 new ClearThumbnails().execute(
426 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700427 // there is no quit on Android. But if we can't restore the state,
428 // we can treat it as a new Browser, remove the old session cookies.
429 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800430 final Intent intent = getIntent();
431 final Bundle extra = intent.getExtras();
432 // Create an initial tab.
433 // If the intent is ACTION_VIEW and data is not null, the Browser is
434 // invoked to view the content by another application. In this case,
435 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700436 UrlData urlData = getUrlDataFromIntent(intent);
437
The Android Open Source Project0c908882009-03-03 19:32:16 -0800438 final TabControl.Tab t = mTabControl.createNewTab(
439 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700440 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700441 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800442 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800443 attachTabToContentView(t);
444 WebView webView = t.getWebView();
445 if (extra != null) {
446 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
447 if (scale > 0 && scale <= 1000) {
448 webView.setInitialScale(scale);
449 }
450 }
451 // If we are not restoring from an icicle, then there is a high
452 // likely hood this is the first run. So, check to see if the
453 // homepage needs to be configured and copy any plugins from our
454 // asset directory to the data partition.
455 if ((extra == null || !extra.getBoolean("testing"))
456 && !mSettings.isLoginInitialized()) {
457 setupHomePage();
458 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800459
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700460 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400461 if (mSettings.isLoginInitialized()) {
462 webView.loadUrl(mSettings.getHomePage());
463 } else {
464 waitForCredentials();
465 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800466 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700467 if (extra != null) {
468 urlData.setPostData(extra
469 .getByteArray(Browser.EXTRA_POST_DATA));
470 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700471 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800472 }
473 } else {
474 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400475 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800476 attachTabToContentView(mTabControl.getCurrentTab());
477 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700478
Feng Qianb3c02da2009-06-29 15:58:08 -0700479 // Read JavaScript flags if it exists.
480 String jsFlags = mSettings.getJsFlags();
481 if (jsFlags.trim().length() != 0) {
482 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
483 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800484 }
485
486 @Override
487 protected void onNewIntent(Intent intent) {
488 TabControl.Tab current = mTabControl.getCurrentTab();
489 // When a tab is closed on exit, the current tab index is set to -1.
490 // Reset before proceed as Browser requires the current tab to be set.
491 if (current == null) {
492 // Try to reset the tab in case the index was incorrect.
493 current = mTabControl.getTab(0);
494 if (current == null) {
495 // No tabs at all so just ignore this intent.
496 return;
497 }
498 mTabControl.setCurrentTab(current);
499 attachTabToContentView(current);
500 resetTitleAndIcon(current.getWebView());
501 }
502 final String action = intent.getAction();
503 final int flags = intent.getFlags();
504 if (Intent.ACTION_MAIN.equals(action) ||
505 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
506 // just resume the browser
507 return;
508 }
509 if (Intent.ACTION_VIEW.equals(action)
510 || Intent.ACTION_SEARCH.equals(action)
511 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
512 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100513 // If this was a search request (e.g. search query directly typed into the address bar),
514 // pass it on to the default web search provider.
515 if (handleWebSearchIntent(intent)) {
516 return;
517 }
518
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700519 UrlData urlData = getUrlDataFromIntent(intent);
520 if (urlData.isEmpty()) {
521 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800522 }
Grace Kloba81678d92009-06-30 07:09:56 -0700523 urlData.setPostData(intent
524 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700525
Grace Klobacc634032009-07-28 15:58:19 -0700526 final String appId = intent
527 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
528 if (Intent.ACTION_VIEW.equals(action)
529 && !getPackageName().equals(appId)
530 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Patrick Scottcd115892009-07-16 09:42:58 -0400531 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700532 if (appTab != null) {
533 Log.i(LOGTAG, "Reusing tab for " + appId);
534 // Dismiss the subwindow if applicable.
535 dismissSubWindow(appTab);
536 // Since we might kill the WebView, remove it from the
537 // content view first.
538 removeTabFromContentView(appTab);
539 // Recreate the main WebView after destroying the old one.
540 // If the WebView has the same original url and is on that
541 // page, it can be reused.
542 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700543 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100544
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700545 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400546 switchToTab(mTabControl.getTabIndex(appTab));
547 if (needsLoad) {
548 urlData.loadIn(appTab.getWebView());
549 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700550 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400551 // If the tab was the current tab, we have to attach
552 // it to the view system again.
553 attachTabToContentView(appTab);
554 if (needsLoad) {
555 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700556 }
557 }
558 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400559 } else {
560 // No matching application tab, try to find a regular tab
561 // with a matching url.
562 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400563 if (appTab != null) {
564 if (current != appTab) {
565 switchToTab(mTabControl.getTabIndex(appTab));
566 }
567 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400568 } else {
569 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
570 // will be opened in a new tab unless we have reached
571 // MAX_TABS. Then the url will be opened in the current
572 // tab. If a new tab is created, it will have "true" for
573 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400574 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400575 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700576 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800577 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700578 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800579 mSettings.toggleDebugSettings();
580 return;
581 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400582 // Get rid of the subwindow if it exists
583 dismissSubWindow(current);
584 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800585 }
586 }
587 }
588
Satish Sampath565505b2009-05-29 15:37:27 +0100589 private int parseUrlShortcut(String url) {
590 if (url == null) return SHORTCUT_INVALID;
591
592 // FIXME: quick search, need to be customized by setting
593 if (url.length() > 2 && url.charAt(1) == ' ') {
594 switch (url.charAt(0)) {
595 case 'g': return SHORTCUT_GOOGLE_SEARCH;
596 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
597 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
598 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
599 }
600 }
601 return SHORTCUT_INVALID;
602 }
603
604 /**
605 * Launches the default web search activity with the query parameters if the given intent's data
606 * are identified as plain search terms and not URLs/shortcuts.
607 * @return true if the intent was handled and web search activity was launched, false if not.
608 */
609 private boolean handleWebSearchIntent(Intent intent) {
610 if (intent == null) return false;
611
612 String url = null;
613 final String action = intent.getAction();
614 if (Intent.ACTION_VIEW.equals(action)) {
615 url = intent.getData().toString();
616 } else if (Intent.ACTION_SEARCH.equals(action)
617 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
618 || Intent.ACTION_WEB_SEARCH.equals(action)) {
619 url = intent.getStringExtra(SearchManager.QUERY);
620 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100621 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
622 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100623 }
624
625 /**
626 * Launches the default web search activity with the query parameters if the given url string
627 * was identified as plain search terms and not URL/shortcut.
628 * @return true if the request was handled and web search activity was launched, false if not.
629 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100630 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100631 if (inUrl == null) return false;
632
633 // In general, we shouldn't modify URL from Intent.
634 // But currently, we get the user-typed URL from search box as well.
635 String url = fixUrl(inUrl).trim();
636
637 // URLs and site specific search shortcuts are handled by the regular flow of control, so
638 // return early.
639 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100640 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100641 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
642 return false;
643 }
644
645 Browser.updateVisitedHistory(mResolver, url, false);
646 Browser.addSearchUrl(mResolver, url);
647
648 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
649 intent.addCategory(Intent.CATEGORY_DEFAULT);
650 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100651 if (appData != null) {
652 intent.putExtra(SearchManager.APP_DATA, appData);
653 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100654 if (extraData != null) {
655 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
656 }
Grace Klobacc634032009-07-28 15:58:19 -0700657 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100658 startActivity(intent);
659
660 return true;
661 }
662
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700663 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800664 String url = null;
665 if (intent != null) {
666 final String action = intent.getAction();
667 if (Intent.ACTION_VIEW.equals(action)) {
668 url = smartUrlFilter(intent.getData());
669 if (url != null && url.startsWith("content:")) {
670 /* Append mimetype so webview knows how to display */
671 String mimeType = intent.resolveType(getContentResolver());
672 if (mimeType != null) {
673 url += "?" + mimeType;
674 }
675 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700676 if ("inline:".equals(url)) {
677 return new InlinedUrlData(
678 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
679 intent.getType(),
680 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
681 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
682 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800683 } else if (Intent.ACTION_SEARCH.equals(action)
684 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
685 || Intent.ACTION_WEB_SEARCH.equals(action)) {
686 url = intent.getStringExtra(SearchManager.QUERY);
687 if (url != null) {
688 mLastEnteredUrl = url;
689 // Don't add Urls, just search terms.
690 // Urls will get added when the page is loaded.
691 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
692 Browser.updateVisitedHistory(mResolver, url, false);
693 }
694 // In general, we shouldn't modify URL from Intent.
695 // But currently, we get the user-typed URL from search box as well.
696 url = fixUrl(url);
697 url = smartUrlFilter(url);
698 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
699 if (url.contains(searchSource)) {
700 String source = null;
701 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
702 if (appData != null) {
703 source = appData.getString(SearchManager.SOURCE);
704 }
705 if (TextUtils.isEmpty(source)) {
706 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
707 }
708 url = url.replace(searchSource, "&source=android-"+source+"&");
709 }
710 }
711 }
712 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700713 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800714 }
715
716 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400717 // FIXME: Converting the url to lower case
718 // duplicates functionality in smartUrlFilter().
719 // However, changing all current callers of fixUrl to
720 // call smartUrlFilter in addition may have unwanted
721 // consequences, and is deferred for now.
722 int colon = inUrl.indexOf(':');
723 boolean allLower = true;
724 for (int index = 0; index < colon; index++) {
725 char ch = inUrl.charAt(index);
726 if (!Character.isLetter(ch)) {
727 break;
728 }
729 allLower &= Character.isLowerCase(ch);
730 if (index == colon - 1 && !allLower) {
731 inUrl = inUrl.substring(0, colon).toLowerCase()
732 + inUrl.substring(colon);
733 }
734 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800735 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
736 return inUrl;
737 if (inUrl.startsWith("http:") ||
738 inUrl.startsWith("https:")) {
739 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
740 inUrl = inUrl.replaceFirst("/", "//");
741 } else inUrl = inUrl.replaceFirst(":", "://");
742 }
743 return inUrl;
744 }
745
746 /**
747 * Looking for the pattern like this
748 *
749 * *
750 * * *
751 * *** * *******
752 * * *
753 * * *
754 * *
755 */
756 private final SensorListener mSensorListener = new SensorListener() {
757 private long mLastGestureTime;
758 private float[] mPrev = new float[3];
759 private float[] mPrevDiff = new float[3];
760 private float[] mDiff = new float[3];
761 private float[] mRevertDiff = new float[3];
762
763 public void onSensorChanged(int sensor, float[] values) {
764 boolean show = false;
765 float[] diff = new float[3];
766
767 for (int i = 0; i < 3; i++) {
768 diff[i] = values[i] - mPrev[i];
769 if (Math.abs(diff[i]) > 1) {
770 show = true;
771 }
772 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
773 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
774 // start track when there is a big move, or revert
775 mRevertDiff[i] = mDiff[i];
776 mDiff[i] = 0;
777 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
778 // reset when it is flat
779 mDiff[i] = mRevertDiff[i] = 0;
780 }
781 mDiff[i] += diff[i];
782 mPrevDiff[i] = diff[i];
783 mPrev[i] = values[i];
784 }
785
786 if (false) {
787 // only shows if we think the delta is big enough, in an attempt
788 // to detect "serious" moves left/right or up/down
789 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
790 + values[0] + ", " + values[1] + ", " + values[2] + ")"
791 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
792 + ")");
793 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
794 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
795 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
796 + mRevertDiff[2] + ")");
797 }
798
799 long now = android.os.SystemClock.uptimeMillis();
800 if (now - mLastGestureTime > 1000) {
801 mLastGestureTime = 0;
802
803 float y = mDiff[1];
804 float z = mDiff[2];
805 float ay = Math.abs(y);
806 float az = Math.abs(z);
807 float ry = mRevertDiff[1];
808 float rz = mRevertDiff[2];
809 float ary = Math.abs(ry);
810 float arz = Math.abs(rz);
811 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
812 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
813
814 if ((gestY || gestZ) && !(gestY && gestZ)) {
815 WebView view = mTabControl.getCurrentWebView();
816
817 if (view != null) {
818 if (gestZ) {
819 if (z < 0) {
820 view.zoomOut();
821 } else {
822 view.zoomIn();
823 }
824 } else {
825 view.flingScroll(0, Math.round(y * 100));
826 }
827 }
828 mLastGestureTime = now;
829 }
830 }
831 }
832
833 public void onAccuracyChanged(int sensor, int accuracy) {
834 // TODO Auto-generated method stub
835
836 }
837 };
838
839 @Override protected void onResume() {
840 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700841 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800842 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
843 }
844
845 if (!mActivityInPause) {
846 Log.e(LOGTAG, "BrowserActivity is already resumed.");
847 return;
848 }
849
Mike Reed7bfa63b2009-05-28 11:08:32 -0400850 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800851 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400852 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800853
854 if (mWakeLock.isHeld()) {
855 mHandler.removeMessages(RELEASE_WAKELOCK);
856 mWakeLock.release();
857 }
858
859 if (mCredsDlg != null) {
860 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
861 // In case credential request never comes back
862 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
863 }
864 }
865
866 registerReceiver(mNetworkStateIntentReceiver,
867 mNetworkStateChangedFilter);
868 WebView.enablePlatformNotifications();
869
870 if (mSettings.doFlick()) {
871 if (mSensorManager == null) {
872 mSensorManager = (SensorManager) getSystemService(
873 Context.SENSOR_SERVICE);
874 }
875 mSensorManager.registerListener(mSensorListener,
876 SensorManager.SENSOR_ACCELEROMETER,
877 SensorManager.SENSOR_DELAY_FASTEST);
878 } else {
879 mSensorManager = null;
880 }
881 }
882
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400883 /**
884 * Since the actual title bar is embedded in the WebView, and removing it
885 * would change its appearance, create a temporary title bar to go at
886 * the top of the screen while the menu is open.
887 */
888 private TitleBar mFakeTitleBar;
889
890 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400891 * Holder for the fake title bar. It will have a foreground shadow, as well
892 * as a white background, so the fake title bar looks like the real one.
893 */
894 private ViewGroup mFakeTitleBarHolder;
895
896 /**
897 * Layout parameters for the fake title bar within mFakeTitleBarHolder
898 */
899 private FrameLayout.LayoutParams mFakeTitleBarParams
900 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400901 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400902 ViewGroup.LayoutParams.WRAP_CONTENT);
903 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400904 * Keeps track of whether the options menu is open. This is important in
905 * determining whether to show or hide the title bar overlay.
906 */
907 private boolean mOptionsMenuOpen;
908
909 /**
910 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
911 * of whether the configuration has changed. The first onMenuOpened call
912 * after a configuration change is simply a reopening of the same menu
913 * (i.e. mIconView did not change).
914 */
915 private boolean mConfigChanged;
916
917 /**
918 * Whether or not the options menu is in its smaller, icon menu form. When
919 * true, we want the title bar overlay to be up. When false, we do not.
920 * Only meaningful if mOptionsMenuOpen is true.
921 */
922 private boolean mIconView;
923
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400924 @Override
925 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400926 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
927 if (mOptionsMenuOpen) {
928 if (mConfigChanged) {
929 // We do not need to make any changes to the state of the
930 // title bar, since the only thing that happened was a
931 // change in orientation
932 mConfigChanged = false;
933 } else {
934 if (mIconView) {
935 // Switching the menu to expanded view, so hide the
936 // title bar.
937 hideFakeTitleBar();
938 mIconView = false;
939 } else {
940 // Switching the menu back to icon view, so show the
941 // title bar once again.
942 showFakeTitleBar();
943 mIconView = true;
944 }
945 }
946 } else {
947 // The options menu is closed, so open it, and show the title
948 showFakeTitleBar();
949 mOptionsMenuOpen = true;
950 mConfigChanged = false;
951 mIconView = true;
952 }
953 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400954 return true;
955 }
956
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400957 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400958 final View decor = getWindow().peekDecorView();
Leon Scroggins4d7e4062009-09-15 15:49:45 -0400959 if (mFakeTitleBar == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400960 && !mActivityInPause && decor != null
961 && decor.getWindowToken() != null) {
Leon Scrogginsf4bb18a2009-09-11 18:37:53 -0400962 final WebView webView = getTopWindow();
Leon Scroggins68579392009-09-15 15:31:54 -0400963 mFakeTitleBar = new TitleBar(this);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400964 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
965 mFakeTitleBar.setProgress(webView.getProgress());
966 mFakeTitleBar.setFavicon(webView.getFavicon());
967 updateLockIconToLatest();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400968
969 WindowManager manager
970 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
971
972 // Add the title bar to the window manager so it can receive touches
973 // while the menu is up
974 WindowManager.LayoutParams params
975 = new WindowManager.LayoutParams(
976 ViewGroup.LayoutParams.FILL_PARENT,
977 ViewGroup.LayoutParams.WRAP_CONTENT,
978 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
979 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400980 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400981 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400982 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400983 boolean atTop = mainView != null && mainView.getScrollY() == 0;
984 params.windowAnimations = atTop ? 0
985 : com.android.internal.R.style.Animation_DropDownDown;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400986 // XXX : Without providing an offset, the fake title bar will be
987 // placed underneath the status bar. Use the global visible rect
988 // of mBrowserFrameLayout to determine the bottom of the status bar
989 Rect rectangle = new Rect();
990 mBrowserFrameLayout.getGlobalVisibleRect(rectangle);
991 params.y = rectangle.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400992 // Add a holder for the title bar. It also holds a shadow to show
993 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400994 if (mFakeTitleBarHolder == null) {
995 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
996 .inflate(R.layout.title_bar_bg, null);
997 }
Leon Scroggins68549862009-09-21 16:02:01 -0400998 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400999 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001000 }
1001 }
1002
1003 @Override
1004 public void onOptionsMenuClosed(Menu menu) {
1005 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04001006 if (!mInLoad) {
1007 hideFakeTitleBar();
1008 } else if (!mIconView) {
1009 // The page is currently loading, and we are in expanded mode, so
1010 // we were not showing the menu. Show it once again. It will be
1011 // removed when the page finishes.
1012 showFakeTitleBar();
1013 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001014 }
1015 private void hideFakeTitleBar() {
1016 if (mFakeTitleBar == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -04001017 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
1018 mFakeTitleBarHolder.getLayoutParams();
1019 WebView mainView = mTabControl.getCurrentWebView();
1020 // Although we decided whether or not to animate based on the current
1021 // scroll position, the scroll position may have changed since the
1022 // fake title bar was displayed. Make sure it has the appropriate
1023 // animation/lack thereof before removing.
1024 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
1025 ? 0 : com.android.internal.R.style.Animation_DropDownDown;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001026 WindowManager manager
1027 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -04001028 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001029 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1030 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001031 mFakeTitleBar = null;
1032 }
1033
The Android Open Source Project0c908882009-03-03 19:32:16 -08001034 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001035 * Special method for the fake title bar to call when displaying its context
1036 * menu, since it is in its own Window, and its parent does not show a
1037 * context menu.
1038 */
1039 /* package */ void showTitleBarContextMenu() {
1040 openContextMenu(mTitleBar);
1041 }
1042
1043 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001044 * onSaveInstanceState(Bundle map)
1045 * onSaveInstanceState is called right before onStop(). The map contains
1046 * the saved state.
1047 */
1048 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001049 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001050 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1051 }
1052 // the default implementation requires each view to have an id. As the
1053 // browser handles the state itself and it doesn't use id for the views,
1054 // don't call the default implementation. Otherwise it will trigger the
1055 // warning like this, "couldn't save which view has focus because the
1056 // focused view XXX has no id".
1057
1058 // Save all the tabs
1059 mTabControl.saveState(outState);
1060 }
1061
1062 @Override protected void onPause() {
1063 super.onPause();
1064
1065 if (mActivityInPause) {
1066 Log.e(LOGTAG, "BrowserActivity is already paused.");
1067 return;
1068 }
1069
Mike Reed7bfa63b2009-05-28 11:08:32 -04001070 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001071 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001072 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001073 mWakeLock.acquire();
1074 mHandler.sendMessageDelayed(mHandler
1075 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1076 }
1077
1078 // Clear the credentials toast if it is up
1079 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1080 mCredsDlg.dismiss();
1081 }
1082 mCredsDlg = null;
1083
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001084 // FIXME: This removes the active tabs page and resets the menu to
1085 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1086 // but then we would need to save it in onSaveInstanceState and restore
1087 // it in onCreate/onRestoreInstanceState
1088 if (mActiveTabsPage != null) {
1089 removeActiveTabPage(true);
1090 }
1091
The Android Open Source Project0c908882009-03-03 19:32:16 -08001092 cancelStopToast();
1093
1094 // unregister network state listener
1095 unregisterReceiver(mNetworkStateIntentReceiver);
1096 WebView.disablePlatformNotifications();
1097
1098 if (mSensorManager != null) {
1099 mSensorManager.unregisterListener(mSensorListener);
1100 }
1101 }
1102
1103 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001104 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001105 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1106 }
1107 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001108
1109 if (mTabControl == null) return;
1110
The Android Open Source Project0c908882009-03-03 19:32:16 -08001111 // Remove the current tab and sub window
1112 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001113 if (t != null) {
1114 dismissSubWindow(t);
1115 removeTabFromContentView(t);
1116 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001117 // Destroy all the tabs
1118 mTabControl.destroy();
1119 WebIconDatabase.getInstance().close();
1120 if (mGlsConnection != null) {
1121 unbindService(mGlsConnection);
1122 mGlsConnection = null;
1123 }
1124
1125 //
1126 // stop MASF proxy service
1127 //
1128 //Intent proxyServiceIntent = new Intent();
1129 //proxyServiceIntent.setComponent
1130 // (new ComponentName(
1131 // "com.android.masfproxyservice",
1132 // "com.android.masfproxyservice.MasfProxyService"));
1133 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001134
1135 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001136 }
1137
1138 @Override
1139 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001140 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001141 super.onConfigurationChanged(newConfig);
1142
1143 if (mPageInfoDialog != null) {
1144 mPageInfoDialog.dismiss();
1145 showPageInfo(
1146 mPageInfoView,
1147 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1148 }
1149 if (mSSLCertificateDialog != null) {
1150 mSSLCertificateDialog.dismiss();
1151 showSSLCertificate(
1152 mSSLCertificateView);
1153 }
1154 if (mSSLCertificateOnErrorDialog != null) {
1155 mSSLCertificateOnErrorDialog.dismiss();
1156 showSSLCertificateOnError(
1157 mSSLCertificateOnErrorView,
1158 mSSLCertificateOnErrorHandler,
1159 mSSLCertificateOnErrorError);
1160 }
1161 if (mHttpAuthenticationDialog != null) {
1162 String title = ((TextView) mHttpAuthenticationDialog
1163 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1164 .toString();
1165 String name = ((TextView) mHttpAuthenticationDialog
1166 .findViewById(R.id.username_edit)).getText().toString();
1167 String password = ((TextView) mHttpAuthenticationDialog
1168 .findViewById(R.id.password_edit)).getText().toString();
1169 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1170 .getId();
1171 mHttpAuthenticationDialog.dismiss();
1172 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1173 name, password, focusId);
1174 }
1175 if (mFindDialog != null && mFindDialog.isShowing()) {
1176 mFindDialog.onConfigurationChanged(newConfig);
1177 }
1178 }
1179
1180 @Override public void onLowMemory() {
1181 super.onLowMemory();
1182 mTabControl.freeMemory();
1183 }
1184
Mike Reed7bfa63b2009-05-28 11:08:32 -04001185 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001186 if ((!mActivityInPause && !mPageStarted) ||
1187 (mActivityInPause && mPageStarted)) {
1188 CookieSyncManager.getInstance().startSync();
1189 WebView w = mTabControl.getCurrentWebView();
1190 if (w != null) {
1191 w.resumeTimers();
1192 }
1193 return true;
1194 } else {
1195 return false;
1196 }
1197 }
1198
Mike Reed7bfa63b2009-05-28 11:08:32 -04001199 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001200 if (mActivityInPause && !mPageStarted) {
1201 CookieSyncManager.getInstance().stopSync();
1202 WebView w = mTabControl.getCurrentWebView();
1203 if (w != null) {
1204 w.pauseTimers();
1205 }
1206 return true;
1207 } else {
1208 return false;
1209 }
1210 }
1211
Leon Scroggins1f005d32009-08-10 17:36:42 -04001212 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001213 /*
1214 * This function is called when we are launching for the first time. We
1215 * are waiting for the login credentials before loading Google home
1216 * pages. This way the user will be logged in straight away.
1217 */
1218 private void waitForCredentials() {
1219 // Show a toast
1220 mCredsDlg = new ProgressDialog(this);
1221 mCredsDlg.setIndeterminate(true);
1222 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1223 // If the user cancels the operation, then cancel the Google
1224 // Credentials request.
1225 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1226 mCredsDlg.show();
1227
1228 // We set a timeout for the retrieval of credentials in onResume()
1229 // as that is when we have freed up some CPU time to get
1230 // the login credentials.
1231 }
1232
1233 /*
1234 * If we have received the credentials or we have timed out and we are
1235 * showing the credentials dialog, then it is time to move on.
1236 */
1237 private void resumeAfterCredentials() {
1238 if (mCredsDlg == null) {
1239 return;
1240 }
1241
1242 // Clear the toast
1243 if (mCredsDlg.isShowing()) {
1244 mCredsDlg.dismiss();
1245 }
1246 mCredsDlg = null;
1247
1248 // Clear any pending timeout
1249 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1250
1251 // Load the page
1252 WebView w = mTabControl.getCurrentWebView();
1253 if (w != null) {
1254 w.loadUrl(mSettings.getHomePage());
1255 }
1256
1257 // Update the settings, need to do this last as it can take a moment
1258 // to persist the settings. In the mean time we could be loading
1259 // content.
1260 mSettings.setLoginInitialized(this);
1261 }
1262
1263 // Open the icon database and retain all the icons for visited sites.
1264 private void retainIconsOnStartup() {
1265 final WebIconDatabase db = WebIconDatabase.getInstance();
1266 db.open(getDir("icons", 0).getPath());
1267 try {
1268 Cursor c = Browser.getAllBookmarks(mResolver);
1269 if (!c.moveToFirst()) {
1270 c.deactivate();
1271 return;
1272 }
1273 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1274 do {
1275 String url = c.getString(urlIndex);
1276 db.retainIconForPageUrl(url);
1277 } while (c.moveToNext());
1278 c.deactivate();
1279 } catch (IllegalStateException e) {
1280 Log.e(LOGTAG, "retainIconsOnStartup", e);
1281 }
1282 }
1283
1284 // Helper method for getting the top window.
1285 WebView getTopWindow() {
1286 return mTabControl.getCurrentTopWebView();
1287 }
1288
1289 @Override
1290 public boolean onCreateOptionsMenu(Menu menu) {
1291 super.onCreateOptionsMenu(menu);
1292
1293 MenuInflater inflater = getMenuInflater();
1294 inflater.inflate(R.menu.browser, menu);
1295 mMenu = menu;
1296 updateInLoadMenuItems();
1297 return true;
1298 }
1299
1300 /**
1301 * As the menu can be open when loading state changes
1302 * we must manually update the state of the stop/reload menu
1303 * item
1304 */
1305 private void updateInLoadMenuItems() {
1306 if (mMenu == null) {
1307 return;
1308 }
1309 MenuItem src = mInLoad ?
1310 mMenu.findItem(R.id.stop_menu_id):
1311 mMenu.findItem(R.id.reload_menu_id);
1312 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1313 dest.setIcon(src.getIcon());
1314 dest.setTitle(src.getTitle());
1315 }
1316
1317 @Override
1318 public boolean onContextItemSelected(MenuItem item) {
1319 // chording is not an issue with context menus, but we use the same
1320 // options selector, so set mCanChord to true so we can access them.
1321 mCanChord = true;
1322 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001323 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001324 // For the context menu from the title bar
1325 case R.id.title_bar_share_page_url:
1326 case R.id.title_bar_copy_page_url:
1327 WebView mainView = mTabControl.getCurrentWebView();
1328 if (null == mainView) {
1329 return false;
1330 }
1331 if (id == R.id.title_bar_share_page_url) {
1332 Browser.sendString(this, mainView.getUrl());
1333 } else {
1334 copy(mainView.getUrl());
1335 }
1336 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001337 // -- Browser context menu
1338 case R.id.open_context_menu_id:
1339 case R.id.open_newtab_context_menu_id:
1340 case R.id.bookmark_context_menu_id:
1341 case R.id.save_link_context_menu_id:
1342 case R.id.share_link_context_menu_id:
1343 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001344 final WebView webView = getTopWindow();
1345 if (null == webView) {
1346 return false;
1347 }
1348 final HashMap hrefMap = new HashMap();
1349 hrefMap.put("webview", webView);
1350 final Message msg = mHandler.obtainMessage(
1351 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001352 webView.requestFocusNodeHref(msg);
1353 break;
1354
1355 default:
1356 // For other context menus
1357 return onOptionsItemSelected(item);
1358 }
1359 mCanChord = false;
1360 return true;
1361 }
1362
1363 private Bundle createGoogleSearchSourceBundle(String source) {
1364 Bundle bundle = new Bundle();
1365 bundle.putString(SearchManager.SOURCE, source);
1366 return bundle;
1367 }
1368
1369 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001370 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001371 */
1372 @Override
1373 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001374 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001375 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001376 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001377 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001378 return true;
1379 }
1380
1381 @Override
1382 public void startSearch(String initialQuery, boolean selectInitialQuery,
1383 Bundle appSearchData, boolean globalSearch) {
1384 if (appSearchData == null) {
1385 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1386 }
1387 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1388 }
1389
Leon Scroggins1f005d32009-08-10 17:36:42 -04001390 /**
1391 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1392 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001393 * @param index Index of the tab to change to, as defined by
1394 * mTabControl.getTabIndex(Tab t).
1395 * @return boolean True if we successfully switched to a different tab. If
1396 * the indexth tab is null, or if that tab is the same as
1397 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001398 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001399 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001400 TabControl.Tab tab = mTabControl.getTab(index);
1401 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1402 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001403 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001404 }
1405 if (currentTab != null) {
1406 // currentTab may be null if it was just removed. In that case,
1407 // we do not need to remove it
1408 removeTabFromContentView(currentTab);
1409 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001410 mTabControl.setCurrentTab(tab);
1411 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001412 resetTitleIconAndProgress();
1413 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001414 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001415 }
1416
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001417 /* package */ TabControl.Tab openTabToHomePage() {
1418 return openTabAndShow(mSettings.getHomePage(), false, null);
1419 }
1420
Leon Scroggins1f005d32009-08-10 17:36:42 -04001421 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001422 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001423 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001424 // This is the last tab. Open a new one, with the home
1425 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001426 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001427 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001428 return;
1429 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001430 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001431 int indexToShow = -1;
1432 if (parent != null) {
1433 indexToShow = mTabControl.getTabIndex(parent);
1434 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001435 final int currentIndex = mTabControl.getCurrentIndex();
1436 // Try to move to the tab to the right
1437 indexToShow = currentIndex + 1;
1438 if (indexToShow > mTabControl.getTabCount() - 1) {
1439 // Try to move to the tab to the left
1440 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001441 }
1442 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001443 if (switchToTab(indexToShow)) {
1444 // Close window
1445 closeTab(current);
1446 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001447 }
1448
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001449 private ActiveTabsPage mActiveTabsPage;
1450
1451 /**
1452 * Remove the active tabs page.
1453 * @param needToAttach If true, the active tabs page did not attach a tab
1454 * to the content view, so we need to do that here.
1455 */
1456 /* package */ void removeActiveTabPage(boolean needToAttach) {
1457 mContentView.removeView(mActiveTabsPage);
1458 mActiveTabsPage = null;
1459 mMenuState = R.id.MAIN_MENU;
1460 if (needToAttach) {
1461 attachTabToContentView(mTabControl.getCurrentTab());
1462 }
1463 getTopWindow().requestFocus();
1464 }
1465
The Android Open Source Project0c908882009-03-03 19:32:16 -08001466 @Override
1467 public boolean onOptionsItemSelected(MenuItem item) {
1468 if (!mCanChord) {
1469 // The user has already fired a shortcut with this hold down of the
1470 // menu key.
1471 return false;
1472 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001473 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001474 return false;
1475 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001476 if (mMenuIsDown) {
1477 // The shortcut action consumes the MENU. Even if it is still down,
1478 // it won't trigger the next shortcut action. In the case of the
1479 // shortcut action triggering a new activity, like Bookmarks, we
1480 // won't get onKeyUp for MENU. So it is important to reset it here.
1481 mMenuIsDown = false;
1482 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001483 switch (item.getItemId()) {
1484 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001485 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001486 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001487 break;
1488
Leon Scroggins64b80f32009-08-07 12:03:34 -04001489 case R.id.goto_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001490 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001491 break;
1492
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001493 case R.id.active_tabs_menu_id:
1494 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1495 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001496 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001497 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1498 mActiveTabsPage.requestFocus();
1499 mMenuState = EMPTY_MENU;
1500 break;
1501
Leon Scroggins1f005d32009-08-10 17:36:42 -04001502 case R.id.add_bookmark_menu_id:
1503 Intent i = new Intent(BrowserActivity.this,
1504 AddBookmarkPage.class);
1505 WebView w = getTopWindow();
1506 i.putExtra("url", w.getUrl());
1507 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001508 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001509 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001510 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001511 break;
1512
1513 case R.id.stop_reload_menu_id:
1514 if (mInLoad) {
1515 stopLoading();
1516 } else {
1517 getTopWindow().reload();
1518 }
1519 break;
1520
1521 case R.id.back_menu_id:
1522 getTopWindow().goBack();
1523 break;
1524
1525 case R.id.forward_menu_id:
1526 getTopWindow().goForward();
1527 break;
1528
1529 case R.id.close_menu_id:
1530 // Close the subwindow if it exists.
1531 if (mTabControl.getCurrentSubWindow() != null) {
1532 dismissSubWindow(mTabControl.getCurrentTab());
1533 break;
1534 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001535 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001536 break;
1537
1538 case R.id.homepage_menu_id:
1539 TabControl.Tab current = mTabControl.getCurrentTab();
1540 if (current != null) {
1541 dismissSubWindow(current);
1542 current.getWebView().loadUrl(mSettings.getHomePage());
1543 }
1544 break;
1545
1546 case R.id.preferences_menu_id:
1547 Intent intent = new Intent(this,
1548 BrowserPreferencesPage.class);
1549 startActivityForResult(intent, PREFERENCES_PAGE);
1550 break;
1551
1552 case R.id.find_menu_id:
1553 if (null == mFindDialog) {
1554 mFindDialog = new FindDialog(this);
1555 }
1556 mFindDialog.setWebView(getTopWindow());
1557 mFindDialog.show();
1558 mMenuState = EMPTY_MENU;
1559 break;
1560
1561 case R.id.select_text_id:
1562 getTopWindow().emulateShiftHeld();
1563 break;
1564 case R.id.page_info_menu_id:
1565 showPageInfo(mTabControl.getCurrentTab(), false);
1566 break;
1567
1568 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001569 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001570 break;
1571
1572 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001573 Browser.sendString(this, getTopWindow().getUrl(),
1574 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001575 break;
1576
1577 case R.id.dump_nav_menu_id:
1578 getTopWindow().debugDump();
1579 break;
1580
1581 case R.id.zoom_in_menu_id:
1582 getTopWindow().zoomIn();
1583 break;
1584
1585 case R.id.zoom_out_menu_id:
1586 getTopWindow().zoomOut();
1587 break;
1588
1589 case R.id.view_downloads_menu_id:
1590 viewDownloads(null);
1591 break;
1592
The Android Open Source Project0c908882009-03-03 19:32:16 -08001593 case R.id.window_one_menu_id:
1594 case R.id.window_two_menu_id:
1595 case R.id.window_three_menu_id:
1596 case R.id.window_four_menu_id:
1597 case R.id.window_five_menu_id:
1598 case R.id.window_six_menu_id:
1599 case R.id.window_seven_menu_id:
1600 case R.id.window_eight_menu_id:
1601 {
1602 int menuid = item.getItemId();
1603 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1604 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1605 TabControl.Tab desiredTab = mTabControl.getTab(id);
1606 if (desiredTab != null &&
1607 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001608 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001609 }
1610 break;
1611 }
1612 }
1613 }
1614 break;
1615
1616 default:
1617 if (!super.onOptionsItemSelected(item)) {
1618 return false;
1619 }
1620 // Otherwise fall through.
1621 }
1622 mCanChord = false;
1623 return true;
1624 }
1625
1626 public void closeFind() {
1627 mMenuState = R.id.MAIN_MENU;
1628 }
1629
1630 @Override public boolean onPrepareOptionsMenu(Menu menu)
1631 {
1632 // This happens when the user begins to hold down the menu key, so
1633 // allow them to chord to get a shortcut.
1634 mCanChord = true;
1635 // Note: setVisible will decide whether an item is visible; while
1636 // setEnabled() will decide whether an item is enabled, which also means
1637 // whether the matching shortcut key will function.
1638 super.onPrepareOptionsMenu(menu);
1639 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001640 case EMPTY_MENU:
1641 if (mCurrentMenuState != mMenuState) {
1642 menu.setGroupVisible(R.id.MAIN_MENU, false);
1643 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1644 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001645 }
1646 break;
1647 default:
1648 if (mCurrentMenuState != mMenuState) {
1649 menu.setGroupVisible(R.id.MAIN_MENU, true);
1650 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1651 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001652 }
1653 final WebView w = getTopWindow();
1654 boolean canGoBack = false;
1655 boolean canGoForward = false;
1656 boolean isHome = false;
1657 if (w != null) {
1658 canGoBack = w.canGoBack();
1659 canGoForward = w.canGoForward();
1660 isHome = mSettings.getHomePage().equals(w.getUrl());
1661 }
1662 final MenuItem back = menu.findItem(R.id.back_menu_id);
1663 back.setEnabled(canGoBack);
1664
1665 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1666 home.setEnabled(!isHome);
1667
1668 menu.findItem(R.id.forward_menu_id)
1669 .setEnabled(canGoForward);
1670
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001671 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1672 mTabControl.getTabCount() < TabControl.MAX_TABS);
1673
The Android Open Source Project0c908882009-03-03 19:32:16 -08001674 // decide whether to show the share link option
1675 PackageManager pm = getPackageManager();
1676 Intent send = new Intent(Intent.ACTION_SEND);
1677 send.setType("text/plain");
1678 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1679 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1680
The Android Open Source Project0c908882009-03-03 19:32:16 -08001681 boolean isNavDump = mSettings.isNavDump();
1682 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1683 nav.setVisible(isNavDump);
1684 nav.setEnabled(isNavDump);
1685 break;
1686 }
1687 mCurrentMenuState = mMenuState;
1688 return true;
1689 }
1690
1691 @Override
1692 public void onCreateContextMenu(ContextMenu menu, View v,
1693 ContextMenuInfo menuInfo) {
1694 WebView webview = (WebView) v;
1695 WebView.HitTestResult result = webview.getHitTestResult();
1696 if (result == null) {
1697 return;
1698 }
1699
1700 int type = result.getType();
1701 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1702 Log.w(LOGTAG,
1703 "We should not show context menu when nothing is touched");
1704 return;
1705 }
1706 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1707 // let TextView handles context menu
1708 return;
1709 }
1710
1711 // Note, http://b/issue?id=1106666 is requesting that
1712 // an inflated menu can be used again. This is not available
1713 // yet, so inflate each time (yuk!)
1714 MenuInflater inflater = getMenuInflater();
1715 inflater.inflate(R.menu.browsercontext, menu);
1716
1717 // Show the correct menu group
1718 String extra = result.getExtra();
1719 menu.setGroupVisible(R.id.PHONE_MENU,
1720 type == WebView.HitTestResult.PHONE_TYPE);
1721 menu.setGroupVisible(R.id.EMAIL_MENU,
1722 type == WebView.HitTestResult.EMAIL_TYPE);
1723 menu.setGroupVisible(R.id.GEO_MENU,
1724 type == WebView.HitTestResult.GEO_TYPE);
1725 menu.setGroupVisible(R.id.IMAGE_MENU,
1726 type == WebView.HitTestResult.IMAGE_TYPE
1727 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1728 menu.setGroupVisible(R.id.ANCHOR_MENU,
1729 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1730 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1731
1732 // Setup custom handling depending on the type
1733 switch (type) {
1734 case WebView.HitTestResult.PHONE_TYPE:
1735 menu.setHeaderTitle(Uri.decode(extra));
1736 menu.findItem(R.id.dial_context_menu_id).setIntent(
1737 new Intent(Intent.ACTION_VIEW, Uri
1738 .parse(WebView.SCHEME_TEL + extra)));
1739 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1740 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001741 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001742 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1743 addIntent);
1744 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1745 new Copy(extra));
1746 break;
1747
1748 case WebView.HitTestResult.EMAIL_TYPE:
1749 menu.setHeaderTitle(extra);
1750 menu.findItem(R.id.email_context_menu_id).setIntent(
1751 new Intent(Intent.ACTION_VIEW, Uri
1752 .parse(WebView.SCHEME_MAILTO + extra)));
1753 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1754 new Copy(extra));
1755 break;
1756
1757 case WebView.HitTestResult.GEO_TYPE:
1758 menu.setHeaderTitle(extra);
1759 menu.findItem(R.id.map_context_menu_id).setIntent(
1760 new Intent(Intent.ACTION_VIEW, Uri
1761 .parse(WebView.SCHEME_GEO
1762 + URLEncoder.encode(extra))));
1763 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1764 new Copy(extra));
1765 break;
1766
1767 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1768 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1769 TextView titleView = (TextView) LayoutInflater.from(this)
1770 .inflate(android.R.layout.browser_link_context_header,
1771 null);
1772 titleView.setText(extra);
1773 menu.setHeaderView(titleView);
1774 // decide whether to show the open link in new tab option
1775 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1776 mTabControl.getTabCount() < TabControl.MAX_TABS);
1777 PackageManager pm = getPackageManager();
1778 Intent send = new Intent(Intent.ACTION_SEND);
1779 send.setType("text/plain");
1780 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1781 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1782 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1783 break;
1784 }
1785 // otherwise fall through to handle image part
1786 case WebView.HitTestResult.IMAGE_TYPE:
1787 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1788 menu.setHeaderTitle(extra);
1789 }
1790 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1791 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1792 menu.findItem(R.id.download_context_menu_id).
1793 setOnMenuItemClickListener(new Download(extra));
1794 break;
1795
1796 default:
1797 Log.w(LOGTAG, "We should not get here.");
1798 break;
1799 }
1800 }
1801
The Android Open Source Project0c908882009-03-03 19:32:16 -08001802 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001803 // this should only be called for the current tab.
The Android Open Source Project0c908882009-03-03 19:32:16 -08001804 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001805 // Attach the container that contains the main WebView and any other UI
1806 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001807 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001808
1809 if (mShouldShowErrorConsole) {
1810 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1811 if (errorConsole.numberOfErrors() == 0) {
1812 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1813 } else {
1814 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1815 }
1816
1817 mErrorConsoleContainer.addView(errorConsole,
1818 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1819 ViewGroup.LayoutParams.WRAP_CONTENT));
1820 }
1821
Grace Klobac928c302009-09-17 11:51:21 -07001822 setLockIconType(t.getLockIconType());
1823 setPrevLockType(t.getPrevLockIconType());
1824
1825 // this is to match the code in removeTabFromContentView()
1826 if (!mPageStarted && t.getTopWindow().getProgress() < 100) {
1827 mPageStarted = true;
Grace Klobaeb6eef42009-09-15 17:56:32 -07001828 }
1829
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001830 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001831 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001832 // Request focus on the top window.
1833 t.getTopWindow().requestFocus();
1834 }
1835
1836 // Attach a sub window to the main WebView of the given tab.
1837 private void attachSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001838 t.attachSubWindow(mContentView);
1839 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001840 }
1841
1842 // Remove the given tab from the content view.
1843 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001844 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001845 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001846
1847 if (mTabControl.getCurrentErrorConsole(false) != null) {
1848 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1849 }
1850
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001851 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001852 if (view != null) {
1853 view.setEmbeddedTitleBar(null);
1854 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001855
Grace Klobac928c302009-09-17 11:51:21 -07001856 // unlike attachTabToContentView(), removeTabFromContentView() can be
1857 // called for the non-current tab. Need to add the check.
Grace Klobaeb6eef42009-09-15 17:56:32 -07001858 if (t == mTabControl.getCurrentTab()) {
1859 t.setLockIconType(getLockIconType());
1860 t.setPrevLockIconType(getPrevLockType());
Grace Klobac928c302009-09-17 11:51:21 -07001861
1862 // this is not a perfect solution. But currently there is one
1863 // WebViewClient for all the WebView. if user switches from an
1864 // in-load window to an already loaded window, mPageStarted will not
1865 // be set to false. If user leaves the Browser, pauseWebViewTimers()
1866 // won't do anything and leaves the timer running even Browser is in
1867 // the background.
1868 if (mPageStarted) {
1869 mPageStarted = false;
1870 }
Grace Klobaeb6eef42009-09-15 17:56:32 -07001871 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001872 }
1873
1874 // Remove the sub window if it exists. Also called by TabControl when the
1875 // user clicks the 'X' to dismiss a sub window.
1876 /* package */ void dismissSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001877 t.removeSubWindow(mContentView);
1878 // Tell the TabControl to dismiss the subwindow. This will destroy
1879 // the WebView.
1880 mTabControl.dismissSubWindow(t);
1881 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001882 }
1883
Leon Scroggins1f005d32009-08-10 17:36:42 -04001884 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001885 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001886 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1887 String appId) {
1888 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001889 }
1890
1891 // This method does a ton of stuff. It will attempt to create a new tab
1892 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001893 // url isn't null, it will load the given url.
1894 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001895 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001896 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1897 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1898 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001899 final TabControl.Tab tab = mTabControl.createNewTab(
1900 closeOnExit, appId, urlData.mUrl);
1901 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001902 // If the last tab was removed from the active tabs page, currentTab
1903 // will be null.
1904 if (currentTab != null) {
1905 removeTabFromContentView(currentTab);
1906 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001907 // We must set the new tab as the current tab to reflect the old
1908 // animation behavior.
1909 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001910 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001911 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001912 urlData.loadIn(webview);
1913 }
1914 return tab;
1915 } else {
1916 // Get rid of the subwindow if it exists
1917 dismissSubWindow(currentTab);
1918 if (!urlData.isEmpty()) {
1919 // Load the given url.
1920 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001921 }
1922 }
Grace Klobac9181842009-04-14 08:53:22 -07001923 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001924 }
1925
Grace Klobac9181842009-04-14 08:53:22 -07001926 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001927 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001928 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001929 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001930 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001931 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001932 }
Grace Klobac9181842009-04-14 08:53:22 -07001933 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001934 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001935 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001936 }
1937 }
1938
1939 private class Copy implements OnMenuItemClickListener {
1940 private CharSequence mText;
1941
1942 public boolean onMenuItemClick(MenuItem item) {
1943 copy(mText);
1944 return true;
1945 }
1946
1947 public Copy(CharSequence toCopy) {
1948 mText = toCopy;
1949 }
1950 }
1951
1952 private class Download implements OnMenuItemClickListener {
1953 private String mText;
1954
1955 public boolean onMenuItemClick(MenuItem item) {
1956 onDownloadStartNoStream(mText, null, null, null, -1);
1957 return true;
1958 }
1959
1960 public Download(String toDownload) {
1961 mText = toDownload;
1962 }
1963 }
1964
1965 private void copy(CharSequence text) {
1966 try {
1967 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1968 if (clip != null) {
1969 clip.setClipboardText(text);
1970 }
1971 } catch (android.os.RemoteException e) {
1972 Log.e(LOGTAG, "Copy failed", e);
1973 }
1974 }
1975
1976 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001977 * Resets the browser title-view to whatever it must be
1978 * (for example, if we had a loading error)
1979 * When we have a new page, we call resetTitle, when we
1980 * have to reset the titlebar to whatever it used to be
1981 * (for example, if the user chose to stop loading), we
1982 * call resetTitleAndRevertLockIcon.
1983 */
1984 /* package */ void resetTitleAndRevertLockIcon() {
1985 revertLockIcon();
1986 resetTitleIconAndProgress();
1987 }
1988
1989 /**
1990 * Reset the title, favicon, and progress.
1991 */
1992 private void resetTitleIconAndProgress() {
1993 WebView current = mTabControl.getCurrentWebView();
1994 if (current == null) {
1995 return;
1996 }
1997 resetTitleAndIcon(current);
1998 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001999 mWebChromeClient.onProgressChanged(current, progress);
2000 }
2001
2002 // Reset the title and the icon based on the given item.
2003 private void resetTitleAndIcon(WebView view) {
2004 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2005 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002006 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002007 setFavicon(item.getFavicon());
2008 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002009 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002010 setFavicon(null);
2011 }
2012 }
2013
2014 /**
2015 * Sets a title composed of the URL and the title string.
2016 * @param url The URL of the site being loaded.
2017 * @param title The title of the site being loaded.
2018 */
Leon Scroggins68579392009-09-15 15:31:54 -04002019 private void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002020 mUrl = url;
2021 mTitle = title;
2022
Leon Scroggins68579392009-09-15 15:31:54 -04002023 mTitleBar.setTitleAndUrl(title, url);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002024 if (mFakeTitleBar != null) {
2025 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002026 }
2027 }
2028
2029 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002030 * @param url The URL to build a title version of the URL from.
2031 * @return The title version of the URL or null if fails.
2032 * The title version of the URL can be either the URL hostname,
2033 * or the hostname with an "https://" prefix (for secure URLs),
2034 * or an empty string if, for example, the URL in question is a
2035 * file:// URL with no hostname.
2036 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002037 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002038 String titleUrl = null;
2039
2040 if (url != null) {
2041 try {
2042 // parse the url string
2043 URL urlObj = new URL(url);
2044 if (urlObj != null) {
2045 titleUrl = "";
2046
2047 String protocol = urlObj.getProtocol();
2048 String host = urlObj.getHost();
2049
2050 if (host != null && 0 < host.length()) {
2051 titleUrl = host;
2052 if (protocol != null) {
2053 // if a secure site, add an "https://" prefix!
2054 if (protocol.equalsIgnoreCase("https")) {
2055 titleUrl = protocol + "://" + host;
2056 }
2057 }
2058 }
2059 }
2060 } catch (MalformedURLException e) {}
2061 }
2062
2063 return titleUrl;
2064 }
2065
2066 // Set the favicon in the title bar.
2067 private void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002068 mTitleBar.setFavicon(icon);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002069 if (mFakeTitleBar != null) {
2070 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002071 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002072 }
2073
2074 /**
2075 * Saves the current lock-icon state before resetting
2076 * the lock icon. If we have an error, we may need to
2077 * roll back to the previous state.
2078 */
2079 private void saveLockIcon() {
2080 mPrevLockType = mLockIconType;
2081 }
2082
2083 /**
2084 * Reverts the lock-icon state to the last saved state,
2085 * for example, if we had an error, and need to cancel
2086 * the load.
2087 */
2088 private void revertLockIcon() {
2089 mLockIconType = mPrevLockType;
2090
Dave Bort31a6d1c2009-04-13 15:56:49 -07002091 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002092 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2093 " revert lock icon to " + mLockIconType);
2094 }
2095
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002096 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002097 }
2098
Leon Scroggins1f005d32009-08-10 17:36:42 -04002099 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002100 * Close the tab, remove its associated title bar, and adjust mTabControl's
2101 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002102 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002103 /* package */ void closeTab(TabControl.Tab t) {
2104 int currentIndex = mTabControl.getCurrentIndex();
2105 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002106 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002107 if (currentIndex >= removeIndex && currentIndex != 0) {
2108 currentIndex--;
2109 }
2110 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002111 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002112 }
2113
2114 private void goBackOnePageOrQuit() {
2115 TabControl.Tab current = mTabControl.getCurrentTab();
2116 if (current == null) {
2117 /*
2118 * Instead of finishing the activity, simply push this to the back
2119 * of the stack and let ActivityManager to choose the foreground
2120 * activity. As BrowserActivity is singleTask, it will be always the
2121 * root of the task. So we can use either true or false for
2122 * moveTaskToBack().
2123 */
2124 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002125 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002126 }
2127 WebView w = current.getWebView();
2128 if (w.canGoBack()) {
2129 w.goBack();
2130 } else {
2131 // Check to see if we are closing a window that was created by
2132 // another window. If so, we switch back to that window.
2133 TabControl.Tab parent = current.getParentTab();
2134 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002135 switchToTab(mTabControl.getTabIndex(parent));
2136 // Now we close the other tab
2137 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002138 } else {
2139 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002140 // force mPageStarted to be false as we are going to either
2141 // finish the activity or remove the tab. This will ensure
2142 // pauseWebView() taking action.
2143 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002144 if (mTabControl.getTabCount() == 1) {
2145 finish();
2146 return;
2147 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002148 // call pauseWebViewTimers() now, we won't be able to call
2149 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002150 // Temporarily change mActivityInPause to be true as
2151 // pauseWebViewTimers() will do nothing if mActivityInPause
2152 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002153 boolean savedState = mActivityInPause;
2154 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002155 Log.e(LOGTAG, "BrowserActivity is already paused "
2156 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002157 }
2158 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002159 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002160 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002161 removeTabFromContentView(current);
2162 mTabControl.removeTab(current);
2163 }
2164 /*
2165 * Instead of finishing the activity, simply push this to the back
2166 * of the stack and let ActivityManager to choose the foreground
2167 * activity. As BrowserActivity is singleTask, it will be always the
2168 * root of the task. So we can use either true or false for
2169 * moveTaskToBack().
2170 */
2171 moveTaskToBack(true);
2172 }
2173 }
2174 }
2175
Grace Kloba5942df02009-09-18 11:48:29 -07002176 @Override
2177 public boolean onKeyDown(int keyCode, KeyEvent event) {
2178 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2179 // still down, we don't want to trigger the search. Pretend to consume
2180 // the key and do nothing.
2181 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002182
Grace Kloba5942df02009-09-18 11:48:29 -07002183 switch(keyCode) {
2184 case KeyEvent.KEYCODE_MENU:
2185 mMenuIsDown = true;
2186 break;
2187 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002188 // WebView/WebTextView handle the keys in the KeyDown. As
2189 // the Activity's shortcut keys are only handled when WebView
2190 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2191 if (event.isShiftPressed()) {
2192 getTopWindow().pageUp(false);
2193 } else {
2194 getTopWindow().pageDown(false);
2195 }
Grace Kloba5942df02009-09-18 11:48:29 -07002196 return true;
2197 case KeyEvent.KEYCODE_BACK:
2198 if (event.getRepeatCount() == 0) {
2199 event.startTracking();
2200 return true;
2201 } else if (mCustomView == null && mActiveTabsPage == null
2202 && event.isLongPress()) {
2203 bookmarksOrHistoryPicker(true);
2204 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002205 }
Grace Kloba5942df02009-09-18 11:48:29 -07002206 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002207 }
Grace Kloba5942df02009-09-18 11:48:29 -07002208 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002209 }
2210
Grace Kloba5942df02009-09-18 11:48:29 -07002211 @Override
2212 public boolean onKeyUp(int keyCode, KeyEvent event) {
2213 switch(keyCode) {
2214 case KeyEvent.KEYCODE_MENU:
2215 mMenuIsDown = false;
2216 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002217 case KeyEvent.KEYCODE_BACK:
2218 if (event.isTracking() && !event.isCanceled()) {
2219 if (mCustomView != null) {
2220 // if a custom view is showing, hide it
2221 mWebChromeClient.onHideCustomView();
2222 } else if (mActiveTabsPage != null) {
2223 // if tab page is showing, hide it
2224 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002225 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002226 WebView subwindow = mTabControl.getCurrentSubWindow();
2227 if (subwindow != null) {
2228 if (subwindow.canGoBack()) {
2229 subwindow.goBack();
2230 } else {
2231 dismissSubWindow(mTabControl.getCurrentTab());
2232 }
2233 } else {
2234 goBackOnePageOrQuit();
2235 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002236 }
Grace Kloba5942df02009-09-18 11:48:29 -07002237 return true;
2238 }
2239 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002240 }
Grace Kloba5942df02009-09-18 11:48:29 -07002241 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002242 }
2243
Leon Scroggins68579392009-09-15 15:31:54 -04002244 /* package */ void stopLoading() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002245 resetTitleAndRevertLockIcon();
2246 WebView w = getTopWindow();
2247 w.stopLoading();
2248 mWebViewClient.onPageFinished(w, w.getUrl());
2249
2250 cancelStopToast();
2251 mStopToast = Toast
2252 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2253 mStopToast.show();
2254 }
2255
2256 private void cancelStopToast() {
2257 if (mStopToast != null) {
2258 mStopToast.cancel();
2259 mStopToast = null;
2260 }
2261 }
2262
2263 // called by a non-UI thread to post the message
2264 public void postMessage(int what, int arg1, int arg2, Object obj) {
2265 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2266 }
2267
2268 // public message ids
2269 public final static int LOAD_URL = 1001;
2270 public final static int STOP_LOAD = 1002;
2271
2272 // Message Ids
2273 private static final int FOCUS_NODE_HREF = 102;
2274 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002275 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002276
2277 // Private handler for handling javascript and saving passwords
2278 private Handler mHandler = new Handler() {
2279
2280 public void handleMessage(Message msg) {
2281 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002282 case FOCUS_NODE_HREF:
2283 String url = (String) msg.getData().get("url");
2284 if (url == null || url.length() == 0) {
2285 break;
2286 }
2287 HashMap focusNodeMap = (HashMap) msg.obj;
2288 WebView view = (WebView) focusNodeMap.get("webview");
2289 // Only apply the action if the top window did not change.
2290 if (getTopWindow() != view) {
2291 break;
2292 }
2293 switch (msg.arg1) {
2294 case R.id.open_context_menu_id:
2295 case R.id.view_image_context_menu_id:
2296 loadURL(getTopWindow(), url);
2297 break;
2298 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002299 final TabControl.Tab parent = mTabControl
2300 .getCurrentTab();
2301 final TabControl.Tab newTab = openTab(url);
2302 if (newTab != parent) {
2303 parent.addChildTab(newTab);
2304 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002305 break;
2306 case R.id.bookmark_context_menu_id:
2307 Intent intent = new Intent(BrowserActivity.this,
2308 AddBookmarkPage.class);
2309 intent.putExtra("url", url);
2310 startActivity(intent);
2311 break;
2312 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002313 Browser.sendString(BrowserActivity.this, url,
2314 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002315 break;
2316 case R.id.copy_link_context_menu_id:
2317 copy(url);
2318 break;
2319 case R.id.save_link_context_menu_id:
2320 case R.id.download_context_menu_id:
2321 onDownloadStartNoStream(url, null, null, null, -1);
2322 break;
2323 }
2324 break;
2325
2326 case LOAD_URL:
2327 loadURL(getTopWindow(), (String) msg.obj);
2328 break;
2329
2330 case STOP_LOAD:
2331 stopLoading();
2332 break;
2333
2334 case CANCEL_CREDS_REQUEST:
2335 resumeAfterCredentials();
2336 break;
2337
The Android Open Source Project0c908882009-03-03 19:32:16 -08002338 case RELEASE_WAKELOCK:
2339 if (mWakeLock.isHeld()) {
2340 mWakeLock.release();
2341 }
2342 break;
2343 }
2344 }
2345 };
2346
Leon Scroggins89c6d362009-07-15 16:54:37 -04002347 private void updateScreenshot(WebView view) {
2348 // If this is a bookmarked site, add a screenshot to the database.
2349 // FIXME: When should we update? Every time?
2350 // FIXME: Would like to make sure there is actually something to
2351 // draw, but the API for that (WebViewCore.pictureReady()) is not
2352 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002353
Patrick Scott3918d442009-08-04 13:22:29 -04002354 ContentResolver cr = getContentResolver();
2355 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002356 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002357 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002358 boolean succeed = c.moveToFirst();
2359 ContentValues values = null;
2360 while (succeed) {
2361 if (values == null) {
2362 final ByteArrayOutputStream os
2363 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002364 Bitmap bm = createScreenshot(view);
Leon Scroggins89c6d362009-07-15 16:54:37 -04002365 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2366 values = new ContentValues();
2367 values.put(Browser.BookmarkColumns.THUMBNAIL,
2368 os.toByteArray());
2369 }
2370 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2371 c.getInt(0)), values, null, null);
2372 succeed = c.moveToNext();
2373 }
2374 c.close();
2375 }
2376 }
2377
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002378 /**
2379 * Constants for the size of the thumbnail created when taking a screenshot
2380 */
2381 /* package */ static final int THUMBNAIL_WIDTH = 130;
2382 /* package */ static final int THUMBNAIL_HEIGHT = 104;
2383
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002384 private Bitmap createScreenshot(WebView view) {
2385 Picture thumbnail = view.capturePicture();
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002386 Bitmap bm = Bitmap.createBitmap(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT,
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002387 Bitmap.Config.ARGB_4444);
2388 Canvas canvas = new Canvas(bm);
2389 // May need to tweak these values to determine what is the
2390 // best scale factor
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002391 int contentWidth = view.getContentWidth();
2392 if (contentWidth > 0) {
2393 float scaleFactor = (float) THUMBNAIL_WIDTH / (float) contentWidth;
2394 canvas.scale(scaleFactor, scaleFactor);
2395 }
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002396 thumbnail.draw(canvas);
2397 return bm;
2398 }
2399
The Android Open Source Project0c908882009-03-03 19:32:16 -08002400 // -------------------------------------------------------------------------
2401 // WebViewClient implementation.
2402 //-------------------------------------------------------------------------
2403
2404 // Use in overrideUrlLoading
2405 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2406 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2407 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2408 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2409
2410 /* package */ WebViewClient getWebViewClient() {
2411 return mWebViewClient;
2412 }
2413
Patrick Scott3918d442009-08-04 13:22:29 -04002414 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002415 if (icon != null) {
2416 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott15525d42009-09-21 13:39:37 -04002417 view.getOriginalUrl(), view.getUrl(), icon);
2418 }
2419 setFavicon(icon);
2420 }
2421
2422 private void updateIcon(String url, Bitmap icon) {
2423 if (icon != null) {
2424 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2425 null, url, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002426 }
2427 setFavicon(icon);
2428 }
2429
2430 private final WebViewClient mWebViewClient = new WebViewClient() {
2431 @Override
2432 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2433 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002434 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002435
Patrick Scott59ce8302009-09-18 16:29:38 -04002436 // If we start a touch icon load and then load a new page, we don't
2437 // want to cancel the current touch icon loader. But, we do want to
2438 // create a new one when the touch icon url is known.
2439 if (mTouchIconLoader != null) {
2440 mTouchIconLoader.mActivity = null;
2441 mTouchIconLoader = null;
2442 }
2443
Ben Murdochbff2d602009-07-01 20:19:05 +01002444 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2445 if (errorConsole != null) {
2446 errorConsole.clearErrorMessages();
2447 if (mShouldShowErrorConsole) {
2448 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2449 }
2450 }
2451
The Android Open Source Project0c908882009-03-03 19:32:16 -08002452 // Call updateIcon instead of setFavicon so the bookmark
2453 // database can be updated.
Patrick Scott15525d42009-09-21 13:39:37 -04002454 updateIcon(url, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002455
Grace Kloba4d7880f2009-08-12 09:35:42 -07002456 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002457 String host;
2458 try {
2459 WebAddress uri = new WebAddress(url);
2460 host = uri.mHost;
2461 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002462 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002463 }
2464 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002465 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002466 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002467 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002468 }
2469
2470 // Performance probe
2471 if (false) {
2472 mStart = SystemClock.uptimeMillis();
2473 mProcessStart = Process.getElapsedCpuTime();
2474 long[] sysCpu = new long[7];
2475 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2476 sysCpu, null)) {
2477 mUserStart = sysCpu[0] + sysCpu[1];
2478 mSystemStart = sysCpu[2];
2479 mIdleStart = sysCpu[3];
2480 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2481 }
2482 mUiStart = SystemClock.currentThreadTimeMillis();
2483 }
2484
2485 if (!mPageStarted) {
2486 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002487 // if onResume() has been called, resumeWebViewTimers() does
2488 // nothing.
2489 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002490 }
2491
2492 // reset sync timer to avoid sync starts during loading a page
2493 CookieSyncManager.getInstance().resetSync();
2494
2495 mInLoad = true;
Leon Scroggins184f5e32009-09-21 10:38:24 -04002496 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002497 updateInLoadMenuItems();
2498 if (!mIsNetworkUp) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04002499 createAndShowNetworkDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002500 if (view != null) {
2501 view.setNetworkAvailable(false);
2502 }
2503 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002504 }
2505
2506 @Override
2507 public void onPageFinished(WebView view, String url) {
2508 // Reset the title and icon in case we stopped a provisional
2509 // load.
2510 resetTitleAndIcon(view);
Ben Murdochaac7aa62009-09-17 16:57:40 +01002511 updateScreenshot(view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002512
2513 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002514 updateLockIconToLatest();
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002515
The Android Open Source Project0c908882009-03-03 19:32:16 -08002516 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002517 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002518 long[] sysCpu = new long[7];
2519 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2520 sysCpu, null)) {
2521 String uiInfo = "UI thread used "
2522 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2523 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002524 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002525 Log.d(LOGTAG, uiInfo);
2526 }
2527 //The string that gets written to the log
2528 String performanceString = "It took total "
2529 + (SystemClock.uptimeMillis() - mStart)
2530 + " ms clock time to load the page."
2531 + "\nbrowser process used "
2532 + (Process.getElapsedCpuTime() - mProcessStart)
2533 + " ms, user processes used "
2534 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2535 + " ms, kernel used "
2536 + (sysCpu[2] - mSystemStart) * 10
2537 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2538 + " ms and irq took "
2539 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2540 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002541 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002542 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2543 }
2544 if (url != null) {
2545 // strip the url to maintain consistency
2546 String newUrl = new String(url);
2547 if (newUrl.startsWith("http://www.")) {
2548 newUrl = newUrl.substring(11);
2549 } else if (newUrl.startsWith("http://")) {
2550 newUrl = newUrl.substring(7);
2551 } else if (newUrl.startsWith("https://www.")) {
2552 newUrl = newUrl.substring(12);
2553 } else if (newUrl.startsWith("https://")) {
2554 newUrl = newUrl.substring(8);
2555 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002556 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002557 Log.d(LOGTAG, newUrl + " loaded");
2558 }
2559 /*
2560 if (sWhiteList.contains(newUrl)) {
2561 // The string that gets pushed to the statistcs
2562 // service
2563 performanceString = performanceString
2564 + "\nWebpage: "
2565 + newUrl
2566 + "\nCarrier: "
2567 + android.os.SystemProperties
2568 .get("gsm.sim.operator.alpha");
2569 if (mWebView != null
2570 && mWebView.getContext() != null
2571 && mWebView.getContext().getSystemService(
2572 Context.CONNECTIVITY_SERVICE) != null) {
2573 ConnectivityManager cManager =
2574 (ConnectivityManager) mWebView
2575 .getContext().getSystemService(
2576 Context.CONNECTIVITY_SERVICE);
2577 NetworkInfo nInfo = cManager
2578 .getActiveNetworkInfo();
2579 if (nInfo != null) {
2580 performanceString = performanceString
2581 + "\nNetwork Type: "
2582 + nInfo.getType().toString();
2583 }
2584 }
2585 Checkin.logEvent(mResolver,
2586 Checkin.Events.Tag.WEBPAGE_LOAD,
2587 performanceString);
2588 Log.w(LOGTAG, "pushed to the statistics service");
2589 }
2590 */
2591 }
2592 }
2593 }
2594
2595 if (mInTrace) {
2596 mInTrace = false;
2597 Debug.stopMethodTracing();
2598 }
2599
2600 if (mPageStarted) {
2601 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002602 // pauseWebViewTimers() will do nothing and return false if
2603 // onPause() is not called yet.
2604 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002605 if (mWakeLock.isHeld()) {
2606 mHandler.removeMessages(RELEASE_WAKELOCK);
2607 mWakeLock.release();
2608 }
2609 }
2610 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002611 }
2612
2613 // return true if want to hijack the url to let another app to handle it
2614 @Override
2615 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2616 if (url.startsWith(SCHEME_WTAI)) {
2617 // wtai://wp/mc;number
2618 // number=string(phone-number)
2619 if (url.startsWith(SCHEME_WTAI_MC)) {
2620 Intent intent = new Intent(Intent.ACTION_VIEW,
2621 Uri.parse(WebView.SCHEME_TEL +
2622 url.substring(SCHEME_WTAI_MC.length())));
2623 startActivity(intent);
2624 return true;
2625 }
2626 // wtai://wp/sd;dtmf
2627 // dtmf=string(dialstring)
2628 if (url.startsWith(SCHEME_WTAI_SD)) {
2629 // TODO
2630 // only send when there is active voice connection
2631 return false;
2632 }
2633 // wtai://wp/ap;number;name
2634 // number=string(phone-number)
2635 // name=string
2636 if (url.startsWith(SCHEME_WTAI_AP)) {
2637 // TODO
2638 return false;
2639 }
2640 }
2641
Dianne Hackborn99189432009-06-17 18:06:18 -07002642 // The "about:" schemes are internal to the browser; don't
2643 // want these to be dispatched to other apps.
2644 if (url.startsWith("about:")) {
2645 return false;
2646 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002647
Dianne Hackborn99189432009-06-17 18:06:18 -07002648 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002649
Dianne Hackborn99189432009-06-17 18:06:18 -07002650 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002651 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002652 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2653 } catch (URISyntaxException ex) {
2654 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002655 return false;
2656 }
2657
Grace Kloba5b078b52009-06-24 20:23:41 -07002658 // check whether the intent can be resolved. If not, we will see
2659 // whether we can download it from the Market.
2660 if (getPackageManager().resolveActivity(intent, 0) == null) {
2661 String packagename = intent.getPackage();
2662 if (packagename != null) {
2663 intent = new Intent(Intent.ACTION_VIEW, Uri
2664 .parse("market://search?q=pname:" + packagename));
2665 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2666 startActivity(intent);
2667 return true;
2668 } else {
2669 return false;
2670 }
2671 }
2672
Dianne Hackborn99189432009-06-17 18:06:18 -07002673 // sanitize the Intent, ensuring web pages can not bypass browser
2674 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002675 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002676 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002677 try {
2678 if (startActivityIfNeeded(intent, -1)) {
2679 return true;
2680 }
2681 } catch (ActivityNotFoundException ex) {
2682 // ignore the error. If no application can handle the URL,
2683 // eg about:blank, assume the browser can handle it.
2684 }
2685
2686 if (mMenuIsDown) {
2687 openTab(url);
2688 closeOptionsMenu();
2689 return true;
2690 }
2691
2692 return false;
2693 }
2694
2695 /**
2696 * Updates the lock icon. This method is called when we discover another
2697 * resource to be loaded for this page (for example, javascript). While
2698 * we update the icon type, we do not update the lock icon itself until
2699 * we are done loading, it is slightly more secure this way.
2700 */
2701 @Override
2702 public void onLoadResource(WebView view, String url) {
2703 if (url != null && url.length() > 0) {
2704 // It is only if the page claims to be secure
2705 // that we may have to update the lock:
2706 if (mLockIconType == LOCK_ICON_SECURE) {
2707 // If NOT a 'safe' url, change the lock to mixed content!
2708 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2709 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002710 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002711 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2712 " updated lock icon to " + mLockIconType + " due to " + url);
2713 }
2714 }
2715 }
2716 }
2717 }
2718
2719 /**
2720 * Show the dialog, asking the user if they would like to continue after
2721 * an excessive number of HTTP redirects.
2722 */
2723 @Override
2724 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2725 final Message continueMsg) {
2726 new AlertDialog.Builder(BrowserActivity.this)
2727 .setTitle(R.string.browserFrameRedirect)
2728 .setMessage(R.string.browserFrame307Post)
2729 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2730 public void onClick(DialogInterface dialog, int which) {
2731 continueMsg.sendToTarget();
2732 }})
2733 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2734 public void onClick(DialogInterface dialog, int which) {
2735 cancelMsg.sendToTarget();
2736 }})
2737 .setOnCancelListener(new OnCancelListener() {
2738 public void onCancel(DialogInterface dialog) {
2739 cancelMsg.sendToTarget();
2740 }})
2741 .show();
2742 }
2743
Patrick Scott37911c72009-03-24 18:02:58 -07002744 // Container class for the next error dialog that needs to be
2745 // displayed.
2746 class ErrorDialog {
2747 public final int mTitle;
2748 public final String mDescription;
2749 public final int mError;
2750 ErrorDialog(int title, String desc, int error) {
2751 mTitle = title;
2752 mDescription = desc;
2753 mError = error;
2754 }
2755 };
2756
2757 private void processNextError() {
2758 if (mQueuedErrors == null) {
2759 return;
2760 }
2761 // The first one is currently displayed so just remove it.
2762 mQueuedErrors.removeFirst();
2763 if (mQueuedErrors.size() == 0) {
2764 mQueuedErrors = null;
2765 return;
2766 }
2767 showError(mQueuedErrors.getFirst());
2768 }
2769
2770 private DialogInterface.OnDismissListener mDialogListener =
2771 new DialogInterface.OnDismissListener() {
2772 public void onDismiss(DialogInterface d) {
2773 processNextError();
2774 }
2775 };
2776 private LinkedList<ErrorDialog> mQueuedErrors;
2777
2778 private void queueError(int err, String desc) {
2779 if (mQueuedErrors == null) {
2780 mQueuedErrors = new LinkedList<ErrorDialog>();
2781 }
2782 for (ErrorDialog d : mQueuedErrors) {
2783 if (d.mError == err) {
2784 // Already saw a similar error, ignore the new one.
2785 return;
2786 }
2787 }
2788 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002789 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002790 R.string.browserFrameFileErrorLabel :
2791 R.string.browserFrameNetworkErrorLabel,
2792 desc, err);
2793 mQueuedErrors.addLast(errDialog);
2794
2795 // Show the dialog now if the queue was empty.
2796 if (mQueuedErrors.size() == 1) {
2797 showError(errDialog);
2798 }
2799 }
2800
2801 private void showError(ErrorDialog errDialog) {
2802 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2803 .setTitle(errDialog.mTitle)
2804 .setMessage(errDialog.mDescription)
2805 .setPositiveButton(R.string.ok, null)
2806 .create();
2807 d.setOnDismissListener(mDialogListener);
2808 d.show();
2809 }
2810
The Android Open Source Project0c908882009-03-03 19:32:16 -08002811 /**
2812 * Show a dialog informing the user of the network error reported by
2813 * WebCore.
2814 */
2815 @Override
2816 public void onReceivedError(WebView view, int errorCode,
2817 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002818 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2819 errorCode != WebViewClient.ERROR_CONNECT &&
2820 errorCode != WebViewClient.ERROR_BAD_URL &&
2821 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2822 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002823 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002824 }
Patrick Scott37911c72009-03-24 18:02:58 -07002825 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2826 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002827
Ben Murdochaac7aa62009-09-17 16:57:40 +01002828 mNeedExtraScreenShot = true;
2829
The Android Open Source Project0c908882009-03-03 19:32:16 -08002830 // We need to reset the title after an error.
2831 resetTitleAndRevertLockIcon();
2832 }
2833
2834 /**
2835 * Check with the user if it is ok to resend POST data as the page they
2836 * are trying to navigate to is the result of a POST.
2837 */
2838 @Override
2839 public void onFormResubmission(WebView view, final Message dontResend,
2840 final Message resend) {
2841 new AlertDialog.Builder(BrowserActivity.this)
2842 .setTitle(R.string.browserFrameFormResubmitLabel)
2843 .setMessage(R.string.browserFrameFormResubmitMessage)
2844 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2845 public void onClick(DialogInterface dialog, int which) {
2846 resend.sendToTarget();
2847 }})
2848 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2849 public void onClick(DialogInterface dialog, int which) {
2850 dontResend.sendToTarget();
2851 }})
2852 .setOnCancelListener(new OnCancelListener() {
2853 public void onCancel(DialogInterface dialog) {
2854 dontResend.sendToTarget();
2855 }})
2856 .show();
2857 }
2858
2859 /**
2860 * Insert the url into the visited history database.
2861 * @param url The url to be inserted.
2862 * @param isReload True if this url is being reloaded.
2863 * FIXME: Not sure what to do when reloading the page.
2864 */
2865 @Override
2866 public void doUpdateVisitedHistory(WebView view, String url,
2867 boolean isReload) {
2868 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2869 return;
2870 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002871 // remove "client" before updating it to the history so that it wont
2872 // show up in the auto-complete list.
2873 int index = url.indexOf("client=ms-");
2874 if (index > 0 && url.contains(".google.")) {
2875 int end = url.indexOf('&', index);
2876 if (end > 0) {
2877 url = url.substring(0, index-1).concat(url.substring(end));
2878 } else {
2879 url = url.substring(0, index-1);
2880 }
2881 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002882 Browser.updateVisitedHistory(mResolver, url, true);
2883 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2884 }
2885
2886 /**
2887 * Displays SSL error(s) dialog to the user.
2888 */
2889 @Override
2890 public void onReceivedSslError(
2891 final WebView view, final SslErrorHandler handler, final SslError error) {
2892
2893 if (mSettings.showSecurityWarnings()) {
2894 final LayoutInflater factory =
2895 LayoutInflater.from(BrowserActivity.this);
2896 final View warningsView =
2897 factory.inflate(R.layout.ssl_warnings, null);
2898 final LinearLayout placeholder =
2899 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2900
2901 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2902 LinearLayout ll = (LinearLayout)factory
2903 .inflate(R.layout.ssl_warning, null);
2904 ((TextView)ll.findViewById(R.id.warning))
2905 .setText(R.string.ssl_untrusted);
2906 placeholder.addView(ll);
2907 }
2908
2909 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2910 LinearLayout ll = (LinearLayout)factory
2911 .inflate(R.layout.ssl_warning, null);
2912 ((TextView)ll.findViewById(R.id.warning))
2913 .setText(R.string.ssl_mismatch);
2914 placeholder.addView(ll);
2915 }
2916
2917 if (error.hasError(SslError.SSL_EXPIRED)) {
2918 LinearLayout ll = (LinearLayout)factory
2919 .inflate(R.layout.ssl_warning, null);
2920 ((TextView)ll.findViewById(R.id.warning))
2921 .setText(R.string.ssl_expired);
2922 placeholder.addView(ll);
2923 }
2924
2925 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2926 LinearLayout ll = (LinearLayout)factory
2927 .inflate(R.layout.ssl_warning, null);
2928 ((TextView)ll.findViewById(R.id.warning))
2929 .setText(R.string.ssl_not_yet_valid);
2930 placeholder.addView(ll);
2931 }
2932
2933 new AlertDialog.Builder(BrowserActivity.this)
2934 .setTitle(R.string.security_warning)
2935 .setIcon(android.R.drawable.ic_dialog_alert)
2936 .setView(warningsView)
2937 .setPositiveButton(R.string.ssl_continue,
2938 new DialogInterface.OnClickListener() {
2939 public void onClick(DialogInterface dialog, int whichButton) {
2940 handler.proceed();
2941 }
2942 })
2943 .setNeutralButton(R.string.view_certificate,
2944 new DialogInterface.OnClickListener() {
2945 public void onClick(DialogInterface dialog, int whichButton) {
2946 showSSLCertificateOnError(view, handler, error);
2947 }
2948 })
2949 .setNegativeButton(R.string.cancel,
2950 new DialogInterface.OnClickListener() {
2951 public void onClick(DialogInterface dialog, int whichButton) {
2952 handler.cancel();
2953 BrowserActivity.this.resetTitleAndRevertLockIcon();
2954 }
2955 })
2956 .setOnCancelListener(
2957 new DialogInterface.OnCancelListener() {
2958 public void onCancel(DialogInterface dialog) {
2959 handler.cancel();
2960 BrowserActivity.this.resetTitleAndRevertLockIcon();
2961 }
2962 })
2963 .show();
2964 } else {
2965 handler.proceed();
2966 }
2967 }
2968
2969 /**
2970 * Handles an HTTP authentication request.
2971 *
2972 * @param handler The authentication handler
2973 * @param host The host
2974 * @param realm The realm
2975 */
2976 @Override
2977 public void onReceivedHttpAuthRequest(WebView view,
2978 final HttpAuthHandler handler, final String host, final String realm) {
2979 String username = null;
2980 String password = null;
2981
2982 boolean reuseHttpAuthUsernamePassword =
2983 handler.useHttpAuthUsernamePassword();
2984
2985 if (reuseHttpAuthUsernamePassword &&
2986 (mTabControl.getCurrentWebView() != null)) {
2987 String[] credentials =
2988 mTabControl.getCurrentWebView()
2989 .getHttpAuthUsernamePassword(host, realm);
2990 if (credentials != null && credentials.length == 2) {
2991 username = credentials[0];
2992 password = credentials[1];
2993 }
2994 }
2995
2996 if (username != null && password != null) {
2997 handler.proceed(username, password);
2998 } else {
2999 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3000 }
3001 }
3002
3003 @Override
3004 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3005 if (mMenuIsDown) {
3006 // only check shortcut key when MENU is held
3007 return getWindow().isShortcutKey(event.getKeyCode(), event);
3008 } else {
3009 return false;
3010 }
3011 }
3012
3013 @Override
3014 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3015 if (view != mTabControl.getCurrentTopWebView()) {
3016 return;
3017 }
3018 if (event.isDown()) {
3019 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3020 } else {
3021 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3022 }
3023 }
3024 };
3025
3026 //--------------------------------------------------------------------------
3027 // WebChromeClient implementation
3028 //--------------------------------------------------------------------------
3029
3030 /* package */ WebChromeClient getWebChromeClient() {
3031 return mWebChromeClient;
3032 }
3033
3034 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3035 // Helper method to create a new tab or sub window.
3036 private void createWindow(final boolean dialog, final Message msg) {
3037 if (dialog) {
3038 mTabControl.createSubWindow();
3039 final TabControl.Tab t = mTabControl.getCurrentTab();
3040 attachSubWindow(t);
3041 WebView.WebViewTransport transport =
3042 (WebView.WebViewTransport) msg.obj;
3043 transport.setWebView(t.getSubWebView());
3044 msg.sendToTarget();
3045 } else {
3046 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003047 final TabControl.Tab newTab
3048 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07003049 if (newTab != parent) {
3050 parent.addChildTab(newTab);
3051 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003052 WebView.WebViewTransport transport =
3053 (WebView.WebViewTransport) msg.obj;
3054 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04003055 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003056 }
3057 }
3058
3059 @Override
3060 public boolean onCreateWindow(WebView view, final boolean dialog,
3061 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003062 // Short-circuit if we can't create any more tabs or sub windows.
3063 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3064 new AlertDialog.Builder(BrowserActivity.this)
3065 .setTitle(R.string.too_many_subwindows_dialog_title)
3066 .setIcon(android.R.drawable.ic_dialog_alert)
3067 .setMessage(R.string.too_many_subwindows_dialog_message)
3068 .setPositiveButton(R.string.ok, null)
3069 .show();
3070 return false;
3071 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3072 new AlertDialog.Builder(BrowserActivity.this)
3073 .setTitle(R.string.too_many_windows_dialog_title)
3074 .setIcon(android.R.drawable.ic_dialog_alert)
3075 .setMessage(R.string.too_many_windows_dialog_message)
3076 .setPositiveButton(R.string.ok, null)
3077 .show();
3078 return false;
3079 }
3080
3081 // Short-circuit if this was a user gesture.
3082 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003083 createWindow(dialog, resultMsg);
3084 return true;
3085 }
3086
3087 // Allow the popup and create the appropriate window.
3088 final AlertDialog.OnClickListener allowListener =
3089 new AlertDialog.OnClickListener() {
3090 public void onClick(DialogInterface d,
3091 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003092 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003093 }
3094 };
3095
3096 // Block the popup by returning a null WebView.
3097 final AlertDialog.OnClickListener blockListener =
3098 new AlertDialog.OnClickListener() {
3099 public void onClick(DialogInterface d, int which) {
3100 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003101 }
3102 };
3103
3104 // Build a confirmation dialog to display to the user.
3105 final AlertDialog d =
3106 new AlertDialog.Builder(BrowserActivity.this)
3107 .setTitle(R.string.attention)
3108 .setIcon(android.R.drawable.ic_dialog_alert)
3109 .setMessage(R.string.popup_window_attempt)
3110 .setPositiveButton(R.string.allow, allowListener)
3111 .setNegativeButton(R.string.block, blockListener)
3112 .setCancelable(false)
3113 .create();
3114
3115 // Show the confirmation dialog.
3116 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003117 return true;
3118 }
3119
3120 @Override
3121 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003122 final TabControl.Tab current = mTabControl.getCurrentTab();
3123 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003124 if (parent != null) {
3125 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003126 switchToTab(mTabControl.getTabIndex(parent));
3127 // Now we need to close the window
3128 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003129 }
3130 }
3131
3132 @Override
3133 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003134 mTitleBar.setProgress(newProgress);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003135 if (mFakeTitleBar != null) {
3136 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003137 }
3138
3139 if (newProgress == 100) {
Ben Murdochaac7aa62009-09-17 16:57:40 +01003140 // onProgressChanged() may continue to be called after the main
3141 // frame has finished loading, as any remaining sub frames
3142 // continue to load. We'll only get called once though with
3143 // newProgress as 100 when everything is loaded.
3144 // (onPageFinished is called once when the main frame completes
3145 // loading regardless of the state of any sub frames so calls
3146 // to onProgressChanges may continue after onPageFinished has
3147 // executed)
3148
3149 // sync cookies and cache promptly here.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003150 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003151 if (mInLoad) {
3152 mInLoad = false;
3153 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003154 // If the options menu is open, leave the title bar
3155 if (!mOptionsMenuOpen || !mIconView) {
3156 hideFakeTitleBar();
3157 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003158 }
Ben Murdochaac7aa62009-09-17 16:57:40 +01003159 if (mNeedExtraScreenShot) {
3160 // if there was an error loading this page, capture a new
3161 // screenshot to ensure that we get the correct thumbnail
3162 // as onPageFinished may have been called before the error
3163 // page was displayed.
3164 updateScreenshot(view);
3165 mNeedExtraScreenShot = false;
3166 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003167 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003168 // onPageFinished may have already been called but a subframe
3169 // is still loading and updating the progress. Reset mInLoad
3170 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003171 mInLoad = true;
3172 updateInLoadMenuItems();
Leon Scroggins184f5e32009-09-21 10:38:24 -04003173 if (!mOptionsMenuOpen || mIconView) {
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003174 // This page has begun to load, so show the title bar
3175 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003176 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003177 }
3178 }
3179
3180 @Override
3181 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003182 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003183
3184 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003185 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003186
3187 if (url == null ||
3188 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3189 return;
3190 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003191 // See if we can find the current url in our history database and
3192 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003193 if (url.startsWith("http://www.")) {
3194 url = url.substring(11);
3195 } else if (url.startsWith("http://")) {
3196 url = url.substring(4);
3197 }
3198 try {
3199 url = "%" + url;
3200 String [] selArgs = new String[] { url };
3201
3202 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3203 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3204 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3205 Browser.HISTORY_PROJECTION, where, selArgs, null);
3206 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003207 // Current implementation of database only has one entry per
3208 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003209 ContentValues map = new ContentValues();
3210 map.put(Browser.BookmarkColumns.TITLE, title);
3211 mResolver.update(Browser.BOOKMARKS_URI, map,
3212 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003213 }
3214 c.close();
3215 } catch (IllegalStateException e) {
3216 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3217 } catch (SQLiteException ex) {
3218 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3219 }
3220 }
3221
3222 @Override
3223 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003224 updateIcon(view, icon);
3225 }
3226
3227 @Override
Patrick Scott59ce8302009-09-18 16:29:38 -04003228 public void onReceivedTouchIconUrl(WebView view, String url,
3229 boolean precomposed) {
Patrick Scott3918d442009-08-04 13:22:29 -04003230 final ContentResolver cr = getContentResolver();
3231 final Cursor c =
3232 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003233 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003234 if (c != null) {
3235 if (c.getCount() > 0) {
Patrick Scott59ce8302009-09-18 16:29:38 -04003236 // Let precomposed icons take precedence over non-composed
3237 // icons.
3238 if (precomposed && mTouchIconLoader != null) {
3239 mTouchIconLoader.cancel(false);
3240 mTouchIconLoader = null;
3241 }
3242 // Have only one async task at a time.
3243 if (mTouchIconLoader == null) {
3244 mTouchIconLoader = new DownloadTouchIcon(
3245 BrowserActivity.this, cr, c, view);
3246 mTouchIconLoader.execute(url);
3247 }
Patrick Scott3918d442009-08-04 13:22:29 -04003248 } else {
3249 c.close();
3250 }
3251 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003252 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003253
Andrei Popescuadc008d2009-06-26 14:11:30 +01003254 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003255 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003256 if (mCustomView != null)
3257 return;
3258
3259 // Add the custom view to its container.
3260 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3261 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003262 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003263 // Save the menu state and set it to empty while the custom
3264 // view is showing.
3265 mOldMenuState = mMenuState;
3266 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003267 // Hide the content view.
3268 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003269 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003270 mCustomViewContainer.setVisibility(View.VISIBLE);
3271 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003272 }
3273
3274 @Override
3275 public void onHideCustomView() {
3276 if (mCustomView == null)
3277 return;
3278
Andrei Popescuc9b55562009-07-07 10:51:15 +01003279 // Hide the custom view.
3280 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003281 // Remove the custom view from its container.
3282 mCustomViewContainer.removeView(mCustomView);
3283 mCustomView = null;
3284 // Reset the old menu state.
3285 mMenuState = mOldMenuState;
3286 mOldMenuState = EMPTY_MENU;
3287 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003288 mCustomViewCallback.onCustomViewHidden();
3289 // Show the content view.
3290 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003291 }
3292
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003293 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003294 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003295 * @param url the URL that exceeded the quota
3296 * @param databaseIdentifier the identifier of the database on
3297 * which the transaction that caused the quota overflow was run
3298 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003299 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003300 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003301 * @param quotaUpdater The callback to run when a decision to allow or
3302 * deny quota has been made. Don't forget to call this!
3303 */
3304 @Override
3305 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003306 String databaseIdentifier, long currentQuota, long estimatedSize,
3307 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003308 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003309 url, databaseIdentifier, currentQuota, estimatedSize,
3310 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003311 }
3312
3313 /**
3314 * The Application Cache has exceeded its max size.
3315 * @param spaceNeeded is the amount of disk space that would be needed
3316 * in order for the last appcache operation to succeed.
3317 * @param totalUsedQuota is the sum of all origins' quota.
3318 * @param quotaUpdater A callback to inform the WebCore thread that a new
3319 * app cache size is available. This callback must always be executed at
3320 * some point to ensure that the sleeping WebCore thread is woken up.
3321 */
3322 @Override
3323 public void onReachedMaxAppCacheSize(long spaceNeeded,
3324 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3325 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3326 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003327 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003328
Steve Block2bc69912009-07-30 14:45:13 +01003329 /**
3330 * Instructs the browser to show a prompt to ask the user to set the
3331 * Geolocation permission state for the specified origin.
3332 * @param origin The origin for which Geolocation permissions are
3333 * requested.
3334 * @param callback The callback to call once the user has set the
3335 * Geolocation permission state.
3336 */
3337 @Override
3338 public void onGeolocationPermissionsShowPrompt(String origin,
3339 GeolocationPermissions.Callback callback) {
3340 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3341 origin, callback);
3342 }
3343
3344 /**
3345 * Instructs the browser to hide the Geolocation permissions prompt.
3346 */
3347 @Override
3348 public void onGeolocationPermissionsHidePrompt() {
3349 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3350 }
3351
Ben Murdoch7db26342009-06-03 18:21:19 +01003352 /* Adds a JavaScript error message to the system log.
3353 * @param message The error message to report.
3354 * @param lineNumber The line number of the error.
3355 * @param sourceID The name of the source file that caused the error.
3356 */
3357 @Override
3358 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003359 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3360 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3361 if (mShouldShowErrorConsole &&
3362 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3363 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3364 }
3365 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003366 }
Andrei Popescu540035d2009-09-18 18:59:20 +01003367
3368 /**
3369 * Ask the browser for an icon to represent a <video> element.
3370 * This icon will be used if the Web page did not specify a poster attribute.
3371 *
3372 * @return Bitmap The icon or null if no such icon is available.
3373 * @hide pending API Council approval
3374 */
3375 @Override
3376 public Bitmap getDefaultVideoPoster() {
3377 if (mDefaultVideoPoster == null) {
3378 mDefaultVideoPoster = BitmapFactory.decodeResource(
3379 getResources(), R.drawable.default_video_poster);
3380 }
3381 return mDefaultVideoPoster;
3382 }
3383
3384 /**
3385 * Ask the host application for a custom progress view to show while
3386 * a <video> is loading.
3387 *
3388 * @return View The progress view.
3389 * @hide pending API Council approval
3390 */
3391 @Override
3392 public View getVideoLoadingProgressView() {
3393 if (mVideoProgressView == null) {
3394 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
3395 mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
3396 }
3397 return mVideoProgressView;
3398 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003399 };
3400
3401 /**
3402 * Notify the host application a download should be done, or that
3403 * the data should be streamed if a streaming viewer is available.
3404 * @param url The full url to the content that should be downloaded
3405 * @param contentDisposition Content-disposition http header, if
3406 * present.
3407 * @param mimetype The mimetype of the content reported by the server
3408 * @param contentLength The file size reported by the server
3409 */
3410 public void onDownloadStart(String url, String userAgent,
3411 String contentDisposition, String mimetype, long contentLength) {
3412 // if we're dealing wih A/V content that's not explicitly marked
3413 // for download, check if it's streamable.
3414 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003415 || !contentDisposition.regionMatches(
3416 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003417 // query the package manager to see if there's a registered handler
3418 // that matches.
3419 Intent intent = new Intent(Intent.ACTION_VIEW);
3420 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003421 ResolveInfo info = getPackageManager().resolveActivity(intent,
3422 PackageManager.MATCH_DEFAULT_ONLY);
3423 if (info != null) {
3424 ComponentName myName = getComponentName();
3425 // If we resolved to ourselves, we don't want to attempt to
3426 // load the url only to try and download it again.
3427 if (!myName.getPackageName().equals(
3428 info.activityInfo.packageName)
3429 || !myName.getClassName().equals(
3430 info.activityInfo.name)) {
3431 // someone (other than us) knows how to handle this mime
3432 // type with this scheme, don't download.
3433 try {
3434 startActivity(intent);
3435 return;
3436 } catch (ActivityNotFoundException ex) {
3437 if (LOGD_ENABLED) {
3438 Log.d(LOGTAG, "activity not found for " + mimetype
3439 + " over " + Uri.parse(url).getScheme(),
3440 ex);
3441 }
3442 // Best behavior is to fall back to a download in this
3443 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003444 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003445 }
3446 }
3447 }
3448 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3449 }
3450
3451 /**
3452 * Notify the host application a download should be done, even if there
3453 * is a streaming viewer available for thise type.
3454 * @param url The full url to the content that should be downloaded
3455 * @param contentDisposition Content-disposition http header, if
3456 * present.
3457 * @param mimetype The mimetype of the content reported by the server
3458 * @param contentLength The file size reported by the server
3459 */
3460 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3461 String contentDisposition, String mimetype, long contentLength) {
3462
3463 String filename = URLUtil.guessFileName(url,
3464 contentDisposition, mimetype);
3465
3466 // Check to see if we have an SDCard
3467 String status = Environment.getExternalStorageState();
3468 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3469 int title;
3470 String msg;
3471
3472 // Check to see if the SDCard is busy, same as the music app
3473 if (status.equals(Environment.MEDIA_SHARED)) {
3474 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3475 title = R.string.download_sdcard_busy_dlg_title;
3476 } else {
3477 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3478 title = R.string.download_no_sdcard_dlg_title;
3479 }
3480
3481 new AlertDialog.Builder(this)
3482 .setTitle(title)
3483 .setIcon(android.R.drawable.ic_dialog_alert)
3484 .setMessage(msg)
3485 .setPositiveButton(R.string.ok, null)
3486 .show();
3487 return;
3488 }
3489
3490 // java.net.URI is a lot stricter than KURL so we have to undo
3491 // KURL's percent-encoding and redo the encoding using java.net.URI.
3492 URI uri = null;
3493 try {
3494 // Undo the percent-encoding that KURL may have done.
3495 String newUrl = new String(URLUtil.decode(url.getBytes()));
3496 // Parse the url into pieces
3497 WebAddress w = new WebAddress(newUrl);
3498 String frag = null;
3499 String query = null;
3500 String path = w.mPath;
3501 // Break the path into path, query, and fragment
3502 if (path.length() > 0) {
3503 // Strip the fragment
3504 int idx = path.lastIndexOf('#');
3505 if (idx != -1) {
3506 frag = path.substring(idx + 1);
3507 path = path.substring(0, idx);
3508 }
3509 idx = path.lastIndexOf('?');
3510 if (idx != -1) {
3511 query = path.substring(idx + 1);
3512 path = path.substring(0, idx);
3513 }
3514 }
3515 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3516 query, frag);
3517 } catch (Exception e) {
3518 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3519 return;
3520 }
3521
3522 // XXX: Have to use the old url since the cookies were stored using the
3523 // old percent-encoded url.
3524 String cookies = CookieManager.getInstance().getCookie(url);
3525
3526 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003527 values.put(Downloads.COLUMN_URI, uri.toString());
3528 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3529 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3530 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003531 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003532 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003533 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003534 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3535 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3536 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3537 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003538 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003539 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003540 }
3541 if (mimetype == null) {
3542 // We must have long pressed on a link or image to download it. We
3543 // are not sure of the mimetype in this case, so do a head request
3544 new FetchUrlMimeType(this).execute(values);
3545 } else {
3546 final Uri contentUri =
3547 getContentResolver().insert(Downloads.CONTENT_URI, values);
3548 viewDownloads(contentUri);
3549 }
3550
3551 }
3552
3553 /**
3554 * Resets the lock icon. This method is called when we start a new load and
3555 * know the url to be loaded.
3556 */
3557 private void resetLockIcon(String url) {
3558 // Save the lock-icon state (we revert to it if the load gets cancelled)
3559 saveLockIcon();
3560
3561 mLockIconType = LOCK_ICON_UNSECURE;
3562 if (URLUtil.isHttpsUrl(url)) {
3563 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003564 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003565 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3566 " reset lock icon to " + mLockIconType);
3567 }
3568 }
3569
3570 updateLockIconImage(LOCK_ICON_UNSECURE);
3571 }
3572
Grace Klobaeb6eef42009-09-15 17:56:32 -07003573 /* package */ void setLockIconType(int type) {
3574 mLockIconType = type;
3575 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003576
Grace Klobaeb6eef42009-09-15 17:56:32 -07003577 /* package */ int getLockIconType() {
3578 return mLockIconType;
3579 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003580
Grace Klobaeb6eef42009-09-15 17:56:32 -07003581 /* package */ void setPrevLockType(int type) {
3582 mPrevLockType = type;
3583 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003584
Grace Klobaeb6eef42009-09-15 17:56:32 -07003585 /* package */ int getPrevLockType() {
3586 return mPrevLockType;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003587 }
3588
3589 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003590 * Update the lock icon to correspond to our latest state.
3591 */
3592 /* package */ void updateLockIconToLatest() {
3593 updateLockIconImage(mLockIconType);
3594 }
3595
3596 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003597 * Updates the lock-icon image in the title-bar.
3598 */
3599 private void updateLockIconImage(int lockIconType) {
3600 Drawable d = null;
3601 if (lockIconType == LOCK_ICON_SECURE) {
3602 d = mSecLockIcon;
3603 } else if (lockIconType == LOCK_ICON_MIXED) {
3604 d = mMixLockIcon;
3605 }
Leon Scroggins68579392009-09-15 15:31:54 -04003606 mTitleBar.setLock(d);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003607 if (mFakeTitleBar != null) {
3608 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003609 }
3610 }
3611
3612 /**
3613 * Displays a page-info dialog.
3614 * @param tab The tab to show info about
3615 * @param fromShowSSLCertificateOnError The flag that indicates whether
3616 * this dialog was opened from the SSL-certificate-on-error dialog or
3617 * not. This is important, since we need to know whether to return to
3618 * the parent dialog or simply dismiss.
3619 */
3620 private void showPageInfo(final TabControl.Tab tab,
3621 final boolean fromShowSSLCertificateOnError) {
3622 final LayoutInflater factory = LayoutInflater
3623 .from(this);
3624
3625 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3626
3627 final WebView view = tab.getWebView();
3628
3629 String url = null;
3630 String title = null;
3631
3632 if (view == null) {
3633 url = tab.getUrl();
3634 title = tab.getTitle();
3635 } else if (view == mTabControl.getCurrentWebView()) {
3636 // Use the cached title and url if this is the current WebView
3637 url = mUrl;
3638 title = mTitle;
3639 } else {
3640 url = view.getUrl();
3641 title = view.getTitle();
3642 }
3643
3644 if (url == null) {
3645 url = "";
3646 }
3647 if (title == null) {
3648 title = "";
3649 }
3650
3651 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3652 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3653
3654 mPageInfoView = tab;
3655 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3656
3657 AlertDialog.Builder alertDialogBuilder =
3658 new AlertDialog.Builder(this)
3659 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3660 .setView(pageInfoView)
3661 .setPositiveButton(
3662 R.string.ok,
3663 new DialogInterface.OnClickListener() {
3664 public void onClick(DialogInterface dialog,
3665 int whichButton) {
3666 mPageInfoDialog = null;
3667 mPageInfoView = null;
3668 mPageInfoFromShowSSLCertificateOnError = null;
3669
3670 // if we came here from the SSL error dialog
3671 if (fromShowSSLCertificateOnError) {
3672 // go back to the SSL error dialog
3673 showSSLCertificateOnError(
3674 mSSLCertificateOnErrorView,
3675 mSSLCertificateOnErrorHandler,
3676 mSSLCertificateOnErrorError);
3677 }
3678 }
3679 })
3680 .setOnCancelListener(
3681 new DialogInterface.OnCancelListener() {
3682 public void onCancel(DialogInterface dialog) {
3683 mPageInfoDialog = null;
3684 mPageInfoView = null;
3685 mPageInfoFromShowSSLCertificateOnError = null;
3686
3687 // if we came here from the SSL error dialog
3688 if (fromShowSSLCertificateOnError) {
3689 // go back to the SSL error dialog
3690 showSSLCertificateOnError(
3691 mSSLCertificateOnErrorView,
3692 mSSLCertificateOnErrorHandler,
3693 mSSLCertificateOnErrorError);
3694 }
3695 }
3696 });
3697
3698 // if we have a main top-level page SSL certificate set or a certificate
3699 // error
3700 if (fromShowSSLCertificateOnError ||
3701 (view != null && view.getCertificate() != null)) {
3702 // add a 'View Certificate' button
3703 alertDialogBuilder.setNeutralButton(
3704 R.string.view_certificate,
3705 new DialogInterface.OnClickListener() {
3706 public void onClick(DialogInterface dialog,
3707 int whichButton) {
3708 mPageInfoDialog = null;
3709 mPageInfoView = null;
3710 mPageInfoFromShowSSLCertificateOnError = null;
3711
3712 // if we came here from the SSL error dialog
3713 if (fromShowSSLCertificateOnError) {
3714 // go back to the SSL error dialog
3715 showSSLCertificateOnError(
3716 mSSLCertificateOnErrorView,
3717 mSSLCertificateOnErrorHandler,
3718 mSSLCertificateOnErrorError);
3719 } else {
3720 // otherwise, display the top-most certificate from
3721 // the chain
3722 if (view.getCertificate() != null) {
3723 showSSLCertificate(tab);
3724 }
3725 }
3726 }
3727 });
3728 }
3729
3730 mPageInfoDialog = alertDialogBuilder.show();
3731 }
3732
3733 /**
3734 * Displays the main top-level page SSL certificate dialog
3735 * (accessible from the Page-Info dialog).
3736 * @param tab The tab to show certificate for.
3737 */
3738 private void showSSLCertificate(final TabControl.Tab tab) {
3739 final View certificateView =
3740 inflateCertificateView(tab.getWebView().getCertificate());
3741 if (certificateView == null) {
3742 return;
3743 }
3744
3745 LayoutInflater factory = LayoutInflater.from(this);
3746
3747 final LinearLayout placeholder =
3748 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3749
3750 LinearLayout ll = (LinearLayout) factory.inflate(
3751 R.layout.ssl_success, placeholder);
3752 ((TextView)ll.findViewById(R.id.success))
3753 .setText(R.string.ssl_certificate_is_valid);
3754
3755 mSSLCertificateView = tab;
3756 mSSLCertificateDialog =
3757 new AlertDialog.Builder(this)
3758 .setTitle(R.string.ssl_certificate).setIcon(
3759 R.drawable.ic_dialog_browser_certificate_secure)
3760 .setView(certificateView)
3761 .setPositiveButton(R.string.ok,
3762 new DialogInterface.OnClickListener() {
3763 public void onClick(DialogInterface dialog,
3764 int whichButton) {
3765 mSSLCertificateDialog = null;
3766 mSSLCertificateView = null;
3767
3768 showPageInfo(tab, false);
3769 }
3770 })
3771 .setOnCancelListener(
3772 new DialogInterface.OnCancelListener() {
3773 public void onCancel(DialogInterface dialog) {
3774 mSSLCertificateDialog = null;
3775 mSSLCertificateView = null;
3776
3777 showPageInfo(tab, false);
3778 }
3779 })
3780 .show();
3781 }
3782
3783 /**
3784 * Displays the SSL error certificate dialog.
3785 * @param view The target web-view.
3786 * @param handler The SSL error handler responsible for cancelling the
3787 * connection that resulted in an SSL error or proceeding per user request.
3788 * @param error The SSL error object.
3789 */
3790 private void showSSLCertificateOnError(
3791 final WebView view, final SslErrorHandler handler, final SslError error) {
3792
3793 final View certificateView =
3794 inflateCertificateView(error.getCertificate());
3795 if (certificateView == null) {
3796 return;
3797 }
3798
3799 LayoutInflater factory = LayoutInflater.from(this);
3800
3801 final LinearLayout placeholder =
3802 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3803
3804 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3805 LinearLayout ll = (LinearLayout)factory
3806 .inflate(R.layout.ssl_warning, placeholder);
3807 ((TextView)ll.findViewById(R.id.warning))
3808 .setText(R.string.ssl_untrusted);
3809 }
3810
3811 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3812 LinearLayout ll = (LinearLayout)factory
3813 .inflate(R.layout.ssl_warning, placeholder);
3814 ((TextView)ll.findViewById(R.id.warning))
3815 .setText(R.string.ssl_mismatch);
3816 }
3817
3818 if (error.hasError(SslError.SSL_EXPIRED)) {
3819 LinearLayout ll = (LinearLayout)factory
3820 .inflate(R.layout.ssl_warning, placeholder);
3821 ((TextView)ll.findViewById(R.id.warning))
3822 .setText(R.string.ssl_expired);
3823 }
3824
3825 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3826 LinearLayout ll = (LinearLayout)factory
3827 .inflate(R.layout.ssl_warning, placeholder);
3828 ((TextView)ll.findViewById(R.id.warning))
3829 .setText(R.string.ssl_not_yet_valid);
3830 }
3831
3832 mSSLCertificateOnErrorHandler = handler;
3833 mSSLCertificateOnErrorView = view;
3834 mSSLCertificateOnErrorError = error;
3835 mSSLCertificateOnErrorDialog =
3836 new AlertDialog.Builder(this)
3837 .setTitle(R.string.ssl_certificate).setIcon(
3838 R.drawable.ic_dialog_browser_certificate_partially_secure)
3839 .setView(certificateView)
3840 .setPositiveButton(R.string.ok,
3841 new DialogInterface.OnClickListener() {
3842 public void onClick(DialogInterface dialog,
3843 int whichButton) {
3844 mSSLCertificateOnErrorDialog = null;
3845 mSSLCertificateOnErrorView = null;
3846 mSSLCertificateOnErrorHandler = null;
3847 mSSLCertificateOnErrorError = null;
3848
3849 mWebViewClient.onReceivedSslError(
3850 view, handler, error);
3851 }
3852 })
3853 .setNeutralButton(R.string.page_info_view,
3854 new DialogInterface.OnClickListener() {
3855 public void onClick(DialogInterface dialog,
3856 int whichButton) {
3857 mSSLCertificateOnErrorDialog = null;
3858
3859 // do not clear the dialog state: we will
3860 // need to show the dialog again once the
3861 // user is done exploring the page-info details
3862
3863 showPageInfo(mTabControl.getTabFromView(view),
3864 true);
3865 }
3866 })
3867 .setOnCancelListener(
3868 new DialogInterface.OnCancelListener() {
3869 public void onCancel(DialogInterface dialog) {
3870 mSSLCertificateOnErrorDialog = null;
3871 mSSLCertificateOnErrorView = null;
3872 mSSLCertificateOnErrorHandler = null;
3873 mSSLCertificateOnErrorError = null;
3874
3875 mWebViewClient.onReceivedSslError(
3876 view, handler, error);
3877 }
3878 })
3879 .show();
3880 }
3881
3882 /**
3883 * Inflates the SSL certificate view (helper method).
3884 * @param certificate The SSL certificate.
3885 * @return The resultant certificate view with issued-to, issued-by,
3886 * issued-on, expires-on, and possibly other fields set.
3887 * If the input certificate is null, returns null.
3888 */
3889 private View inflateCertificateView(SslCertificate certificate) {
3890 if (certificate == null) {
3891 return null;
3892 }
3893
3894 LayoutInflater factory = LayoutInflater.from(this);
3895
3896 View certificateView = factory.inflate(
3897 R.layout.ssl_certificate, null);
3898
3899 // issued to:
3900 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3901 if (issuedTo != null) {
3902 ((TextView) certificateView.findViewById(R.id.to_common))
3903 .setText(issuedTo.getCName());
3904 ((TextView) certificateView.findViewById(R.id.to_org))
3905 .setText(issuedTo.getOName());
3906 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3907 .setText(issuedTo.getUName());
3908 }
3909
3910 // issued by:
3911 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3912 if (issuedBy != null) {
3913 ((TextView) certificateView.findViewById(R.id.by_common))
3914 .setText(issuedBy.getCName());
3915 ((TextView) certificateView.findViewById(R.id.by_org))
3916 .setText(issuedBy.getOName());
3917 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3918 .setText(issuedBy.getUName());
3919 }
3920
3921 // issued on:
3922 String issuedOn = reformatCertificateDate(
3923 certificate.getValidNotBefore());
3924 ((TextView) certificateView.findViewById(R.id.issued_on))
3925 .setText(issuedOn);
3926
3927 // expires on:
3928 String expiresOn = reformatCertificateDate(
3929 certificate.getValidNotAfter());
3930 ((TextView) certificateView.findViewById(R.id.expires_on))
3931 .setText(expiresOn);
3932
3933 return certificateView;
3934 }
3935
3936 /**
3937 * Re-formats the certificate date (Date.toString()) string to
3938 * a properly localized date string.
3939 * @return Properly localized version of the certificate date string and
3940 * the original certificate date string if fails to localize.
3941 * If the original string is null, returns an empty string "".
3942 */
3943 private String reformatCertificateDate(String certificateDate) {
3944 String reformattedDate = null;
3945
3946 if (certificateDate != null) {
3947 Date date = null;
3948 try {
3949 date = java.text.DateFormat.getInstance().parse(certificateDate);
3950 } catch (ParseException e) {
3951 date = null;
3952 }
3953
3954 if (date != null) {
3955 reformattedDate =
3956 DateFormat.getDateFormat(this).format(date);
3957 }
3958 }
3959
3960 return reformattedDate != null ? reformattedDate :
3961 (certificateDate != null ? certificateDate : "");
3962 }
3963
3964 /**
3965 * Displays an http-authentication dialog.
3966 */
3967 private void showHttpAuthentication(final HttpAuthHandler handler,
3968 final String host, final String realm, final String title,
3969 final String name, final String password, int focusId) {
3970 LayoutInflater factory = LayoutInflater.from(this);
3971 final View v = factory
3972 .inflate(R.layout.http_authentication, null);
3973 if (name != null) {
3974 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3975 }
3976 if (password != null) {
3977 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3978 }
3979
3980 String titleText = title;
3981 if (titleText == null) {
3982 titleText = getText(R.string.sign_in_to).toString().replace(
3983 "%s1", host).replace("%s2", realm);
3984 }
3985
3986 mHttpAuthHandler = handler;
3987 AlertDialog dialog = new AlertDialog.Builder(this)
3988 .setTitle(titleText)
3989 .setIcon(android.R.drawable.ic_dialog_alert)
3990 .setView(v)
3991 .setPositiveButton(R.string.action,
3992 new DialogInterface.OnClickListener() {
3993 public void onClick(DialogInterface dialog,
3994 int whichButton) {
3995 String nm = ((EditText) v
3996 .findViewById(R.id.username_edit))
3997 .getText().toString();
3998 String pw = ((EditText) v
3999 .findViewById(R.id.password_edit))
4000 .getText().toString();
4001 BrowserActivity.this.setHttpAuthUsernamePassword
4002 (host, realm, nm, pw);
4003 handler.proceed(nm, pw);
4004 mHttpAuthenticationDialog = null;
4005 mHttpAuthHandler = null;
4006 }})
4007 .setNegativeButton(R.string.cancel,
4008 new DialogInterface.OnClickListener() {
4009 public void onClick(DialogInterface dialog,
4010 int whichButton) {
4011 handler.cancel();
4012 BrowserActivity.this.resetTitleAndRevertLockIcon();
4013 mHttpAuthenticationDialog = null;
4014 mHttpAuthHandler = null;
4015 }})
4016 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4017 public void onCancel(DialogInterface dialog) {
4018 handler.cancel();
4019 BrowserActivity.this.resetTitleAndRevertLockIcon();
4020 mHttpAuthenticationDialog = null;
4021 mHttpAuthHandler = null;
4022 }})
4023 .create();
4024 // Make the IME appear when the dialog is displayed if applicable.
4025 dialog.getWindow().setSoftInputMode(
4026 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4027 dialog.show();
4028 if (focusId != 0) {
4029 dialog.findViewById(focusId).requestFocus();
4030 } else {
4031 v.findViewById(R.id.username_edit).requestFocus();
4032 }
4033 mHttpAuthenticationDialog = dialog;
4034 }
4035
4036 public int getProgress() {
4037 WebView w = mTabControl.getCurrentWebView();
4038 if (w != null) {
4039 return w.getProgress();
4040 } else {
4041 return 100;
4042 }
4043 }
4044
4045 /**
4046 * Set HTTP authentication password.
4047 *
4048 * @param host The host for the password
4049 * @param realm The realm for the password
4050 * @param username The username for the password. If it is null, it means
4051 * password can't be saved.
4052 * @param password The password
4053 */
4054 public void setHttpAuthUsernamePassword(String host, String realm,
4055 String username,
4056 String password) {
4057 WebView w = mTabControl.getCurrentWebView();
4058 if (w != null) {
4059 w.setHttpAuthUsernamePassword(host, realm, username, password);
4060 }
4061 }
4062
4063 /**
4064 * connectivity manager says net has come or gone... inform the user
4065 * @param up true if net has come up, false if net has gone down
4066 */
4067 public void onNetworkToggle(boolean up) {
4068 if (up == mIsNetworkUp) {
4069 return;
4070 } else if (up) {
4071 mIsNetworkUp = true;
4072 if (mAlertDialog != null) {
4073 mAlertDialog.cancel();
4074 mAlertDialog = null;
4075 }
4076 } else {
4077 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004078 if (mInLoad) {
4079 createAndShowNetworkDialog();
4080 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004081 }
4082 WebView w = mTabControl.getCurrentWebView();
4083 if (w != null) {
4084 w.setNetworkAvailable(up);
4085 }
4086 }
4087
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004088 // This method shows the network dialog alerting the user that the net is
4089 // down. It will only show the dialog if mAlertDialog is null.
4090 private void createAndShowNetworkDialog() {
4091 if (mAlertDialog == null) {
4092 mAlertDialog = new AlertDialog.Builder(this)
4093 .setTitle(R.string.loadSuspendedTitle)
4094 .setMessage(R.string.loadSuspended)
4095 .setPositiveButton(R.string.ok, null)
4096 .show();
4097 }
4098 }
4099
The Android Open Source Project0c908882009-03-03 19:32:16 -08004100 @Override
4101 protected void onActivityResult(int requestCode, int resultCode,
4102 Intent intent) {
4103 switch (requestCode) {
4104 case COMBO_PAGE:
4105 if (resultCode == RESULT_OK && intent != null) {
4106 String data = intent.getAction();
4107 Bundle extras = intent.getExtras();
4108 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04004109 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004110 } else {
4111 final TabControl.Tab currentTab =
4112 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04004113 dismissSubWindow(currentTab);
4114 if (data != null && data.length() != 0) {
4115 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004116 }
4117 }
4118 }
4119 break;
4120 default:
4121 break;
4122 }
Leon Scroggins30444232009-09-04 18:36:20 -04004123 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004124 }
4125
4126 /*
4127 * This method is called as a result of the user selecting the options
4128 * menu to see the download window, or when a download changes state. It
4129 * shows the download window ontop of the current window.
4130 */
4131 /* package */ void viewDownloads(Uri downloadRecord) {
4132 Intent intent = new Intent(this,
4133 BrowserDownloadPage.class);
4134 intent.setData(downloadRecord);
4135 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4136
4137 }
4138
Leon Scroggins160a7e72009-08-14 18:28:01 -04004139 /**
4140 * Open the Go page.
4141 * @param startWithHistory If true, open starting on the history tab.
4142 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004143 */
Leon Scroggins30444232009-09-04 18:36:20 -04004144 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004145 WebView current = mTabControl.getCurrentWebView();
4146 if (current == null) {
4147 return;
4148 }
4149 Intent intent = new Intent(this,
4150 CombinedBookmarkHistoryActivity.class);
4151 String title = current.getTitle();
4152 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004153 Bitmap thumbnail = createScreenshot(current);
4154
The Android Open Source Project0c908882009-03-03 19:32:16 -08004155 // Just in case the user opens bookmarks before a page finishes loading
4156 // so the current history item, and therefore the page, is null.
4157 if (null == url) {
4158 url = mLastEnteredUrl;
4159 // This can happen.
4160 if (null == url) {
4161 url = mSettings.getHomePage();
4162 }
4163 }
4164 // In case the web page has not yet received its associated title.
4165 if (title == null) {
4166 title = url;
4167 }
4168 intent.putExtra("title", title);
4169 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004170 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04004171 // Disable opening in a new window if we have maxed out the windows
4172 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4173 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004174 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004175 if (startWithHistory) {
4176 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4177 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4178 }
4179 startActivityForResult(intent, COMBO_PAGE);
4180 }
4181
4182 // Called when loading from context menu or LOAD_URL message
4183 private void loadURL(WebView view, String url) {
4184 // In case the user enters nothing.
4185 if (url != null && url.length() != 0 && view != null) {
4186 url = smartUrlFilter(url);
4187 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4188 view.loadUrl(url);
4189 }
4190 }
4191 }
4192
The Android Open Source Project0c908882009-03-03 19:32:16 -08004193 private String smartUrlFilter(Uri inUri) {
4194 if (inUri != null) {
4195 return smartUrlFilter(inUri.toString());
4196 }
4197 return null;
4198 }
4199
4200
4201 // get window count
4202
4203 int getWindowCount(){
4204 if(mTabControl != null){
4205 return mTabControl.getTabCount();
4206 }
4207 return 0;
4208 }
4209
Feng Qianb34f87a2009-03-24 21:27:26 -07004210 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004211 "(?i)" + // switch on case insensitive matching
4212 "(" + // begin group for schema
4213 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004214 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004215 ")" +
4216 "(.*)" );
4217
4218 /**
4219 * Attempts to determine whether user input is a URL or search
4220 * terms. Anything with a space is passed to search.
4221 *
4222 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4223 * "Http://" converts to "http://"
4224 *
4225 * @return Original or modified URL
4226 *
4227 */
4228 String smartUrlFilter(String url) {
4229
4230 String inUrl = url.trim();
4231 boolean hasSpace = inUrl.indexOf(' ') != -1;
4232
4233 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4234 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004235 // force scheme to lowercase
4236 String scheme = matcher.group(1);
4237 String lcScheme = scheme.toLowerCase();
4238 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004239 inUrl = lcScheme + matcher.group(2);
4240 }
4241 if (hasSpace) {
4242 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004243 }
4244 return inUrl;
4245 }
4246 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004247 // FIXME: Is this the correct place to add to searches?
4248 // what if someone else calls this function?
4249 int shortcut = parseUrlShortcut(inUrl);
4250 if (shortcut != SHORTCUT_INVALID) {
4251 Browser.addSearchUrl(mResolver, inUrl);
4252 String query = inUrl.substring(2);
4253 switch (shortcut) {
4254 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004255 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004256 case SHORTCUT_WIKIPEDIA_SEARCH:
4257 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4258 case SHORTCUT_DICTIONARY_SEARCH:
4259 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4260 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004261 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004262 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004263 }
4264 }
4265 } else {
4266 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4267 return URLUtil.guessUrl(inUrl);
4268 }
4269 }
4270
4271 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004272 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004273 }
4274
Ben Murdochbff2d602009-07-01 20:19:05 +01004275 /* package */ void setShouldShowErrorConsole(boolean flag) {
4276 if (flag == mShouldShowErrorConsole) {
4277 // Nothing to do.
4278 return;
4279 }
4280
4281 mShouldShowErrorConsole = flag;
4282
4283 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4284
4285 if (flag) {
4286 // Setting the show state of the console will cause it's the layout to be inflated.
4287 if (errorConsole.numberOfErrors() > 0) {
4288 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4289 } else {
4290 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4291 }
4292
4293 // Now we can add it to the main view.
4294 mErrorConsoleContainer.addView(errorConsole,
4295 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4296 ViewGroup.LayoutParams.WRAP_CONTENT));
4297 } else {
4298 mErrorConsoleContainer.removeView(errorConsole);
4299 }
4300
4301 }
4302
Grace Klobaeb6eef42009-09-15 17:56:32 -07004303 final static int LOCK_ICON_UNSECURE = 0;
4304 final static int LOCK_ICON_SECURE = 1;
4305 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004306
4307 private int mLockIconType = LOCK_ICON_UNSECURE;
4308 private int mPrevLockType = LOCK_ICON_UNSECURE;
4309
4310 private BrowserSettings mSettings;
4311 private TabControl mTabControl;
4312 private ContentResolver mResolver;
4313 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004314 private View mCustomView;
4315 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004316 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004317
4318 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4319 // view, we should rewrite this.
4320 private int mCurrentMenuState = 0;
4321 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004322 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004323 private static final int EMPTY_MENU = -1;
4324 private Menu mMenu;
4325
4326 private FindDialog mFindDialog;
4327 // Used to prevent chording to result in firing two shortcuts immediately
4328 // one after another. Fixes bug 1211714.
4329 boolean mCanChord;
4330
4331 private boolean mInLoad;
4332 private boolean mIsNetworkUp;
4333
4334 private boolean mPageStarted;
4335 private boolean mActivityInPause = true;
4336
Ben Murdochaac7aa62009-09-17 16:57:40 +01004337 // If the frame fails to load, we should snap a second screenshot
4338 // to ensure that we get the right thumbnail (i.e. of the error page).
4339 private boolean mNeedExtraScreenShot = false;
4340
The Android Open Source Project0c908882009-03-03 19:32:16 -08004341 private boolean mMenuIsDown;
4342
The Android Open Source Project0c908882009-03-03 19:32:16 -08004343 private static boolean mInTrace;
4344
4345 // Performance probe
4346 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4347 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4348 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4349 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4350 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4351 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4352 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4353 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4354 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4355 };
4356
4357 private long mStart;
4358 private long mProcessStart;
4359 private long mUserStart;
4360 private long mSystemStart;
4361 private long mIdleStart;
4362 private long mIrqStart;
4363
4364 private long mUiStart;
4365
4366 private Drawable mMixLockIcon;
4367 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004368
4369 /* hold a ref so we can auto-cancel if necessary */
4370 private AlertDialog mAlertDialog;
4371
4372 // Wait for credentials before loading google.com
4373 private ProgressDialog mCredsDlg;
4374
4375 // The up-to-date URL and title (these can be different from those stored
4376 // in WebView, since it takes some time for the information in WebView to
4377 // get updated)
4378 private String mUrl;
4379 private String mTitle;
4380
4381 // As PageInfo has different style for landscape / portrait, we have
4382 // to re-open it when configuration changed
4383 private AlertDialog mPageInfoDialog;
4384 private TabControl.Tab mPageInfoView;
4385 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4386 // dialog, we should not just dismiss it, but should get back to the
4387 // SSL-certificate-on-error dialog. This flag is used to store this state
4388 private Boolean mPageInfoFromShowSSLCertificateOnError;
4389
4390 // as SSLCertificateOnError has different style for landscape / portrait,
4391 // we have to re-open it when configuration changed
4392 private AlertDialog mSSLCertificateOnErrorDialog;
4393 private WebView mSSLCertificateOnErrorView;
4394 private SslErrorHandler mSSLCertificateOnErrorHandler;
4395 private SslError mSSLCertificateOnErrorError;
4396
4397 // as SSLCertificate has different style for landscape / portrait, we
4398 // have to re-open it when configuration changed
4399 private AlertDialog mSSLCertificateDialog;
4400 private TabControl.Tab mSSLCertificateView;
4401
4402 // as HttpAuthentication has different style for landscape / portrait, we
4403 // have to re-open it when configuration changed
4404 private AlertDialog mHttpAuthenticationDialog;
4405 private HttpAuthHandler mHttpAuthHandler;
4406
4407 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4408 new FrameLayout.LayoutParams(
4409 ViewGroup.LayoutParams.FILL_PARENT,
4410 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004411 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4412 new FrameLayout.LayoutParams(
4413 ViewGroup.LayoutParams.FILL_PARENT,
4414 ViewGroup.LayoutParams.FILL_PARENT,
4415 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004416 // Google search
4417 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004418 // Wikipedia search
4419 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4420 // Dictionary search
4421 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4422 // Google Mobile Local search
4423 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4424
4425 final static String QUERY_PLACE_HOLDER = "%s";
4426
4427 // "source" parameter for Google search through search key
4428 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4429 // "source" parameter for Google search through goto menu
4430 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4431 // "source" parameter for Google search through simplily type
4432 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4433 // "source" parameter for Google search suggested by the browser
4434 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4435 // "source" parameter for Google search from unknown source
4436 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4437
4438 private final static String LOGTAG = "browser";
4439
The Android Open Source Project0c908882009-03-03 19:32:16 -08004440 private String mLastEnteredUrl;
4441
4442 private PowerManager.WakeLock mWakeLock;
4443 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4444
4445 private Toast mStopToast;
4446
Leon Scroggins68579392009-09-15 15:31:54 -04004447 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004448
Ben Murdochbff2d602009-07-01 20:19:05 +01004449 private LinearLayout mErrorConsoleContainer = null;
4450 private boolean mShouldShowErrorConsole = false;
4451
The Android Open Source Project0c908882009-03-03 19:32:16 -08004452 // As the ids are dynamically created, we can't guarantee that they will
4453 // be in sequence, so this static array maps ids to a window number.
4454 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4455 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4456 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4457 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4458
4459 // monitor platform changes
4460 private IntentFilter mNetworkStateChangedFilter;
4461 private BroadcastReceiver mNetworkStateIntentReceiver;
4462
Grace Klobab4da0ad2009-05-14 14:45:40 -07004463 private BroadcastReceiver mPackageInstallationReceiver;
4464
Patrick Scott59ce8302009-09-18 16:29:38 -04004465 // AsyncTask for downloading touch icons
4466 /* package */ DownloadTouchIcon mTouchIconLoader;
4467
The Android Open Source Project0c908882009-03-03 19:32:16 -08004468 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004469 final static int COMBO_PAGE = 1;
4470 final static int DOWNLOAD_PAGE = 2;
4471 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004472
Andrei Popescu540035d2009-09-18 18:59:20 +01004473 // the default <video> poster
4474 private Bitmap mDefaultVideoPoster;
4475 // the video progress view
4476 private View mVideoProgressView;
4477
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004478 /**
4479 * A UrlData class to abstract how the content will be set to WebView.
4480 * This base class uses loadUrl to show the content.
4481 */
4482 private static class UrlData {
4483 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004484 byte[] mPostData;
4485
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004486 UrlData(String url) {
4487 this.mUrl = url;
4488 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004489
4490 void setPostData(byte[] postData) {
4491 mPostData = postData;
4492 }
4493
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004494 boolean isEmpty() {
4495 return mUrl == null || mUrl.length() == 0;
4496 }
4497
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004498 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004499 if (mPostData != null) {
4500 webView.postUrl(mUrl, mPostData);
4501 } else {
4502 webView.loadUrl(mUrl);
4503 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004504 }
4505 };
4506
4507 /**
4508 * A subclass of UrlData class that can display inlined content using
4509 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4510 */
4511 private static class InlinedUrlData extends UrlData {
4512 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4513 super(failUrl);
4514 mInlined = inlined;
4515 mMimeType = mimeType;
4516 mEncoding = encoding;
4517 }
4518 String mMimeType;
4519 String mInlined;
4520 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004521 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004522 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004523 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004524 }
4525
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004526 @Override
4527 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004528 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4529 }
4530 }
4531
Leon Scroggins1f005d32009-08-10 17:36:42 -04004532 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004533}