blob: c4797addd775f6ac7d676d0959e2b980bd2281d7 [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;
79import android.provider.Contacts;
80import android.provider.Downloads;
81import android.provider.MediaStore;
82import android.provider.Contacts.Intents.Insert;
83import android.text.IClipboard;
84import android.text.TextUtils;
85import android.text.format.DateFormat;
86import android.text.util.Regex;
The Android Open Source Project0c908882009-03-03 19:32:16 -080087import android.util.Log;
88import android.view.ContextMenu;
89import android.view.Gravity;
90import android.view.KeyEvent;
91import android.view.LayoutInflater;
92import android.view.Menu;
93import android.view.MenuInflater;
94import android.view.MenuItem;
95import android.view.View;
96import android.view.ViewGroup;
97import android.view.Window;
98import android.view.WindowManager;
99import android.view.ContextMenu.ContextMenuInfo;
100import android.view.MenuItem.OnMenuItemClickListener;
101import android.view.animation.AlphaAnimation;
102import android.view.animation.Animation;
103import android.view.animation.AnimationSet;
104import android.view.animation.DecelerateInterpolator;
105import android.view.animation.ScaleAnimation;
106import android.view.animation.TranslateAnimation;
107import android.webkit.CookieManager;
108import android.webkit.CookieSyncManager;
109import android.webkit.DownloadListener;
Steve Block2bc69912009-07-30 14:45:13 +0100110import android.webkit.GeolocationPermissions;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800111import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -0700112import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113import android.webkit.SslErrorHandler;
114import android.webkit.URLUtil;
115import android.webkit.WebChromeClient;
Andrei Popescuc9b55562009-07-07 10:51:15 +0100116import android.webkit.WebChromeClient.CustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import android.webkit.WebHistoryItem;
118import android.webkit.WebIconDatabase;
Ben Murdoch092dd5d2009-04-22 12:34:12 +0100119import android.webkit.WebStorage;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import android.webkit.WebView;
121import android.webkit.WebViewClient;
122import android.widget.EditText;
123import android.widget.FrameLayout;
124import android.widget.LinearLayout;
125import android.widget.TextView;
126import android.widget.Toast;
127
128import java.io.BufferedOutputStream;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400129import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130import java.io.File;
131import java.io.FileInputStream;
132import java.io.FileOutputStream;
133import java.io.IOException;
134import java.io.InputStream;
135import java.net.MalformedURLException;
136import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700137import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800138import java.net.URL;
139import java.net.URLEncoder;
140import java.text.ParseException;
141import java.util.Date;
142import java.util.Enumeration;
143import java.util.HashMap;
Patrick Scott37911c72009-03-24 18:02:58 -0700144import java.util.LinkedList;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800145import java.util.Vector;
146import java.util.regex.Matcher;
147import java.util.regex.Pattern;
148import java.util.zip.ZipEntry;
149import java.util.zip.ZipFile;
150
151public class BrowserActivity extends Activity
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
The Android Open Source Project0c908882009-03-03 19:32:16 -0800308 //
309 // start MASF proxy service
310 //
311 //Intent proxyServiceIntent = new Intent();
312 //proxyServiceIntent.setComponent
313 // (new ComponentName(
314 // "com.android.masfproxyservice",
315 // "com.android.masfproxyservice.MasfProxyService"));
316 //startService(proxyServiceIntent, null);
317
318 mSecLockIcon = Resources.getSystem().getDrawable(
319 android.R.drawable.ic_secure);
320 mMixLockIcon = Resources.getSystem().getDrawable(
321 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800322
Leon Scroggins81db3662009-06-04 17:45:11 -0400323 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
324 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400325 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
326 .inflate(R.layout.custom_screen, null);
327 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
328 R.id.main_content);
329 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
330 .findViewById(R.id.error_console);
331 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
332 .findViewById(R.id.fullscreen_custom_content);
333 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400334 mTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800335
336 // Create the tab control and our initial tab
337 mTabControl = new TabControl(this);
338
339 // Open the icon database and retain all the bookmark urls for favicons
340 retainIconsOnStartup();
341
342 // Keep a settings instance handy.
343 mSettings = BrowserSettings.getInstance();
344 mSettings.setTabControl(mTabControl);
345 mSettings.loadFromDb(this);
346
347 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
348 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
349
Grace Klobaa34f6862009-07-31 16:28:17 -0700350 /* enables registration for changes in network status from
351 http stack */
352 mNetworkStateChangedFilter = new IntentFilter();
353 mNetworkStateChangedFilter.addAction(
354 ConnectivityManager.CONNECTIVITY_ACTION);
355 mNetworkStateIntentReceiver = new BroadcastReceiver() {
356 @Override
357 public void onReceive(Context context, Intent intent) {
358 if (intent.getAction().equals(
359 ConnectivityManager.CONNECTIVITY_ACTION)) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -0400360 NetworkInfo info =
361 (NetworkInfo) intent.getParcelableExtra(
362 ConnectivityManager.EXTRA_NETWORK_INFO);
363 onNetworkToggle(
364 (info != null) ? info.isConnected() : false);
Grace Klobaa34f6862009-07-31 16:28:17 -0700365 }
366 }
367 };
368
Grace Kloba615c6c92009-08-03 10:22:44 -0700369 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
370 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
371 filter.addDataScheme("package");
372 mPackageInstallationReceiver = new BroadcastReceiver() {
373 @Override
374 public void onReceive(Context context, Intent intent) {
375 final String action = intent.getAction();
376 final String packageName = intent.getData()
377 .getSchemeSpecificPart();
378 final boolean replacing = intent.getBooleanExtra(
379 Intent.EXTRA_REPLACING, false);
380 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
381 // if it is replacing, refreshPlugins() when adding
382 return;
383 }
384 PackageManager pm = BrowserActivity.this.getPackageManager();
385 PackageInfo pkgInfo = null;
386 try {
387 pkgInfo = pm.getPackageInfo(packageName,
388 PackageManager.GET_PERMISSIONS);
389 } catch (PackageManager.NameNotFoundException e) {
390 return;
391 }
392 if (pkgInfo != null) {
393 String permissions[] = pkgInfo.requestedPermissions;
394 if (permissions == null) {
395 return;
396 }
397 boolean permissionOk = false;
398 for (String permit : permissions) {
399 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
400 permissionOk = true;
401 break;
402 }
403 }
404 if (permissionOk) {
405 PluginManager.getInstance(BrowserActivity.this)
406 .refreshPlugins(
407 Intent.ACTION_PACKAGE_ADDED
408 .equals(action));
409 }
410 }
411 }
412 };
413 registerReceiver(mPackageInstallationReceiver, filter);
414
Satish Sampath565505b2009-05-29 15:37:27 +0100415 // If this was a web search request, pass it on to the default web search provider.
416 if (handleWebSearchIntent(getIntent())) {
417 moveTaskToBack(true);
418 return;
419 }
420
The Android Open Source Project0c908882009-03-03 19:32:16 -0800421 if (!mTabControl.restoreState(icicle)) {
422 // clear up the thumbnail directory if we can't restore the state as
423 // none of the files in the directory are referenced any more.
424 new ClearThumbnails().execute(
425 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700426 // there is no quit on Android. But if we can't restore the state,
427 // we can treat it as a new Browser, remove the old session cookies.
428 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800429 final Intent intent = getIntent();
430 final Bundle extra = intent.getExtras();
431 // Create an initial tab.
432 // If the intent is ACTION_VIEW and data is not null, the Browser is
433 // invoked to view the content by another application. In this case,
434 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700435 UrlData urlData = getUrlDataFromIntent(intent);
436
The Android Open Source Project0c908882009-03-03 19:32:16 -0800437 final TabControl.Tab t = mTabControl.createNewTab(
438 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700439 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700440 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800441 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800442 attachTabToContentView(t);
443 WebView webView = t.getWebView();
444 if (extra != null) {
445 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
446 if (scale > 0 && scale <= 1000) {
447 webView.setInitialScale(scale);
448 }
449 }
450 // If we are not restoring from an icicle, then there is a high
451 // likely hood this is the first run. So, check to see if the
452 // homepage needs to be configured and copy any plugins from our
453 // asset directory to the data partition.
454 if ((extra == null || !extra.getBoolean("testing"))
455 && !mSettings.isLoginInitialized()) {
456 setupHomePage();
457 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800458
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700459 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400460 if (mSettings.isLoginInitialized()) {
461 webView.loadUrl(mSettings.getHomePage());
462 } else {
463 waitForCredentials();
464 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800465 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700466 if (extra != null) {
467 urlData.setPostData(extra
468 .getByteArray(Browser.EXTRA_POST_DATA));
469 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700470 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800471 }
472 } else {
473 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400474 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800475 attachTabToContentView(mTabControl.getCurrentTab());
476 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700477
Feng Qianb3c02da2009-06-29 15:58:08 -0700478 // Read JavaScript flags if it exists.
479 String jsFlags = mSettings.getJsFlags();
480 if (jsFlags.trim().length() != 0) {
481 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
482 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800483 }
484
485 @Override
486 protected void onNewIntent(Intent intent) {
487 TabControl.Tab current = mTabControl.getCurrentTab();
488 // When a tab is closed on exit, the current tab index is set to -1.
489 // Reset before proceed as Browser requires the current tab to be set.
490 if (current == null) {
491 // Try to reset the tab in case the index was incorrect.
492 current = mTabControl.getTab(0);
493 if (current == null) {
494 // No tabs at all so just ignore this intent.
495 return;
496 }
497 mTabControl.setCurrentTab(current);
498 attachTabToContentView(current);
499 resetTitleAndIcon(current.getWebView());
500 }
501 final String action = intent.getAction();
502 final int flags = intent.getFlags();
503 if (Intent.ACTION_MAIN.equals(action) ||
504 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
505 // just resume the browser
506 return;
507 }
508 if (Intent.ACTION_VIEW.equals(action)
509 || Intent.ACTION_SEARCH.equals(action)
510 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
511 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100512 // If this was a search request (e.g. search query directly typed into the address bar),
513 // pass it on to the default web search provider.
514 if (handleWebSearchIntent(intent)) {
515 return;
516 }
517
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700518 UrlData urlData = getUrlDataFromIntent(intent);
519 if (urlData.isEmpty()) {
520 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800521 }
Grace Kloba81678d92009-06-30 07:09:56 -0700522 urlData.setPostData(intent
523 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700524
Grace Klobacc634032009-07-28 15:58:19 -0700525 final String appId = intent
526 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
527 if (Intent.ACTION_VIEW.equals(action)
528 && !getPackageName().equals(appId)
529 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Patrick Scottcd115892009-07-16 09:42:58 -0400530 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700531 if (appTab != null) {
532 Log.i(LOGTAG, "Reusing tab for " + appId);
533 // Dismiss the subwindow if applicable.
534 dismissSubWindow(appTab);
535 // Since we might kill the WebView, remove it from the
536 // content view first.
537 removeTabFromContentView(appTab);
538 // Recreate the main WebView after destroying the old one.
539 // If the WebView has the same original url and is on that
540 // page, it can be reused.
541 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700542 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100543
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700544 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400545 switchToTab(mTabControl.getTabIndex(appTab));
546 if (needsLoad) {
547 urlData.loadIn(appTab.getWebView());
548 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700549 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400550 // If the tab was the current tab, we have to attach
551 // it to the view system again.
552 attachTabToContentView(appTab);
553 if (needsLoad) {
554 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700555 }
556 }
557 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400558 } else {
559 // No matching application tab, try to find a regular tab
560 // with a matching url.
561 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400562 if (appTab != null) {
563 if (current != appTab) {
564 switchToTab(mTabControl.getTabIndex(appTab));
565 }
566 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400567 } else {
568 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
569 // will be opened in a new tab unless we have reached
570 // MAX_TABS. Then the url will be opened in the current
571 // tab. If a new tab is created, it will have "true" for
572 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400573 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400574 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700575 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800576 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700577 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800578 mSettings.toggleDebugSettings();
579 return;
580 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400581 // Get rid of the subwindow if it exists
582 dismissSubWindow(current);
583 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800584 }
585 }
586 }
587
Satish Sampath565505b2009-05-29 15:37:27 +0100588 private int parseUrlShortcut(String url) {
589 if (url == null) return SHORTCUT_INVALID;
590
591 // FIXME: quick search, need to be customized by setting
592 if (url.length() > 2 && url.charAt(1) == ' ') {
593 switch (url.charAt(0)) {
594 case 'g': return SHORTCUT_GOOGLE_SEARCH;
595 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
596 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
597 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
598 }
599 }
600 return SHORTCUT_INVALID;
601 }
602
603 /**
604 * Launches the default web search activity with the query parameters if the given intent's data
605 * are identified as plain search terms and not URLs/shortcuts.
606 * @return true if the intent was handled and web search activity was launched, false if not.
607 */
608 private boolean handleWebSearchIntent(Intent intent) {
609 if (intent == null) return false;
610
611 String url = null;
612 final String action = intent.getAction();
613 if (Intent.ACTION_VIEW.equals(action)) {
614 url = intent.getData().toString();
615 } else if (Intent.ACTION_SEARCH.equals(action)
616 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
617 || Intent.ACTION_WEB_SEARCH.equals(action)) {
618 url = intent.getStringExtra(SearchManager.QUERY);
619 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100620 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
621 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100622 }
623
624 /**
625 * Launches the default web search activity with the query parameters if the given url string
626 * was identified as plain search terms and not URL/shortcut.
627 * @return true if the request was handled and web search activity was launched, false if not.
628 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100629 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100630 if (inUrl == null) return false;
631
632 // In general, we shouldn't modify URL from Intent.
633 // But currently, we get the user-typed URL from search box as well.
634 String url = fixUrl(inUrl).trim();
635
636 // URLs and site specific search shortcuts are handled by the regular flow of control, so
637 // return early.
638 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100639 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100640 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
641 return false;
642 }
643
644 Browser.updateVisitedHistory(mResolver, url, false);
645 Browser.addSearchUrl(mResolver, url);
646
647 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
648 intent.addCategory(Intent.CATEGORY_DEFAULT);
649 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100650 if (appData != null) {
651 intent.putExtra(SearchManager.APP_DATA, appData);
652 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100653 if (extraData != null) {
654 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
655 }
Grace Klobacc634032009-07-28 15:58:19 -0700656 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100657 startActivity(intent);
658
659 return true;
660 }
661
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700662 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800663 String url = null;
664 if (intent != null) {
665 final String action = intent.getAction();
666 if (Intent.ACTION_VIEW.equals(action)) {
667 url = smartUrlFilter(intent.getData());
668 if (url != null && url.startsWith("content:")) {
669 /* Append mimetype so webview knows how to display */
670 String mimeType = intent.resolveType(getContentResolver());
671 if (mimeType != null) {
672 url += "?" + mimeType;
673 }
674 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700675 if ("inline:".equals(url)) {
676 return new InlinedUrlData(
677 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
678 intent.getType(),
679 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
680 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
681 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800682 } else if (Intent.ACTION_SEARCH.equals(action)
683 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
684 || Intent.ACTION_WEB_SEARCH.equals(action)) {
685 url = intent.getStringExtra(SearchManager.QUERY);
686 if (url != null) {
687 mLastEnteredUrl = url;
688 // Don't add Urls, just search terms.
689 // Urls will get added when the page is loaded.
690 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
691 Browser.updateVisitedHistory(mResolver, url, false);
692 }
693 // In general, we shouldn't modify URL from Intent.
694 // But currently, we get the user-typed URL from search box as well.
695 url = fixUrl(url);
696 url = smartUrlFilter(url);
697 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
698 if (url.contains(searchSource)) {
699 String source = null;
700 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
701 if (appData != null) {
702 source = appData.getString(SearchManager.SOURCE);
703 }
704 if (TextUtils.isEmpty(source)) {
705 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
706 }
707 url = url.replace(searchSource, "&source=android-"+source+"&");
708 }
709 }
710 }
711 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700712 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800713 }
714
715 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400716 // FIXME: Converting the url to lower case
717 // duplicates functionality in smartUrlFilter().
718 // However, changing all current callers of fixUrl to
719 // call smartUrlFilter in addition may have unwanted
720 // consequences, and is deferred for now.
721 int colon = inUrl.indexOf(':');
722 boolean allLower = true;
723 for (int index = 0; index < colon; index++) {
724 char ch = inUrl.charAt(index);
725 if (!Character.isLetter(ch)) {
726 break;
727 }
728 allLower &= Character.isLowerCase(ch);
729 if (index == colon - 1 && !allLower) {
730 inUrl = inUrl.substring(0, colon).toLowerCase()
731 + inUrl.substring(colon);
732 }
733 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800734 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
735 return inUrl;
736 if (inUrl.startsWith("http:") ||
737 inUrl.startsWith("https:")) {
738 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
739 inUrl = inUrl.replaceFirst("/", "//");
740 } else inUrl = inUrl.replaceFirst(":", "://");
741 }
742 return inUrl;
743 }
744
745 /**
746 * Looking for the pattern like this
747 *
748 * *
749 * * *
750 * *** * *******
751 * * *
752 * * *
753 * *
754 */
755 private final SensorListener mSensorListener = new SensorListener() {
756 private long mLastGestureTime;
757 private float[] mPrev = new float[3];
758 private float[] mPrevDiff = new float[3];
759 private float[] mDiff = new float[3];
760 private float[] mRevertDiff = new float[3];
761
762 public void onSensorChanged(int sensor, float[] values) {
763 boolean show = false;
764 float[] diff = new float[3];
765
766 for (int i = 0; i < 3; i++) {
767 diff[i] = values[i] - mPrev[i];
768 if (Math.abs(diff[i]) > 1) {
769 show = true;
770 }
771 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
772 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
773 // start track when there is a big move, or revert
774 mRevertDiff[i] = mDiff[i];
775 mDiff[i] = 0;
776 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
777 // reset when it is flat
778 mDiff[i] = mRevertDiff[i] = 0;
779 }
780 mDiff[i] += diff[i];
781 mPrevDiff[i] = diff[i];
782 mPrev[i] = values[i];
783 }
784
785 if (false) {
786 // only shows if we think the delta is big enough, in an attempt
787 // to detect "serious" moves left/right or up/down
788 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
789 + values[0] + ", " + values[1] + ", " + values[2] + ")"
790 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
791 + ")");
792 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
793 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
794 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
795 + mRevertDiff[2] + ")");
796 }
797
798 long now = android.os.SystemClock.uptimeMillis();
799 if (now - mLastGestureTime > 1000) {
800 mLastGestureTime = 0;
801
802 float y = mDiff[1];
803 float z = mDiff[2];
804 float ay = Math.abs(y);
805 float az = Math.abs(z);
806 float ry = mRevertDiff[1];
807 float rz = mRevertDiff[2];
808 float ary = Math.abs(ry);
809 float arz = Math.abs(rz);
810 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
811 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
812
813 if ((gestY || gestZ) && !(gestY && gestZ)) {
814 WebView view = mTabControl.getCurrentWebView();
815
816 if (view != null) {
817 if (gestZ) {
818 if (z < 0) {
819 view.zoomOut();
820 } else {
821 view.zoomIn();
822 }
823 } else {
824 view.flingScroll(0, Math.round(y * 100));
825 }
826 }
827 mLastGestureTime = now;
828 }
829 }
830 }
831
832 public void onAccuracyChanged(int sensor, int accuracy) {
833 // TODO Auto-generated method stub
834
835 }
836 };
837
838 @Override protected void onResume() {
839 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700840 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800841 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
842 }
843
844 if (!mActivityInPause) {
845 Log.e(LOGTAG, "BrowserActivity is already resumed.");
846 return;
847 }
848
Mike Reed7bfa63b2009-05-28 11:08:32 -0400849 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800850 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400851 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800852
853 if (mWakeLock.isHeld()) {
854 mHandler.removeMessages(RELEASE_WAKELOCK);
855 mWakeLock.release();
856 }
857
858 if (mCredsDlg != null) {
859 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
860 // In case credential request never comes back
861 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
862 }
863 }
864
865 registerReceiver(mNetworkStateIntentReceiver,
866 mNetworkStateChangedFilter);
867 WebView.enablePlatformNotifications();
868
869 if (mSettings.doFlick()) {
870 if (mSensorManager == null) {
871 mSensorManager = (SensorManager) getSystemService(
872 Context.SENSOR_SERVICE);
873 }
874 mSensorManager.registerListener(mSensorListener,
875 SensorManager.SENSOR_ACCELEROMETER,
876 SensorManager.SENSOR_DELAY_FASTEST);
877 } else {
878 mSensorManager = null;
879 }
880 }
881
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400882 /**
883 * Since the actual title bar is embedded in the WebView, and removing it
884 * would change its appearance, create a temporary title bar to go at
885 * the top of the screen while the menu is open.
886 */
887 private TitleBar mFakeTitleBar;
888
889 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400890 * Holder for the fake title bar. It will have a foreground shadow, as well
891 * as a white background, so the fake title bar looks like the real one.
892 */
893 private ViewGroup mFakeTitleBarHolder;
894
895 /**
896 * Layout parameters for the fake title bar within mFakeTitleBarHolder
897 */
898 private FrameLayout.LayoutParams mFakeTitleBarParams
899 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400900 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400901 ViewGroup.LayoutParams.WRAP_CONTENT);
902 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400903 * Keeps track of whether the options menu is open. This is important in
904 * determining whether to show or hide the title bar overlay.
905 */
906 private boolean mOptionsMenuOpen;
907
908 /**
909 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
910 * of whether the configuration has changed. The first onMenuOpened call
911 * after a configuration change is simply a reopening of the same menu
912 * (i.e. mIconView did not change).
913 */
914 private boolean mConfigChanged;
915
916 /**
917 * Whether or not the options menu is in its smaller, icon menu form. When
918 * true, we want the title bar overlay to be up. When false, we do not.
919 * Only meaningful if mOptionsMenuOpen is true.
920 */
921 private boolean mIconView;
922
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400923 @Override
924 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400925 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
926 if (mOptionsMenuOpen) {
927 if (mConfigChanged) {
928 // We do not need to make any changes to the state of the
929 // title bar, since the only thing that happened was a
930 // change in orientation
931 mConfigChanged = false;
932 } else {
933 if (mIconView) {
934 // Switching the menu to expanded view, so hide the
935 // title bar.
936 hideFakeTitleBar();
937 mIconView = false;
938 } else {
939 // Switching the menu back to icon view, so show the
940 // title bar once again.
941 showFakeTitleBar();
942 mIconView = true;
943 }
944 }
945 } else {
946 // The options menu is closed, so open it, and show the title
947 showFakeTitleBar();
948 mOptionsMenuOpen = true;
949 mConfigChanged = false;
950 mIconView = true;
951 }
952 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400953 return true;
954 }
955
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400956 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400957 final View decor = getWindow().peekDecorView();
Leon Scroggins4d7e4062009-09-15 15:49:45 -0400958 if (mFakeTitleBar == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400959 && !mActivityInPause && decor != null
960 && decor.getWindowToken() != null) {
Leon Scrogginsf4bb18a2009-09-11 18:37:53 -0400961 final WebView webView = getTopWindow();
Leon Scroggins68579392009-09-15 15:31:54 -0400962 mFakeTitleBar = new TitleBar(this);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400963 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
964 mFakeTitleBar.setProgress(webView.getProgress());
965 mFakeTitleBar.setFavicon(webView.getFavicon());
966 updateLockIconToLatest();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400967
968 WindowManager manager
969 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
970
971 // Add the title bar to the window manager so it can receive touches
972 // while the menu is up
973 WindowManager.LayoutParams params
974 = new WindowManager.LayoutParams(
975 ViewGroup.LayoutParams.FILL_PARENT,
976 ViewGroup.LayoutParams.WRAP_CONTENT,
977 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
978 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400979 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400980 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400981 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400982 boolean atTop = mainView != null && mainView.getScrollY() == 0;
983 params.windowAnimations = atTop ? 0
984 : com.android.internal.R.style.Animation_DropDownDown;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400985 // XXX : Without providing an offset, the fake title bar will be
986 // placed underneath the status bar. Use the global visible rect
987 // of mBrowserFrameLayout to determine the bottom of the status bar
988 Rect rectangle = new Rect();
989 mBrowserFrameLayout.getGlobalVisibleRect(rectangle);
990 params.y = rectangle.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400991 // Add a holder for the title bar. It also holds a shadow to show
992 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400993 if (mFakeTitleBarHolder == null) {
994 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
995 .inflate(R.layout.title_bar_bg, null);
996 }
Leon Scroggins68549862009-09-21 16:02:01 -0400997 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400998 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400999 }
1000 }
1001
1002 @Override
1003 public void onOptionsMenuClosed(Menu menu) {
1004 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04001005 if (!mInLoad) {
1006 hideFakeTitleBar();
1007 } else if (!mIconView) {
1008 // The page is currently loading, and we are in expanded mode, so
1009 // we were not showing the menu. Show it once again. It will be
1010 // removed when the page finishes.
1011 showFakeTitleBar();
1012 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001013 }
1014 private void hideFakeTitleBar() {
1015 if (mFakeTitleBar == null) return;
1016 WindowManager manager
1017 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001018 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1019 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001020 mFakeTitleBar = null;
1021 }
1022
The Android Open Source Project0c908882009-03-03 19:32:16 -08001023 /**
1024 * onSaveInstanceState(Bundle map)
1025 * onSaveInstanceState is called right before onStop(). The map contains
1026 * the saved state.
1027 */
1028 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001029 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001030 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1031 }
1032 // the default implementation requires each view to have an id. As the
1033 // browser handles the state itself and it doesn't use id for the views,
1034 // don't call the default implementation. Otherwise it will trigger the
1035 // warning like this, "couldn't save which view has focus because the
1036 // focused view XXX has no id".
1037
1038 // Save all the tabs
1039 mTabControl.saveState(outState);
1040 }
1041
1042 @Override protected void onPause() {
1043 super.onPause();
1044
1045 if (mActivityInPause) {
1046 Log.e(LOGTAG, "BrowserActivity is already paused.");
1047 return;
1048 }
1049
Mike Reed7bfa63b2009-05-28 11:08:32 -04001050 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001051 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001052 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001053 mWakeLock.acquire();
1054 mHandler.sendMessageDelayed(mHandler
1055 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1056 }
1057
1058 // Clear the credentials toast if it is up
1059 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1060 mCredsDlg.dismiss();
1061 }
1062 mCredsDlg = null;
1063
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001064 // FIXME: This removes the active tabs page and resets the menu to
1065 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1066 // but then we would need to save it in onSaveInstanceState and restore
1067 // it in onCreate/onRestoreInstanceState
1068 if (mActiveTabsPage != null) {
1069 removeActiveTabPage(true);
1070 }
1071
The Android Open Source Project0c908882009-03-03 19:32:16 -08001072 cancelStopToast();
1073
1074 // unregister network state listener
1075 unregisterReceiver(mNetworkStateIntentReceiver);
1076 WebView.disablePlatformNotifications();
1077
1078 if (mSensorManager != null) {
1079 mSensorManager.unregisterListener(mSensorListener);
1080 }
1081 }
1082
1083 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001084 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001085 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1086 }
1087 super.onDestroy();
1088 // Remove the current tab and sub window
1089 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001090 if (t != null) {
1091 dismissSubWindow(t);
1092 removeTabFromContentView(t);
1093 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001094 // Destroy all the tabs
1095 mTabControl.destroy();
1096 WebIconDatabase.getInstance().close();
1097 if (mGlsConnection != null) {
1098 unbindService(mGlsConnection);
1099 mGlsConnection = null;
1100 }
1101
1102 //
1103 // stop MASF proxy service
1104 //
1105 //Intent proxyServiceIntent = new Intent();
1106 //proxyServiceIntent.setComponent
1107 // (new ComponentName(
1108 // "com.android.masfproxyservice",
1109 // "com.android.masfproxyservice.MasfProxyService"));
1110 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001111
1112 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001113 }
1114
1115 @Override
1116 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001117 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001118 super.onConfigurationChanged(newConfig);
1119
1120 if (mPageInfoDialog != null) {
1121 mPageInfoDialog.dismiss();
1122 showPageInfo(
1123 mPageInfoView,
1124 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1125 }
1126 if (mSSLCertificateDialog != null) {
1127 mSSLCertificateDialog.dismiss();
1128 showSSLCertificate(
1129 mSSLCertificateView);
1130 }
1131 if (mSSLCertificateOnErrorDialog != null) {
1132 mSSLCertificateOnErrorDialog.dismiss();
1133 showSSLCertificateOnError(
1134 mSSLCertificateOnErrorView,
1135 mSSLCertificateOnErrorHandler,
1136 mSSLCertificateOnErrorError);
1137 }
1138 if (mHttpAuthenticationDialog != null) {
1139 String title = ((TextView) mHttpAuthenticationDialog
1140 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1141 .toString();
1142 String name = ((TextView) mHttpAuthenticationDialog
1143 .findViewById(R.id.username_edit)).getText().toString();
1144 String password = ((TextView) mHttpAuthenticationDialog
1145 .findViewById(R.id.password_edit)).getText().toString();
1146 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1147 .getId();
1148 mHttpAuthenticationDialog.dismiss();
1149 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1150 name, password, focusId);
1151 }
1152 if (mFindDialog != null && mFindDialog.isShowing()) {
1153 mFindDialog.onConfigurationChanged(newConfig);
1154 }
1155 }
1156
1157 @Override public void onLowMemory() {
1158 super.onLowMemory();
1159 mTabControl.freeMemory();
1160 }
1161
Mike Reed7bfa63b2009-05-28 11:08:32 -04001162 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001163 if ((!mActivityInPause && !mPageStarted) ||
1164 (mActivityInPause && mPageStarted)) {
1165 CookieSyncManager.getInstance().startSync();
1166 WebView w = mTabControl.getCurrentWebView();
1167 if (w != null) {
1168 w.resumeTimers();
1169 }
1170 return true;
1171 } else {
1172 return false;
1173 }
1174 }
1175
Mike Reed7bfa63b2009-05-28 11:08:32 -04001176 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001177 if (mActivityInPause && !mPageStarted) {
1178 CookieSyncManager.getInstance().stopSync();
1179 WebView w = mTabControl.getCurrentWebView();
1180 if (w != null) {
1181 w.pauseTimers();
1182 }
1183 return true;
1184 } else {
1185 return false;
1186 }
1187 }
1188
Leon Scroggins1f005d32009-08-10 17:36:42 -04001189 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001190 /*
1191 * This function is called when we are launching for the first time. We
1192 * are waiting for the login credentials before loading Google home
1193 * pages. This way the user will be logged in straight away.
1194 */
1195 private void waitForCredentials() {
1196 // Show a toast
1197 mCredsDlg = new ProgressDialog(this);
1198 mCredsDlg.setIndeterminate(true);
1199 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1200 // If the user cancels the operation, then cancel the Google
1201 // Credentials request.
1202 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1203 mCredsDlg.show();
1204
1205 // We set a timeout for the retrieval of credentials in onResume()
1206 // as that is when we have freed up some CPU time to get
1207 // the login credentials.
1208 }
1209
1210 /*
1211 * If we have received the credentials or we have timed out and we are
1212 * showing the credentials dialog, then it is time to move on.
1213 */
1214 private void resumeAfterCredentials() {
1215 if (mCredsDlg == null) {
1216 return;
1217 }
1218
1219 // Clear the toast
1220 if (mCredsDlg.isShowing()) {
1221 mCredsDlg.dismiss();
1222 }
1223 mCredsDlg = null;
1224
1225 // Clear any pending timeout
1226 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1227
1228 // Load the page
1229 WebView w = mTabControl.getCurrentWebView();
1230 if (w != null) {
1231 w.loadUrl(mSettings.getHomePage());
1232 }
1233
1234 // Update the settings, need to do this last as it can take a moment
1235 // to persist the settings. In the mean time we could be loading
1236 // content.
1237 mSettings.setLoginInitialized(this);
1238 }
1239
1240 // Open the icon database and retain all the icons for visited sites.
1241 private void retainIconsOnStartup() {
1242 final WebIconDatabase db = WebIconDatabase.getInstance();
1243 db.open(getDir("icons", 0).getPath());
1244 try {
1245 Cursor c = Browser.getAllBookmarks(mResolver);
1246 if (!c.moveToFirst()) {
1247 c.deactivate();
1248 return;
1249 }
1250 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1251 do {
1252 String url = c.getString(urlIndex);
1253 db.retainIconForPageUrl(url);
1254 } while (c.moveToNext());
1255 c.deactivate();
1256 } catch (IllegalStateException e) {
1257 Log.e(LOGTAG, "retainIconsOnStartup", e);
1258 }
1259 }
1260
1261 // Helper method for getting the top window.
1262 WebView getTopWindow() {
1263 return mTabControl.getCurrentTopWebView();
1264 }
1265
1266 @Override
1267 public boolean onCreateOptionsMenu(Menu menu) {
1268 super.onCreateOptionsMenu(menu);
1269
1270 MenuInflater inflater = getMenuInflater();
1271 inflater.inflate(R.menu.browser, menu);
1272 mMenu = menu;
1273 updateInLoadMenuItems();
1274 return true;
1275 }
1276
1277 /**
1278 * As the menu can be open when loading state changes
1279 * we must manually update the state of the stop/reload menu
1280 * item
1281 */
1282 private void updateInLoadMenuItems() {
1283 if (mMenu == null) {
1284 return;
1285 }
1286 MenuItem src = mInLoad ?
1287 mMenu.findItem(R.id.stop_menu_id):
1288 mMenu.findItem(R.id.reload_menu_id);
1289 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1290 dest.setIcon(src.getIcon());
1291 dest.setTitle(src.getTitle());
1292 }
1293
1294 @Override
1295 public boolean onContextItemSelected(MenuItem item) {
1296 // chording is not an issue with context menus, but we use the same
1297 // options selector, so set mCanChord to true so we can access them.
1298 mCanChord = true;
1299 int id = item.getItemId();
1300 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001301 if (null == webView) {
1302 return false;
1303 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001304 final HashMap hrefMap = new HashMap();
1305 hrefMap.put("webview", webView);
1306 final Message msg = mHandler.obtainMessage(
1307 FOCUS_NODE_HREF, id, 0, hrefMap);
1308 switch (id) {
1309 // -- Browser context menu
1310 case R.id.open_context_menu_id:
1311 case R.id.open_newtab_context_menu_id:
1312 case R.id.bookmark_context_menu_id:
1313 case R.id.save_link_context_menu_id:
1314 case R.id.share_link_context_menu_id:
1315 case R.id.copy_link_context_menu_id:
1316 webView.requestFocusNodeHref(msg);
1317 break;
1318
1319 default:
1320 // For other context menus
1321 return onOptionsItemSelected(item);
1322 }
1323 mCanChord = false;
1324 return true;
1325 }
1326
1327 private Bundle createGoogleSearchSourceBundle(String source) {
1328 Bundle bundle = new Bundle();
1329 bundle.putString(SearchManager.SOURCE, source);
1330 return bundle;
1331 }
1332
1333 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001334 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001335 */
1336 @Override
1337 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001338 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001339 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001340 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001341 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001342 return true;
1343 }
1344
1345 @Override
1346 public void startSearch(String initialQuery, boolean selectInitialQuery,
1347 Bundle appSearchData, boolean globalSearch) {
1348 if (appSearchData == null) {
1349 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1350 }
1351 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1352 }
1353
Leon Scroggins1f005d32009-08-10 17:36:42 -04001354 /**
1355 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1356 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001357 * @param index Index of the tab to change to, as defined by
1358 * mTabControl.getTabIndex(Tab t).
1359 * @return boolean True if we successfully switched to a different tab. If
1360 * the indexth tab is null, or if that tab is the same as
1361 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001362 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001363 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001364 TabControl.Tab tab = mTabControl.getTab(index);
1365 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1366 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001367 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001368 }
1369 if (currentTab != null) {
1370 // currentTab may be null if it was just removed. In that case,
1371 // we do not need to remove it
1372 removeTabFromContentView(currentTab);
1373 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001374 mTabControl.setCurrentTab(tab);
1375 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001376 resetTitleIconAndProgress();
1377 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001378 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001379 }
1380
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001381 /* package */ TabControl.Tab openTabToHomePage() {
1382 return openTabAndShow(mSettings.getHomePage(), false, null);
1383 }
1384
Leon Scroggins1f005d32009-08-10 17:36:42 -04001385 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001386 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001387 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001388 // This is the last tab. Open a new one, with the home
1389 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001390 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001391 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001392 return;
1393 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001394 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001395 int indexToShow = -1;
1396 if (parent != null) {
1397 indexToShow = mTabControl.getTabIndex(parent);
1398 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001399 final int currentIndex = mTabControl.getCurrentIndex();
1400 // Try to move to the tab to the right
1401 indexToShow = currentIndex + 1;
1402 if (indexToShow > mTabControl.getTabCount() - 1) {
1403 // Try to move to the tab to the left
1404 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001405 }
1406 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001407 if (switchToTab(indexToShow)) {
1408 // Close window
1409 closeTab(current);
1410 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001411 }
1412
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001413 private ActiveTabsPage mActiveTabsPage;
1414
1415 /**
1416 * Remove the active tabs page.
1417 * @param needToAttach If true, the active tabs page did not attach a tab
1418 * to the content view, so we need to do that here.
1419 */
1420 /* package */ void removeActiveTabPage(boolean needToAttach) {
1421 mContentView.removeView(mActiveTabsPage);
1422 mActiveTabsPage = null;
1423 mMenuState = R.id.MAIN_MENU;
1424 if (needToAttach) {
1425 attachTabToContentView(mTabControl.getCurrentTab());
1426 }
1427 getTopWindow().requestFocus();
1428 }
1429
The Android Open Source Project0c908882009-03-03 19:32:16 -08001430 @Override
1431 public boolean onOptionsItemSelected(MenuItem item) {
1432 if (!mCanChord) {
1433 // The user has already fired a shortcut with this hold down of the
1434 // menu key.
1435 return false;
1436 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001437 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001438 return false;
1439 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001440 if (mMenuIsDown) {
1441 // The shortcut action consumes the MENU. Even if it is still down,
1442 // it won't trigger the next shortcut action. In the case of the
1443 // shortcut action triggering a new activity, like Bookmarks, we
1444 // won't get onKeyUp for MENU. So it is important to reset it here.
1445 mMenuIsDown = false;
1446 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001447 switch (item.getItemId()) {
1448 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001449 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001450 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001451 break;
1452
Leon Scroggins64b80f32009-08-07 12:03:34 -04001453 case R.id.goto_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001454 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001455 break;
1456
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001457 case R.id.active_tabs_menu_id:
1458 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1459 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001460 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001461 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1462 mActiveTabsPage.requestFocus();
1463 mMenuState = EMPTY_MENU;
1464 break;
1465
Leon Scroggins1f005d32009-08-10 17:36:42 -04001466 case R.id.add_bookmark_menu_id:
1467 Intent i = new Intent(BrowserActivity.this,
1468 AddBookmarkPage.class);
1469 WebView w = getTopWindow();
1470 i.putExtra("url", w.getUrl());
1471 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001472 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001473 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001474 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001475 break;
1476
1477 case R.id.stop_reload_menu_id:
1478 if (mInLoad) {
1479 stopLoading();
1480 } else {
1481 getTopWindow().reload();
1482 }
1483 break;
1484
1485 case R.id.back_menu_id:
1486 getTopWindow().goBack();
1487 break;
1488
1489 case R.id.forward_menu_id:
1490 getTopWindow().goForward();
1491 break;
1492
1493 case R.id.close_menu_id:
1494 // Close the subwindow if it exists.
1495 if (mTabControl.getCurrentSubWindow() != null) {
1496 dismissSubWindow(mTabControl.getCurrentTab());
1497 break;
1498 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001499 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001500 break;
1501
1502 case R.id.homepage_menu_id:
1503 TabControl.Tab current = mTabControl.getCurrentTab();
1504 if (current != null) {
1505 dismissSubWindow(current);
1506 current.getWebView().loadUrl(mSettings.getHomePage());
1507 }
1508 break;
1509
1510 case R.id.preferences_menu_id:
1511 Intent intent = new Intent(this,
1512 BrowserPreferencesPage.class);
1513 startActivityForResult(intent, PREFERENCES_PAGE);
1514 break;
1515
1516 case R.id.find_menu_id:
1517 if (null == mFindDialog) {
1518 mFindDialog = new FindDialog(this);
1519 }
1520 mFindDialog.setWebView(getTopWindow());
1521 mFindDialog.show();
1522 mMenuState = EMPTY_MENU;
1523 break;
1524
1525 case R.id.select_text_id:
1526 getTopWindow().emulateShiftHeld();
1527 break;
1528 case R.id.page_info_menu_id:
1529 showPageInfo(mTabControl.getCurrentTab(), false);
1530 break;
1531
1532 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001533 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001534 break;
1535
1536 case R.id.share_page_menu_id:
1537 Browser.sendString(this, getTopWindow().getUrl());
1538 break;
1539
1540 case R.id.dump_nav_menu_id:
1541 getTopWindow().debugDump();
1542 break;
1543
1544 case R.id.zoom_in_menu_id:
1545 getTopWindow().zoomIn();
1546 break;
1547
1548 case R.id.zoom_out_menu_id:
1549 getTopWindow().zoomOut();
1550 break;
1551
1552 case R.id.view_downloads_menu_id:
1553 viewDownloads(null);
1554 break;
1555
The Android Open Source Project0c908882009-03-03 19:32:16 -08001556 case R.id.window_one_menu_id:
1557 case R.id.window_two_menu_id:
1558 case R.id.window_three_menu_id:
1559 case R.id.window_four_menu_id:
1560 case R.id.window_five_menu_id:
1561 case R.id.window_six_menu_id:
1562 case R.id.window_seven_menu_id:
1563 case R.id.window_eight_menu_id:
1564 {
1565 int menuid = item.getItemId();
1566 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1567 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1568 TabControl.Tab desiredTab = mTabControl.getTab(id);
1569 if (desiredTab != null &&
1570 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001571 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001572 }
1573 break;
1574 }
1575 }
1576 }
1577 break;
1578
1579 default:
1580 if (!super.onOptionsItemSelected(item)) {
1581 return false;
1582 }
1583 // Otherwise fall through.
1584 }
1585 mCanChord = false;
1586 return true;
1587 }
1588
1589 public void closeFind() {
1590 mMenuState = R.id.MAIN_MENU;
1591 }
1592
1593 @Override public boolean onPrepareOptionsMenu(Menu menu)
1594 {
1595 // This happens when the user begins to hold down the menu key, so
1596 // allow them to chord to get a shortcut.
1597 mCanChord = true;
1598 // Note: setVisible will decide whether an item is visible; while
1599 // setEnabled() will decide whether an item is enabled, which also means
1600 // whether the matching shortcut key will function.
1601 super.onPrepareOptionsMenu(menu);
1602 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001603 case EMPTY_MENU:
1604 if (mCurrentMenuState != mMenuState) {
1605 menu.setGroupVisible(R.id.MAIN_MENU, false);
1606 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1607 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001608 }
1609 break;
1610 default:
1611 if (mCurrentMenuState != mMenuState) {
1612 menu.setGroupVisible(R.id.MAIN_MENU, true);
1613 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1614 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001615 }
1616 final WebView w = getTopWindow();
1617 boolean canGoBack = false;
1618 boolean canGoForward = false;
1619 boolean isHome = false;
1620 if (w != null) {
1621 canGoBack = w.canGoBack();
1622 canGoForward = w.canGoForward();
1623 isHome = mSettings.getHomePage().equals(w.getUrl());
1624 }
1625 final MenuItem back = menu.findItem(R.id.back_menu_id);
1626 back.setEnabled(canGoBack);
1627
1628 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1629 home.setEnabled(!isHome);
1630
1631 menu.findItem(R.id.forward_menu_id)
1632 .setEnabled(canGoForward);
1633
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001634 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1635 mTabControl.getTabCount() < TabControl.MAX_TABS);
1636
The Android Open Source Project0c908882009-03-03 19:32:16 -08001637 // decide whether to show the share link option
1638 PackageManager pm = getPackageManager();
1639 Intent send = new Intent(Intent.ACTION_SEND);
1640 send.setType("text/plain");
1641 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1642 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1643
The Android Open Source Project0c908882009-03-03 19:32:16 -08001644 boolean isNavDump = mSettings.isNavDump();
1645 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1646 nav.setVisible(isNavDump);
1647 nav.setEnabled(isNavDump);
1648 break;
1649 }
1650 mCurrentMenuState = mMenuState;
1651 return true;
1652 }
1653
1654 @Override
1655 public void onCreateContextMenu(ContextMenu menu, View v,
1656 ContextMenuInfo menuInfo) {
1657 WebView webview = (WebView) v;
1658 WebView.HitTestResult result = webview.getHitTestResult();
1659 if (result == null) {
1660 return;
1661 }
1662
1663 int type = result.getType();
1664 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1665 Log.w(LOGTAG,
1666 "We should not show context menu when nothing is touched");
1667 return;
1668 }
1669 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1670 // let TextView handles context menu
1671 return;
1672 }
1673
1674 // Note, http://b/issue?id=1106666 is requesting that
1675 // an inflated menu can be used again. This is not available
1676 // yet, so inflate each time (yuk!)
1677 MenuInflater inflater = getMenuInflater();
1678 inflater.inflate(R.menu.browsercontext, menu);
1679
1680 // Show the correct menu group
1681 String extra = result.getExtra();
1682 menu.setGroupVisible(R.id.PHONE_MENU,
1683 type == WebView.HitTestResult.PHONE_TYPE);
1684 menu.setGroupVisible(R.id.EMAIL_MENU,
1685 type == WebView.HitTestResult.EMAIL_TYPE);
1686 menu.setGroupVisible(R.id.GEO_MENU,
1687 type == WebView.HitTestResult.GEO_TYPE);
1688 menu.setGroupVisible(R.id.IMAGE_MENU,
1689 type == WebView.HitTestResult.IMAGE_TYPE
1690 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1691 menu.setGroupVisible(R.id.ANCHOR_MENU,
1692 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1693 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1694
1695 // Setup custom handling depending on the type
1696 switch (type) {
1697 case WebView.HitTestResult.PHONE_TYPE:
1698 menu.setHeaderTitle(Uri.decode(extra));
1699 menu.findItem(R.id.dial_context_menu_id).setIntent(
1700 new Intent(Intent.ACTION_VIEW, Uri
1701 .parse(WebView.SCHEME_TEL + extra)));
1702 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1703 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1704 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1705 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1706 addIntent);
1707 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1708 new Copy(extra));
1709 break;
1710
1711 case WebView.HitTestResult.EMAIL_TYPE:
1712 menu.setHeaderTitle(extra);
1713 menu.findItem(R.id.email_context_menu_id).setIntent(
1714 new Intent(Intent.ACTION_VIEW, Uri
1715 .parse(WebView.SCHEME_MAILTO + extra)));
1716 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1717 new Copy(extra));
1718 break;
1719
1720 case WebView.HitTestResult.GEO_TYPE:
1721 menu.setHeaderTitle(extra);
1722 menu.findItem(R.id.map_context_menu_id).setIntent(
1723 new Intent(Intent.ACTION_VIEW, Uri
1724 .parse(WebView.SCHEME_GEO
1725 + URLEncoder.encode(extra))));
1726 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1727 new Copy(extra));
1728 break;
1729
1730 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1731 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1732 TextView titleView = (TextView) LayoutInflater.from(this)
1733 .inflate(android.R.layout.browser_link_context_header,
1734 null);
1735 titleView.setText(extra);
1736 menu.setHeaderView(titleView);
1737 // decide whether to show the open link in new tab option
1738 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1739 mTabControl.getTabCount() < TabControl.MAX_TABS);
1740 PackageManager pm = getPackageManager();
1741 Intent send = new Intent(Intent.ACTION_SEND);
1742 send.setType("text/plain");
1743 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1744 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1745 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1746 break;
1747 }
1748 // otherwise fall through to handle image part
1749 case WebView.HitTestResult.IMAGE_TYPE:
1750 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1751 menu.setHeaderTitle(extra);
1752 }
1753 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1754 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1755 menu.findItem(R.id.download_context_menu_id).
1756 setOnMenuItemClickListener(new Download(extra));
1757 break;
1758
1759 default:
1760 Log.w(LOGTAG, "We should not get here.");
1761 break;
1762 }
1763 }
1764
The Android Open Source Project0c908882009-03-03 19:32:16 -08001765 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001766 // this should only be called for the current tab.
The Android Open Source Project0c908882009-03-03 19:32:16 -08001767 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001768 // Attach the container that contains the main WebView and any other UI
1769 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001770 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001771
1772 if (mShouldShowErrorConsole) {
1773 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1774 if (errorConsole.numberOfErrors() == 0) {
1775 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1776 } else {
1777 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1778 }
1779
1780 mErrorConsoleContainer.addView(errorConsole,
1781 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1782 ViewGroup.LayoutParams.WRAP_CONTENT));
1783 }
1784
Grace Klobac928c302009-09-17 11:51:21 -07001785 setLockIconType(t.getLockIconType());
1786 setPrevLockType(t.getPrevLockIconType());
1787
1788 // this is to match the code in removeTabFromContentView()
1789 if (!mPageStarted && t.getTopWindow().getProgress() < 100) {
1790 mPageStarted = true;
Grace Klobaeb6eef42009-09-15 17:56:32 -07001791 }
1792
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001793 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001794 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001795 // Request focus on the top window.
1796 t.getTopWindow().requestFocus();
1797 }
1798
1799 // Attach a sub window to the main WebView of the given tab.
1800 private void attachSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001801 t.attachSubWindow(mContentView);
1802 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001803 }
1804
1805 // Remove the given tab from the content view.
1806 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001807 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001808 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001809
1810 if (mTabControl.getCurrentErrorConsole(false) != null) {
1811 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1812 }
1813
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001814 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001815 if (view != null) {
1816 view.setEmbeddedTitleBar(null);
1817 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001818
Grace Klobac928c302009-09-17 11:51:21 -07001819 // unlike attachTabToContentView(), removeTabFromContentView() can be
1820 // called for the non-current tab. Need to add the check.
Grace Klobaeb6eef42009-09-15 17:56:32 -07001821 if (t == mTabControl.getCurrentTab()) {
1822 t.setLockIconType(getLockIconType());
1823 t.setPrevLockIconType(getPrevLockType());
Grace Klobac928c302009-09-17 11:51:21 -07001824
1825 // this is not a perfect solution. But currently there is one
1826 // WebViewClient for all the WebView. if user switches from an
1827 // in-load window to an already loaded window, mPageStarted will not
1828 // be set to false. If user leaves the Browser, pauseWebViewTimers()
1829 // won't do anything and leaves the timer running even Browser is in
1830 // the background.
1831 if (mPageStarted) {
1832 mPageStarted = false;
1833 }
Grace Klobaeb6eef42009-09-15 17:56:32 -07001834 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001835 }
1836
1837 // Remove the sub window if it exists. Also called by TabControl when the
1838 // user clicks the 'X' to dismiss a sub window.
1839 /* package */ void dismissSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001840 t.removeSubWindow(mContentView);
1841 // Tell the TabControl to dismiss the subwindow. This will destroy
1842 // the WebView.
1843 mTabControl.dismissSubWindow(t);
1844 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001845 }
1846
Leon Scroggins1f005d32009-08-10 17:36:42 -04001847 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001848 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001849 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1850 String appId) {
1851 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001852 }
1853
1854 // This method does a ton of stuff. It will attempt to create a new tab
1855 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001856 // url isn't null, it will load the given url.
1857 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001858 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001859 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1860 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1861 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001862 final TabControl.Tab tab = mTabControl.createNewTab(
1863 closeOnExit, appId, urlData.mUrl);
1864 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001865 // If the last tab was removed from the active tabs page, currentTab
1866 // will be null.
1867 if (currentTab != null) {
1868 removeTabFromContentView(currentTab);
1869 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001870 // We must set the new tab as the current tab to reflect the old
1871 // animation behavior.
1872 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001873 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001874 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001875 urlData.loadIn(webview);
1876 }
1877 return tab;
1878 } else {
1879 // Get rid of the subwindow if it exists
1880 dismissSubWindow(currentTab);
1881 if (!urlData.isEmpty()) {
1882 // Load the given url.
1883 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001884 }
1885 }
Grace Klobac9181842009-04-14 08:53:22 -07001886 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001887 }
1888
Grace Klobac9181842009-04-14 08:53:22 -07001889 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001890 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001891 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001892 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001893 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001894 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001895 }
Grace Klobac9181842009-04-14 08:53:22 -07001896 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001897 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001898 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001899 }
1900 }
1901
1902 private class Copy implements OnMenuItemClickListener {
1903 private CharSequence mText;
1904
1905 public boolean onMenuItemClick(MenuItem item) {
1906 copy(mText);
1907 return true;
1908 }
1909
1910 public Copy(CharSequence toCopy) {
1911 mText = toCopy;
1912 }
1913 }
1914
1915 private class Download implements OnMenuItemClickListener {
1916 private String mText;
1917
1918 public boolean onMenuItemClick(MenuItem item) {
1919 onDownloadStartNoStream(mText, null, null, null, -1);
1920 return true;
1921 }
1922
1923 public Download(String toDownload) {
1924 mText = toDownload;
1925 }
1926 }
1927
1928 private void copy(CharSequence text) {
1929 try {
1930 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1931 if (clip != null) {
1932 clip.setClipboardText(text);
1933 }
1934 } catch (android.os.RemoteException e) {
1935 Log.e(LOGTAG, "Copy failed", e);
1936 }
1937 }
1938
1939 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001940 * Resets the browser title-view to whatever it must be
1941 * (for example, if we had a loading error)
1942 * When we have a new page, we call resetTitle, when we
1943 * have to reset the titlebar to whatever it used to be
1944 * (for example, if the user chose to stop loading), we
1945 * call resetTitleAndRevertLockIcon.
1946 */
1947 /* package */ void resetTitleAndRevertLockIcon() {
1948 revertLockIcon();
1949 resetTitleIconAndProgress();
1950 }
1951
1952 /**
1953 * Reset the title, favicon, and progress.
1954 */
1955 private void resetTitleIconAndProgress() {
1956 WebView current = mTabControl.getCurrentWebView();
1957 if (current == null) {
1958 return;
1959 }
1960 resetTitleAndIcon(current);
1961 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001962 mWebChromeClient.onProgressChanged(current, progress);
1963 }
1964
1965 // Reset the title and the icon based on the given item.
1966 private void resetTitleAndIcon(WebView view) {
1967 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1968 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001969 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001970 setFavicon(item.getFavicon());
1971 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001972 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001973 setFavicon(null);
1974 }
1975 }
1976
1977 /**
1978 * Sets a title composed of the URL and the title string.
1979 * @param url The URL of the site being loaded.
1980 * @param title The title of the site being loaded.
1981 */
Leon Scroggins68579392009-09-15 15:31:54 -04001982 private void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001983 mUrl = url;
1984 mTitle = title;
1985
Leon Scroggins68579392009-09-15 15:31:54 -04001986 mTitleBar.setTitleAndUrl(title, url);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001987 if (mFakeTitleBar != null) {
1988 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001989 }
1990 }
1991
1992 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001993 * @param url The URL to build a title version of the URL from.
1994 * @return The title version of the URL or null if fails.
1995 * The title version of the URL can be either the URL hostname,
1996 * or the hostname with an "https://" prefix (for secure URLs),
1997 * or an empty string if, for example, the URL in question is a
1998 * file:// URL with no hostname.
1999 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002000 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002001 String titleUrl = null;
2002
2003 if (url != null) {
2004 try {
2005 // parse the url string
2006 URL urlObj = new URL(url);
2007 if (urlObj != null) {
2008 titleUrl = "";
2009
2010 String protocol = urlObj.getProtocol();
2011 String host = urlObj.getHost();
2012
2013 if (host != null && 0 < host.length()) {
2014 titleUrl = host;
2015 if (protocol != null) {
2016 // if a secure site, add an "https://" prefix!
2017 if (protocol.equalsIgnoreCase("https")) {
2018 titleUrl = protocol + "://" + host;
2019 }
2020 }
2021 }
2022 }
2023 } catch (MalformedURLException e) {}
2024 }
2025
2026 return titleUrl;
2027 }
2028
2029 // Set the favicon in the title bar.
2030 private void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002031 mTitleBar.setFavicon(icon);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002032 if (mFakeTitleBar != null) {
2033 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002034 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002035 }
2036
2037 /**
2038 * Saves the current lock-icon state before resetting
2039 * the lock icon. If we have an error, we may need to
2040 * roll back to the previous state.
2041 */
2042 private void saveLockIcon() {
2043 mPrevLockType = mLockIconType;
2044 }
2045
2046 /**
2047 * Reverts the lock-icon state to the last saved state,
2048 * for example, if we had an error, and need to cancel
2049 * the load.
2050 */
2051 private void revertLockIcon() {
2052 mLockIconType = mPrevLockType;
2053
Dave Bort31a6d1c2009-04-13 15:56:49 -07002054 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002055 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2056 " revert lock icon to " + mLockIconType);
2057 }
2058
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002059 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002060 }
2061
Leon Scroggins1f005d32009-08-10 17:36:42 -04002062 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002063 * Close the tab, remove its associated title bar, and adjust mTabControl's
2064 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002065 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002066 /* package */ void closeTab(TabControl.Tab t) {
2067 int currentIndex = mTabControl.getCurrentIndex();
2068 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002069 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002070 if (currentIndex >= removeIndex && currentIndex != 0) {
2071 currentIndex--;
2072 }
2073 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
The Android Open Source Project0c908882009-03-03 19:32:16 -08002074 }
2075
2076 private void goBackOnePageOrQuit() {
2077 TabControl.Tab current = mTabControl.getCurrentTab();
2078 if (current == null) {
2079 /*
2080 * Instead of finishing the activity, simply push this to the back
2081 * of the stack and let ActivityManager to choose the foreground
2082 * activity. As BrowserActivity is singleTask, it will be always the
2083 * root of the task. So we can use either true or false for
2084 * moveTaskToBack().
2085 */
2086 moveTaskToBack(true);
2087 }
2088 WebView w = current.getWebView();
2089 if (w.canGoBack()) {
2090 w.goBack();
2091 } else {
2092 // Check to see if we are closing a window that was created by
2093 // another window. If so, we switch back to that window.
2094 TabControl.Tab parent = current.getParentTab();
2095 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002096 switchToTab(mTabControl.getTabIndex(parent));
2097 // Now we close the other tab
2098 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002099 } else {
2100 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002101 // force mPageStarted to be false as we are going to either
2102 // finish the activity or remove the tab. This will ensure
2103 // pauseWebView() taking action.
2104 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002105 if (mTabControl.getTabCount() == 1) {
2106 finish();
2107 return;
2108 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002109 // call pauseWebViewTimers() now, we won't be able to call
2110 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002111 // Temporarily change mActivityInPause to be true as
2112 // pauseWebViewTimers() will do nothing if mActivityInPause
2113 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002114 boolean savedState = mActivityInPause;
2115 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002116 Log.e(LOGTAG, "BrowserActivity is already paused "
2117 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002118 }
2119 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002120 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002121 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002122 removeTabFromContentView(current);
2123 mTabControl.removeTab(current);
2124 }
2125 /*
2126 * Instead of finishing the activity, simply push this to the back
2127 * of the stack and let ActivityManager to choose the foreground
2128 * activity. As BrowserActivity is singleTask, it will be always the
2129 * root of the task. So we can use either true or false for
2130 * moveTaskToBack().
2131 */
2132 moveTaskToBack(true);
2133 }
2134 }
2135 }
2136
Grace Kloba5942df02009-09-18 11:48:29 -07002137 @Override
2138 public boolean onKeyDown(int keyCode, KeyEvent event) {
2139 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2140 // still down, we don't want to trigger the search. Pretend to consume
2141 // the key and do nothing.
2142 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002143
Grace Kloba5942df02009-09-18 11:48:29 -07002144 switch(keyCode) {
2145 case KeyEvent.KEYCODE_MENU:
2146 mMenuIsDown = true;
2147 break;
2148 case KeyEvent.KEYCODE_SPACE:
2149 // Browser's hidden shortcut key. Don't call super so that
2150 // search won't be triggered.
2151 return true;
2152 case KeyEvent.KEYCODE_BACK:
2153 if (event.getRepeatCount() == 0) {
2154 event.startTracking();
2155 return true;
2156 } else if (mCustomView == null && mActiveTabsPage == null
2157 && event.isLongPress()) {
2158 bookmarksOrHistoryPicker(true);
2159 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002160 }
Grace Kloba5942df02009-09-18 11:48:29 -07002161 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002162 }
Grace Kloba5942df02009-09-18 11:48:29 -07002163 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002164 }
2165
Grace Kloba5942df02009-09-18 11:48:29 -07002166 @Override
2167 public boolean onKeyUp(int keyCode, KeyEvent event) {
2168 switch(keyCode) {
2169 case KeyEvent.KEYCODE_MENU:
2170 mMenuIsDown = false;
2171 break;
2172 case KeyEvent.KEYCODE_SPACE:
2173 if (event.isShiftPressed()) {
2174 getTopWindow().pageUp(false);
2175 } else {
2176 getTopWindow().pageDown(false);
2177 }
2178 return true;
2179 case KeyEvent.KEYCODE_BACK:
2180 if (event.isTracking() && !event.isCanceled()) {
2181 if (mCustomView != null) {
2182 // if a custom view is showing, hide it
2183 mWebChromeClient.onHideCustomView();
2184 } else if (mActiveTabsPage != null) {
2185 // if tab page is showing, hide it
2186 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002187 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002188 WebView subwindow = mTabControl.getCurrentSubWindow();
2189 if (subwindow != null) {
2190 if (subwindow.canGoBack()) {
2191 subwindow.goBack();
2192 } else {
2193 dismissSubWindow(mTabControl.getCurrentTab());
2194 }
2195 } else {
2196 goBackOnePageOrQuit();
2197 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002198 }
Grace Kloba5942df02009-09-18 11:48:29 -07002199 return true;
2200 }
2201 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002202 }
Grace Kloba5942df02009-09-18 11:48:29 -07002203 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002204 }
2205
Leon Scroggins68579392009-09-15 15:31:54 -04002206 /* package */ void stopLoading() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002207 resetTitleAndRevertLockIcon();
2208 WebView w = getTopWindow();
2209 w.stopLoading();
2210 mWebViewClient.onPageFinished(w, w.getUrl());
2211
2212 cancelStopToast();
2213 mStopToast = Toast
2214 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2215 mStopToast.show();
2216 }
2217
2218 private void cancelStopToast() {
2219 if (mStopToast != null) {
2220 mStopToast.cancel();
2221 mStopToast = null;
2222 }
2223 }
2224
2225 // called by a non-UI thread to post the message
2226 public void postMessage(int what, int arg1, int arg2, Object obj) {
2227 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2228 }
2229
2230 // public message ids
2231 public final static int LOAD_URL = 1001;
2232 public final static int STOP_LOAD = 1002;
2233
2234 // Message Ids
2235 private static final int FOCUS_NODE_HREF = 102;
2236 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002237 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002238
2239 // Private handler for handling javascript and saving passwords
2240 private Handler mHandler = new Handler() {
2241
2242 public void handleMessage(Message msg) {
2243 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002244 case FOCUS_NODE_HREF:
2245 String url = (String) msg.getData().get("url");
2246 if (url == null || url.length() == 0) {
2247 break;
2248 }
2249 HashMap focusNodeMap = (HashMap) msg.obj;
2250 WebView view = (WebView) focusNodeMap.get("webview");
2251 // Only apply the action if the top window did not change.
2252 if (getTopWindow() != view) {
2253 break;
2254 }
2255 switch (msg.arg1) {
2256 case R.id.open_context_menu_id:
2257 case R.id.view_image_context_menu_id:
2258 loadURL(getTopWindow(), url);
2259 break;
2260 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002261 final TabControl.Tab parent = mTabControl
2262 .getCurrentTab();
2263 final TabControl.Tab newTab = openTab(url);
2264 if (newTab != parent) {
2265 parent.addChildTab(newTab);
2266 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002267 break;
2268 case R.id.bookmark_context_menu_id:
2269 Intent intent = new Intent(BrowserActivity.this,
2270 AddBookmarkPage.class);
2271 intent.putExtra("url", url);
2272 startActivity(intent);
2273 break;
2274 case R.id.share_link_context_menu_id:
2275 Browser.sendString(BrowserActivity.this, url);
2276 break;
2277 case R.id.copy_link_context_menu_id:
2278 copy(url);
2279 break;
2280 case R.id.save_link_context_menu_id:
2281 case R.id.download_context_menu_id:
2282 onDownloadStartNoStream(url, null, null, null, -1);
2283 break;
2284 }
2285 break;
2286
2287 case LOAD_URL:
2288 loadURL(getTopWindow(), (String) msg.obj);
2289 break;
2290
2291 case STOP_LOAD:
2292 stopLoading();
2293 break;
2294
2295 case CANCEL_CREDS_REQUEST:
2296 resumeAfterCredentials();
2297 break;
2298
The Android Open Source Project0c908882009-03-03 19:32:16 -08002299 case RELEASE_WAKELOCK:
2300 if (mWakeLock.isHeld()) {
2301 mWakeLock.release();
2302 }
2303 break;
2304 }
2305 }
2306 };
2307
Leon Scroggins89c6d362009-07-15 16:54:37 -04002308 private void updateScreenshot(WebView view) {
2309 // If this is a bookmarked site, add a screenshot to the database.
2310 // FIXME: When should we update? Every time?
2311 // FIXME: Would like to make sure there is actually something to
2312 // draw, but the API for that (WebViewCore.pictureReady()) is not
2313 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002314 ContentResolver cr = getContentResolver();
2315 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002316 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002317 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002318 boolean succeed = c.moveToFirst();
2319 ContentValues values = null;
2320 while (succeed) {
2321 if (values == null) {
2322 final ByteArrayOutputStream os
2323 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002324 Bitmap bm = createScreenshot(view);
Leon Scroggins89c6d362009-07-15 16:54:37 -04002325 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2326 values = new ContentValues();
2327 values.put(Browser.BookmarkColumns.THUMBNAIL,
2328 os.toByteArray());
2329 }
2330 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2331 c.getInt(0)), values, null, null);
2332 succeed = c.moveToNext();
2333 }
2334 c.close();
2335 }
2336 }
2337
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002338 private Bitmap createScreenshot(WebView view) {
2339 Picture thumbnail = view.capturePicture();
2340 // Keep width and height in sync with BrowserBookmarksPage
2341 // and bookmark_thumb
2342 Bitmap bm = Bitmap.createBitmap(100, 80,
2343 Bitmap.Config.ARGB_4444);
2344 Canvas canvas = new Canvas(bm);
2345 // May need to tweak these values to determine what is the
2346 // best scale factor
2347 canvas.scale(.5f, .5f);
2348 thumbnail.draw(canvas);
2349 return bm;
2350 }
2351
The Android Open Source Project0c908882009-03-03 19:32:16 -08002352 // -------------------------------------------------------------------------
2353 // WebViewClient implementation.
2354 //-------------------------------------------------------------------------
2355
2356 // Use in overrideUrlLoading
2357 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2358 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2359 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2360 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2361
2362 /* package */ WebViewClient getWebViewClient() {
2363 return mWebViewClient;
2364 }
2365
Patrick Scott3918d442009-08-04 13:22:29 -04002366 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002367 if (icon != null) {
2368 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott15525d42009-09-21 13:39:37 -04002369 view.getOriginalUrl(), view.getUrl(), icon);
2370 }
2371 setFavicon(icon);
2372 }
2373
2374 private void updateIcon(String url, Bitmap icon) {
2375 if (icon != null) {
2376 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2377 null, url, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002378 }
2379 setFavicon(icon);
2380 }
2381
2382 private final WebViewClient mWebViewClient = new WebViewClient() {
2383 @Override
2384 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2385 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002386 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002387
Patrick Scott59ce8302009-09-18 16:29:38 -04002388 // If we start a touch icon load and then load a new page, we don't
2389 // want to cancel the current touch icon loader. But, we do want to
2390 // create a new one when the touch icon url is known.
2391 if (mTouchIconLoader != null) {
2392 mTouchIconLoader.mActivity = null;
2393 mTouchIconLoader = null;
2394 }
2395
Ben Murdochbff2d602009-07-01 20:19:05 +01002396 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2397 if (errorConsole != null) {
2398 errorConsole.clearErrorMessages();
2399 if (mShouldShowErrorConsole) {
2400 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2401 }
2402 }
2403
The Android Open Source Project0c908882009-03-03 19:32:16 -08002404 // Call updateIcon instead of setFavicon so the bookmark
2405 // database can be updated.
Patrick Scott15525d42009-09-21 13:39:37 -04002406 updateIcon(url, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002407
Grace Kloba4d7880f2009-08-12 09:35:42 -07002408 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002409 String host;
2410 try {
2411 WebAddress uri = new WebAddress(url);
2412 host = uri.mHost;
2413 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002414 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002415 }
2416 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002417 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002418 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002419 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002420 }
2421
2422 // Performance probe
2423 if (false) {
2424 mStart = SystemClock.uptimeMillis();
2425 mProcessStart = Process.getElapsedCpuTime();
2426 long[] sysCpu = new long[7];
2427 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2428 sysCpu, null)) {
2429 mUserStart = sysCpu[0] + sysCpu[1];
2430 mSystemStart = sysCpu[2];
2431 mIdleStart = sysCpu[3];
2432 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2433 }
2434 mUiStart = SystemClock.currentThreadTimeMillis();
2435 }
2436
2437 if (!mPageStarted) {
2438 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002439 // if onResume() has been called, resumeWebViewTimers() does
2440 // nothing.
2441 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002442 }
2443
2444 // reset sync timer to avoid sync starts during loading a page
2445 CookieSyncManager.getInstance().resetSync();
2446
2447 mInLoad = true;
Leon Scroggins184f5e32009-09-21 10:38:24 -04002448 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002449 updateInLoadMenuItems();
2450 if (!mIsNetworkUp) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04002451 createAndShowNetworkDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002452 if (view != null) {
2453 view.setNetworkAvailable(false);
2454 }
2455 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002456 }
2457
2458 @Override
2459 public void onPageFinished(WebView view, String url) {
2460 // Reset the title and icon in case we stopped a provisional
2461 // load.
2462 resetTitleAndIcon(view);
2463
2464 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002465 updateLockIconToLatest();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002466 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002467
The Android Open Source Project0c908882009-03-03 19:32:16 -08002468 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002469 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002470 long[] sysCpu = new long[7];
2471 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2472 sysCpu, null)) {
2473 String uiInfo = "UI thread used "
2474 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2475 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002476 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002477 Log.d(LOGTAG, uiInfo);
2478 }
2479 //The string that gets written to the log
2480 String performanceString = "It took total "
2481 + (SystemClock.uptimeMillis() - mStart)
2482 + " ms clock time to load the page."
2483 + "\nbrowser process used "
2484 + (Process.getElapsedCpuTime() - mProcessStart)
2485 + " ms, user processes used "
2486 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2487 + " ms, kernel used "
2488 + (sysCpu[2] - mSystemStart) * 10
2489 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2490 + " ms and irq took "
2491 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2492 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002493 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002494 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2495 }
2496 if (url != null) {
2497 // strip the url to maintain consistency
2498 String newUrl = new String(url);
2499 if (newUrl.startsWith("http://www.")) {
2500 newUrl = newUrl.substring(11);
2501 } else if (newUrl.startsWith("http://")) {
2502 newUrl = newUrl.substring(7);
2503 } else if (newUrl.startsWith("https://www.")) {
2504 newUrl = newUrl.substring(12);
2505 } else if (newUrl.startsWith("https://")) {
2506 newUrl = newUrl.substring(8);
2507 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002508 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002509 Log.d(LOGTAG, newUrl + " loaded");
2510 }
2511 /*
2512 if (sWhiteList.contains(newUrl)) {
2513 // The string that gets pushed to the statistcs
2514 // service
2515 performanceString = performanceString
2516 + "\nWebpage: "
2517 + newUrl
2518 + "\nCarrier: "
2519 + android.os.SystemProperties
2520 .get("gsm.sim.operator.alpha");
2521 if (mWebView != null
2522 && mWebView.getContext() != null
2523 && mWebView.getContext().getSystemService(
2524 Context.CONNECTIVITY_SERVICE) != null) {
2525 ConnectivityManager cManager =
2526 (ConnectivityManager) mWebView
2527 .getContext().getSystemService(
2528 Context.CONNECTIVITY_SERVICE);
2529 NetworkInfo nInfo = cManager
2530 .getActiveNetworkInfo();
2531 if (nInfo != null) {
2532 performanceString = performanceString
2533 + "\nNetwork Type: "
2534 + nInfo.getType().toString();
2535 }
2536 }
2537 Checkin.logEvent(mResolver,
2538 Checkin.Events.Tag.WEBPAGE_LOAD,
2539 performanceString);
2540 Log.w(LOGTAG, "pushed to the statistics service");
2541 }
2542 */
2543 }
2544 }
2545 }
2546
2547 if (mInTrace) {
2548 mInTrace = false;
2549 Debug.stopMethodTracing();
2550 }
2551
2552 if (mPageStarted) {
2553 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002554 // pauseWebViewTimers() will do nothing and return false if
2555 // onPause() is not called yet.
2556 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002557 if (mWakeLock.isHeld()) {
2558 mHandler.removeMessages(RELEASE_WAKELOCK);
2559 mWakeLock.release();
2560 }
2561 }
2562 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002563 }
2564
2565 // return true if want to hijack the url to let another app to handle it
2566 @Override
2567 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2568 if (url.startsWith(SCHEME_WTAI)) {
2569 // wtai://wp/mc;number
2570 // number=string(phone-number)
2571 if (url.startsWith(SCHEME_WTAI_MC)) {
2572 Intent intent = new Intent(Intent.ACTION_VIEW,
2573 Uri.parse(WebView.SCHEME_TEL +
2574 url.substring(SCHEME_WTAI_MC.length())));
2575 startActivity(intent);
2576 return true;
2577 }
2578 // wtai://wp/sd;dtmf
2579 // dtmf=string(dialstring)
2580 if (url.startsWith(SCHEME_WTAI_SD)) {
2581 // TODO
2582 // only send when there is active voice connection
2583 return false;
2584 }
2585 // wtai://wp/ap;number;name
2586 // number=string(phone-number)
2587 // name=string
2588 if (url.startsWith(SCHEME_WTAI_AP)) {
2589 // TODO
2590 return false;
2591 }
2592 }
2593
Dianne Hackborn99189432009-06-17 18:06:18 -07002594 // The "about:" schemes are internal to the browser; don't
2595 // want these to be dispatched to other apps.
2596 if (url.startsWith("about:")) {
2597 return false;
2598 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002599
Dianne Hackborn99189432009-06-17 18:06:18 -07002600 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002601
Dianne Hackborn99189432009-06-17 18:06:18 -07002602 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002603 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002604 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2605 } catch (URISyntaxException ex) {
2606 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002607 return false;
2608 }
2609
Grace Kloba5b078b52009-06-24 20:23:41 -07002610 // check whether the intent can be resolved. If not, we will see
2611 // whether we can download it from the Market.
2612 if (getPackageManager().resolveActivity(intent, 0) == null) {
2613 String packagename = intent.getPackage();
2614 if (packagename != null) {
2615 intent = new Intent(Intent.ACTION_VIEW, Uri
2616 .parse("market://search?q=pname:" + packagename));
2617 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2618 startActivity(intent);
2619 return true;
2620 } else {
2621 return false;
2622 }
2623 }
2624
Dianne Hackborn99189432009-06-17 18:06:18 -07002625 // sanitize the Intent, ensuring web pages can not bypass browser
2626 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002627 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002628 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002629 try {
2630 if (startActivityIfNeeded(intent, -1)) {
2631 return true;
2632 }
2633 } catch (ActivityNotFoundException ex) {
2634 // ignore the error. If no application can handle the URL,
2635 // eg about:blank, assume the browser can handle it.
2636 }
2637
2638 if (mMenuIsDown) {
2639 openTab(url);
2640 closeOptionsMenu();
2641 return true;
2642 }
2643
2644 return false;
2645 }
2646
2647 /**
2648 * Updates the lock icon. This method is called when we discover another
2649 * resource to be loaded for this page (for example, javascript). While
2650 * we update the icon type, we do not update the lock icon itself until
2651 * we are done loading, it is slightly more secure this way.
2652 */
2653 @Override
2654 public void onLoadResource(WebView view, String url) {
2655 if (url != null && url.length() > 0) {
2656 // It is only if the page claims to be secure
2657 // that we may have to update the lock:
2658 if (mLockIconType == LOCK_ICON_SECURE) {
2659 // If NOT a 'safe' url, change the lock to mixed content!
2660 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2661 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002662 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002663 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2664 " updated lock icon to " + mLockIconType + " due to " + url);
2665 }
2666 }
2667 }
2668 }
2669 }
2670
2671 /**
2672 * Show the dialog, asking the user if they would like to continue after
2673 * an excessive number of HTTP redirects.
2674 */
2675 @Override
2676 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2677 final Message continueMsg) {
2678 new AlertDialog.Builder(BrowserActivity.this)
2679 .setTitle(R.string.browserFrameRedirect)
2680 .setMessage(R.string.browserFrame307Post)
2681 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2682 public void onClick(DialogInterface dialog, int which) {
2683 continueMsg.sendToTarget();
2684 }})
2685 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2686 public void onClick(DialogInterface dialog, int which) {
2687 cancelMsg.sendToTarget();
2688 }})
2689 .setOnCancelListener(new OnCancelListener() {
2690 public void onCancel(DialogInterface dialog) {
2691 cancelMsg.sendToTarget();
2692 }})
2693 .show();
2694 }
2695
Patrick Scott37911c72009-03-24 18:02:58 -07002696 // Container class for the next error dialog that needs to be
2697 // displayed.
2698 class ErrorDialog {
2699 public final int mTitle;
2700 public final String mDescription;
2701 public final int mError;
2702 ErrorDialog(int title, String desc, int error) {
2703 mTitle = title;
2704 mDescription = desc;
2705 mError = error;
2706 }
2707 };
2708
2709 private void processNextError() {
2710 if (mQueuedErrors == null) {
2711 return;
2712 }
2713 // The first one is currently displayed so just remove it.
2714 mQueuedErrors.removeFirst();
2715 if (mQueuedErrors.size() == 0) {
2716 mQueuedErrors = null;
2717 return;
2718 }
2719 showError(mQueuedErrors.getFirst());
2720 }
2721
2722 private DialogInterface.OnDismissListener mDialogListener =
2723 new DialogInterface.OnDismissListener() {
2724 public void onDismiss(DialogInterface d) {
2725 processNextError();
2726 }
2727 };
2728 private LinkedList<ErrorDialog> mQueuedErrors;
2729
2730 private void queueError(int err, String desc) {
2731 if (mQueuedErrors == null) {
2732 mQueuedErrors = new LinkedList<ErrorDialog>();
2733 }
2734 for (ErrorDialog d : mQueuedErrors) {
2735 if (d.mError == err) {
2736 // Already saw a similar error, ignore the new one.
2737 return;
2738 }
2739 }
2740 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002741 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002742 R.string.browserFrameFileErrorLabel :
2743 R.string.browserFrameNetworkErrorLabel,
2744 desc, err);
2745 mQueuedErrors.addLast(errDialog);
2746
2747 // Show the dialog now if the queue was empty.
2748 if (mQueuedErrors.size() == 1) {
2749 showError(errDialog);
2750 }
2751 }
2752
2753 private void showError(ErrorDialog errDialog) {
2754 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2755 .setTitle(errDialog.mTitle)
2756 .setMessage(errDialog.mDescription)
2757 .setPositiveButton(R.string.ok, null)
2758 .create();
2759 d.setOnDismissListener(mDialogListener);
2760 d.show();
2761 }
2762
The Android Open Source Project0c908882009-03-03 19:32:16 -08002763 /**
2764 * Show a dialog informing the user of the network error reported by
2765 * WebCore.
2766 */
2767 @Override
2768 public void onReceivedError(WebView view, int errorCode,
2769 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002770 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2771 errorCode != WebViewClient.ERROR_CONNECT &&
2772 errorCode != WebViewClient.ERROR_BAD_URL &&
2773 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2774 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002775 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002776 }
Patrick Scott37911c72009-03-24 18:02:58 -07002777 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2778 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002779
2780 // We need to reset the title after an error.
2781 resetTitleAndRevertLockIcon();
2782 }
2783
2784 /**
2785 * Check with the user if it is ok to resend POST data as the page they
2786 * are trying to navigate to is the result of a POST.
2787 */
2788 @Override
2789 public void onFormResubmission(WebView view, final Message dontResend,
2790 final Message resend) {
2791 new AlertDialog.Builder(BrowserActivity.this)
2792 .setTitle(R.string.browserFrameFormResubmitLabel)
2793 .setMessage(R.string.browserFrameFormResubmitMessage)
2794 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2795 public void onClick(DialogInterface dialog, int which) {
2796 resend.sendToTarget();
2797 }})
2798 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2799 public void onClick(DialogInterface dialog, int which) {
2800 dontResend.sendToTarget();
2801 }})
2802 .setOnCancelListener(new OnCancelListener() {
2803 public void onCancel(DialogInterface dialog) {
2804 dontResend.sendToTarget();
2805 }})
2806 .show();
2807 }
2808
2809 /**
2810 * Insert the url into the visited history database.
2811 * @param url The url to be inserted.
2812 * @param isReload True if this url is being reloaded.
2813 * FIXME: Not sure what to do when reloading the page.
2814 */
2815 @Override
2816 public void doUpdateVisitedHistory(WebView view, String url,
2817 boolean isReload) {
2818 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2819 return;
2820 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002821 // remove "client" before updating it to the history so that it wont
2822 // show up in the auto-complete list.
2823 int index = url.indexOf("client=ms-");
2824 if (index > 0 && url.contains(".google.")) {
2825 int end = url.indexOf('&', index);
2826 if (end > 0) {
2827 url = url.substring(0, index-1).concat(url.substring(end));
2828 } else {
2829 url = url.substring(0, index-1);
2830 }
2831 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002832 Browser.updateVisitedHistory(mResolver, url, true);
2833 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2834 }
2835
2836 /**
2837 * Displays SSL error(s) dialog to the user.
2838 */
2839 @Override
2840 public void onReceivedSslError(
2841 final WebView view, final SslErrorHandler handler, final SslError error) {
2842
2843 if (mSettings.showSecurityWarnings()) {
2844 final LayoutInflater factory =
2845 LayoutInflater.from(BrowserActivity.this);
2846 final View warningsView =
2847 factory.inflate(R.layout.ssl_warnings, null);
2848 final LinearLayout placeholder =
2849 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2850
2851 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2852 LinearLayout ll = (LinearLayout)factory
2853 .inflate(R.layout.ssl_warning, null);
2854 ((TextView)ll.findViewById(R.id.warning))
2855 .setText(R.string.ssl_untrusted);
2856 placeholder.addView(ll);
2857 }
2858
2859 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2860 LinearLayout ll = (LinearLayout)factory
2861 .inflate(R.layout.ssl_warning, null);
2862 ((TextView)ll.findViewById(R.id.warning))
2863 .setText(R.string.ssl_mismatch);
2864 placeholder.addView(ll);
2865 }
2866
2867 if (error.hasError(SslError.SSL_EXPIRED)) {
2868 LinearLayout ll = (LinearLayout)factory
2869 .inflate(R.layout.ssl_warning, null);
2870 ((TextView)ll.findViewById(R.id.warning))
2871 .setText(R.string.ssl_expired);
2872 placeholder.addView(ll);
2873 }
2874
2875 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2876 LinearLayout ll = (LinearLayout)factory
2877 .inflate(R.layout.ssl_warning, null);
2878 ((TextView)ll.findViewById(R.id.warning))
2879 .setText(R.string.ssl_not_yet_valid);
2880 placeholder.addView(ll);
2881 }
2882
2883 new AlertDialog.Builder(BrowserActivity.this)
2884 .setTitle(R.string.security_warning)
2885 .setIcon(android.R.drawable.ic_dialog_alert)
2886 .setView(warningsView)
2887 .setPositiveButton(R.string.ssl_continue,
2888 new DialogInterface.OnClickListener() {
2889 public void onClick(DialogInterface dialog, int whichButton) {
2890 handler.proceed();
2891 }
2892 })
2893 .setNeutralButton(R.string.view_certificate,
2894 new DialogInterface.OnClickListener() {
2895 public void onClick(DialogInterface dialog, int whichButton) {
2896 showSSLCertificateOnError(view, handler, error);
2897 }
2898 })
2899 .setNegativeButton(R.string.cancel,
2900 new DialogInterface.OnClickListener() {
2901 public void onClick(DialogInterface dialog, int whichButton) {
2902 handler.cancel();
2903 BrowserActivity.this.resetTitleAndRevertLockIcon();
2904 }
2905 })
2906 .setOnCancelListener(
2907 new DialogInterface.OnCancelListener() {
2908 public void onCancel(DialogInterface dialog) {
2909 handler.cancel();
2910 BrowserActivity.this.resetTitleAndRevertLockIcon();
2911 }
2912 })
2913 .show();
2914 } else {
2915 handler.proceed();
2916 }
2917 }
2918
2919 /**
2920 * Handles an HTTP authentication request.
2921 *
2922 * @param handler The authentication handler
2923 * @param host The host
2924 * @param realm The realm
2925 */
2926 @Override
2927 public void onReceivedHttpAuthRequest(WebView view,
2928 final HttpAuthHandler handler, final String host, final String realm) {
2929 String username = null;
2930 String password = null;
2931
2932 boolean reuseHttpAuthUsernamePassword =
2933 handler.useHttpAuthUsernamePassword();
2934
2935 if (reuseHttpAuthUsernamePassword &&
2936 (mTabControl.getCurrentWebView() != null)) {
2937 String[] credentials =
2938 mTabControl.getCurrentWebView()
2939 .getHttpAuthUsernamePassword(host, realm);
2940 if (credentials != null && credentials.length == 2) {
2941 username = credentials[0];
2942 password = credentials[1];
2943 }
2944 }
2945
2946 if (username != null && password != null) {
2947 handler.proceed(username, password);
2948 } else {
2949 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2950 }
2951 }
2952
2953 @Override
2954 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2955 if (mMenuIsDown) {
2956 // only check shortcut key when MENU is held
2957 return getWindow().isShortcutKey(event.getKeyCode(), event);
2958 } else {
2959 return false;
2960 }
2961 }
2962
2963 @Override
2964 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2965 if (view != mTabControl.getCurrentTopWebView()) {
2966 return;
2967 }
2968 if (event.isDown()) {
2969 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2970 } else {
2971 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2972 }
2973 }
2974 };
2975
2976 //--------------------------------------------------------------------------
2977 // WebChromeClient implementation
2978 //--------------------------------------------------------------------------
2979
2980 /* package */ WebChromeClient getWebChromeClient() {
2981 return mWebChromeClient;
2982 }
2983
2984 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2985 // Helper method to create a new tab or sub window.
2986 private void createWindow(final boolean dialog, final Message msg) {
2987 if (dialog) {
2988 mTabControl.createSubWindow();
2989 final TabControl.Tab t = mTabControl.getCurrentTab();
2990 attachSubWindow(t);
2991 WebView.WebViewTransport transport =
2992 (WebView.WebViewTransport) msg.obj;
2993 transport.setWebView(t.getSubWebView());
2994 msg.sendToTarget();
2995 } else {
2996 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04002997 final TabControl.Tab newTab
2998 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07002999 if (newTab != parent) {
3000 parent.addChildTab(newTab);
3001 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003002 WebView.WebViewTransport transport =
3003 (WebView.WebViewTransport) msg.obj;
3004 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04003005 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003006 }
3007 }
3008
3009 @Override
3010 public boolean onCreateWindow(WebView view, final boolean dialog,
3011 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003012 // Short-circuit if we can't create any more tabs or sub windows.
3013 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3014 new AlertDialog.Builder(BrowserActivity.this)
3015 .setTitle(R.string.too_many_subwindows_dialog_title)
3016 .setIcon(android.R.drawable.ic_dialog_alert)
3017 .setMessage(R.string.too_many_subwindows_dialog_message)
3018 .setPositiveButton(R.string.ok, null)
3019 .show();
3020 return false;
3021 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3022 new AlertDialog.Builder(BrowserActivity.this)
3023 .setTitle(R.string.too_many_windows_dialog_title)
3024 .setIcon(android.R.drawable.ic_dialog_alert)
3025 .setMessage(R.string.too_many_windows_dialog_message)
3026 .setPositiveButton(R.string.ok, null)
3027 .show();
3028 return false;
3029 }
3030
3031 // Short-circuit if this was a user gesture.
3032 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003033 createWindow(dialog, resultMsg);
3034 return true;
3035 }
3036
3037 // Allow the popup and create the appropriate window.
3038 final AlertDialog.OnClickListener allowListener =
3039 new AlertDialog.OnClickListener() {
3040 public void onClick(DialogInterface d,
3041 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003042 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003043 }
3044 };
3045
3046 // Block the popup by returning a null WebView.
3047 final AlertDialog.OnClickListener blockListener =
3048 new AlertDialog.OnClickListener() {
3049 public void onClick(DialogInterface d, int which) {
3050 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003051 }
3052 };
3053
3054 // Build a confirmation dialog to display to the user.
3055 final AlertDialog d =
3056 new AlertDialog.Builder(BrowserActivity.this)
3057 .setTitle(R.string.attention)
3058 .setIcon(android.R.drawable.ic_dialog_alert)
3059 .setMessage(R.string.popup_window_attempt)
3060 .setPositiveButton(R.string.allow, allowListener)
3061 .setNegativeButton(R.string.block, blockListener)
3062 .setCancelable(false)
3063 .create();
3064
3065 // Show the confirmation dialog.
3066 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003067 return true;
3068 }
3069
3070 @Override
3071 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003072 final TabControl.Tab current = mTabControl.getCurrentTab();
3073 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003074 if (parent != null) {
3075 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003076 switchToTab(mTabControl.getTabIndex(parent));
3077 // Now we need to close the window
3078 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003079 }
3080 }
3081
3082 @Override
3083 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003084 mTitleBar.setProgress(newProgress);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003085 if (mFakeTitleBar != null) {
3086 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003087 }
3088
3089 if (newProgress == 100) {
3090 // onProgressChanged() is called for sub-frame too while
3091 // onPageFinished() is only called for the main frame. sync
3092 // cookie and cache promptly here.
3093 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003094 if (mInLoad) {
3095 mInLoad = false;
3096 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003097 // If the options menu is open, leave the title bar
3098 if (!mOptionsMenuOpen || !mIconView) {
3099 hideFakeTitleBar();
3100 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003101 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003102 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003103 // onPageFinished may have already been called but a subframe
3104 // is still loading and updating the progress. Reset mInLoad
3105 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003106 mInLoad = true;
3107 updateInLoadMenuItems();
Leon Scroggins184f5e32009-09-21 10:38:24 -04003108 if (!mOptionsMenuOpen || mIconView) {
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003109 // This page has begun to load, so show the title bar
3110 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003111 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003112 }
3113 }
3114
3115 @Override
3116 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003117 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003118
3119 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003120 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003121
3122 if (url == null ||
3123 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3124 return;
3125 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003126 // See if we can find the current url in our history database and
3127 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003128 if (url.startsWith("http://www.")) {
3129 url = url.substring(11);
3130 } else if (url.startsWith("http://")) {
3131 url = url.substring(4);
3132 }
3133 try {
3134 url = "%" + url;
3135 String [] selArgs = new String[] { url };
3136
3137 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3138 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3139 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3140 Browser.HISTORY_PROJECTION, where, selArgs, null);
3141 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003142 // Current implementation of database only has one entry per
3143 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003144 ContentValues map = new ContentValues();
3145 map.put(Browser.BookmarkColumns.TITLE, title);
3146 mResolver.update(Browser.BOOKMARKS_URI, map,
3147 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003148 }
3149 c.close();
3150 } catch (IllegalStateException e) {
3151 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3152 } catch (SQLiteException ex) {
3153 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3154 }
3155 }
3156
3157 @Override
3158 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003159 updateIcon(view, icon);
3160 }
3161
3162 @Override
Patrick Scott59ce8302009-09-18 16:29:38 -04003163 public void onReceivedTouchIconUrl(WebView view, String url,
3164 boolean precomposed) {
Patrick Scott3918d442009-08-04 13:22:29 -04003165 final ContentResolver cr = getContentResolver();
3166 final Cursor c =
3167 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003168 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003169 if (c != null) {
3170 if (c.getCount() > 0) {
Patrick Scott59ce8302009-09-18 16:29:38 -04003171 // Let precomposed icons take precedence over non-composed
3172 // icons.
3173 if (precomposed && mTouchIconLoader != null) {
3174 mTouchIconLoader.cancel(false);
3175 mTouchIconLoader = null;
3176 }
3177 // Have only one async task at a time.
3178 if (mTouchIconLoader == null) {
3179 mTouchIconLoader = new DownloadTouchIcon(
3180 BrowserActivity.this, cr, c, view);
3181 mTouchIconLoader.execute(url);
3182 }
Patrick Scott3918d442009-08-04 13:22:29 -04003183 } else {
3184 c.close();
3185 }
3186 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003187 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003188
Andrei Popescuadc008d2009-06-26 14:11:30 +01003189 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003190 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003191 if (mCustomView != null)
3192 return;
3193
3194 // Add the custom view to its container.
3195 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3196 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003197 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003198 // Save the menu state and set it to empty while the custom
3199 // view is showing.
3200 mOldMenuState = mMenuState;
3201 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003202 // Hide the content view.
3203 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003204 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003205 mCustomViewContainer.setVisibility(View.VISIBLE);
3206 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003207 }
3208
3209 @Override
3210 public void onHideCustomView() {
3211 if (mCustomView == null)
3212 return;
3213
Andrei Popescuc9b55562009-07-07 10:51:15 +01003214 // Hide the custom view.
3215 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003216 // Remove the custom view from its container.
3217 mCustomViewContainer.removeView(mCustomView);
3218 mCustomView = null;
3219 // Reset the old menu state.
3220 mMenuState = mOldMenuState;
3221 mOldMenuState = EMPTY_MENU;
3222 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003223 mCustomViewCallback.onCustomViewHidden();
3224 // Show the content view.
3225 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003226 }
3227
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003228 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003229 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003230 * @param url the URL that exceeded the quota
3231 * @param databaseIdentifier the identifier of the database on
3232 * which the transaction that caused the quota overflow was run
3233 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003234 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003235 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003236 * @param quotaUpdater The callback to run when a decision to allow or
3237 * deny quota has been made. Don't forget to call this!
3238 */
3239 @Override
3240 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003241 String databaseIdentifier, long currentQuota, long estimatedSize,
3242 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003243 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003244 url, databaseIdentifier, currentQuota, estimatedSize,
3245 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003246 }
3247
3248 /**
3249 * The Application Cache has exceeded its max size.
3250 * @param spaceNeeded is the amount of disk space that would be needed
3251 * in order for the last appcache operation to succeed.
3252 * @param totalUsedQuota is the sum of all origins' quota.
3253 * @param quotaUpdater A callback to inform the WebCore thread that a new
3254 * app cache size is available. This callback must always be executed at
3255 * some point to ensure that the sleeping WebCore thread is woken up.
3256 */
3257 @Override
3258 public void onReachedMaxAppCacheSize(long spaceNeeded,
3259 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3260 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3261 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003262 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003263
Steve Block2bc69912009-07-30 14:45:13 +01003264 /**
3265 * Instructs the browser to show a prompt to ask the user to set the
3266 * Geolocation permission state for the specified origin.
3267 * @param origin The origin for which Geolocation permissions are
3268 * requested.
3269 * @param callback The callback to call once the user has set the
3270 * Geolocation permission state.
3271 */
3272 @Override
3273 public void onGeolocationPermissionsShowPrompt(String origin,
3274 GeolocationPermissions.Callback callback) {
3275 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3276 origin, callback);
3277 }
3278
3279 /**
3280 * Instructs the browser to hide the Geolocation permissions prompt.
3281 */
3282 @Override
3283 public void onGeolocationPermissionsHidePrompt() {
3284 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3285 }
3286
Ben Murdoch7db26342009-06-03 18:21:19 +01003287 /* Adds a JavaScript error message to the system log.
3288 * @param message The error message to report.
3289 * @param lineNumber The line number of the error.
3290 * @param sourceID The name of the source file that caused the error.
3291 */
3292 @Override
3293 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003294 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3295 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3296 if (mShouldShowErrorConsole &&
3297 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3298 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3299 }
3300 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003301 }
Andrei Popescu540035d2009-09-18 18:59:20 +01003302
3303 /**
3304 * Ask the browser for an icon to represent a <video> element.
3305 * This icon will be used if the Web page did not specify a poster attribute.
3306 *
3307 * @return Bitmap The icon or null if no such icon is available.
3308 * @hide pending API Council approval
3309 */
3310 @Override
3311 public Bitmap getDefaultVideoPoster() {
3312 if (mDefaultVideoPoster == null) {
3313 mDefaultVideoPoster = BitmapFactory.decodeResource(
3314 getResources(), R.drawable.default_video_poster);
3315 }
3316 return mDefaultVideoPoster;
3317 }
3318
3319 /**
3320 * Ask the host application for a custom progress view to show while
3321 * a <video> is loading.
3322 *
3323 * @return View The progress view.
3324 * @hide pending API Council approval
3325 */
3326 @Override
3327 public View getVideoLoadingProgressView() {
3328 if (mVideoProgressView == null) {
3329 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
3330 mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
3331 }
3332 return mVideoProgressView;
3333 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003334 };
3335
3336 /**
3337 * Notify the host application a download should be done, or that
3338 * the data should be streamed if a streaming viewer is available.
3339 * @param url The full url to the content that should be downloaded
3340 * @param contentDisposition Content-disposition http header, if
3341 * present.
3342 * @param mimetype The mimetype of the content reported by the server
3343 * @param contentLength The file size reported by the server
3344 */
3345 public void onDownloadStart(String url, String userAgent,
3346 String contentDisposition, String mimetype, long contentLength) {
3347 // if we're dealing wih A/V content that's not explicitly marked
3348 // for download, check if it's streamable.
3349 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003350 || !contentDisposition.regionMatches(
3351 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003352 // query the package manager to see if there's a registered handler
3353 // that matches.
3354 Intent intent = new Intent(Intent.ACTION_VIEW);
3355 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003356 ResolveInfo info = getPackageManager().resolveActivity(intent,
3357 PackageManager.MATCH_DEFAULT_ONLY);
3358 if (info != null) {
3359 ComponentName myName = getComponentName();
3360 // If we resolved to ourselves, we don't want to attempt to
3361 // load the url only to try and download it again.
3362 if (!myName.getPackageName().equals(
3363 info.activityInfo.packageName)
3364 || !myName.getClassName().equals(
3365 info.activityInfo.name)) {
3366 // someone (other than us) knows how to handle this mime
3367 // type with this scheme, don't download.
3368 try {
3369 startActivity(intent);
3370 return;
3371 } catch (ActivityNotFoundException ex) {
3372 if (LOGD_ENABLED) {
3373 Log.d(LOGTAG, "activity not found for " + mimetype
3374 + " over " + Uri.parse(url).getScheme(),
3375 ex);
3376 }
3377 // Best behavior is to fall back to a download in this
3378 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003379 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003380 }
3381 }
3382 }
3383 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3384 }
3385
3386 /**
3387 * Notify the host application a download should be done, even if there
3388 * is a streaming viewer available for thise type.
3389 * @param url The full url to the content that should be downloaded
3390 * @param contentDisposition Content-disposition http header, if
3391 * present.
3392 * @param mimetype The mimetype of the content reported by the server
3393 * @param contentLength The file size reported by the server
3394 */
3395 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3396 String contentDisposition, String mimetype, long contentLength) {
3397
3398 String filename = URLUtil.guessFileName(url,
3399 contentDisposition, mimetype);
3400
3401 // Check to see if we have an SDCard
3402 String status = Environment.getExternalStorageState();
3403 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3404 int title;
3405 String msg;
3406
3407 // Check to see if the SDCard is busy, same as the music app
3408 if (status.equals(Environment.MEDIA_SHARED)) {
3409 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3410 title = R.string.download_sdcard_busy_dlg_title;
3411 } else {
3412 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3413 title = R.string.download_no_sdcard_dlg_title;
3414 }
3415
3416 new AlertDialog.Builder(this)
3417 .setTitle(title)
3418 .setIcon(android.R.drawable.ic_dialog_alert)
3419 .setMessage(msg)
3420 .setPositiveButton(R.string.ok, null)
3421 .show();
3422 return;
3423 }
3424
3425 // java.net.URI is a lot stricter than KURL so we have to undo
3426 // KURL's percent-encoding and redo the encoding using java.net.URI.
3427 URI uri = null;
3428 try {
3429 // Undo the percent-encoding that KURL may have done.
3430 String newUrl = new String(URLUtil.decode(url.getBytes()));
3431 // Parse the url into pieces
3432 WebAddress w = new WebAddress(newUrl);
3433 String frag = null;
3434 String query = null;
3435 String path = w.mPath;
3436 // Break the path into path, query, and fragment
3437 if (path.length() > 0) {
3438 // Strip the fragment
3439 int idx = path.lastIndexOf('#');
3440 if (idx != -1) {
3441 frag = path.substring(idx + 1);
3442 path = path.substring(0, idx);
3443 }
3444 idx = path.lastIndexOf('?');
3445 if (idx != -1) {
3446 query = path.substring(idx + 1);
3447 path = path.substring(0, idx);
3448 }
3449 }
3450 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3451 query, frag);
3452 } catch (Exception e) {
3453 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3454 return;
3455 }
3456
3457 // XXX: Have to use the old url since the cookies were stored using the
3458 // old percent-encoded url.
3459 String cookies = CookieManager.getInstance().getCookie(url);
3460
3461 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003462 values.put(Downloads.COLUMN_URI, uri.toString());
3463 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3464 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3465 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003466 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003467 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003468 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003469 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3470 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3471 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3472 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003473 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003474 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003475 }
3476 if (mimetype == null) {
3477 // We must have long pressed on a link or image to download it. We
3478 // are not sure of the mimetype in this case, so do a head request
3479 new FetchUrlMimeType(this).execute(values);
3480 } else {
3481 final Uri contentUri =
3482 getContentResolver().insert(Downloads.CONTENT_URI, values);
3483 viewDownloads(contentUri);
3484 }
3485
3486 }
3487
3488 /**
3489 * Resets the lock icon. This method is called when we start a new load and
3490 * know the url to be loaded.
3491 */
3492 private void resetLockIcon(String url) {
3493 // Save the lock-icon state (we revert to it if the load gets cancelled)
3494 saveLockIcon();
3495
3496 mLockIconType = LOCK_ICON_UNSECURE;
3497 if (URLUtil.isHttpsUrl(url)) {
3498 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003499 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003500 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3501 " reset lock icon to " + mLockIconType);
3502 }
3503 }
3504
3505 updateLockIconImage(LOCK_ICON_UNSECURE);
3506 }
3507
Grace Klobaeb6eef42009-09-15 17:56:32 -07003508 /* package */ void setLockIconType(int type) {
3509 mLockIconType = type;
3510 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003511
Grace Klobaeb6eef42009-09-15 17:56:32 -07003512 /* package */ int getLockIconType() {
3513 return mLockIconType;
3514 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003515
Grace Klobaeb6eef42009-09-15 17:56:32 -07003516 /* package */ void setPrevLockType(int type) {
3517 mPrevLockType = type;
3518 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003519
Grace Klobaeb6eef42009-09-15 17:56:32 -07003520 /* package */ int getPrevLockType() {
3521 return mPrevLockType;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003522 }
3523
3524 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003525 * Update the lock icon to correspond to our latest state.
3526 */
3527 /* package */ void updateLockIconToLatest() {
3528 updateLockIconImage(mLockIconType);
3529 }
3530
3531 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003532 * Updates the lock-icon image in the title-bar.
3533 */
3534 private void updateLockIconImage(int lockIconType) {
3535 Drawable d = null;
3536 if (lockIconType == LOCK_ICON_SECURE) {
3537 d = mSecLockIcon;
3538 } else if (lockIconType == LOCK_ICON_MIXED) {
3539 d = mMixLockIcon;
3540 }
Leon Scroggins68579392009-09-15 15:31:54 -04003541 mTitleBar.setLock(d);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003542 if (mFakeTitleBar != null) {
3543 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003544 }
3545 }
3546
3547 /**
3548 * Displays a page-info dialog.
3549 * @param tab The tab to show info about
3550 * @param fromShowSSLCertificateOnError The flag that indicates whether
3551 * this dialog was opened from the SSL-certificate-on-error dialog or
3552 * not. This is important, since we need to know whether to return to
3553 * the parent dialog or simply dismiss.
3554 */
3555 private void showPageInfo(final TabControl.Tab tab,
3556 final boolean fromShowSSLCertificateOnError) {
3557 final LayoutInflater factory = LayoutInflater
3558 .from(this);
3559
3560 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3561
3562 final WebView view = tab.getWebView();
3563
3564 String url = null;
3565 String title = null;
3566
3567 if (view == null) {
3568 url = tab.getUrl();
3569 title = tab.getTitle();
3570 } else if (view == mTabControl.getCurrentWebView()) {
3571 // Use the cached title and url if this is the current WebView
3572 url = mUrl;
3573 title = mTitle;
3574 } else {
3575 url = view.getUrl();
3576 title = view.getTitle();
3577 }
3578
3579 if (url == null) {
3580 url = "";
3581 }
3582 if (title == null) {
3583 title = "";
3584 }
3585
3586 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3587 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3588
3589 mPageInfoView = tab;
3590 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3591
3592 AlertDialog.Builder alertDialogBuilder =
3593 new AlertDialog.Builder(this)
3594 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3595 .setView(pageInfoView)
3596 .setPositiveButton(
3597 R.string.ok,
3598 new DialogInterface.OnClickListener() {
3599 public void onClick(DialogInterface dialog,
3600 int whichButton) {
3601 mPageInfoDialog = null;
3602 mPageInfoView = null;
3603 mPageInfoFromShowSSLCertificateOnError = null;
3604
3605 // if we came here from the SSL error dialog
3606 if (fromShowSSLCertificateOnError) {
3607 // go back to the SSL error dialog
3608 showSSLCertificateOnError(
3609 mSSLCertificateOnErrorView,
3610 mSSLCertificateOnErrorHandler,
3611 mSSLCertificateOnErrorError);
3612 }
3613 }
3614 })
3615 .setOnCancelListener(
3616 new DialogInterface.OnCancelListener() {
3617 public void onCancel(DialogInterface dialog) {
3618 mPageInfoDialog = null;
3619 mPageInfoView = null;
3620 mPageInfoFromShowSSLCertificateOnError = null;
3621
3622 // if we came here from the SSL error dialog
3623 if (fromShowSSLCertificateOnError) {
3624 // go back to the SSL error dialog
3625 showSSLCertificateOnError(
3626 mSSLCertificateOnErrorView,
3627 mSSLCertificateOnErrorHandler,
3628 mSSLCertificateOnErrorError);
3629 }
3630 }
3631 });
3632
3633 // if we have a main top-level page SSL certificate set or a certificate
3634 // error
3635 if (fromShowSSLCertificateOnError ||
3636 (view != null && view.getCertificate() != null)) {
3637 // add a 'View Certificate' button
3638 alertDialogBuilder.setNeutralButton(
3639 R.string.view_certificate,
3640 new DialogInterface.OnClickListener() {
3641 public void onClick(DialogInterface dialog,
3642 int whichButton) {
3643 mPageInfoDialog = null;
3644 mPageInfoView = null;
3645 mPageInfoFromShowSSLCertificateOnError = null;
3646
3647 // if we came here from the SSL error dialog
3648 if (fromShowSSLCertificateOnError) {
3649 // go back to the SSL error dialog
3650 showSSLCertificateOnError(
3651 mSSLCertificateOnErrorView,
3652 mSSLCertificateOnErrorHandler,
3653 mSSLCertificateOnErrorError);
3654 } else {
3655 // otherwise, display the top-most certificate from
3656 // the chain
3657 if (view.getCertificate() != null) {
3658 showSSLCertificate(tab);
3659 }
3660 }
3661 }
3662 });
3663 }
3664
3665 mPageInfoDialog = alertDialogBuilder.show();
3666 }
3667
3668 /**
3669 * Displays the main top-level page SSL certificate dialog
3670 * (accessible from the Page-Info dialog).
3671 * @param tab The tab to show certificate for.
3672 */
3673 private void showSSLCertificate(final TabControl.Tab tab) {
3674 final View certificateView =
3675 inflateCertificateView(tab.getWebView().getCertificate());
3676 if (certificateView == null) {
3677 return;
3678 }
3679
3680 LayoutInflater factory = LayoutInflater.from(this);
3681
3682 final LinearLayout placeholder =
3683 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3684
3685 LinearLayout ll = (LinearLayout) factory.inflate(
3686 R.layout.ssl_success, placeholder);
3687 ((TextView)ll.findViewById(R.id.success))
3688 .setText(R.string.ssl_certificate_is_valid);
3689
3690 mSSLCertificateView = tab;
3691 mSSLCertificateDialog =
3692 new AlertDialog.Builder(this)
3693 .setTitle(R.string.ssl_certificate).setIcon(
3694 R.drawable.ic_dialog_browser_certificate_secure)
3695 .setView(certificateView)
3696 .setPositiveButton(R.string.ok,
3697 new DialogInterface.OnClickListener() {
3698 public void onClick(DialogInterface dialog,
3699 int whichButton) {
3700 mSSLCertificateDialog = null;
3701 mSSLCertificateView = null;
3702
3703 showPageInfo(tab, false);
3704 }
3705 })
3706 .setOnCancelListener(
3707 new DialogInterface.OnCancelListener() {
3708 public void onCancel(DialogInterface dialog) {
3709 mSSLCertificateDialog = null;
3710 mSSLCertificateView = null;
3711
3712 showPageInfo(tab, false);
3713 }
3714 })
3715 .show();
3716 }
3717
3718 /**
3719 * Displays the SSL error certificate dialog.
3720 * @param view The target web-view.
3721 * @param handler The SSL error handler responsible for cancelling the
3722 * connection that resulted in an SSL error or proceeding per user request.
3723 * @param error The SSL error object.
3724 */
3725 private void showSSLCertificateOnError(
3726 final WebView view, final SslErrorHandler handler, final SslError error) {
3727
3728 final View certificateView =
3729 inflateCertificateView(error.getCertificate());
3730 if (certificateView == null) {
3731 return;
3732 }
3733
3734 LayoutInflater factory = LayoutInflater.from(this);
3735
3736 final LinearLayout placeholder =
3737 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3738
3739 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3740 LinearLayout ll = (LinearLayout)factory
3741 .inflate(R.layout.ssl_warning, placeholder);
3742 ((TextView)ll.findViewById(R.id.warning))
3743 .setText(R.string.ssl_untrusted);
3744 }
3745
3746 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3747 LinearLayout ll = (LinearLayout)factory
3748 .inflate(R.layout.ssl_warning, placeholder);
3749 ((TextView)ll.findViewById(R.id.warning))
3750 .setText(R.string.ssl_mismatch);
3751 }
3752
3753 if (error.hasError(SslError.SSL_EXPIRED)) {
3754 LinearLayout ll = (LinearLayout)factory
3755 .inflate(R.layout.ssl_warning, placeholder);
3756 ((TextView)ll.findViewById(R.id.warning))
3757 .setText(R.string.ssl_expired);
3758 }
3759
3760 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3761 LinearLayout ll = (LinearLayout)factory
3762 .inflate(R.layout.ssl_warning, placeholder);
3763 ((TextView)ll.findViewById(R.id.warning))
3764 .setText(R.string.ssl_not_yet_valid);
3765 }
3766
3767 mSSLCertificateOnErrorHandler = handler;
3768 mSSLCertificateOnErrorView = view;
3769 mSSLCertificateOnErrorError = error;
3770 mSSLCertificateOnErrorDialog =
3771 new AlertDialog.Builder(this)
3772 .setTitle(R.string.ssl_certificate).setIcon(
3773 R.drawable.ic_dialog_browser_certificate_partially_secure)
3774 .setView(certificateView)
3775 .setPositiveButton(R.string.ok,
3776 new DialogInterface.OnClickListener() {
3777 public void onClick(DialogInterface dialog,
3778 int whichButton) {
3779 mSSLCertificateOnErrorDialog = null;
3780 mSSLCertificateOnErrorView = null;
3781 mSSLCertificateOnErrorHandler = null;
3782 mSSLCertificateOnErrorError = null;
3783
3784 mWebViewClient.onReceivedSslError(
3785 view, handler, error);
3786 }
3787 })
3788 .setNeutralButton(R.string.page_info_view,
3789 new DialogInterface.OnClickListener() {
3790 public void onClick(DialogInterface dialog,
3791 int whichButton) {
3792 mSSLCertificateOnErrorDialog = null;
3793
3794 // do not clear the dialog state: we will
3795 // need to show the dialog again once the
3796 // user is done exploring the page-info details
3797
3798 showPageInfo(mTabControl.getTabFromView(view),
3799 true);
3800 }
3801 })
3802 .setOnCancelListener(
3803 new DialogInterface.OnCancelListener() {
3804 public void onCancel(DialogInterface dialog) {
3805 mSSLCertificateOnErrorDialog = null;
3806 mSSLCertificateOnErrorView = null;
3807 mSSLCertificateOnErrorHandler = null;
3808 mSSLCertificateOnErrorError = null;
3809
3810 mWebViewClient.onReceivedSslError(
3811 view, handler, error);
3812 }
3813 })
3814 .show();
3815 }
3816
3817 /**
3818 * Inflates the SSL certificate view (helper method).
3819 * @param certificate The SSL certificate.
3820 * @return The resultant certificate view with issued-to, issued-by,
3821 * issued-on, expires-on, and possibly other fields set.
3822 * If the input certificate is null, returns null.
3823 */
3824 private View inflateCertificateView(SslCertificate certificate) {
3825 if (certificate == null) {
3826 return null;
3827 }
3828
3829 LayoutInflater factory = LayoutInflater.from(this);
3830
3831 View certificateView = factory.inflate(
3832 R.layout.ssl_certificate, null);
3833
3834 // issued to:
3835 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3836 if (issuedTo != null) {
3837 ((TextView) certificateView.findViewById(R.id.to_common))
3838 .setText(issuedTo.getCName());
3839 ((TextView) certificateView.findViewById(R.id.to_org))
3840 .setText(issuedTo.getOName());
3841 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3842 .setText(issuedTo.getUName());
3843 }
3844
3845 // issued by:
3846 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3847 if (issuedBy != null) {
3848 ((TextView) certificateView.findViewById(R.id.by_common))
3849 .setText(issuedBy.getCName());
3850 ((TextView) certificateView.findViewById(R.id.by_org))
3851 .setText(issuedBy.getOName());
3852 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3853 .setText(issuedBy.getUName());
3854 }
3855
3856 // issued on:
3857 String issuedOn = reformatCertificateDate(
3858 certificate.getValidNotBefore());
3859 ((TextView) certificateView.findViewById(R.id.issued_on))
3860 .setText(issuedOn);
3861
3862 // expires on:
3863 String expiresOn = reformatCertificateDate(
3864 certificate.getValidNotAfter());
3865 ((TextView) certificateView.findViewById(R.id.expires_on))
3866 .setText(expiresOn);
3867
3868 return certificateView;
3869 }
3870
3871 /**
3872 * Re-formats the certificate date (Date.toString()) string to
3873 * a properly localized date string.
3874 * @return Properly localized version of the certificate date string and
3875 * the original certificate date string if fails to localize.
3876 * If the original string is null, returns an empty string "".
3877 */
3878 private String reformatCertificateDate(String certificateDate) {
3879 String reformattedDate = null;
3880
3881 if (certificateDate != null) {
3882 Date date = null;
3883 try {
3884 date = java.text.DateFormat.getInstance().parse(certificateDate);
3885 } catch (ParseException e) {
3886 date = null;
3887 }
3888
3889 if (date != null) {
3890 reformattedDate =
3891 DateFormat.getDateFormat(this).format(date);
3892 }
3893 }
3894
3895 return reformattedDate != null ? reformattedDate :
3896 (certificateDate != null ? certificateDate : "");
3897 }
3898
3899 /**
3900 * Displays an http-authentication dialog.
3901 */
3902 private void showHttpAuthentication(final HttpAuthHandler handler,
3903 final String host, final String realm, final String title,
3904 final String name, final String password, int focusId) {
3905 LayoutInflater factory = LayoutInflater.from(this);
3906 final View v = factory
3907 .inflate(R.layout.http_authentication, null);
3908 if (name != null) {
3909 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3910 }
3911 if (password != null) {
3912 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3913 }
3914
3915 String titleText = title;
3916 if (titleText == null) {
3917 titleText = getText(R.string.sign_in_to).toString().replace(
3918 "%s1", host).replace("%s2", realm);
3919 }
3920
3921 mHttpAuthHandler = handler;
3922 AlertDialog dialog = new AlertDialog.Builder(this)
3923 .setTitle(titleText)
3924 .setIcon(android.R.drawable.ic_dialog_alert)
3925 .setView(v)
3926 .setPositiveButton(R.string.action,
3927 new DialogInterface.OnClickListener() {
3928 public void onClick(DialogInterface dialog,
3929 int whichButton) {
3930 String nm = ((EditText) v
3931 .findViewById(R.id.username_edit))
3932 .getText().toString();
3933 String pw = ((EditText) v
3934 .findViewById(R.id.password_edit))
3935 .getText().toString();
3936 BrowserActivity.this.setHttpAuthUsernamePassword
3937 (host, realm, nm, pw);
3938 handler.proceed(nm, pw);
3939 mHttpAuthenticationDialog = null;
3940 mHttpAuthHandler = null;
3941 }})
3942 .setNegativeButton(R.string.cancel,
3943 new DialogInterface.OnClickListener() {
3944 public void onClick(DialogInterface dialog,
3945 int whichButton) {
3946 handler.cancel();
3947 BrowserActivity.this.resetTitleAndRevertLockIcon();
3948 mHttpAuthenticationDialog = null;
3949 mHttpAuthHandler = null;
3950 }})
3951 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3952 public void onCancel(DialogInterface dialog) {
3953 handler.cancel();
3954 BrowserActivity.this.resetTitleAndRevertLockIcon();
3955 mHttpAuthenticationDialog = null;
3956 mHttpAuthHandler = null;
3957 }})
3958 .create();
3959 // Make the IME appear when the dialog is displayed if applicable.
3960 dialog.getWindow().setSoftInputMode(
3961 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3962 dialog.show();
3963 if (focusId != 0) {
3964 dialog.findViewById(focusId).requestFocus();
3965 } else {
3966 v.findViewById(R.id.username_edit).requestFocus();
3967 }
3968 mHttpAuthenticationDialog = dialog;
3969 }
3970
3971 public int getProgress() {
3972 WebView w = mTabControl.getCurrentWebView();
3973 if (w != null) {
3974 return w.getProgress();
3975 } else {
3976 return 100;
3977 }
3978 }
3979
3980 /**
3981 * Set HTTP authentication password.
3982 *
3983 * @param host The host for the password
3984 * @param realm The realm for the password
3985 * @param username The username for the password. If it is null, it means
3986 * password can't be saved.
3987 * @param password The password
3988 */
3989 public void setHttpAuthUsernamePassword(String host, String realm,
3990 String username,
3991 String password) {
3992 WebView w = mTabControl.getCurrentWebView();
3993 if (w != null) {
3994 w.setHttpAuthUsernamePassword(host, realm, username, password);
3995 }
3996 }
3997
3998 /**
3999 * connectivity manager says net has come or gone... inform the user
4000 * @param up true if net has come up, false if net has gone down
4001 */
4002 public void onNetworkToggle(boolean up) {
4003 if (up == mIsNetworkUp) {
4004 return;
4005 } else if (up) {
4006 mIsNetworkUp = true;
4007 if (mAlertDialog != null) {
4008 mAlertDialog.cancel();
4009 mAlertDialog = null;
4010 }
4011 } else {
4012 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004013 if (mInLoad) {
4014 createAndShowNetworkDialog();
4015 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004016 }
4017 WebView w = mTabControl.getCurrentWebView();
4018 if (w != null) {
4019 w.setNetworkAvailable(up);
4020 }
4021 }
4022
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004023 // This method shows the network dialog alerting the user that the net is
4024 // down. It will only show the dialog if mAlertDialog is null.
4025 private void createAndShowNetworkDialog() {
4026 if (mAlertDialog == null) {
4027 mAlertDialog = new AlertDialog.Builder(this)
4028 .setTitle(R.string.loadSuspendedTitle)
4029 .setMessage(R.string.loadSuspended)
4030 .setPositiveButton(R.string.ok, null)
4031 .show();
4032 }
4033 }
4034
The Android Open Source Project0c908882009-03-03 19:32:16 -08004035 @Override
4036 protected void onActivityResult(int requestCode, int resultCode,
4037 Intent intent) {
4038 switch (requestCode) {
4039 case COMBO_PAGE:
4040 if (resultCode == RESULT_OK && intent != null) {
4041 String data = intent.getAction();
4042 Bundle extras = intent.getExtras();
4043 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04004044 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004045 } else {
4046 final TabControl.Tab currentTab =
4047 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04004048 dismissSubWindow(currentTab);
4049 if (data != null && data.length() != 0) {
4050 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004051 }
4052 }
4053 }
4054 break;
4055 default:
4056 break;
4057 }
Leon Scroggins30444232009-09-04 18:36:20 -04004058 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004059 }
4060
4061 /*
4062 * This method is called as a result of the user selecting the options
4063 * menu to see the download window, or when a download changes state. It
4064 * shows the download window ontop of the current window.
4065 */
4066 /* package */ void viewDownloads(Uri downloadRecord) {
4067 Intent intent = new Intent(this,
4068 BrowserDownloadPage.class);
4069 intent.setData(downloadRecord);
4070 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4071
4072 }
4073
Leon Scroggins160a7e72009-08-14 18:28:01 -04004074 /**
4075 * Open the Go page.
4076 * @param startWithHistory If true, open starting on the history tab.
4077 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004078 */
Leon Scroggins30444232009-09-04 18:36:20 -04004079 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004080 WebView current = mTabControl.getCurrentWebView();
4081 if (current == null) {
4082 return;
4083 }
4084 Intent intent = new Intent(this,
4085 CombinedBookmarkHistoryActivity.class);
4086 String title = current.getTitle();
4087 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004088 Bitmap thumbnail = createScreenshot(current);
4089
The Android Open Source Project0c908882009-03-03 19:32:16 -08004090 // Just in case the user opens bookmarks before a page finishes loading
4091 // so the current history item, and therefore the page, is null.
4092 if (null == url) {
4093 url = mLastEnteredUrl;
4094 // This can happen.
4095 if (null == url) {
4096 url = mSettings.getHomePage();
4097 }
4098 }
4099 // In case the web page has not yet received its associated title.
4100 if (title == null) {
4101 title = url;
4102 }
4103 intent.putExtra("title", title);
4104 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004105 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04004106 // Disable opening in a new window if we have maxed out the windows
4107 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4108 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004109 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004110 if (startWithHistory) {
4111 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4112 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4113 }
4114 startActivityForResult(intent, COMBO_PAGE);
4115 }
4116
4117 // Called when loading from context menu or LOAD_URL message
4118 private void loadURL(WebView view, String url) {
4119 // In case the user enters nothing.
4120 if (url != null && url.length() != 0 && view != null) {
4121 url = smartUrlFilter(url);
4122 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4123 view.loadUrl(url);
4124 }
4125 }
4126 }
4127
The Android Open Source Project0c908882009-03-03 19:32:16 -08004128 private String smartUrlFilter(Uri inUri) {
4129 if (inUri != null) {
4130 return smartUrlFilter(inUri.toString());
4131 }
4132 return null;
4133 }
4134
4135
4136 // get window count
4137
4138 int getWindowCount(){
4139 if(mTabControl != null){
4140 return mTabControl.getTabCount();
4141 }
4142 return 0;
4143 }
4144
Feng Qianb34f87a2009-03-24 21:27:26 -07004145 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004146 "(?i)" + // switch on case insensitive matching
4147 "(" + // begin group for schema
4148 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004149 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004150 ")" +
4151 "(.*)" );
4152
4153 /**
4154 * Attempts to determine whether user input is a URL or search
4155 * terms. Anything with a space is passed to search.
4156 *
4157 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4158 * "Http://" converts to "http://"
4159 *
4160 * @return Original or modified URL
4161 *
4162 */
4163 String smartUrlFilter(String url) {
4164
4165 String inUrl = url.trim();
4166 boolean hasSpace = inUrl.indexOf(' ') != -1;
4167
4168 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4169 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004170 // force scheme to lowercase
4171 String scheme = matcher.group(1);
4172 String lcScheme = scheme.toLowerCase();
4173 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004174 inUrl = lcScheme + matcher.group(2);
4175 }
4176 if (hasSpace) {
4177 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004178 }
4179 return inUrl;
4180 }
4181 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004182 // FIXME: Is this the correct place to add to searches?
4183 // what if someone else calls this function?
4184 int shortcut = parseUrlShortcut(inUrl);
4185 if (shortcut != SHORTCUT_INVALID) {
4186 Browser.addSearchUrl(mResolver, inUrl);
4187 String query = inUrl.substring(2);
4188 switch (shortcut) {
4189 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004190 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004191 case SHORTCUT_WIKIPEDIA_SEARCH:
4192 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4193 case SHORTCUT_DICTIONARY_SEARCH:
4194 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4195 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004196 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004197 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004198 }
4199 }
4200 } else {
4201 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4202 return URLUtil.guessUrl(inUrl);
4203 }
4204 }
4205
4206 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004207 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004208 }
4209
Ben Murdochbff2d602009-07-01 20:19:05 +01004210 /* package */ void setShouldShowErrorConsole(boolean flag) {
4211 if (flag == mShouldShowErrorConsole) {
4212 // Nothing to do.
4213 return;
4214 }
4215
4216 mShouldShowErrorConsole = flag;
4217
4218 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4219
4220 if (flag) {
4221 // Setting the show state of the console will cause it's the layout to be inflated.
4222 if (errorConsole.numberOfErrors() > 0) {
4223 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4224 } else {
4225 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4226 }
4227
4228 // Now we can add it to the main view.
4229 mErrorConsoleContainer.addView(errorConsole,
4230 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4231 ViewGroup.LayoutParams.WRAP_CONTENT));
4232 } else {
4233 mErrorConsoleContainer.removeView(errorConsole);
4234 }
4235
4236 }
4237
Grace Klobaeb6eef42009-09-15 17:56:32 -07004238 final static int LOCK_ICON_UNSECURE = 0;
4239 final static int LOCK_ICON_SECURE = 1;
4240 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004241
4242 private int mLockIconType = LOCK_ICON_UNSECURE;
4243 private int mPrevLockType = LOCK_ICON_UNSECURE;
4244
4245 private BrowserSettings mSettings;
4246 private TabControl mTabControl;
4247 private ContentResolver mResolver;
4248 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004249 private View mCustomView;
4250 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004251 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004252
4253 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4254 // view, we should rewrite this.
4255 private int mCurrentMenuState = 0;
4256 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004257 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004258 private static final int EMPTY_MENU = -1;
4259 private Menu mMenu;
4260
4261 private FindDialog mFindDialog;
4262 // Used to prevent chording to result in firing two shortcuts immediately
4263 // one after another. Fixes bug 1211714.
4264 boolean mCanChord;
4265
4266 private boolean mInLoad;
4267 private boolean mIsNetworkUp;
4268
4269 private boolean mPageStarted;
4270 private boolean mActivityInPause = true;
4271
4272 private boolean mMenuIsDown;
4273
The Android Open Source Project0c908882009-03-03 19:32:16 -08004274 private static boolean mInTrace;
4275
4276 // Performance probe
4277 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4278 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4279 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4280 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4281 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4282 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4283 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4284 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4285 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4286 };
4287
4288 private long mStart;
4289 private long mProcessStart;
4290 private long mUserStart;
4291 private long mSystemStart;
4292 private long mIdleStart;
4293 private long mIrqStart;
4294
4295 private long mUiStart;
4296
4297 private Drawable mMixLockIcon;
4298 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004299
4300 /* hold a ref so we can auto-cancel if necessary */
4301 private AlertDialog mAlertDialog;
4302
4303 // Wait for credentials before loading google.com
4304 private ProgressDialog mCredsDlg;
4305
4306 // The up-to-date URL and title (these can be different from those stored
4307 // in WebView, since it takes some time for the information in WebView to
4308 // get updated)
4309 private String mUrl;
4310 private String mTitle;
4311
4312 // As PageInfo has different style for landscape / portrait, we have
4313 // to re-open it when configuration changed
4314 private AlertDialog mPageInfoDialog;
4315 private TabControl.Tab mPageInfoView;
4316 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4317 // dialog, we should not just dismiss it, but should get back to the
4318 // SSL-certificate-on-error dialog. This flag is used to store this state
4319 private Boolean mPageInfoFromShowSSLCertificateOnError;
4320
4321 // as SSLCertificateOnError has different style for landscape / portrait,
4322 // we have to re-open it when configuration changed
4323 private AlertDialog mSSLCertificateOnErrorDialog;
4324 private WebView mSSLCertificateOnErrorView;
4325 private SslErrorHandler mSSLCertificateOnErrorHandler;
4326 private SslError mSSLCertificateOnErrorError;
4327
4328 // as SSLCertificate has different style for landscape / portrait, we
4329 // have to re-open it when configuration changed
4330 private AlertDialog mSSLCertificateDialog;
4331 private TabControl.Tab mSSLCertificateView;
4332
4333 // as HttpAuthentication has different style for landscape / portrait, we
4334 // have to re-open it when configuration changed
4335 private AlertDialog mHttpAuthenticationDialog;
4336 private HttpAuthHandler mHttpAuthHandler;
4337
4338 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4339 new FrameLayout.LayoutParams(
4340 ViewGroup.LayoutParams.FILL_PARENT,
4341 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004342 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4343 new FrameLayout.LayoutParams(
4344 ViewGroup.LayoutParams.FILL_PARENT,
4345 ViewGroup.LayoutParams.FILL_PARENT,
4346 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004347 // Google search
4348 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004349 // Wikipedia search
4350 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4351 // Dictionary search
4352 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4353 // Google Mobile Local search
4354 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4355
4356 final static String QUERY_PLACE_HOLDER = "%s";
4357
4358 // "source" parameter for Google search through search key
4359 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4360 // "source" parameter for Google search through goto menu
4361 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4362 // "source" parameter for Google search through simplily type
4363 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4364 // "source" parameter for Google search suggested by the browser
4365 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4366 // "source" parameter for Google search from unknown source
4367 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4368
4369 private final static String LOGTAG = "browser";
4370
The Android Open Source Project0c908882009-03-03 19:32:16 -08004371 private String mLastEnteredUrl;
4372
4373 private PowerManager.WakeLock mWakeLock;
4374 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4375
4376 private Toast mStopToast;
4377
Leon Scroggins68579392009-09-15 15:31:54 -04004378 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004379
Ben Murdochbff2d602009-07-01 20:19:05 +01004380 private LinearLayout mErrorConsoleContainer = null;
4381 private boolean mShouldShowErrorConsole = false;
4382
The Android Open Source Project0c908882009-03-03 19:32:16 -08004383 // As the ids are dynamically created, we can't guarantee that they will
4384 // be in sequence, so this static array maps ids to a window number.
4385 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4386 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4387 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4388 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4389
4390 // monitor platform changes
4391 private IntentFilter mNetworkStateChangedFilter;
4392 private BroadcastReceiver mNetworkStateIntentReceiver;
4393
Grace Klobab4da0ad2009-05-14 14:45:40 -07004394 private BroadcastReceiver mPackageInstallationReceiver;
4395
Patrick Scott59ce8302009-09-18 16:29:38 -04004396 // AsyncTask for downloading touch icons
4397 /* package */ DownloadTouchIcon mTouchIconLoader;
4398
The Android Open Source Project0c908882009-03-03 19:32:16 -08004399 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004400 final static int COMBO_PAGE = 1;
4401 final static int DOWNLOAD_PAGE = 2;
4402 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004403
Andrei Popescu540035d2009-09-18 18:59:20 +01004404 // the default <video> poster
4405 private Bitmap mDefaultVideoPoster;
4406 // the video progress view
4407 private View mVideoProgressView;
4408
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004409 /**
4410 * A UrlData class to abstract how the content will be set to WebView.
4411 * This base class uses loadUrl to show the content.
4412 */
4413 private static class UrlData {
4414 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004415 byte[] mPostData;
4416
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004417 UrlData(String url) {
4418 this.mUrl = url;
4419 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004420
4421 void setPostData(byte[] postData) {
4422 mPostData = postData;
4423 }
4424
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004425 boolean isEmpty() {
4426 return mUrl == null || mUrl.length() == 0;
4427 }
4428
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004429 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004430 if (mPostData != null) {
4431 webView.postUrl(mUrl, mPostData);
4432 } else {
4433 webView.loadUrl(mUrl);
4434 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004435 }
4436 };
4437
4438 /**
4439 * A subclass of UrlData class that can display inlined content using
4440 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4441 */
4442 private static class InlinedUrlData extends UrlData {
4443 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4444 super(failUrl);
4445 mInlined = inlined;
4446 mMimeType = mimeType;
4447 mEncoding = encoding;
4448 }
4449 String mMimeType;
4450 String mInlined;
4451 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004452 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004453 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004454 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004455 }
4456
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004457 @Override
4458 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004459 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4460 }
4461 }
4462
Leon Scroggins1f005d32009-08-10 17:36:42 -04004463 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004464}