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