blob: e5434ed603875b525bc55d0d63b1f866597bf513 [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 /**
1035 * onSaveInstanceState(Bundle map)
1036 * onSaveInstanceState is called right before onStop(). The map contains
1037 * the saved state.
1038 */
1039 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001040 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001041 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1042 }
1043 // the default implementation requires each view to have an id. As the
1044 // browser handles the state itself and it doesn't use id for the views,
1045 // don't call the default implementation. Otherwise it will trigger the
1046 // warning like this, "couldn't save which view has focus because the
1047 // focused view XXX has no id".
1048
1049 // Save all the tabs
1050 mTabControl.saveState(outState);
1051 }
1052
1053 @Override protected void onPause() {
1054 super.onPause();
1055
1056 if (mActivityInPause) {
1057 Log.e(LOGTAG, "BrowserActivity is already paused.");
1058 return;
1059 }
1060
Mike Reed7bfa63b2009-05-28 11:08:32 -04001061 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001062 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001063 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001064 mWakeLock.acquire();
1065 mHandler.sendMessageDelayed(mHandler
1066 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1067 }
1068
1069 // Clear the credentials toast if it is up
1070 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1071 mCredsDlg.dismiss();
1072 }
1073 mCredsDlg = null;
1074
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001075 // FIXME: This removes the active tabs page and resets the menu to
1076 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1077 // but then we would need to save it in onSaveInstanceState and restore
1078 // it in onCreate/onRestoreInstanceState
1079 if (mActiveTabsPage != null) {
1080 removeActiveTabPage(true);
1081 }
1082
The Android Open Source Project0c908882009-03-03 19:32:16 -08001083 cancelStopToast();
1084
1085 // unregister network state listener
1086 unregisterReceiver(mNetworkStateIntentReceiver);
1087 WebView.disablePlatformNotifications();
1088
1089 if (mSensorManager != null) {
1090 mSensorManager.unregisterListener(mSensorListener);
1091 }
1092 }
1093
1094 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001095 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001096 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1097 }
1098 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001099
1100 if (mTabControl == null) return;
1101
The Android Open Source Project0c908882009-03-03 19:32:16 -08001102 // Remove the current tab and sub window
1103 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001104 if (t != null) {
1105 dismissSubWindow(t);
1106 removeTabFromContentView(t);
1107 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001108 // Destroy all the tabs
1109 mTabControl.destroy();
1110 WebIconDatabase.getInstance().close();
1111 if (mGlsConnection != null) {
1112 unbindService(mGlsConnection);
1113 mGlsConnection = null;
1114 }
1115
1116 //
1117 // stop MASF proxy service
1118 //
1119 //Intent proxyServiceIntent = new Intent();
1120 //proxyServiceIntent.setComponent
1121 // (new ComponentName(
1122 // "com.android.masfproxyservice",
1123 // "com.android.masfproxyservice.MasfProxyService"));
1124 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001125
1126 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001127 }
1128
1129 @Override
1130 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001131 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001132 super.onConfigurationChanged(newConfig);
1133
1134 if (mPageInfoDialog != null) {
1135 mPageInfoDialog.dismiss();
1136 showPageInfo(
1137 mPageInfoView,
1138 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1139 }
1140 if (mSSLCertificateDialog != null) {
1141 mSSLCertificateDialog.dismiss();
1142 showSSLCertificate(
1143 mSSLCertificateView);
1144 }
1145 if (mSSLCertificateOnErrorDialog != null) {
1146 mSSLCertificateOnErrorDialog.dismiss();
1147 showSSLCertificateOnError(
1148 mSSLCertificateOnErrorView,
1149 mSSLCertificateOnErrorHandler,
1150 mSSLCertificateOnErrorError);
1151 }
1152 if (mHttpAuthenticationDialog != null) {
1153 String title = ((TextView) mHttpAuthenticationDialog
1154 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1155 .toString();
1156 String name = ((TextView) mHttpAuthenticationDialog
1157 .findViewById(R.id.username_edit)).getText().toString();
1158 String password = ((TextView) mHttpAuthenticationDialog
1159 .findViewById(R.id.password_edit)).getText().toString();
1160 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1161 .getId();
1162 mHttpAuthenticationDialog.dismiss();
1163 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1164 name, password, focusId);
1165 }
1166 if (mFindDialog != null && mFindDialog.isShowing()) {
1167 mFindDialog.onConfigurationChanged(newConfig);
1168 }
1169 }
1170
1171 @Override public void onLowMemory() {
1172 super.onLowMemory();
1173 mTabControl.freeMemory();
1174 }
1175
Mike Reed7bfa63b2009-05-28 11:08:32 -04001176 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001177 if ((!mActivityInPause && !mPageStarted) ||
1178 (mActivityInPause && mPageStarted)) {
1179 CookieSyncManager.getInstance().startSync();
1180 WebView w = mTabControl.getCurrentWebView();
1181 if (w != null) {
1182 w.resumeTimers();
1183 }
1184 return true;
1185 } else {
1186 return false;
1187 }
1188 }
1189
Mike Reed7bfa63b2009-05-28 11:08:32 -04001190 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001191 if (mActivityInPause && !mPageStarted) {
1192 CookieSyncManager.getInstance().stopSync();
1193 WebView w = mTabControl.getCurrentWebView();
1194 if (w != null) {
1195 w.pauseTimers();
1196 }
1197 return true;
1198 } else {
1199 return false;
1200 }
1201 }
1202
Leon Scroggins1f005d32009-08-10 17:36:42 -04001203 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001204 /*
1205 * This function is called when we are launching for the first time. We
1206 * are waiting for the login credentials before loading Google home
1207 * pages. This way the user will be logged in straight away.
1208 */
1209 private void waitForCredentials() {
1210 // Show a toast
1211 mCredsDlg = new ProgressDialog(this);
1212 mCredsDlg.setIndeterminate(true);
1213 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1214 // If the user cancels the operation, then cancel the Google
1215 // Credentials request.
1216 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1217 mCredsDlg.show();
1218
1219 // We set a timeout for the retrieval of credentials in onResume()
1220 // as that is when we have freed up some CPU time to get
1221 // the login credentials.
1222 }
1223
1224 /*
1225 * If we have received the credentials or we have timed out and we are
1226 * showing the credentials dialog, then it is time to move on.
1227 */
1228 private void resumeAfterCredentials() {
1229 if (mCredsDlg == null) {
1230 return;
1231 }
1232
1233 // Clear the toast
1234 if (mCredsDlg.isShowing()) {
1235 mCredsDlg.dismiss();
1236 }
1237 mCredsDlg = null;
1238
1239 // Clear any pending timeout
1240 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1241
1242 // Load the page
1243 WebView w = mTabControl.getCurrentWebView();
1244 if (w != null) {
1245 w.loadUrl(mSettings.getHomePage());
1246 }
1247
1248 // Update the settings, need to do this last as it can take a moment
1249 // to persist the settings. In the mean time we could be loading
1250 // content.
1251 mSettings.setLoginInitialized(this);
1252 }
1253
1254 // Open the icon database and retain all the icons for visited sites.
1255 private void retainIconsOnStartup() {
1256 final WebIconDatabase db = WebIconDatabase.getInstance();
1257 db.open(getDir("icons", 0).getPath());
1258 try {
1259 Cursor c = Browser.getAllBookmarks(mResolver);
1260 if (!c.moveToFirst()) {
1261 c.deactivate();
1262 return;
1263 }
1264 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1265 do {
1266 String url = c.getString(urlIndex);
1267 db.retainIconForPageUrl(url);
1268 } while (c.moveToNext());
1269 c.deactivate();
1270 } catch (IllegalStateException e) {
1271 Log.e(LOGTAG, "retainIconsOnStartup", e);
1272 }
1273 }
1274
1275 // Helper method for getting the top window.
1276 WebView getTopWindow() {
1277 return mTabControl.getCurrentTopWebView();
1278 }
1279
1280 @Override
1281 public boolean onCreateOptionsMenu(Menu menu) {
1282 super.onCreateOptionsMenu(menu);
1283
1284 MenuInflater inflater = getMenuInflater();
1285 inflater.inflate(R.menu.browser, menu);
1286 mMenu = menu;
1287 updateInLoadMenuItems();
1288 return true;
1289 }
1290
1291 /**
1292 * As the menu can be open when loading state changes
1293 * we must manually update the state of the stop/reload menu
1294 * item
1295 */
1296 private void updateInLoadMenuItems() {
1297 if (mMenu == null) {
1298 return;
1299 }
1300 MenuItem src = mInLoad ?
1301 mMenu.findItem(R.id.stop_menu_id):
1302 mMenu.findItem(R.id.reload_menu_id);
1303 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1304 dest.setIcon(src.getIcon());
1305 dest.setTitle(src.getTitle());
1306 }
1307
1308 @Override
1309 public boolean onContextItemSelected(MenuItem item) {
1310 // chording is not an issue with context menus, but we use the same
1311 // options selector, so set mCanChord to true so we can access them.
1312 mCanChord = true;
1313 int id = item.getItemId();
1314 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001315 if (null == webView) {
1316 return false;
1317 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001318 final HashMap hrefMap = new HashMap();
1319 hrefMap.put("webview", webView);
1320 final Message msg = mHandler.obtainMessage(
1321 FOCUS_NODE_HREF, id, 0, hrefMap);
1322 switch (id) {
1323 // -- Browser context menu
1324 case R.id.open_context_menu_id:
1325 case R.id.open_newtab_context_menu_id:
1326 case R.id.bookmark_context_menu_id:
1327 case R.id.save_link_context_menu_id:
1328 case R.id.share_link_context_menu_id:
1329 case R.id.copy_link_context_menu_id:
1330 webView.requestFocusNodeHref(msg);
1331 break;
1332
1333 default:
1334 // For other context menus
1335 return onOptionsItemSelected(item);
1336 }
1337 mCanChord = false;
1338 return true;
1339 }
1340
1341 private Bundle createGoogleSearchSourceBundle(String source) {
1342 Bundle bundle = new Bundle();
1343 bundle.putString(SearchManager.SOURCE, source);
1344 return bundle;
1345 }
1346
1347 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001348 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001349 */
1350 @Override
1351 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001352 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001353 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001354 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001355 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001356 return true;
1357 }
1358
1359 @Override
1360 public void startSearch(String initialQuery, boolean selectInitialQuery,
1361 Bundle appSearchData, boolean globalSearch) {
1362 if (appSearchData == null) {
1363 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1364 }
1365 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1366 }
1367
Leon Scroggins1f005d32009-08-10 17:36:42 -04001368 /**
1369 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1370 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001371 * @param index Index of the tab to change to, as defined by
1372 * mTabControl.getTabIndex(Tab t).
1373 * @return boolean True if we successfully switched to a different tab. If
1374 * the indexth tab is null, or if that tab is the same as
1375 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001376 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001377 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001378 TabControl.Tab tab = mTabControl.getTab(index);
1379 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1380 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001381 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001382 }
1383 if (currentTab != null) {
1384 // currentTab may be null if it was just removed. In that case,
1385 // we do not need to remove it
1386 removeTabFromContentView(currentTab);
1387 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001388 mTabControl.setCurrentTab(tab);
1389 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001390 resetTitleIconAndProgress();
1391 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001392 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001393 }
1394
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001395 /* package */ TabControl.Tab openTabToHomePage() {
1396 return openTabAndShow(mSettings.getHomePage(), false, null);
1397 }
1398
Leon Scroggins1f005d32009-08-10 17:36:42 -04001399 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001400 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001401 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001402 // This is the last tab. Open a new one, with the home
1403 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001404 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001405 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001406 return;
1407 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001408 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001409 int indexToShow = -1;
1410 if (parent != null) {
1411 indexToShow = mTabControl.getTabIndex(parent);
1412 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001413 final int currentIndex = mTabControl.getCurrentIndex();
1414 // Try to move to the tab to the right
1415 indexToShow = currentIndex + 1;
1416 if (indexToShow > mTabControl.getTabCount() - 1) {
1417 // Try to move to the tab to the left
1418 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001419 }
1420 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001421 if (switchToTab(indexToShow)) {
1422 // Close window
1423 closeTab(current);
1424 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001425 }
1426
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001427 private ActiveTabsPage mActiveTabsPage;
1428
1429 /**
1430 * Remove the active tabs page.
1431 * @param needToAttach If true, the active tabs page did not attach a tab
1432 * to the content view, so we need to do that here.
1433 */
1434 /* package */ void removeActiveTabPage(boolean needToAttach) {
1435 mContentView.removeView(mActiveTabsPage);
1436 mActiveTabsPage = null;
1437 mMenuState = R.id.MAIN_MENU;
1438 if (needToAttach) {
1439 attachTabToContentView(mTabControl.getCurrentTab());
1440 }
1441 getTopWindow().requestFocus();
1442 }
1443
The Android Open Source Project0c908882009-03-03 19:32:16 -08001444 @Override
1445 public boolean onOptionsItemSelected(MenuItem item) {
1446 if (!mCanChord) {
1447 // The user has already fired a shortcut with this hold down of the
1448 // menu key.
1449 return false;
1450 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001451 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001452 return false;
1453 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001454 if (mMenuIsDown) {
1455 // The shortcut action consumes the MENU. Even if it is still down,
1456 // it won't trigger the next shortcut action. In the case of the
1457 // shortcut action triggering a new activity, like Bookmarks, we
1458 // won't get onKeyUp for MENU. So it is important to reset it here.
1459 mMenuIsDown = false;
1460 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001461 switch (item.getItemId()) {
1462 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001463 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001464 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001465 break;
1466
Leon Scroggins64b80f32009-08-07 12:03:34 -04001467 case R.id.goto_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001468 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001469 break;
1470
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001471 case R.id.active_tabs_menu_id:
1472 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1473 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001474 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001475 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1476 mActiveTabsPage.requestFocus();
1477 mMenuState = EMPTY_MENU;
1478 break;
1479
Leon Scroggins1f005d32009-08-10 17:36:42 -04001480 case R.id.add_bookmark_menu_id:
1481 Intent i = new Intent(BrowserActivity.this,
1482 AddBookmarkPage.class);
1483 WebView w = getTopWindow();
1484 i.putExtra("url", w.getUrl());
1485 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001486 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001487 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001488 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001489 break;
1490
1491 case R.id.stop_reload_menu_id:
1492 if (mInLoad) {
1493 stopLoading();
1494 } else {
1495 getTopWindow().reload();
1496 }
1497 break;
1498
1499 case R.id.back_menu_id:
1500 getTopWindow().goBack();
1501 break;
1502
1503 case R.id.forward_menu_id:
1504 getTopWindow().goForward();
1505 break;
1506
1507 case R.id.close_menu_id:
1508 // Close the subwindow if it exists.
1509 if (mTabControl.getCurrentSubWindow() != null) {
1510 dismissSubWindow(mTabControl.getCurrentTab());
1511 break;
1512 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001513 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001514 break;
1515
1516 case R.id.homepage_menu_id:
1517 TabControl.Tab current = mTabControl.getCurrentTab();
1518 if (current != null) {
1519 dismissSubWindow(current);
1520 current.getWebView().loadUrl(mSettings.getHomePage());
1521 }
1522 break;
1523
1524 case R.id.preferences_menu_id:
1525 Intent intent = new Intent(this,
1526 BrowserPreferencesPage.class);
1527 startActivityForResult(intent, PREFERENCES_PAGE);
1528 break;
1529
1530 case R.id.find_menu_id:
1531 if (null == mFindDialog) {
1532 mFindDialog = new FindDialog(this);
1533 }
1534 mFindDialog.setWebView(getTopWindow());
1535 mFindDialog.show();
1536 mMenuState = EMPTY_MENU;
1537 break;
1538
1539 case R.id.select_text_id:
1540 getTopWindow().emulateShiftHeld();
1541 break;
1542 case R.id.page_info_menu_id:
1543 showPageInfo(mTabControl.getCurrentTab(), false);
1544 break;
1545
1546 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001547 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001548 break;
1549
1550 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001551 Browser.sendString(this, getTopWindow().getUrl(),
1552 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001553 break;
1554
1555 case R.id.dump_nav_menu_id:
1556 getTopWindow().debugDump();
1557 break;
1558
1559 case R.id.zoom_in_menu_id:
1560 getTopWindow().zoomIn();
1561 break;
1562
1563 case R.id.zoom_out_menu_id:
1564 getTopWindow().zoomOut();
1565 break;
1566
1567 case R.id.view_downloads_menu_id:
1568 viewDownloads(null);
1569 break;
1570
The Android Open Source Project0c908882009-03-03 19:32:16 -08001571 case R.id.window_one_menu_id:
1572 case R.id.window_two_menu_id:
1573 case R.id.window_three_menu_id:
1574 case R.id.window_four_menu_id:
1575 case R.id.window_five_menu_id:
1576 case R.id.window_six_menu_id:
1577 case R.id.window_seven_menu_id:
1578 case R.id.window_eight_menu_id:
1579 {
1580 int menuid = item.getItemId();
1581 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1582 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1583 TabControl.Tab desiredTab = mTabControl.getTab(id);
1584 if (desiredTab != null &&
1585 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001586 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001587 }
1588 break;
1589 }
1590 }
1591 }
1592 break;
1593
1594 default:
1595 if (!super.onOptionsItemSelected(item)) {
1596 return false;
1597 }
1598 // Otherwise fall through.
1599 }
1600 mCanChord = false;
1601 return true;
1602 }
1603
1604 public void closeFind() {
1605 mMenuState = R.id.MAIN_MENU;
1606 }
1607
1608 @Override public boolean onPrepareOptionsMenu(Menu menu)
1609 {
1610 // This happens when the user begins to hold down the menu key, so
1611 // allow them to chord to get a shortcut.
1612 mCanChord = true;
1613 // Note: setVisible will decide whether an item is visible; while
1614 // setEnabled() will decide whether an item is enabled, which also means
1615 // whether the matching shortcut key will function.
1616 super.onPrepareOptionsMenu(menu);
1617 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001618 case EMPTY_MENU:
1619 if (mCurrentMenuState != mMenuState) {
1620 menu.setGroupVisible(R.id.MAIN_MENU, false);
1621 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1622 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001623 }
1624 break;
1625 default:
1626 if (mCurrentMenuState != mMenuState) {
1627 menu.setGroupVisible(R.id.MAIN_MENU, true);
1628 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1629 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001630 }
1631 final WebView w = getTopWindow();
1632 boolean canGoBack = false;
1633 boolean canGoForward = false;
1634 boolean isHome = false;
1635 if (w != null) {
1636 canGoBack = w.canGoBack();
1637 canGoForward = w.canGoForward();
1638 isHome = mSettings.getHomePage().equals(w.getUrl());
1639 }
1640 final MenuItem back = menu.findItem(R.id.back_menu_id);
1641 back.setEnabled(canGoBack);
1642
1643 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1644 home.setEnabled(!isHome);
1645
1646 menu.findItem(R.id.forward_menu_id)
1647 .setEnabled(canGoForward);
1648
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001649 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1650 mTabControl.getTabCount() < TabControl.MAX_TABS);
1651
The Android Open Source Project0c908882009-03-03 19:32:16 -08001652 // decide whether to show the share link option
1653 PackageManager pm = getPackageManager();
1654 Intent send = new Intent(Intent.ACTION_SEND);
1655 send.setType("text/plain");
1656 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1657 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1658
The Android Open Source Project0c908882009-03-03 19:32:16 -08001659 boolean isNavDump = mSettings.isNavDump();
1660 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1661 nav.setVisible(isNavDump);
1662 nav.setEnabled(isNavDump);
1663 break;
1664 }
1665 mCurrentMenuState = mMenuState;
1666 return true;
1667 }
1668
1669 @Override
1670 public void onCreateContextMenu(ContextMenu menu, View v,
1671 ContextMenuInfo menuInfo) {
1672 WebView webview = (WebView) v;
1673 WebView.HitTestResult result = webview.getHitTestResult();
1674 if (result == null) {
1675 return;
1676 }
1677
1678 int type = result.getType();
1679 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1680 Log.w(LOGTAG,
1681 "We should not show context menu when nothing is touched");
1682 return;
1683 }
1684 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1685 // let TextView handles context menu
1686 return;
1687 }
1688
1689 // Note, http://b/issue?id=1106666 is requesting that
1690 // an inflated menu can be used again. This is not available
1691 // yet, so inflate each time (yuk!)
1692 MenuInflater inflater = getMenuInflater();
1693 inflater.inflate(R.menu.browsercontext, menu);
1694
1695 // Show the correct menu group
1696 String extra = result.getExtra();
1697 menu.setGroupVisible(R.id.PHONE_MENU,
1698 type == WebView.HitTestResult.PHONE_TYPE);
1699 menu.setGroupVisible(R.id.EMAIL_MENU,
1700 type == WebView.HitTestResult.EMAIL_TYPE);
1701 menu.setGroupVisible(R.id.GEO_MENU,
1702 type == WebView.HitTestResult.GEO_TYPE);
1703 menu.setGroupVisible(R.id.IMAGE_MENU,
1704 type == WebView.HitTestResult.IMAGE_TYPE
1705 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1706 menu.setGroupVisible(R.id.ANCHOR_MENU,
1707 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1708 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1709
1710 // Setup custom handling depending on the type
1711 switch (type) {
1712 case WebView.HitTestResult.PHONE_TYPE:
1713 menu.setHeaderTitle(Uri.decode(extra));
1714 menu.findItem(R.id.dial_context_menu_id).setIntent(
1715 new Intent(Intent.ACTION_VIEW, Uri
1716 .parse(WebView.SCHEME_TEL + extra)));
1717 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1718 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001719 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001720 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1721 addIntent);
1722 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1723 new Copy(extra));
1724 break;
1725
1726 case WebView.HitTestResult.EMAIL_TYPE:
1727 menu.setHeaderTitle(extra);
1728 menu.findItem(R.id.email_context_menu_id).setIntent(
1729 new Intent(Intent.ACTION_VIEW, Uri
1730 .parse(WebView.SCHEME_MAILTO + extra)));
1731 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1732 new Copy(extra));
1733 break;
1734
1735 case WebView.HitTestResult.GEO_TYPE:
1736 menu.setHeaderTitle(extra);
1737 menu.findItem(R.id.map_context_menu_id).setIntent(
1738 new Intent(Intent.ACTION_VIEW, Uri
1739 .parse(WebView.SCHEME_GEO
1740 + URLEncoder.encode(extra))));
1741 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1742 new Copy(extra));
1743 break;
1744
1745 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1746 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1747 TextView titleView = (TextView) LayoutInflater.from(this)
1748 .inflate(android.R.layout.browser_link_context_header,
1749 null);
1750 titleView.setText(extra);
1751 menu.setHeaderView(titleView);
1752 // decide whether to show the open link in new tab option
1753 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1754 mTabControl.getTabCount() < TabControl.MAX_TABS);
1755 PackageManager pm = getPackageManager();
1756 Intent send = new Intent(Intent.ACTION_SEND);
1757 send.setType("text/plain");
1758 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1759 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1760 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1761 break;
1762 }
1763 // otherwise fall through to handle image part
1764 case WebView.HitTestResult.IMAGE_TYPE:
1765 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1766 menu.setHeaderTitle(extra);
1767 }
1768 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1769 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1770 menu.findItem(R.id.download_context_menu_id).
1771 setOnMenuItemClickListener(new Download(extra));
1772 break;
1773
1774 default:
1775 Log.w(LOGTAG, "We should not get here.");
1776 break;
1777 }
1778 }
1779
The Android Open Source Project0c908882009-03-03 19:32:16 -08001780 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001781 // this should only be called for the current tab.
The Android Open Source Project0c908882009-03-03 19:32:16 -08001782 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001783 // Attach the container that contains the main WebView and any other UI
1784 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001785 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001786
1787 if (mShouldShowErrorConsole) {
1788 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1789 if (errorConsole.numberOfErrors() == 0) {
1790 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1791 } else {
1792 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1793 }
1794
1795 mErrorConsoleContainer.addView(errorConsole,
1796 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1797 ViewGroup.LayoutParams.WRAP_CONTENT));
1798 }
1799
Grace Klobac928c302009-09-17 11:51:21 -07001800 setLockIconType(t.getLockIconType());
1801 setPrevLockType(t.getPrevLockIconType());
1802
1803 // this is to match the code in removeTabFromContentView()
1804 if (!mPageStarted && t.getTopWindow().getProgress() < 100) {
1805 mPageStarted = true;
Grace Klobaeb6eef42009-09-15 17:56:32 -07001806 }
1807
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001808 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001809 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001810 // Request focus on the top window.
1811 t.getTopWindow().requestFocus();
1812 }
1813
1814 // Attach a sub window to the main WebView of the given tab.
1815 private void attachSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001816 t.attachSubWindow(mContentView);
1817 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001818 }
1819
1820 // Remove the given tab from the content view.
1821 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001822 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001823 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001824
1825 if (mTabControl.getCurrentErrorConsole(false) != null) {
1826 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1827 }
1828
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001829 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001830 if (view != null) {
1831 view.setEmbeddedTitleBar(null);
1832 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001833
Grace Klobac928c302009-09-17 11:51:21 -07001834 // unlike attachTabToContentView(), removeTabFromContentView() can be
1835 // called for the non-current tab. Need to add the check.
Grace Klobaeb6eef42009-09-15 17:56:32 -07001836 if (t == mTabControl.getCurrentTab()) {
1837 t.setLockIconType(getLockIconType());
1838 t.setPrevLockIconType(getPrevLockType());
Grace Klobac928c302009-09-17 11:51:21 -07001839
1840 // this is not a perfect solution. But currently there is one
1841 // WebViewClient for all the WebView. if user switches from an
1842 // in-load window to an already loaded window, mPageStarted will not
1843 // be set to false. If user leaves the Browser, pauseWebViewTimers()
1844 // won't do anything and leaves the timer running even Browser is in
1845 // the background.
1846 if (mPageStarted) {
1847 mPageStarted = false;
1848 }
Grace Klobaeb6eef42009-09-15 17:56:32 -07001849 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001850 }
1851
1852 // Remove the sub window if it exists. Also called by TabControl when the
1853 // user clicks the 'X' to dismiss a sub window.
1854 /* package */ void dismissSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001855 t.removeSubWindow(mContentView);
1856 // Tell the TabControl to dismiss the subwindow. This will destroy
1857 // the WebView.
1858 mTabControl.dismissSubWindow(t);
1859 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001860 }
1861
Leon Scroggins1f005d32009-08-10 17:36:42 -04001862 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001863 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001864 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1865 String appId) {
1866 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001867 }
1868
1869 // This method does a ton of stuff. It will attempt to create a new tab
1870 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001871 // url isn't null, it will load the given url.
1872 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001873 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001874 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1875 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1876 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001877 final TabControl.Tab tab = mTabControl.createNewTab(
1878 closeOnExit, appId, urlData.mUrl);
1879 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001880 // If the last tab was removed from the active tabs page, currentTab
1881 // will be null.
1882 if (currentTab != null) {
1883 removeTabFromContentView(currentTab);
1884 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001885 // We must set the new tab as the current tab to reflect the old
1886 // animation behavior.
1887 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001888 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001889 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001890 urlData.loadIn(webview);
1891 }
1892 return tab;
1893 } else {
1894 // Get rid of the subwindow if it exists
1895 dismissSubWindow(currentTab);
1896 if (!urlData.isEmpty()) {
1897 // Load the given url.
1898 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001899 }
1900 }
Grace Klobac9181842009-04-14 08:53:22 -07001901 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001902 }
1903
Grace Klobac9181842009-04-14 08:53:22 -07001904 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001905 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001906 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001907 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001908 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001909 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001910 }
Grace Klobac9181842009-04-14 08:53:22 -07001911 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001912 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001913 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001914 }
1915 }
1916
1917 private class Copy implements OnMenuItemClickListener {
1918 private CharSequence mText;
1919
1920 public boolean onMenuItemClick(MenuItem item) {
1921 copy(mText);
1922 return true;
1923 }
1924
1925 public Copy(CharSequence toCopy) {
1926 mText = toCopy;
1927 }
1928 }
1929
1930 private class Download implements OnMenuItemClickListener {
1931 private String mText;
1932
1933 public boolean onMenuItemClick(MenuItem item) {
1934 onDownloadStartNoStream(mText, null, null, null, -1);
1935 return true;
1936 }
1937
1938 public Download(String toDownload) {
1939 mText = toDownload;
1940 }
1941 }
1942
1943 private void copy(CharSequence text) {
1944 try {
1945 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1946 if (clip != null) {
1947 clip.setClipboardText(text);
1948 }
1949 } catch (android.os.RemoteException e) {
1950 Log.e(LOGTAG, "Copy failed", e);
1951 }
1952 }
1953
1954 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001955 * Resets the browser title-view to whatever it must be
1956 * (for example, if we had a loading error)
1957 * When we have a new page, we call resetTitle, when we
1958 * have to reset the titlebar to whatever it used to be
1959 * (for example, if the user chose to stop loading), we
1960 * call resetTitleAndRevertLockIcon.
1961 */
1962 /* package */ void resetTitleAndRevertLockIcon() {
1963 revertLockIcon();
1964 resetTitleIconAndProgress();
1965 }
1966
1967 /**
1968 * Reset the title, favicon, and progress.
1969 */
1970 private void resetTitleIconAndProgress() {
1971 WebView current = mTabControl.getCurrentWebView();
1972 if (current == null) {
1973 return;
1974 }
1975 resetTitleAndIcon(current);
1976 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001977 mWebChromeClient.onProgressChanged(current, progress);
1978 }
1979
1980 // Reset the title and the icon based on the given item.
1981 private void resetTitleAndIcon(WebView view) {
1982 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1983 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001984 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001985 setFavicon(item.getFavicon());
1986 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001987 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001988 setFavicon(null);
1989 }
1990 }
1991
1992 /**
1993 * Sets a title composed of the URL and the title string.
1994 * @param url The URL of the site being loaded.
1995 * @param title The title of the site being loaded.
1996 */
Leon Scroggins68579392009-09-15 15:31:54 -04001997 private void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001998 mUrl = url;
1999 mTitle = title;
2000
Leon Scroggins68579392009-09-15 15:31:54 -04002001 mTitleBar.setTitleAndUrl(title, url);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002002 if (mFakeTitleBar != null) {
2003 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002004 }
2005 }
2006
2007 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002008 * @param url The URL to build a title version of the URL from.
2009 * @return The title version of the URL or null if fails.
2010 * The title version of the URL can be either the URL hostname,
2011 * or the hostname with an "https://" prefix (for secure URLs),
2012 * or an empty string if, for example, the URL in question is a
2013 * file:// URL with no hostname.
2014 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002015 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002016 String titleUrl = null;
2017
2018 if (url != null) {
2019 try {
2020 // parse the url string
2021 URL urlObj = new URL(url);
2022 if (urlObj != null) {
2023 titleUrl = "";
2024
2025 String protocol = urlObj.getProtocol();
2026 String host = urlObj.getHost();
2027
2028 if (host != null && 0 < host.length()) {
2029 titleUrl = host;
2030 if (protocol != null) {
2031 // if a secure site, add an "https://" prefix!
2032 if (protocol.equalsIgnoreCase("https")) {
2033 titleUrl = protocol + "://" + host;
2034 }
2035 }
2036 }
2037 }
2038 } catch (MalformedURLException e) {}
2039 }
2040
2041 return titleUrl;
2042 }
2043
2044 // Set the favicon in the title bar.
2045 private void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002046 mTitleBar.setFavicon(icon);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002047 if (mFakeTitleBar != null) {
2048 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002049 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002050 }
2051
2052 /**
2053 * Saves the current lock-icon state before resetting
2054 * the lock icon. If we have an error, we may need to
2055 * roll back to the previous state.
2056 */
2057 private void saveLockIcon() {
2058 mPrevLockType = mLockIconType;
2059 }
2060
2061 /**
2062 * Reverts the lock-icon state to the last saved state,
2063 * for example, if we had an error, and need to cancel
2064 * the load.
2065 */
2066 private void revertLockIcon() {
2067 mLockIconType = mPrevLockType;
2068
Dave Bort31a6d1c2009-04-13 15:56:49 -07002069 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002070 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2071 " revert lock icon to " + mLockIconType);
2072 }
2073
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002074 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002075 }
2076
Leon Scroggins1f005d32009-08-10 17:36:42 -04002077 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002078 * Close the tab, remove its associated title bar, and adjust mTabControl's
2079 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002080 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002081 /* package */ void closeTab(TabControl.Tab t) {
2082 int currentIndex = mTabControl.getCurrentIndex();
2083 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002084 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002085 if (currentIndex >= removeIndex && currentIndex != 0) {
2086 currentIndex--;
2087 }
2088 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002089 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002090 }
2091
2092 private void goBackOnePageOrQuit() {
2093 TabControl.Tab current = mTabControl.getCurrentTab();
2094 if (current == null) {
2095 /*
2096 * Instead of finishing the activity, simply push this to the back
2097 * of the stack and let ActivityManager to choose the foreground
2098 * activity. As BrowserActivity is singleTask, it will be always the
2099 * root of the task. So we can use either true or false for
2100 * moveTaskToBack().
2101 */
2102 moveTaskToBack(true);
2103 }
2104 WebView w = current.getWebView();
2105 if (w.canGoBack()) {
2106 w.goBack();
2107 } else {
2108 // Check to see if we are closing a window that was created by
2109 // another window. If so, we switch back to that window.
2110 TabControl.Tab parent = current.getParentTab();
2111 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002112 switchToTab(mTabControl.getTabIndex(parent));
2113 // Now we close the other tab
2114 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002115 } else {
2116 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002117 // force mPageStarted to be false as we are going to either
2118 // finish the activity or remove the tab. This will ensure
2119 // pauseWebView() taking action.
2120 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002121 if (mTabControl.getTabCount() == 1) {
2122 finish();
2123 return;
2124 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002125 // call pauseWebViewTimers() now, we won't be able to call
2126 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002127 // Temporarily change mActivityInPause to be true as
2128 // pauseWebViewTimers() will do nothing if mActivityInPause
2129 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002130 boolean savedState = mActivityInPause;
2131 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002132 Log.e(LOGTAG, "BrowserActivity is already paused "
2133 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002134 }
2135 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002136 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002137 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002138 removeTabFromContentView(current);
2139 mTabControl.removeTab(current);
2140 }
2141 /*
2142 * Instead of finishing the activity, simply push this to the back
2143 * of the stack and let ActivityManager to choose the foreground
2144 * activity. As BrowserActivity is singleTask, it will be always the
2145 * root of the task. So we can use either true or false for
2146 * moveTaskToBack().
2147 */
2148 moveTaskToBack(true);
2149 }
2150 }
2151 }
2152
Grace Kloba5942df02009-09-18 11:48:29 -07002153 @Override
2154 public boolean onKeyDown(int keyCode, KeyEvent event) {
2155 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2156 // still down, we don't want to trigger the search. Pretend to consume
2157 // the key and do nothing.
2158 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002159
Grace Kloba5942df02009-09-18 11:48:29 -07002160 switch(keyCode) {
2161 case KeyEvent.KEYCODE_MENU:
2162 mMenuIsDown = true;
2163 break;
2164 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002165 // WebView/WebTextView handle the keys in the KeyDown. As
2166 // the Activity's shortcut keys are only handled when WebView
2167 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2168 if (event.isShiftPressed()) {
2169 getTopWindow().pageUp(false);
2170 } else {
2171 getTopWindow().pageDown(false);
2172 }
Grace Kloba5942df02009-09-18 11:48:29 -07002173 return true;
2174 case KeyEvent.KEYCODE_BACK:
2175 if (event.getRepeatCount() == 0) {
2176 event.startTracking();
2177 return true;
2178 } else if (mCustomView == null && mActiveTabsPage == null
2179 && event.isLongPress()) {
2180 bookmarksOrHistoryPicker(true);
2181 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002182 }
Grace Kloba5942df02009-09-18 11:48:29 -07002183 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002184 }
Grace Kloba5942df02009-09-18 11:48:29 -07002185 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002186 }
2187
Grace Kloba5942df02009-09-18 11:48:29 -07002188 @Override
2189 public boolean onKeyUp(int keyCode, KeyEvent event) {
2190 switch(keyCode) {
2191 case KeyEvent.KEYCODE_MENU:
2192 mMenuIsDown = false;
2193 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002194 case KeyEvent.KEYCODE_BACK:
2195 if (event.isTracking() && !event.isCanceled()) {
2196 if (mCustomView != null) {
2197 // if a custom view is showing, hide it
2198 mWebChromeClient.onHideCustomView();
2199 } else if (mActiveTabsPage != null) {
2200 // if tab page is showing, hide it
2201 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002202 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002203 WebView subwindow = mTabControl.getCurrentSubWindow();
2204 if (subwindow != null) {
2205 if (subwindow.canGoBack()) {
2206 subwindow.goBack();
2207 } else {
2208 dismissSubWindow(mTabControl.getCurrentTab());
2209 }
2210 } else {
2211 goBackOnePageOrQuit();
2212 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002213 }
Grace Kloba5942df02009-09-18 11:48:29 -07002214 return true;
2215 }
2216 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002217 }
Grace Kloba5942df02009-09-18 11:48:29 -07002218 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002219 }
2220
Leon Scroggins68579392009-09-15 15:31:54 -04002221 /* package */ void stopLoading() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002222 resetTitleAndRevertLockIcon();
2223 WebView w = getTopWindow();
2224 w.stopLoading();
2225 mWebViewClient.onPageFinished(w, w.getUrl());
2226
2227 cancelStopToast();
2228 mStopToast = Toast
2229 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2230 mStopToast.show();
2231 }
2232
2233 private void cancelStopToast() {
2234 if (mStopToast != null) {
2235 mStopToast.cancel();
2236 mStopToast = null;
2237 }
2238 }
2239
2240 // called by a non-UI thread to post the message
2241 public void postMessage(int what, int arg1, int arg2, Object obj) {
2242 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2243 }
2244
2245 // public message ids
2246 public final static int LOAD_URL = 1001;
2247 public final static int STOP_LOAD = 1002;
2248
2249 // Message Ids
2250 private static final int FOCUS_NODE_HREF = 102;
2251 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002252 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002253
2254 // Private handler for handling javascript and saving passwords
2255 private Handler mHandler = new Handler() {
2256
2257 public void handleMessage(Message msg) {
2258 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002259 case FOCUS_NODE_HREF:
2260 String url = (String) msg.getData().get("url");
2261 if (url == null || url.length() == 0) {
2262 break;
2263 }
2264 HashMap focusNodeMap = (HashMap) msg.obj;
2265 WebView view = (WebView) focusNodeMap.get("webview");
2266 // Only apply the action if the top window did not change.
2267 if (getTopWindow() != view) {
2268 break;
2269 }
2270 switch (msg.arg1) {
2271 case R.id.open_context_menu_id:
2272 case R.id.view_image_context_menu_id:
2273 loadURL(getTopWindow(), url);
2274 break;
2275 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002276 final TabControl.Tab parent = mTabControl
2277 .getCurrentTab();
2278 final TabControl.Tab newTab = openTab(url);
2279 if (newTab != parent) {
2280 parent.addChildTab(newTab);
2281 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002282 break;
2283 case R.id.bookmark_context_menu_id:
2284 Intent intent = new Intent(BrowserActivity.this,
2285 AddBookmarkPage.class);
2286 intent.putExtra("url", url);
2287 startActivity(intent);
2288 break;
2289 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002290 Browser.sendString(BrowserActivity.this, url,
2291 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002292 break;
2293 case R.id.copy_link_context_menu_id:
2294 copy(url);
2295 break;
2296 case R.id.save_link_context_menu_id:
2297 case R.id.download_context_menu_id:
2298 onDownloadStartNoStream(url, null, null, null, -1);
2299 break;
2300 }
2301 break;
2302
2303 case LOAD_URL:
2304 loadURL(getTopWindow(), (String) msg.obj);
2305 break;
2306
2307 case STOP_LOAD:
2308 stopLoading();
2309 break;
2310
2311 case CANCEL_CREDS_REQUEST:
2312 resumeAfterCredentials();
2313 break;
2314
The Android Open Source Project0c908882009-03-03 19:32:16 -08002315 case RELEASE_WAKELOCK:
2316 if (mWakeLock.isHeld()) {
2317 mWakeLock.release();
2318 }
2319 break;
2320 }
2321 }
2322 };
2323
Leon Scroggins89c6d362009-07-15 16:54:37 -04002324 private void updateScreenshot(WebView view) {
2325 // If this is a bookmarked site, add a screenshot to the database.
2326 // FIXME: When should we update? Every time?
2327 // FIXME: Would like to make sure there is actually something to
2328 // draw, but the API for that (WebViewCore.pictureReady()) is not
2329 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002330 ContentResolver cr = getContentResolver();
2331 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002332 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002333 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002334 boolean succeed = c.moveToFirst();
2335 ContentValues values = null;
2336 while (succeed) {
2337 if (values == null) {
2338 final ByteArrayOutputStream os
2339 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002340 Bitmap bm = createScreenshot(view);
Leon Scroggins89c6d362009-07-15 16:54:37 -04002341 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2342 values = new ContentValues();
2343 values.put(Browser.BookmarkColumns.THUMBNAIL,
2344 os.toByteArray());
2345 }
2346 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2347 c.getInt(0)), values, null, null);
2348 succeed = c.moveToNext();
2349 }
2350 c.close();
2351 }
2352 }
2353
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002354 /**
2355 * Constants for the size of the thumbnail created when taking a screenshot
2356 */
2357 /* package */ static final int THUMBNAIL_WIDTH = 130;
2358 /* package */ static final int THUMBNAIL_HEIGHT = 104;
2359
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002360 private Bitmap createScreenshot(WebView view) {
2361 Picture thumbnail = view.capturePicture();
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002362 Bitmap bm = Bitmap.createBitmap(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT,
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002363 Bitmap.Config.ARGB_4444);
2364 Canvas canvas = new Canvas(bm);
2365 // May need to tweak these values to determine what is the
2366 // best scale factor
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002367 int contentWidth = view.getContentWidth();
2368 if (contentWidth > 0) {
2369 float scaleFactor = (float) THUMBNAIL_WIDTH / (float) contentWidth;
2370 canvas.scale(scaleFactor, scaleFactor);
2371 }
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002372 thumbnail.draw(canvas);
2373 return bm;
2374 }
2375
The Android Open Source Project0c908882009-03-03 19:32:16 -08002376 // -------------------------------------------------------------------------
2377 // WebViewClient implementation.
2378 //-------------------------------------------------------------------------
2379
2380 // Use in overrideUrlLoading
2381 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2382 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2383 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2384 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2385
2386 /* package */ WebViewClient getWebViewClient() {
2387 return mWebViewClient;
2388 }
2389
Patrick Scott3918d442009-08-04 13:22:29 -04002390 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002391 if (icon != null) {
2392 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott15525d42009-09-21 13:39:37 -04002393 view.getOriginalUrl(), view.getUrl(), icon);
2394 }
2395 setFavicon(icon);
2396 }
2397
2398 private void updateIcon(String url, Bitmap icon) {
2399 if (icon != null) {
2400 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2401 null, url, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002402 }
2403 setFavicon(icon);
2404 }
2405
2406 private final WebViewClient mWebViewClient = new WebViewClient() {
2407 @Override
2408 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2409 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002410 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002411
Patrick Scott59ce8302009-09-18 16:29:38 -04002412 // If we start a touch icon load and then load a new page, we don't
2413 // want to cancel the current touch icon loader. But, we do want to
2414 // create a new one when the touch icon url is known.
2415 if (mTouchIconLoader != null) {
2416 mTouchIconLoader.mActivity = null;
2417 mTouchIconLoader = null;
2418 }
2419
Ben Murdochbff2d602009-07-01 20:19:05 +01002420 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2421 if (errorConsole != null) {
2422 errorConsole.clearErrorMessages();
2423 if (mShouldShowErrorConsole) {
2424 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2425 }
2426 }
2427
The Android Open Source Project0c908882009-03-03 19:32:16 -08002428 // Call updateIcon instead of setFavicon so the bookmark
2429 // database can be updated.
Patrick Scott15525d42009-09-21 13:39:37 -04002430 updateIcon(url, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002431
Grace Kloba4d7880f2009-08-12 09:35:42 -07002432 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002433 String host;
2434 try {
2435 WebAddress uri = new WebAddress(url);
2436 host = uri.mHost;
2437 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002438 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002439 }
2440 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002441 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002442 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002443 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002444 }
2445
2446 // Performance probe
2447 if (false) {
2448 mStart = SystemClock.uptimeMillis();
2449 mProcessStart = Process.getElapsedCpuTime();
2450 long[] sysCpu = new long[7];
2451 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2452 sysCpu, null)) {
2453 mUserStart = sysCpu[0] + sysCpu[1];
2454 mSystemStart = sysCpu[2];
2455 mIdleStart = sysCpu[3];
2456 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2457 }
2458 mUiStart = SystemClock.currentThreadTimeMillis();
2459 }
2460
2461 if (!mPageStarted) {
2462 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002463 // if onResume() has been called, resumeWebViewTimers() does
2464 // nothing.
2465 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002466 }
2467
2468 // reset sync timer to avoid sync starts during loading a page
2469 CookieSyncManager.getInstance().resetSync();
2470
2471 mInLoad = true;
Leon Scroggins184f5e32009-09-21 10:38:24 -04002472 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002473 updateInLoadMenuItems();
2474 if (!mIsNetworkUp) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04002475 createAndShowNetworkDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002476 if (view != null) {
2477 view.setNetworkAvailable(false);
2478 }
2479 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002480 }
2481
2482 @Override
2483 public void onPageFinished(WebView view, String url) {
2484 // Reset the title and icon in case we stopped a provisional
2485 // load.
2486 resetTitleAndIcon(view);
2487
2488 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002489 updateLockIconToLatest();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002490 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002491
The Android Open Source Project0c908882009-03-03 19:32:16 -08002492 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002493 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002494 long[] sysCpu = new long[7];
2495 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2496 sysCpu, null)) {
2497 String uiInfo = "UI thread used "
2498 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2499 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002500 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002501 Log.d(LOGTAG, uiInfo);
2502 }
2503 //The string that gets written to the log
2504 String performanceString = "It took total "
2505 + (SystemClock.uptimeMillis() - mStart)
2506 + " ms clock time to load the page."
2507 + "\nbrowser process used "
2508 + (Process.getElapsedCpuTime() - mProcessStart)
2509 + " ms, user processes used "
2510 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2511 + " ms, kernel used "
2512 + (sysCpu[2] - mSystemStart) * 10
2513 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2514 + " ms and irq took "
2515 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2516 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002517 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002518 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2519 }
2520 if (url != null) {
2521 // strip the url to maintain consistency
2522 String newUrl = new String(url);
2523 if (newUrl.startsWith("http://www.")) {
2524 newUrl = newUrl.substring(11);
2525 } else if (newUrl.startsWith("http://")) {
2526 newUrl = newUrl.substring(7);
2527 } else if (newUrl.startsWith("https://www.")) {
2528 newUrl = newUrl.substring(12);
2529 } else if (newUrl.startsWith("https://")) {
2530 newUrl = newUrl.substring(8);
2531 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002532 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002533 Log.d(LOGTAG, newUrl + " loaded");
2534 }
2535 /*
2536 if (sWhiteList.contains(newUrl)) {
2537 // The string that gets pushed to the statistcs
2538 // service
2539 performanceString = performanceString
2540 + "\nWebpage: "
2541 + newUrl
2542 + "\nCarrier: "
2543 + android.os.SystemProperties
2544 .get("gsm.sim.operator.alpha");
2545 if (mWebView != null
2546 && mWebView.getContext() != null
2547 && mWebView.getContext().getSystemService(
2548 Context.CONNECTIVITY_SERVICE) != null) {
2549 ConnectivityManager cManager =
2550 (ConnectivityManager) mWebView
2551 .getContext().getSystemService(
2552 Context.CONNECTIVITY_SERVICE);
2553 NetworkInfo nInfo = cManager
2554 .getActiveNetworkInfo();
2555 if (nInfo != null) {
2556 performanceString = performanceString
2557 + "\nNetwork Type: "
2558 + nInfo.getType().toString();
2559 }
2560 }
2561 Checkin.logEvent(mResolver,
2562 Checkin.Events.Tag.WEBPAGE_LOAD,
2563 performanceString);
2564 Log.w(LOGTAG, "pushed to the statistics service");
2565 }
2566 */
2567 }
2568 }
2569 }
2570
2571 if (mInTrace) {
2572 mInTrace = false;
2573 Debug.stopMethodTracing();
2574 }
2575
2576 if (mPageStarted) {
2577 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002578 // pauseWebViewTimers() will do nothing and return false if
2579 // onPause() is not called yet.
2580 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002581 if (mWakeLock.isHeld()) {
2582 mHandler.removeMessages(RELEASE_WAKELOCK);
2583 mWakeLock.release();
2584 }
2585 }
2586 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002587 }
2588
2589 // return true if want to hijack the url to let another app to handle it
2590 @Override
2591 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2592 if (url.startsWith(SCHEME_WTAI)) {
2593 // wtai://wp/mc;number
2594 // number=string(phone-number)
2595 if (url.startsWith(SCHEME_WTAI_MC)) {
2596 Intent intent = new Intent(Intent.ACTION_VIEW,
2597 Uri.parse(WebView.SCHEME_TEL +
2598 url.substring(SCHEME_WTAI_MC.length())));
2599 startActivity(intent);
2600 return true;
2601 }
2602 // wtai://wp/sd;dtmf
2603 // dtmf=string(dialstring)
2604 if (url.startsWith(SCHEME_WTAI_SD)) {
2605 // TODO
2606 // only send when there is active voice connection
2607 return false;
2608 }
2609 // wtai://wp/ap;number;name
2610 // number=string(phone-number)
2611 // name=string
2612 if (url.startsWith(SCHEME_WTAI_AP)) {
2613 // TODO
2614 return false;
2615 }
2616 }
2617
Dianne Hackborn99189432009-06-17 18:06:18 -07002618 // The "about:" schemes are internal to the browser; don't
2619 // want these to be dispatched to other apps.
2620 if (url.startsWith("about:")) {
2621 return false;
2622 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002623
Dianne Hackborn99189432009-06-17 18:06:18 -07002624 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002625
Dianne Hackborn99189432009-06-17 18:06:18 -07002626 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002627 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002628 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2629 } catch (URISyntaxException ex) {
2630 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002631 return false;
2632 }
2633
Grace Kloba5b078b52009-06-24 20:23:41 -07002634 // check whether the intent can be resolved. If not, we will see
2635 // whether we can download it from the Market.
2636 if (getPackageManager().resolveActivity(intent, 0) == null) {
2637 String packagename = intent.getPackage();
2638 if (packagename != null) {
2639 intent = new Intent(Intent.ACTION_VIEW, Uri
2640 .parse("market://search?q=pname:" + packagename));
2641 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2642 startActivity(intent);
2643 return true;
2644 } else {
2645 return false;
2646 }
2647 }
2648
Dianne Hackborn99189432009-06-17 18:06:18 -07002649 // sanitize the Intent, ensuring web pages can not bypass browser
2650 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002651 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002652 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002653 try {
2654 if (startActivityIfNeeded(intent, -1)) {
2655 return true;
2656 }
2657 } catch (ActivityNotFoundException ex) {
2658 // ignore the error. If no application can handle the URL,
2659 // eg about:blank, assume the browser can handle it.
2660 }
2661
2662 if (mMenuIsDown) {
2663 openTab(url);
2664 closeOptionsMenu();
2665 return true;
2666 }
2667
2668 return false;
2669 }
2670
2671 /**
2672 * Updates the lock icon. This method is called when we discover another
2673 * resource to be loaded for this page (for example, javascript). While
2674 * we update the icon type, we do not update the lock icon itself until
2675 * we are done loading, it is slightly more secure this way.
2676 */
2677 @Override
2678 public void onLoadResource(WebView view, String url) {
2679 if (url != null && url.length() > 0) {
2680 // It is only if the page claims to be secure
2681 // that we may have to update the lock:
2682 if (mLockIconType == LOCK_ICON_SECURE) {
2683 // If NOT a 'safe' url, change the lock to mixed content!
2684 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2685 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002686 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002687 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2688 " updated lock icon to " + mLockIconType + " due to " + url);
2689 }
2690 }
2691 }
2692 }
2693 }
2694
2695 /**
2696 * Show the dialog, asking the user if they would like to continue after
2697 * an excessive number of HTTP redirects.
2698 */
2699 @Override
2700 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2701 final Message continueMsg) {
2702 new AlertDialog.Builder(BrowserActivity.this)
2703 .setTitle(R.string.browserFrameRedirect)
2704 .setMessage(R.string.browserFrame307Post)
2705 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2706 public void onClick(DialogInterface dialog, int which) {
2707 continueMsg.sendToTarget();
2708 }})
2709 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2710 public void onClick(DialogInterface dialog, int which) {
2711 cancelMsg.sendToTarget();
2712 }})
2713 .setOnCancelListener(new OnCancelListener() {
2714 public void onCancel(DialogInterface dialog) {
2715 cancelMsg.sendToTarget();
2716 }})
2717 .show();
2718 }
2719
Patrick Scott37911c72009-03-24 18:02:58 -07002720 // Container class for the next error dialog that needs to be
2721 // displayed.
2722 class ErrorDialog {
2723 public final int mTitle;
2724 public final String mDescription;
2725 public final int mError;
2726 ErrorDialog(int title, String desc, int error) {
2727 mTitle = title;
2728 mDescription = desc;
2729 mError = error;
2730 }
2731 };
2732
2733 private void processNextError() {
2734 if (mQueuedErrors == null) {
2735 return;
2736 }
2737 // The first one is currently displayed so just remove it.
2738 mQueuedErrors.removeFirst();
2739 if (mQueuedErrors.size() == 0) {
2740 mQueuedErrors = null;
2741 return;
2742 }
2743 showError(mQueuedErrors.getFirst());
2744 }
2745
2746 private DialogInterface.OnDismissListener mDialogListener =
2747 new DialogInterface.OnDismissListener() {
2748 public void onDismiss(DialogInterface d) {
2749 processNextError();
2750 }
2751 };
2752 private LinkedList<ErrorDialog> mQueuedErrors;
2753
2754 private void queueError(int err, String desc) {
2755 if (mQueuedErrors == null) {
2756 mQueuedErrors = new LinkedList<ErrorDialog>();
2757 }
2758 for (ErrorDialog d : mQueuedErrors) {
2759 if (d.mError == err) {
2760 // Already saw a similar error, ignore the new one.
2761 return;
2762 }
2763 }
2764 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002765 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002766 R.string.browserFrameFileErrorLabel :
2767 R.string.browserFrameNetworkErrorLabel,
2768 desc, err);
2769 mQueuedErrors.addLast(errDialog);
2770
2771 // Show the dialog now if the queue was empty.
2772 if (mQueuedErrors.size() == 1) {
2773 showError(errDialog);
2774 }
2775 }
2776
2777 private void showError(ErrorDialog errDialog) {
2778 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2779 .setTitle(errDialog.mTitle)
2780 .setMessage(errDialog.mDescription)
2781 .setPositiveButton(R.string.ok, null)
2782 .create();
2783 d.setOnDismissListener(mDialogListener);
2784 d.show();
2785 }
2786
The Android Open Source Project0c908882009-03-03 19:32:16 -08002787 /**
2788 * Show a dialog informing the user of the network error reported by
2789 * WebCore.
2790 */
2791 @Override
2792 public void onReceivedError(WebView view, int errorCode,
2793 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002794 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2795 errorCode != WebViewClient.ERROR_CONNECT &&
2796 errorCode != WebViewClient.ERROR_BAD_URL &&
2797 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2798 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002799 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002800 }
Patrick Scott37911c72009-03-24 18:02:58 -07002801 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2802 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002803
2804 // We need to reset the title after an error.
2805 resetTitleAndRevertLockIcon();
2806 }
2807
2808 /**
2809 * Check with the user if it is ok to resend POST data as the page they
2810 * are trying to navigate to is the result of a POST.
2811 */
2812 @Override
2813 public void onFormResubmission(WebView view, final Message dontResend,
2814 final Message resend) {
2815 new AlertDialog.Builder(BrowserActivity.this)
2816 .setTitle(R.string.browserFrameFormResubmitLabel)
2817 .setMessage(R.string.browserFrameFormResubmitMessage)
2818 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2819 public void onClick(DialogInterface dialog, int which) {
2820 resend.sendToTarget();
2821 }})
2822 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2823 public void onClick(DialogInterface dialog, int which) {
2824 dontResend.sendToTarget();
2825 }})
2826 .setOnCancelListener(new OnCancelListener() {
2827 public void onCancel(DialogInterface dialog) {
2828 dontResend.sendToTarget();
2829 }})
2830 .show();
2831 }
2832
2833 /**
2834 * Insert the url into the visited history database.
2835 * @param url The url to be inserted.
2836 * @param isReload True if this url is being reloaded.
2837 * FIXME: Not sure what to do when reloading the page.
2838 */
2839 @Override
2840 public void doUpdateVisitedHistory(WebView view, String url,
2841 boolean isReload) {
2842 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2843 return;
2844 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002845 // remove "client" before updating it to the history so that it wont
2846 // show up in the auto-complete list.
2847 int index = url.indexOf("client=ms-");
2848 if (index > 0 && url.contains(".google.")) {
2849 int end = url.indexOf('&', index);
2850 if (end > 0) {
2851 url = url.substring(0, index-1).concat(url.substring(end));
2852 } else {
2853 url = url.substring(0, index-1);
2854 }
2855 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002856 Browser.updateVisitedHistory(mResolver, url, true);
2857 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2858 }
2859
2860 /**
2861 * Displays SSL error(s) dialog to the user.
2862 */
2863 @Override
2864 public void onReceivedSslError(
2865 final WebView view, final SslErrorHandler handler, final SslError error) {
2866
2867 if (mSettings.showSecurityWarnings()) {
2868 final LayoutInflater factory =
2869 LayoutInflater.from(BrowserActivity.this);
2870 final View warningsView =
2871 factory.inflate(R.layout.ssl_warnings, null);
2872 final LinearLayout placeholder =
2873 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2874
2875 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2876 LinearLayout ll = (LinearLayout)factory
2877 .inflate(R.layout.ssl_warning, null);
2878 ((TextView)ll.findViewById(R.id.warning))
2879 .setText(R.string.ssl_untrusted);
2880 placeholder.addView(ll);
2881 }
2882
2883 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2884 LinearLayout ll = (LinearLayout)factory
2885 .inflate(R.layout.ssl_warning, null);
2886 ((TextView)ll.findViewById(R.id.warning))
2887 .setText(R.string.ssl_mismatch);
2888 placeholder.addView(ll);
2889 }
2890
2891 if (error.hasError(SslError.SSL_EXPIRED)) {
2892 LinearLayout ll = (LinearLayout)factory
2893 .inflate(R.layout.ssl_warning, null);
2894 ((TextView)ll.findViewById(R.id.warning))
2895 .setText(R.string.ssl_expired);
2896 placeholder.addView(ll);
2897 }
2898
2899 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2900 LinearLayout ll = (LinearLayout)factory
2901 .inflate(R.layout.ssl_warning, null);
2902 ((TextView)ll.findViewById(R.id.warning))
2903 .setText(R.string.ssl_not_yet_valid);
2904 placeholder.addView(ll);
2905 }
2906
2907 new AlertDialog.Builder(BrowserActivity.this)
2908 .setTitle(R.string.security_warning)
2909 .setIcon(android.R.drawable.ic_dialog_alert)
2910 .setView(warningsView)
2911 .setPositiveButton(R.string.ssl_continue,
2912 new DialogInterface.OnClickListener() {
2913 public void onClick(DialogInterface dialog, int whichButton) {
2914 handler.proceed();
2915 }
2916 })
2917 .setNeutralButton(R.string.view_certificate,
2918 new DialogInterface.OnClickListener() {
2919 public void onClick(DialogInterface dialog, int whichButton) {
2920 showSSLCertificateOnError(view, handler, error);
2921 }
2922 })
2923 .setNegativeButton(R.string.cancel,
2924 new DialogInterface.OnClickListener() {
2925 public void onClick(DialogInterface dialog, int whichButton) {
2926 handler.cancel();
2927 BrowserActivity.this.resetTitleAndRevertLockIcon();
2928 }
2929 })
2930 .setOnCancelListener(
2931 new DialogInterface.OnCancelListener() {
2932 public void onCancel(DialogInterface dialog) {
2933 handler.cancel();
2934 BrowserActivity.this.resetTitleAndRevertLockIcon();
2935 }
2936 })
2937 .show();
2938 } else {
2939 handler.proceed();
2940 }
2941 }
2942
2943 /**
2944 * Handles an HTTP authentication request.
2945 *
2946 * @param handler The authentication handler
2947 * @param host The host
2948 * @param realm The realm
2949 */
2950 @Override
2951 public void onReceivedHttpAuthRequest(WebView view,
2952 final HttpAuthHandler handler, final String host, final String realm) {
2953 String username = null;
2954 String password = null;
2955
2956 boolean reuseHttpAuthUsernamePassword =
2957 handler.useHttpAuthUsernamePassword();
2958
2959 if (reuseHttpAuthUsernamePassword &&
2960 (mTabControl.getCurrentWebView() != null)) {
2961 String[] credentials =
2962 mTabControl.getCurrentWebView()
2963 .getHttpAuthUsernamePassword(host, realm);
2964 if (credentials != null && credentials.length == 2) {
2965 username = credentials[0];
2966 password = credentials[1];
2967 }
2968 }
2969
2970 if (username != null && password != null) {
2971 handler.proceed(username, password);
2972 } else {
2973 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2974 }
2975 }
2976
2977 @Override
2978 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2979 if (mMenuIsDown) {
2980 // only check shortcut key when MENU is held
2981 return getWindow().isShortcutKey(event.getKeyCode(), event);
2982 } else {
2983 return false;
2984 }
2985 }
2986
2987 @Override
2988 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2989 if (view != mTabControl.getCurrentTopWebView()) {
2990 return;
2991 }
2992 if (event.isDown()) {
2993 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2994 } else {
2995 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2996 }
2997 }
2998 };
2999
3000 //--------------------------------------------------------------------------
3001 // WebChromeClient implementation
3002 //--------------------------------------------------------------------------
3003
3004 /* package */ WebChromeClient getWebChromeClient() {
3005 return mWebChromeClient;
3006 }
3007
3008 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3009 // Helper method to create a new tab or sub window.
3010 private void createWindow(final boolean dialog, final Message msg) {
3011 if (dialog) {
3012 mTabControl.createSubWindow();
3013 final TabControl.Tab t = mTabControl.getCurrentTab();
3014 attachSubWindow(t);
3015 WebView.WebViewTransport transport =
3016 (WebView.WebViewTransport) msg.obj;
3017 transport.setWebView(t.getSubWebView());
3018 msg.sendToTarget();
3019 } else {
3020 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003021 final TabControl.Tab newTab
3022 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07003023 if (newTab != parent) {
3024 parent.addChildTab(newTab);
3025 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003026 WebView.WebViewTransport transport =
3027 (WebView.WebViewTransport) msg.obj;
3028 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04003029 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003030 }
3031 }
3032
3033 @Override
3034 public boolean onCreateWindow(WebView view, final boolean dialog,
3035 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003036 // Short-circuit if we can't create any more tabs or sub windows.
3037 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3038 new AlertDialog.Builder(BrowserActivity.this)
3039 .setTitle(R.string.too_many_subwindows_dialog_title)
3040 .setIcon(android.R.drawable.ic_dialog_alert)
3041 .setMessage(R.string.too_many_subwindows_dialog_message)
3042 .setPositiveButton(R.string.ok, null)
3043 .show();
3044 return false;
3045 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3046 new AlertDialog.Builder(BrowserActivity.this)
3047 .setTitle(R.string.too_many_windows_dialog_title)
3048 .setIcon(android.R.drawable.ic_dialog_alert)
3049 .setMessage(R.string.too_many_windows_dialog_message)
3050 .setPositiveButton(R.string.ok, null)
3051 .show();
3052 return false;
3053 }
3054
3055 // Short-circuit if this was a user gesture.
3056 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003057 createWindow(dialog, resultMsg);
3058 return true;
3059 }
3060
3061 // Allow the popup and create the appropriate window.
3062 final AlertDialog.OnClickListener allowListener =
3063 new AlertDialog.OnClickListener() {
3064 public void onClick(DialogInterface d,
3065 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003066 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003067 }
3068 };
3069
3070 // Block the popup by returning a null WebView.
3071 final AlertDialog.OnClickListener blockListener =
3072 new AlertDialog.OnClickListener() {
3073 public void onClick(DialogInterface d, int which) {
3074 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003075 }
3076 };
3077
3078 // Build a confirmation dialog to display to the user.
3079 final AlertDialog d =
3080 new AlertDialog.Builder(BrowserActivity.this)
3081 .setTitle(R.string.attention)
3082 .setIcon(android.R.drawable.ic_dialog_alert)
3083 .setMessage(R.string.popup_window_attempt)
3084 .setPositiveButton(R.string.allow, allowListener)
3085 .setNegativeButton(R.string.block, blockListener)
3086 .setCancelable(false)
3087 .create();
3088
3089 // Show the confirmation dialog.
3090 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003091 return true;
3092 }
3093
3094 @Override
3095 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003096 final TabControl.Tab current = mTabControl.getCurrentTab();
3097 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003098 if (parent != null) {
3099 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003100 switchToTab(mTabControl.getTabIndex(parent));
3101 // Now we need to close the window
3102 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003103 }
3104 }
3105
3106 @Override
3107 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003108 mTitleBar.setProgress(newProgress);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003109 if (mFakeTitleBar != null) {
3110 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003111 }
3112
3113 if (newProgress == 100) {
3114 // onProgressChanged() is called for sub-frame too while
3115 // onPageFinished() is only called for the main frame. sync
3116 // cookie and cache promptly here.
3117 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003118 if (mInLoad) {
3119 mInLoad = false;
3120 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003121 // If the options menu is open, leave the title bar
3122 if (!mOptionsMenuOpen || !mIconView) {
3123 hideFakeTitleBar();
3124 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003125 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003126 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003127 // onPageFinished may have already been called but a subframe
3128 // is still loading and updating the progress. Reset mInLoad
3129 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003130 mInLoad = true;
3131 updateInLoadMenuItems();
Leon Scroggins184f5e32009-09-21 10:38:24 -04003132 if (!mOptionsMenuOpen || mIconView) {
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003133 // This page has begun to load, so show the title bar
3134 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003135 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003136 }
3137 }
3138
3139 @Override
3140 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003141 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003142
3143 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003144 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003145
3146 if (url == null ||
3147 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3148 return;
3149 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003150 // See if we can find the current url in our history database and
3151 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003152 if (url.startsWith("http://www.")) {
3153 url = url.substring(11);
3154 } else if (url.startsWith("http://")) {
3155 url = url.substring(4);
3156 }
3157 try {
3158 url = "%" + url;
3159 String [] selArgs = new String[] { url };
3160
3161 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3162 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3163 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3164 Browser.HISTORY_PROJECTION, where, selArgs, null);
3165 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003166 // Current implementation of database only has one entry per
3167 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003168 ContentValues map = new ContentValues();
3169 map.put(Browser.BookmarkColumns.TITLE, title);
3170 mResolver.update(Browser.BOOKMARKS_URI, map,
3171 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003172 }
3173 c.close();
3174 } catch (IllegalStateException e) {
3175 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3176 } catch (SQLiteException ex) {
3177 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3178 }
3179 }
3180
3181 @Override
3182 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003183 updateIcon(view, icon);
3184 }
3185
3186 @Override
Patrick Scott59ce8302009-09-18 16:29:38 -04003187 public void onReceivedTouchIconUrl(WebView view, String url,
3188 boolean precomposed) {
Patrick Scott3918d442009-08-04 13:22:29 -04003189 final ContentResolver cr = getContentResolver();
3190 final Cursor c =
3191 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003192 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003193 if (c != null) {
3194 if (c.getCount() > 0) {
Patrick Scott59ce8302009-09-18 16:29:38 -04003195 // Let precomposed icons take precedence over non-composed
3196 // icons.
3197 if (precomposed && mTouchIconLoader != null) {
3198 mTouchIconLoader.cancel(false);
3199 mTouchIconLoader = null;
3200 }
3201 // Have only one async task at a time.
3202 if (mTouchIconLoader == null) {
3203 mTouchIconLoader = new DownloadTouchIcon(
3204 BrowserActivity.this, cr, c, view);
3205 mTouchIconLoader.execute(url);
3206 }
Patrick Scott3918d442009-08-04 13:22:29 -04003207 } else {
3208 c.close();
3209 }
3210 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003211 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003212
Andrei Popescuadc008d2009-06-26 14:11:30 +01003213 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003214 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003215 if (mCustomView != null)
3216 return;
3217
3218 // Add the custom view to its container.
3219 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3220 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003221 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003222 // Save the menu state and set it to empty while the custom
3223 // view is showing.
3224 mOldMenuState = mMenuState;
3225 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003226 // Hide the content view.
3227 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003228 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003229 mCustomViewContainer.setVisibility(View.VISIBLE);
3230 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003231 }
3232
3233 @Override
3234 public void onHideCustomView() {
3235 if (mCustomView == null)
3236 return;
3237
Andrei Popescuc9b55562009-07-07 10:51:15 +01003238 // Hide the custom view.
3239 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003240 // Remove the custom view from its container.
3241 mCustomViewContainer.removeView(mCustomView);
3242 mCustomView = null;
3243 // Reset the old menu state.
3244 mMenuState = mOldMenuState;
3245 mOldMenuState = EMPTY_MENU;
3246 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003247 mCustomViewCallback.onCustomViewHidden();
3248 // Show the content view.
3249 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003250 }
3251
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003252 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003253 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003254 * @param url the URL that exceeded the quota
3255 * @param databaseIdentifier the identifier of the database on
3256 * which the transaction that caused the quota overflow was run
3257 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003258 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003259 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003260 * @param quotaUpdater The callback to run when a decision to allow or
3261 * deny quota has been made. Don't forget to call this!
3262 */
3263 @Override
3264 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003265 String databaseIdentifier, long currentQuota, long estimatedSize,
3266 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003267 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003268 url, databaseIdentifier, currentQuota, estimatedSize,
3269 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003270 }
3271
3272 /**
3273 * The Application Cache has exceeded its max size.
3274 * @param spaceNeeded is the amount of disk space that would be needed
3275 * in order for the last appcache operation to succeed.
3276 * @param totalUsedQuota is the sum of all origins' quota.
3277 * @param quotaUpdater A callback to inform the WebCore thread that a new
3278 * app cache size is available. This callback must always be executed at
3279 * some point to ensure that the sleeping WebCore thread is woken up.
3280 */
3281 @Override
3282 public void onReachedMaxAppCacheSize(long spaceNeeded,
3283 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3284 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3285 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003286 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003287
Steve Block2bc69912009-07-30 14:45:13 +01003288 /**
3289 * Instructs the browser to show a prompt to ask the user to set the
3290 * Geolocation permission state for the specified origin.
3291 * @param origin The origin for which Geolocation permissions are
3292 * requested.
3293 * @param callback The callback to call once the user has set the
3294 * Geolocation permission state.
3295 */
3296 @Override
3297 public void onGeolocationPermissionsShowPrompt(String origin,
3298 GeolocationPermissions.Callback callback) {
3299 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3300 origin, callback);
3301 }
3302
3303 /**
3304 * Instructs the browser to hide the Geolocation permissions prompt.
3305 */
3306 @Override
3307 public void onGeolocationPermissionsHidePrompt() {
3308 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3309 }
3310
Ben Murdoch7db26342009-06-03 18:21:19 +01003311 /* Adds a JavaScript error message to the system log.
3312 * @param message The error message to report.
3313 * @param lineNumber The line number of the error.
3314 * @param sourceID The name of the source file that caused the error.
3315 */
3316 @Override
3317 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003318 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3319 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3320 if (mShouldShowErrorConsole &&
3321 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3322 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3323 }
3324 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003325 }
Andrei Popescu540035d2009-09-18 18:59:20 +01003326
3327 /**
3328 * Ask the browser for an icon to represent a <video> element.
3329 * This icon will be used if the Web page did not specify a poster attribute.
3330 *
3331 * @return Bitmap The icon or null if no such icon is available.
3332 * @hide pending API Council approval
3333 */
3334 @Override
3335 public Bitmap getDefaultVideoPoster() {
3336 if (mDefaultVideoPoster == null) {
3337 mDefaultVideoPoster = BitmapFactory.decodeResource(
3338 getResources(), R.drawable.default_video_poster);
3339 }
3340 return mDefaultVideoPoster;
3341 }
3342
3343 /**
3344 * Ask the host application for a custom progress view to show while
3345 * a <video> is loading.
3346 *
3347 * @return View The progress view.
3348 * @hide pending API Council approval
3349 */
3350 @Override
3351 public View getVideoLoadingProgressView() {
3352 if (mVideoProgressView == null) {
3353 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
3354 mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
3355 }
3356 return mVideoProgressView;
3357 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003358 };
3359
3360 /**
3361 * Notify the host application a download should be done, or that
3362 * the data should be streamed if a streaming viewer is available.
3363 * @param url The full url to the content that should be downloaded
3364 * @param contentDisposition Content-disposition http header, if
3365 * present.
3366 * @param mimetype The mimetype of the content reported by the server
3367 * @param contentLength The file size reported by the server
3368 */
3369 public void onDownloadStart(String url, String userAgent,
3370 String contentDisposition, String mimetype, long contentLength) {
3371 // if we're dealing wih A/V content that's not explicitly marked
3372 // for download, check if it's streamable.
3373 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003374 || !contentDisposition.regionMatches(
3375 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003376 // query the package manager to see if there's a registered handler
3377 // that matches.
3378 Intent intent = new Intent(Intent.ACTION_VIEW);
3379 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003380 ResolveInfo info = getPackageManager().resolveActivity(intent,
3381 PackageManager.MATCH_DEFAULT_ONLY);
3382 if (info != null) {
3383 ComponentName myName = getComponentName();
3384 // If we resolved to ourselves, we don't want to attempt to
3385 // load the url only to try and download it again.
3386 if (!myName.getPackageName().equals(
3387 info.activityInfo.packageName)
3388 || !myName.getClassName().equals(
3389 info.activityInfo.name)) {
3390 // someone (other than us) knows how to handle this mime
3391 // type with this scheme, don't download.
3392 try {
3393 startActivity(intent);
3394 return;
3395 } catch (ActivityNotFoundException ex) {
3396 if (LOGD_ENABLED) {
3397 Log.d(LOGTAG, "activity not found for " + mimetype
3398 + " over " + Uri.parse(url).getScheme(),
3399 ex);
3400 }
3401 // Best behavior is to fall back to a download in this
3402 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003403 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003404 }
3405 }
3406 }
3407 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3408 }
3409
3410 /**
3411 * Notify the host application a download should be done, even if there
3412 * is a streaming viewer available for thise type.
3413 * @param url The full url to the content that should be downloaded
3414 * @param contentDisposition Content-disposition http header, if
3415 * present.
3416 * @param mimetype The mimetype of the content reported by the server
3417 * @param contentLength The file size reported by the server
3418 */
3419 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3420 String contentDisposition, String mimetype, long contentLength) {
3421
3422 String filename = URLUtil.guessFileName(url,
3423 contentDisposition, mimetype);
3424
3425 // Check to see if we have an SDCard
3426 String status = Environment.getExternalStorageState();
3427 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3428 int title;
3429 String msg;
3430
3431 // Check to see if the SDCard is busy, same as the music app
3432 if (status.equals(Environment.MEDIA_SHARED)) {
3433 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3434 title = R.string.download_sdcard_busy_dlg_title;
3435 } else {
3436 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3437 title = R.string.download_no_sdcard_dlg_title;
3438 }
3439
3440 new AlertDialog.Builder(this)
3441 .setTitle(title)
3442 .setIcon(android.R.drawable.ic_dialog_alert)
3443 .setMessage(msg)
3444 .setPositiveButton(R.string.ok, null)
3445 .show();
3446 return;
3447 }
3448
3449 // java.net.URI is a lot stricter than KURL so we have to undo
3450 // KURL's percent-encoding and redo the encoding using java.net.URI.
3451 URI uri = null;
3452 try {
3453 // Undo the percent-encoding that KURL may have done.
3454 String newUrl = new String(URLUtil.decode(url.getBytes()));
3455 // Parse the url into pieces
3456 WebAddress w = new WebAddress(newUrl);
3457 String frag = null;
3458 String query = null;
3459 String path = w.mPath;
3460 // Break the path into path, query, and fragment
3461 if (path.length() > 0) {
3462 // Strip the fragment
3463 int idx = path.lastIndexOf('#');
3464 if (idx != -1) {
3465 frag = path.substring(idx + 1);
3466 path = path.substring(0, idx);
3467 }
3468 idx = path.lastIndexOf('?');
3469 if (idx != -1) {
3470 query = path.substring(idx + 1);
3471 path = path.substring(0, idx);
3472 }
3473 }
3474 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3475 query, frag);
3476 } catch (Exception e) {
3477 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3478 return;
3479 }
3480
3481 // XXX: Have to use the old url since the cookies were stored using the
3482 // old percent-encoded url.
3483 String cookies = CookieManager.getInstance().getCookie(url);
3484
3485 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003486 values.put(Downloads.COLUMN_URI, uri.toString());
3487 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3488 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3489 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003490 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003491 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003492 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003493 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3494 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3495 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3496 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003497 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003498 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003499 }
3500 if (mimetype == null) {
3501 // We must have long pressed on a link or image to download it. We
3502 // are not sure of the mimetype in this case, so do a head request
3503 new FetchUrlMimeType(this).execute(values);
3504 } else {
3505 final Uri contentUri =
3506 getContentResolver().insert(Downloads.CONTENT_URI, values);
3507 viewDownloads(contentUri);
3508 }
3509
3510 }
3511
3512 /**
3513 * Resets the lock icon. This method is called when we start a new load and
3514 * know the url to be loaded.
3515 */
3516 private void resetLockIcon(String url) {
3517 // Save the lock-icon state (we revert to it if the load gets cancelled)
3518 saveLockIcon();
3519
3520 mLockIconType = LOCK_ICON_UNSECURE;
3521 if (URLUtil.isHttpsUrl(url)) {
3522 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003523 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003524 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3525 " reset lock icon to " + mLockIconType);
3526 }
3527 }
3528
3529 updateLockIconImage(LOCK_ICON_UNSECURE);
3530 }
3531
Grace Klobaeb6eef42009-09-15 17:56:32 -07003532 /* package */ void setLockIconType(int type) {
3533 mLockIconType = type;
3534 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003535
Grace Klobaeb6eef42009-09-15 17:56:32 -07003536 /* package */ int getLockIconType() {
3537 return mLockIconType;
3538 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003539
Grace Klobaeb6eef42009-09-15 17:56:32 -07003540 /* package */ void setPrevLockType(int type) {
3541 mPrevLockType = type;
3542 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003543
Grace Klobaeb6eef42009-09-15 17:56:32 -07003544 /* package */ int getPrevLockType() {
3545 return mPrevLockType;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003546 }
3547
3548 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003549 * Update the lock icon to correspond to our latest state.
3550 */
3551 /* package */ void updateLockIconToLatest() {
3552 updateLockIconImage(mLockIconType);
3553 }
3554
3555 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003556 * Updates the lock-icon image in the title-bar.
3557 */
3558 private void updateLockIconImage(int lockIconType) {
3559 Drawable d = null;
3560 if (lockIconType == LOCK_ICON_SECURE) {
3561 d = mSecLockIcon;
3562 } else if (lockIconType == LOCK_ICON_MIXED) {
3563 d = mMixLockIcon;
3564 }
Leon Scroggins68579392009-09-15 15:31:54 -04003565 mTitleBar.setLock(d);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003566 if (mFakeTitleBar != null) {
3567 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003568 }
3569 }
3570
3571 /**
3572 * Displays a page-info dialog.
3573 * @param tab The tab to show info about
3574 * @param fromShowSSLCertificateOnError The flag that indicates whether
3575 * this dialog was opened from the SSL-certificate-on-error dialog or
3576 * not. This is important, since we need to know whether to return to
3577 * the parent dialog or simply dismiss.
3578 */
3579 private void showPageInfo(final TabControl.Tab tab,
3580 final boolean fromShowSSLCertificateOnError) {
3581 final LayoutInflater factory = LayoutInflater
3582 .from(this);
3583
3584 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3585
3586 final WebView view = tab.getWebView();
3587
3588 String url = null;
3589 String title = null;
3590
3591 if (view == null) {
3592 url = tab.getUrl();
3593 title = tab.getTitle();
3594 } else if (view == mTabControl.getCurrentWebView()) {
3595 // Use the cached title and url if this is the current WebView
3596 url = mUrl;
3597 title = mTitle;
3598 } else {
3599 url = view.getUrl();
3600 title = view.getTitle();
3601 }
3602
3603 if (url == null) {
3604 url = "";
3605 }
3606 if (title == null) {
3607 title = "";
3608 }
3609
3610 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3611 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3612
3613 mPageInfoView = tab;
3614 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3615
3616 AlertDialog.Builder alertDialogBuilder =
3617 new AlertDialog.Builder(this)
3618 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3619 .setView(pageInfoView)
3620 .setPositiveButton(
3621 R.string.ok,
3622 new DialogInterface.OnClickListener() {
3623 public void onClick(DialogInterface dialog,
3624 int whichButton) {
3625 mPageInfoDialog = null;
3626 mPageInfoView = null;
3627 mPageInfoFromShowSSLCertificateOnError = null;
3628
3629 // if we came here from the SSL error dialog
3630 if (fromShowSSLCertificateOnError) {
3631 // go back to the SSL error dialog
3632 showSSLCertificateOnError(
3633 mSSLCertificateOnErrorView,
3634 mSSLCertificateOnErrorHandler,
3635 mSSLCertificateOnErrorError);
3636 }
3637 }
3638 })
3639 .setOnCancelListener(
3640 new DialogInterface.OnCancelListener() {
3641 public void onCancel(DialogInterface dialog) {
3642 mPageInfoDialog = null;
3643 mPageInfoView = null;
3644 mPageInfoFromShowSSLCertificateOnError = null;
3645
3646 // if we came here from the SSL error dialog
3647 if (fromShowSSLCertificateOnError) {
3648 // go back to the SSL error dialog
3649 showSSLCertificateOnError(
3650 mSSLCertificateOnErrorView,
3651 mSSLCertificateOnErrorHandler,
3652 mSSLCertificateOnErrorError);
3653 }
3654 }
3655 });
3656
3657 // if we have a main top-level page SSL certificate set or a certificate
3658 // error
3659 if (fromShowSSLCertificateOnError ||
3660 (view != null && view.getCertificate() != null)) {
3661 // add a 'View Certificate' button
3662 alertDialogBuilder.setNeutralButton(
3663 R.string.view_certificate,
3664 new DialogInterface.OnClickListener() {
3665 public void onClick(DialogInterface dialog,
3666 int whichButton) {
3667 mPageInfoDialog = null;
3668 mPageInfoView = null;
3669 mPageInfoFromShowSSLCertificateOnError = null;
3670
3671 // if we came here from the SSL error dialog
3672 if (fromShowSSLCertificateOnError) {
3673 // go back to the SSL error dialog
3674 showSSLCertificateOnError(
3675 mSSLCertificateOnErrorView,
3676 mSSLCertificateOnErrorHandler,
3677 mSSLCertificateOnErrorError);
3678 } else {
3679 // otherwise, display the top-most certificate from
3680 // the chain
3681 if (view.getCertificate() != null) {
3682 showSSLCertificate(tab);
3683 }
3684 }
3685 }
3686 });
3687 }
3688
3689 mPageInfoDialog = alertDialogBuilder.show();
3690 }
3691
3692 /**
3693 * Displays the main top-level page SSL certificate dialog
3694 * (accessible from the Page-Info dialog).
3695 * @param tab The tab to show certificate for.
3696 */
3697 private void showSSLCertificate(final TabControl.Tab tab) {
3698 final View certificateView =
3699 inflateCertificateView(tab.getWebView().getCertificate());
3700 if (certificateView == null) {
3701 return;
3702 }
3703
3704 LayoutInflater factory = LayoutInflater.from(this);
3705
3706 final LinearLayout placeholder =
3707 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3708
3709 LinearLayout ll = (LinearLayout) factory.inflate(
3710 R.layout.ssl_success, placeholder);
3711 ((TextView)ll.findViewById(R.id.success))
3712 .setText(R.string.ssl_certificate_is_valid);
3713
3714 mSSLCertificateView = tab;
3715 mSSLCertificateDialog =
3716 new AlertDialog.Builder(this)
3717 .setTitle(R.string.ssl_certificate).setIcon(
3718 R.drawable.ic_dialog_browser_certificate_secure)
3719 .setView(certificateView)
3720 .setPositiveButton(R.string.ok,
3721 new DialogInterface.OnClickListener() {
3722 public void onClick(DialogInterface dialog,
3723 int whichButton) {
3724 mSSLCertificateDialog = null;
3725 mSSLCertificateView = null;
3726
3727 showPageInfo(tab, false);
3728 }
3729 })
3730 .setOnCancelListener(
3731 new DialogInterface.OnCancelListener() {
3732 public void onCancel(DialogInterface dialog) {
3733 mSSLCertificateDialog = null;
3734 mSSLCertificateView = null;
3735
3736 showPageInfo(tab, false);
3737 }
3738 })
3739 .show();
3740 }
3741
3742 /**
3743 * Displays the SSL error certificate dialog.
3744 * @param view The target web-view.
3745 * @param handler The SSL error handler responsible for cancelling the
3746 * connection that resulted in an SSL error or proceeding per user request.
3747 * @param error The SSL error object.
3748 */
3749 private void showSSLCertificateOnError(
3750 final WebView view, final SslErrorHandler handler, final SslError error) {
3751
3752 final View certificateView =
3753 inflateCertificateView(error.getCertificate());
3754 if (certificateView == null) {
3755 return;
3756 }
3757
3758 LayoutInflater factory = LayoutInflater.from(this);
3759
3760 final LinearLayout placeholder =
3761 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3762
3763 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3764 LinearLayout ll = (LinearLayout)factory
3765 .inflate(R.layout.ssl_warning, placeholder);
3766 ((TextView)ll.findViewById(R.id.warning))
3767 .setText(R.string.ssl_untrusted);
3768 }
3769
3770 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3771 LinearLayout ll = (LinearLayout)factory
3772 .inflate(R.layout.ssl_warning, placeholder);
3773 ((TextView)ll.findViewById(R.id.warning))
3774 .setText(R.string.ssl_mismatch);
3775 }
3776
3777 if (error.hasError(SslError.SSL_EXPIRED)) {
3778 LinearLayout ll = (LinearLayout)factory
3779 .inflate(R.layout.ssl_warning, placeholder);
3780 ((TextView)ll.findViewById(R.id.warning))
3781 .setText(R.string.ssl_expired);
3782 }
3783
3784 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3785 LinearLayout ll = (LinearLayout)factory
3786 .inflate(R.layout.ssl_warning, placeholder);
3787 ((TextView)ll.findViewById(R.id.warning))
3788 .setText(R.string.ssl_not_yet_valid);
3789 }
3790
3791 mSSLCertificateOnErrorHandler = handler;
3792 mSSLCertificateOnErrorView = view;
3793 mSSLCertificateOnErrorError = error;
3794 mSSLCertificateOnErrorDialog =
3795 new AlertDialog.Builder(this)
3796 .setTitle(R.string.ssl_certificate).setIcon(
3797 R.drawable.ic_dialog_browser_certificate_partially_secure)
3798 .setView(certificateView)
3799 .setPositiveButton(R.string.ok,
3800 new DialogInterface.OnClickListener() {
3801 public void onClick(DialogInterface dialog,
3802 int whichButton) {
3803 mSSLCertificateOnErrorDialog = null;
3804 mSSLCertificateOnErrorView = null;
3805 mSSLCertificateOnErrorHandler = null;
3806 mSSLCertificateOnErrorError = null;
3807
3808 mWebViewClient.onReceivedSslError(
3809 view, handler, error);
3810 }
3811 })
3812 .setNeutralButton(R.string.page_info_view,
3813 new DialogInterface.OnClickListener() {
3814 public void onClick(DialogInterface dialog,
3815 int whichButton) {
3816 mSSLCertificateOnErrorDialog = null;
3817
3818 // do not clear the dialog state: we will
3819 // need to show the dialog again once the
3820 // user is done exploring the page-info details
3821
3822 showPageInfo(mTabControl.getTabFromView(view),
3823 true);
3824 }
3825 })
3826 .setOnCancelListener(
3827 new DialogInterface.OnCancelListener() {
3828 public void onCancel(DialogInterface dialog) {
3829 mSSLCertificateOnErrorDialog = null;
3830 mSSLCertificateOnErrorView = null;
3831 mSSLCertificateOnErrorHandler = null;
3832 mSSLCertificateOnErrorError = null;
3833
3834 mWebViewClient.onReceivedSslError(
3835 view, handler, error);
3836 }
3837 })
3838 .show();
3839 }
3840
3841 /**
3842 * Inflates the SSL certificate view (helper method).
3843 * @param certificate The SSL certificate.
3844 * @return The resultant certificate view with issued-to, issued-by,
3845 * issued-on, expires-on, and possibly other fields set.
3846 * If the input certificate is null, returns null.
3847 */
3848 private View inflateCertificateView(SslCertificate certificate) {
3849 if (certificate == null) {
3850 return null;
3851 }
3852
3853 LayoutInflater factory = LayoutInflater.from(this);
3854
3855 View certificateView = factory.inflate(
3856 R.layout.ssl_certificate, null);
3857
3858 // issued to:
3859 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3860 if (issuedTo != null) {
3861 ((TextView) certificateView.findViewById(R.id.to_common))
3862 .setText(issuedTo.getCName());
3863 ((TextView) certificateView.findViewById(R.id.to_org))
3864 .setText(issuedTo.getOName());
3865 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3866 .setText(issuedTo.getUName());
3867 }
3868
3869 // issued by:
3870 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3871 if (issuedBy != null) {
3872 ((TextView) certificateView.findViewById(R.id.by_common))
3873 .setText(issuedBy.getCName());
3874 ((TextView) certificateView.findViewById(R.id.by_org))
3875 .setText(issuedBy.getOName());
3876 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3877 .setText(issuedBy.getUName());
3878 }
3879
3880 // issued on:
3881 String issuedOn = reformatCertificateDate(
3882 certificate.getValidNotBefore());
3883 ((TextView) certificateView.findViewById(R.id.issued_on))
3884 .setText(issuedOn);
3885
3886 // expires on:
3887 String expiresOn = reformatCertificateDate(
3888 certificate.getValidNotAfter());
3889 ((TextView) certificateView.findViewById(R.id.expires_on))
3890 .setText(expiresOn);
3891
3892 return certificateView;
3893 }
3894
3895 /**
3896 * Re-formats the certificate date (Date.toString()) string to
3897 * a properly localized date string.
3898 * @return Properly localized version of the certificate date string and
3899 * the original certificate date string if fails to localize.
3900 * If the original string is null, returns an empty string "".
3901 */
3902 private String reformatCertificateDate(String certificateDate) {
3903 String reformattedDate = null;
3904
3905 if (certificateDate != null) {
3906 Date date = null;
3907 try {
3908 date = java.text.DateFormat.getInstance().parse(certificateDate);
3909 } catch (ParseException e) {
3910 date = null;
3911 }
3912
3913 if (date != null) {
3914 reformattedDate =
3915 DateFormat.getDateFormat(this).format(date);
3916 }
3917 }
3918
3919 return reformattedDate != null ? reformattedDate :
3920 (certificateDate != null ? certificateDate : "");
3921 }
3922
3923 /**
3924 * Displays an http-authentication dialog.
3925 */
3926 private void showHttpAuthentication(final HttpAuthHandler handler,
3927 final String host, final String realm, final String title,
3928 final String name, final String password, int focusId) {
3929 LayoutInflater factory = LayoutInflater.from(this);
3930 final View v = factory
3931 .inflate(R.layout.http_authentication, null);
3932 if (name != null) {
3933 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3934 }
3935 if (password != null) {
3936 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3937 }
3938
3939 String titleText = title;
3940 if (titleText == null) {
3941 titleText = getText(R.string.sign_in_to).toString().replace(
3942 "%s1", host).replace("%s2", realm);
3943 }
3944
3945 mHttpAuthHandler = handler;
3946 AlertDialog dialog = new AlertDialog.Builder(this)
3947 .setTitle(titleText)
3948 .setIcon(android.R.drawable.ic_dialog_alert)
3949 .setView(v)
3950 .setPositiveButton(R.string.action,
3951 new DialogInterface.OnClickListener() {
3952 public void onClick(DialogInterface dialog,
3953 int whichButton) {
3954 String nm = ((EditText) v
3955 .findViewById(R.id.username_edit))
3956 .getText().toString();
3957 String pw = ((EditText) v
3958 .findViewById(R.id.password_edit))
3959 .getText().toString();
3960 BrowserActivity.this.setHttpAuthUsernamePassword
3961 (host, realm, nm, pw);
3962 handler.proceed(nm, pw);
3963 mHttpAuthenticationDialog = null;
3964 mHttpAuthHandler = null;
3965 }})
3966 .setNegativeButton(R.string.cancel,
3967 new DialogInterface.OnClickListener() {
3968 public void onClick(DialogInterface dialog,
3969 int whichButton) {
3970 handler.cancel();
3971 BrowserActivity.this.resetTitleAndRevertLockIcon();
3972 mHttpAuthenticationDialog = null;
3973 mHttpAuthHandler = null;
3974 }})
3975 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3976 public void onCancel(DialogInterface dialog) {
3977 handler.cancel();
3978 BrowserActivity.this.resetTitleAndRevertLockIcon();
3979 mHttpAuthenticationDialog = null;
3980 mHttpAuthHandler = null;
3981 }})
3982 .create();
3983 // Make the IME appear when the dialog is displayed if applicable.
3984 dialog.getWindow().setSoftInputMode(
3985 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3986 dialog.show();
3987 if (focusId != 0) {
3988 dialog.findViewById(focusId).requestFocus();
3989 } else {
3990 v.findViewById(R.id.username_edit).requestFocus();
3991 }
3992 mHttpAuthenticationDialog = dialog;
3993 }
3994
3995 public int getProgress() {
3996 WebView w = mTabControl.getCurrentWebView();
3997 if (w != null) {
3998 return w.getProgress();
3999 } else {
4000 return 100;
4001 }
4002 }
4003
4004 /**
4005 * Set HTTP authentication password.
4006 *
4007 * @param host The host for the password
4008 * @param realm The realm for the password
4009 * @param username The username for the password. If it is null, it means
4010 * password can't be saved.
4011 * @param password The password
4012 */
4013 public void setHttpAuthUsernamePassword(String host, String realm,
4014 String username,
4015 String password) {
4016 WebView w = mTabControl.getCurrentWebView();
4017 if (w != null) {
4018 w.setHttpAuthUsernamePassword(host, realm, username, password);
4019 }
4020 }
4021
4022 /**
4023 * connectivity manager says net has come or gone... inform the user
4024 * @param up true if net has come up, false if net has gone down
4025 */
4026 public void onNetworkToggle(boolean up) {
4027 if (up == mIsNetworkUp) {
4028 return;
4029 } else if (up) {
4030 mIsNetworkUp = true;
4031 if (mAlertDialog != null) {
4032 mAlertDialog.cancel();
4033 mAlertDialog = null;
4034 }
4035 } else {
4036 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004037 if (mInLoad) {
4038 createAndShowNetworkDialog();
4039 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004040 }
4041 WebView w = mTabControl.getCurrentWebView();
4042 if (w != null) {
4043 w.setNetworkAvailable(up);
4044 }
4045 }
4046
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004047 // This method shows the network dialog alerting the user that the net is
4048 // down. It will only show the dialog if mAlertDialog is null.
4049 private void createAndShowNetworkDialog() {
4050 if (mAlertDialog == null) {
4051 mAlertDialog = new AlertDialog.Builder(this)
4052 .setTitle(R.string.loadSuspendedTitle)
4053 .setMessage(R.string.loadSuspended)
4054 .setPositiveButton(R.string.ok, null)
4055 .show();
4056 }
4057 }
4058
The Android Open Source Project0c908882009-03-03 19:32:16 -08004059 @Override
4060 protected void onActivityResult(int requestCode, int resultCode,
4061 Intent intent) {
4062 switch (requestCode) {
4063 case COMBO_PAGE:
4064 if (resultCode == RESULT_OK && intent != null) {
4065 String data = intent.getAction();
4066 Bundle extras = intent.getExtras();
4067 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04004068 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004069 } else {
4070 final TabControl.Tab currentTab =
4071 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04004072 dismissSubWindow(currentTab);
4073 if (data != null && data.length() != 0) {
4074 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004075 }
4076 }
4077 }
4078 break;
4079 default:
4080 break;
4081 }
Leon Scroggins30444232009-09-04 18:36:20 -04004082 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004083 }
4084
4085 /*
4086 * This method is called as a result of the user selecting the options
4087 * menu to see the download window, or when a download changes state. It
4088 * shows the download window ontop of the current window.
4089 */
4090 /* package */ void viewDownloads(Uri downloadRecord) {
4091 Intent intent = new Intent(this,
4092 BrowserDownloadPage.class);
4093 intent.setData(downloadRecord);
4094 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4095
4096 }
4097
Leon Scroggins160a7e72009-08-14 18:28:01 -04004098 /**
4099 * Open the Go page.
4100 * @param startWithHistory If true, open starting on the history tab.
4101 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004102 */
Leon Scroggins30444232009-09-04 18:36:20 -04004103 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004104 WebView current = mTabControl.getCurrentWebView();
4105 if (current == null) {
4106 return;
4107 }
4108 Intent intent = new Intent(this,
4109 CombinedBookmarkHistoryActivity.class);
4110 String title = current.getTitle();
4111 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004112 Bitmap thumbnail = createScreenshot(current);
4113
The Android Open Source Project0c908882009-03-03 19:32:16 -08004114 // Just in case the user opens bookmarks before a page finishes loading
4115 // so the current history item, and therefore the page, is null.
4116 if (null == url) {
4117 url = mLastEnteredUrl;
4118 // This can happen.
4119 if (null == url) {
4120 url = mSettings.getHomePage();
4121 }
4122 }
4123 // In case the web page has not yet received its associated title.
4124 if (title == null) {
4125 title = url;
4126 }
4127 intent.putExtra("title", title);
4128 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004129 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04004130 // Disable opening in a new window if we have maxed out the windows
4131 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4132 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004133 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004134 if (startWithHistory) {
4135 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4136 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4137 }
4138 startActivityForResult(intent, COMBO_PAGE);
4139 }
4140
4141 // Called when loading from context menu or LOAD_URL message
4142 private void loadURL(WebView view, String url) {
4143 // In case the user enters nothing.
4144 if (url != null && url.length() != 0 && view != null) {
4145 url = smartUrlFilter(url);
4146 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4147 view.loadUrl(url);
4148 }
4149 }
4150 }
4151
The Android Open Source Project0c908882009-03-03 19:32:16 -08004152 private String smartUrlFilter(Uri inUri) {
4153 if (inUri != null) {
4154 return smartUrlFilter(inUri.toString());
4155 }
4156 return null;
4157 }
4158
4159
4160 // get window count
4161
4162 int getWindowCount(){
4163 if(mTabControl != null){
4164 return mTabControl.getTabCount();
4165 }
4166 return 0;
4167 }
4168
Feng Qianb34f87a2009-03-24 21:27:26 -07004169 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004170 "(?i)" + // switch on case insensitive matching
4171 "(" + // begin group for schema
4172 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004173 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004174 ")" +
4175 "(.*)" );
4176
4177 /**
4178 * Attempts to determine whether user input is a URL or search
4179 * terms. Anything with a space is passed to search.
4180 *
4181 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4182 * "Http://" converts to "http://"
4183 *
4184 * @return Original or modified URL
4185 *
4186 */
4187 String smartUrlFilter(String url) {
4188
4189 String inUrl = url.trim();
4190 boolean hasSpace = inUrl.indexOf(' ') != -1;
4191
4192 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4193 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004194 // force scheme to lowercase
4195 String scheme = matcher.group(1);
4196 String lcScheme = scheme.toLowerCase();
4197 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004198 inUrl = lcScheme + matcher.group(2);
4199 }
4200 if (hasSpace) {
4201 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004202 }
4203 return inUrl;
4204 }
4205 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004206 // FIXME: Is this the correct place to add to searches?
4207 // what if someone else calls this function?
4208 int shortcut = parseUrlShortcut(inUrl);
4209 if (shortcut != SHORTCUT_INVALID) {
4210 Browser.addSearchUrl(mResolver, inUrl);
4211 String query = inUrl.substring(2);
4212 switch (shortcut) {
4213 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004214 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004215 case SHORTCUT_WIKIPEDIA_SEARCH:
4216 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4217 case SHORTCUT_DICTIONARY_SEARCH:
4218 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4219 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004220 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004221 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004222 }
4223 }
4224 } else {
4225 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4226 return URLUtil.guessUrl(inUrl);
4227 }
4228 }
4229
4230 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004231 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004232 }
4233
Ben Murdochbff2d602009-07-01 20:19:05 +01004234 /* package */ void setShouldShowErrorConsole(boolean flag) {
4235 if (flag == mShouldShowErrorConsole) {
4236 // Nothing to do.
4237 return;
4238 }
4239
4240 mShouldShowErrorConsole = flag;
4241
4242 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4243
4244 if (flag) {
4245 // Setting the show state of the console will cause it's the layout to be inflated.
4246 if (errorConsole.numberOfErrors() > 0) {
4247 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4248 } else {
4249 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4250 }
4251
4252 // Now we can add it to the main view.
4253 mErrorConsoleContainer.addView(errorConsole,
4254 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4255 ViewGroup.LayoutParams.WRAP_CONTENT));
4256 } else {
4257 mErrorConsoleContainer.removeView(errorConsole);
4258 }
4259
4260 }
4261
Grace Klobaeb6eef42009-09-15 17:56:32 -07004262 final static int LOCK_ICON_UNSECURE = 0;
4263 final static int LOCK_ICON_SECURE = 1;
4264 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004265
4266 private int mLockIconType = LOCK_ICON_UNSECURE;
4267 private int mPrevLockType = LOCK_ICON_UNSECURE;
4268
4269 private BrowserSettings mSettings;
4270 private TabControl mTabControl;
4271 private ContentResolver mResolver;
4272 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004273 private View mCustomView;
4274 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004275 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004276
4277 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4278 // view, we should rewrite this.
4279 private int mCurrentMenuState = 0;
4280 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004281 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004282 private static final int EMPTY_MENU = -1;
4283 private Menu mMenu;
4284
4285 private FindDialog mFindDialog;
4286 // Used to prevent chording to result in firing two shortcuts immediately
4287 // one after another. Fixes bug 1211714.
4288 boolean mCanChord;
4289
4290 private boolean mInLoad;
4291 private boolean mIsNetworkUp;
4292
4293 private boolean mPageStarted;
4294 private boolean mActivityInPause = true;
4295
4296 private boolean mMenuIsDown;
4297
The Android Open Source Project0c908882009-03-03 19:32:16 -08004298 private static boolean mInTrace;
4299
4300 // Performance probe
4301 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4302 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4303 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4304 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4305 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4306 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4307 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4308 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4309 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4310 };
4311
4312 private long mStart;
4313 private long mProcessStart;
4314 private long mUserStart;
4315 private long mSystemStart;
4316 private long mIdleStart;
4317 private long mIrqStart;
4318
4319 private long mUiStart;
4320
4321 private Drawable mMixLockIcon;
4322 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004323
4324 /* hold a ref so we can auto-cancel if necessary */
4325 private AlertDialog mAlertDialog;
4326
4327 // Wait for credentials before loading google.com
4328 private ProgressDialog mCredsDlg;
4329
4330 // The up-to-date URL and title (these can be different from those stored
4331 // in WebView, since it takes some time for the information in WebView to
4332 // get updated)
4333 private String mUrl;
4334 private String mTitle;
4335
4336 // As PageInfo has different style for landscape / portrait, we have
4337 // to re-open it when configuration changed
4338 private AlertDialog mPageInfoDialog;
4339 private TabControl.Tab mPageInfoView;
4340 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4341 // dialog, we should not just dismiss it, but should get back to the
4342 // SSL-certificate-on-error dialog. This flag is used to store this state
4343 private Boolean mPageInfoFromShowSSLCertificateOnError;
4344
4345 // as SSLCertificateOnError has different style for landscape / portrait,
4346 // we have to re-open it when configuration changed
4347 private AlertDialog mSSLCertificateOnErrorDialog;
4348 private WebView mSSLCertificateOnErrorView;
4349 private SslErrorHandler mSSLCertificateOnErrorHandler;
4350 private SslError mSSLCertificateOnErrorError;
4351
4352 // as SSLCertificate has different style for landscape / portrait, we
4353 // have to re-open it when configuration changed
4354 private AlertDialog mSSLCertificateDialog;
4355 private TabControl.Tab mSSLCertificateView;
4356
4357 // as HttpAuthentication has different style for landscape / portrait, we
4358 // have to re-open it when configuration changed
4359 private AlertDialog mHttpAuthenticationDialog;
4360 private HttpAuthHandler mHttpAuthHandler;
4361
4362 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4363 new FrameLayout.LayoutParams(
4364 ViewGroup.LayoutParams.FILL_PARENT,
4365 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004366 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4367 new FrameLayout.LayoutParams(
4368 ViewGroup.LayoutParams.FILL_PARENT,
4369 ViewGroup.LayoutParams.FILL_PARENT,
4370 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004371 // Google search
4372 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004373 // Wikipedia search
4374 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4375 // Dictionary search
4376 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4377 // Google Mobile Local search
4378 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4379
4380 final static String QUERY_PLACE_HOLDER = "%s";
4381
4382 // "source" parameter for Google search through search key
4383 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4384 // "source" parameter for Google search through goto menu
4385 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4386 // "source" parameter for Google search through simplily type
4387 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4388 // "source" parameter for Google search suggested by the browser
4389 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4390 // "source" parameter for Google search from unknown source
4391 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4392
4393 private final static String LOGTAG = "browser";
4394
The Android Open Source Project0c908882009-03-03 19:32:16 -08004395 private String mLastEnteredUrl;
4396
4397 private PowerManager.WakeLock mWakeLock;
4398 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4399
4400 private Toast mStopToast;
4401
Leon Scroggins68579392009-09-15 15:31:54 -04004402 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004403
Ben Murdochbff2d602009-07-01 20:19:05 +01004404 private LinearLayout mErrorConsoleContainer = null;
4405 private boolean mShouldShowErrorConsole = false;
4406
The Android Open Source Project0c908882009-03-03 19:32:16 -08004407 // As the ids are dynamically created, we can't guarantee that they will
4408 // be in sequence, so this static array maps ids to a window number.
4409 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4410 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4411 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4412 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4413
4414 // monitor platform changes
4415 private IntentFilter mNetworkStateChangedFilter;
4416 private BroadcastReceiver mNetworkStateIntentReceiver;
4417
Grace Klobab4da0ad2009-05-14 14:45:40 -07004418 private BroadcastReceiver mPackageInstallationReceiver;
4419
Patrick Scott59ce8302009-09-18 16:29:38 -04004420 // AsyncTask for downloading touch icons
4421 /* package */ DownloadTouchIcon mTouchIconLoader;
4422
The Android Open Source Project0c908882009-03-03 19:32:16 -08004423 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004424 final static int COMBO_PAGE = 1;
4425 final static int DOWNLOAD_PAGE = 2;
4426 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004427
Andrei Popescu540035d2009-09-18 18:59:20 +01004428 // the default <video> poster
4429 private Bitmap mDefaultVideoPoster;
4430 // the video progress view
4431 private View mVideoProgressView;
4432
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004433 /**
4434 * A UrlData class to abstract how the content will be set to WebView.
4435 * This base class uses loadUrl to show the content.
4436 */
4437 private static class UrlData {
4438 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004439 byte[] mPostData;
4440
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004441 UrlData(String url) {
4442 this.mUrl = url;
4443 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004444
4445 void setPostData(byte[] postData) {
4446 mPostData = postData;
4447 }
4448
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004449 boolean isEmpty() {
4450 return mUrl == null || mUrl.length() == 0;
4451 }
4452
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004453 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004454 if (mPostData != null) {
4455 webView.postUrl(mUrl, mPostData);
4456 } else {
4457 webView.loadUrl(mUrl);
4458 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004459 }
4460 };
4461
4462 /**
4463 * A subclass of UrlData class that can display inlined content using
4464 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4465 */
4466 private static class InlinedUrlData extends UrlData {
4467 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4468 super(failUrl);
4469 mInlined = inlined;
4470 mMimeType = mimeType;
4471 mEncoding = encoding;
4472 }
4473 String mMimeType;
4474 String mInlined;
4475 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004476 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004477 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004478 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004479 }
4480
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004481 @Override
4482 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004483 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4484 }
4485 }
4486
Leon Scroggins1f005d32009-08-10 17:36:42 -04004487 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004488}