blob: 4a8ddb49157285e7d1f8121b0eeae203e49c2a86 [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 }
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100620 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA));
Satish Sampath565505b2009-05-29 15:37:27 +0100621 }
622
623 /**
624 * Launches the default web search activity with the query parameters if the given url string
625 * was identified as plain search terms and not URL/shortcut.
626 * @return true if the request was handled and web search activity was launched, false if not.
627 */
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100628 private boolean handleWebSearchRequest(String inUrl, Bundle appData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100629 if (inUrl == null) return false;
630
631 // In general, we shouldn't modify URL from Intent.
632 // But currently, we get the user-typed URL from search box as well.
633 String url = fixUrl(inUrl).trim();
634
635 // URLs and site specific search shortcuts are handled by the regular flow of control, so
636 // return early.
637 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100638 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100639 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
640 return false;
641 }
642
643 Browser.updateVisitedHistory(mResolver, url, false);
644 Browser.addSearchUrl(mResolver, url);
645
646 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
647 intent.addCategory(Intent.CATEGORY_DEFAULT);
648 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100649 if (appData != null) {
650 intent.putExtra(SearchManager.APP_DATA, appData);
651 }
Grace Klobacc634032009-07-28 15:58:19 -0700652 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100653 startActivity(intent);
654
655 return true;
656 }
657
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700658 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800659 String url = null;
660 if (intent != null) {
661 final String action = intent.getAction();
662 if (Intent.ACTION_VIEW.equals(action)) {
663 url = smartUrlFilter(intent.getData());
664 if (url != null && url.startsWith("content:")) {
665 /* Append mimetype so webview knows how to display */
666 String mimeType = intent.resolveType(getContentResolver());
667 if (mimeType != null) {
668 url += "?" + mimeType;
669 }
670 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700671 if ("inline:".equals(url)) {
672 return new InlinedUrlData(
673 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
674 intent.getType(),
675 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
676 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
677 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800678 } else if (Intent.ACTION_SEARCH.equals(action)
679 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
680 || Intent.ACTION_WEB_SEARCH.equals(action)) {
681 url = intent.getStringExtra(SearchManager.QUERY);
682 if (url != null) {
683 mLastEnteredUrl = url;
684 // Don't add Urls, just search terms.
685 // Urls will get added when the page is loaded.
686 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
687 Browser.updateVisitedHistory(mResolver, url, false);
688 }
689 // In general, we shouldn't modify URL from Intent.
690 // But currently, we get the user-typed URL from search box as well.
691 url = fixUrl(url);
692 url = smartUrlFilter(url);
693 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
694 if (url.contains(searchSource)) {
695 String source = null;
696 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
697 if (appData != null) {
698 source = appData.getString(SearchManager.SOURCE);
699 }
700 if (TextUtils.isEmpty(source)) {
701 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
702 }
703 url = url.replace(searchSource, "&source=android-"+source+"&");
704 }
705 }
706 }
707 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700708 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800709 }
710
711 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400712 // FIXME: Converting the url to lower case
713 // duplicates functionality in smartUrlFilter().
714 // However, changing all current callers of fixUrl to
715 // call smartUrlFilter in addition may have unwanted
716 // consequences, and is deferred for now.
717 int colon = inUrl.indexOf(':');
718 boolean allLower = true;
719 for (int index = 0; index < colon; index++) {
720 char ch = inUrl.charAt(index);
721 if (!Character.isLetter(ch)) {
722 break;
723 }
724 allLower &= Character.isLowerCase(ch);
725 if (index == colon - 1 && !allLower) {
726 inUrl = inUrl.substring(0, colon).toLowerCase()
727 + inUrl.substring(colon);
728 }
729 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800730 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
731 return inUrl;
732 if (inUrl.startsWith("http:") ||
733 inUrl.startsWith("https:")) {
734 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
735 inUrl = inUrl.replaceFirst("/", "//");
736 } else inUrl = inUrl.replaceFirst(":", "://");
737 }
738 return inUrl;
739 }
740
741 /**
742 * Looking for the pattern like this
743 *
744 * *
745 * * *
746 * *** * *******
747 * * *
748 * * *
749 * *
750 */
751 private final SensorListener mSensorListener = new SensorListener() {
752 private long mLastGestureTime;
753 private float[] mPrev = new float[3];
754 private float[] mPrevDiff = new float[3];
755 private float[] mDiff = new float[3];
756 private float[] mRevertDiff = new float[3];
757
758 public void onSensorChanged(int sensor, float[] values) {
759 boolean show = false;
760 float[] diff = new float[3];
761
762 for (int i = 0; i < 3; i++) {
763 diff[i] = values[i] - mPrev[i];
764 if (Math.abs(diff[i]) > 1) {
765 show = true;
766 }
767 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
768 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
769 // start track when there is a big move, or revert
770 mRevertDiff[i] = mDiff[i];
771 mDiff[i] = 0;
772 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
773 // reset when it is flat
774 mDiff[i] = mRevertDiff[i] = 0;
775 }
776 mDiff[i] += diff[i];
777 mPrevDiff[i] = diff[i];
778 mPrev[i] = values[i];
779 }
780
781 if (false) {
782 // only shows if we think the delta is big enough, in an attempt
783 // to detect "serious" moves left/right or up/down
784 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
785 + values[0] + ", " + values[1] + ", " + values[2] + ")"
786 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
787 + ")");
788 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
789 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
790 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
791 + mRevertDiff[2] + ")");
792 }
793
794 long now = android.os.SystemClock.uptimeMillis();
795 if (now - mLastGestureTime > 1000) {
796 mLastGestureTime = 0;
797
798 float y = mDiff[1];
799 float z = mDiff[2];
800 float ay = Math.abs(y);
801 float az = Math.abs(z);
802 float ry = mRevertDiff[1];
803 float rz = mRevertDiff[2];
804 float ary = Math.abs(ry);
805 float arz = Math.abs(rz);
806 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
807 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
808
809 if ((gestY || gestZ) && !(gestY && gestZ)) {
810 WebView view = mTabControl.getCurrentWebView();
811
812 if (view != null) {
813 if (gestZ) {
814 if (z < 0) {
815 view.zoomOut();
816 } else {
817 view.zoomIn();
818 }
819 } else {
820 view.flingScroll(0, Math.round(y * 100));
821 }
822 }
823 mLastGestureTime = now;
824 }
825 }
826 }
827
828 public void onAccuracyChanged(int sensor, int accuracy) {
829 // TODO Auto-generated method stub
830
831 }
832 };
833
834 @Override protected void onResume() {
835 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700836 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800837 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
838 }
839
840 if (!mActivityInPause) {
841 Log.e(LOGTAG, "BrowserActivity is already resumed.");
842 return;
843 }
844
Mike Reed7bfa63b2009-05-28 11:08:32 -0400845 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800846 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400847 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800848
849 if (mWakeLock.isHeld()) {
850 mHandler.removeMessages(RELEASE_WAKELOCK);
851 mWakeLock.release();
852 }
853
854 if (mCredsDlg != null) {
855 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
856 // In case credential request never comes back
857 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
858 }
859 }
860
861 registerReceiver(mNetworkStateIntentReceiver,
862 mNetworkStateChangedFilter);
863 WebView.enablePlatformNotifications();
864
865 if (mSettings.doFlick()) {
866 if (mSensorManager == null) {
867 mSensorManager = (SensorManager) getSystemService(
868 Context.SENSOR_SERVICE);
869 }
870 mSensorManager.registerListener(mSensorListener,
871 SensorManager.SENSOR_ACCELEROMETER,
872 SensorManager.SENSOR_DELAY_FASTEST);
873 } else {
874 mSensorManager = null;
875 }
876 }
877
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400878 /**
879 * Since the actual title bar is embedded in the WebView, and removing it
880 * would change its appearance, create a temporary title bar to go at
881 * the top of the screen while the menu is open.
882 */
883 private TitleBar mFakeTitleBar;
884
885 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400886 * Holder for the fake title bar. It will have a foreground shadow, as well
887 * as a white background, so the fake title bar looks like the real one.
888 */
889 private ViewGroup mFakeTitleBarHolder;
890
891 /**
892 * Layout parameters for the fake title bar within mFakeTitleBarHolder
893 */
894 private FrameLayout.LayoutParams mFakeTitleBarParams
895 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400896 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400897 ViewGroup.LayoutParams.WRAP_CONTENT);
898 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400899 * Keeps track of whether the options menu is open. This is important in
900 * determining whether to show or hide the title bar overlay.
901 */
902 private boolean mOptionsMenuOpen;
903
904 /**
905 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
906 * of whether the configuration has changed. The first onMenuOpened call
907 * after a configuration change is simply a reopening of the same menu
908 * (i.e. mIconView did not change).
909 */
910 private boolean mConfigChanged;
911
912 /**
913 * Whether or not the options menu is in its smaller, icon menu form. When
914 * true, we want the title bar overlay to be up. When false, we do not.
915 * Only meaningful if mOptionsMenuOpen is true.
916 */
917 private boolean mIconView;
918
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400919 @Override
920 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400921 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
922 if (mOptionsMenuOpen) {
923 if (mConfigChanged) {
924 // We do not need to make any changes to the state of the
925 // title bar, since the only thing that happened was a
926 // change in orientation
927 mConfigChanged = false;
928 } else {
929 if (mIconView) {
930 // Switching the menu to expanded view, so hide the
931 // title bar.
932 hideFakeTitleBar();
933 mIconView = false;
934 } else {
935 // Switching the menu back to icon view, so show the
936 // title bar once again.
937 showFakeTitleBar();
938 mIconView = true;
939 }
940 }
941 } else {
942 // The options menu is closed, so open it, and show the title
943 showFakeTitleBar();
944 mOptionsMenuOpen = true;
945 mConfigChanged = false;
946 mIconView = true;
947 }
948 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400949 return true;
950 }
951
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400952 private void showFakeTitleBar() {
Leon Scroggins4d7e4062009-09-15 15:49:45 -0400953 if (mFakeTitleBar == null && mActiveTabsPage == null
954 && !mActivityInPause) {
Leon Scrogginsf4bb18a2009-09-11 18:37:53 -0400955 final WebView webView = getTopWindow();
Leon Scroggins68579392009-09-15 15:31:54 -0400956 mFakeTitleBar = new TitleBar(this);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400957 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
958 mFakeTitleBar.setProgress(webView.getProgress());
959 mFakeTitleBar.setFavicon(webView.getFavicon());
960 updateLockIconToLatest();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400961
962 WindowManager manager
963 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
964
965 // Add the title bar to the window manager so it can receive touches
966 // while the menu is up
967 WindowManager.LayoutParams params
968 = new WindowManager.LayoutParams(
969 ViewGroup.LayoutParams.FILL_PARENT,
970 ViewGroup.LayoutParams.WRAP_CONTENT,
971 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
972 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
973 PixelFormat.OPAQUE);
974 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400975 WebView mainView = mTabControl.getCurrentWebView();
976 params.windowAnimations = mainView == null
977 || mainView.getScrollY() != 0
978 ? com.android.internal.R.style.Animation_DropDownDown : 0;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400979 // XXX : Without providing an offset, the fake title bar will be
980 // placed underneath the status bar. Use the global visible rect
981 // of mBrowserFrameLayout to determine the bottom of the status bar
982 Rect rectangle = new Rect();
983 mBrowserFrameLayout.getGlobalVisibleRect(rectangle);
984 params.y = rectangle.top;
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400985 // Add a holder for the title bar. It is a FrameLayout, which
986 // allows it to have an overlay shadow. It also has a white
987 // background, which is the same as the background when it is
988 // placed in a WebView.
989 if (mFakeTitleBarHolder == null) {
990 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
991 .inflate(R.layout.title_bar_bg, null);
992 }
993 mFakeTitleBarHolder.addView(mFakeTitleBar, mFakeTitleBarParams);
994 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400995 }
996 }
997
998 @Override
999 public void onOptionsMenuClosed(Menu menu) {
1000 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04001001 if (!mInLoad) {
1002 hideFakeTitleBar();
1003 } else if (!mIconView) {
1004 // The page is currently loading, and we are in expanded mode, so
1005 // we were not showing the menu. Show it once again. It will be
1006 // removed when the page finishes.
1007 showFakeTitleBar();
1008 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001009 }
1010 private void hideFakeTitleBar() {
1011 if (mFakeTitleBar == null) return;
1012 WindowManager manager
1013 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001014 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1015 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001016 mFakeTitleBar = null;
1017 }
1018
The Android Open Source Project0c908882009-03-03 19:32:16 -08001019 /**
1020 * onSaveInstanceState(Bundle map)
1021 * onSaveInstanceState is called right before onStop(). The map contains
1022 * the saved state.
1023 */
1024 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001025 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001026 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1027 }
1028 // the default implementation requires each view to have an id. As the
1029 // browser handles the state itself and it doesn't use id for the views,
1030 // don't call the default implementation. Otherwise it will trigger the
1031 // warning like this, "couldn't save which view has focus because the
1032 // focused view XXX has no id".
1033
1034 // Save all the tabs
1035 mTabControl.saveState(outState);
1036 }
1037
1038 @Override protected void onPause() {
1039 super.onPause();
1040
1041 if (mActivityInPause) {
1042 Log.e(LOGTAG, "BrowserActivity is already paused.");
1043 return;
1044 }
1045
Mike Reed7bfa63b2009-05-28 11:08:32 -04001046 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001047 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001048 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001049 mWakeLock.acquire();
1050 mHandler.sendMessageDelayed(mHandler
1051 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1052 }
1053
1054 // Clear the credentials toast if it is up
1055 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1056 mCredsDlg.dismiss();
1057 }
1058 mCredsDlg = null;
1059
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001060 // FIXME: This removes the active tabs page and resets the menu to
1061 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1062 // but then we would need to save it in onSaveInstanceState and restore
1063 // it in onCreate/onRestoreInstanceState
1064 if (mActiveTabsPage != null) {
1065 removeActiveTabPage(true);
1066 }
1067
The Android Open Source Project0c908882009-03-03 19:32:16 -08001068 cancelStopToast();
1069
1070 // unregister network state listener
1071 unregisterReceiver(mNetworkStateIntentReceiver);
1072 WebView.disablePlatformNotifications();
1073
1074 if (mSensorManager != null) {
1075 mSensorManager.unregisterListener(mSensorListener);
1076 }
1077 }
1078
1079 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001080 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001081 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1082 }
1083 super.onDestroy();
1084 // Remove the current tab and sub window
1085 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001086 if (t != null) {
1087 dismissSubWindow(t);
1088 removeTabFromContentView(t);
1089 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001090 // Destroy all the tabs
1091 mTabControl.destroy();
1092 WebIconDatabase.getInstance().close();
1093 if (mGlsConnection != null) {
1094 unbindService(mGlsConnection);
1095 mGlsConnection = null;
1096 }
1097
1098 //
1099 // stop MASF proxy service
1100 //
1101 //Intent proxyServiceIntent = new Intent();
1102 //proxyServiceIntent.setComponent
1103 // (new ComponentName(
1104 // "com.android.masfproxyservice",
1105 // "com.android.masfproxyservice.MasfProxyService"));
1106 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001107
1108 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001109 }
1110
1111 @Override
1112 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001113 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001114 super.onConfigurationChanged(newConfig);
1115
1116 if (mPageInfoDialog != null) {
1117 mPageInfoDialog.dismiss();
1118 showPageInfo(
1119 mPageInfoView,
1120 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1121 }
1122 if (mSSLCertificateDialog != null) {
1123 mSSLCertificateDialog.dismiss();
1124 showSSLCertificate(
1125 mSSLCertificateView);
1126 }
1127 if (mSSLCertificateOnErrorDialog != null) {
1128 mSSLCertificateOnErrorDialog.dismiss();
1129 showSSLCertificateOnError(
1130 mSSLCertificateOnErrorView,
1131 mSSLCertificateOnErrorHandler,
1132 mSSLCertificateOnErrorError);
1133 }
1134 if (mHttpAuthenticationDialog != null) {
1135 String title = ((TextView) mHttpAuthenticationDialog
1136 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1137 .toString();
1138 String name = ((TextView) mHttpAuthenticationDialog
1139 .findViewById(R.id.username_edit)).getText().toString();
1140 String password = ((TextView) mHttpAuthenticationDialog
1141 .findViewById(R.id.password_edit)).getText().toString();
1142 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1143 .getId();
1144 mHttpAuthenticationDialog.dismiss();
1145 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1146 name, password, focusId);
1147 }
1148 if (mFindDialog != null && mFindDialog.isShowing()) {
1149 mFindDialog.onConfigurationChanged(newConfig);
1150 }
1151 }
1152
1153 @Override public void onLowMemory() {
1154 super.onLowMemory();
1155 mTabControl.freeMemory();
1156 }
1157
Mike Reed7bfa63b2009-05-28 11:08:32 -04001158 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001159 if ((!mActivityInPause && !mPageStarted) ||
1160 (mActivityInPause && mPageStarted)) {
1161 CookieSyncManager.getInstance().startSync();
1162 WebView w = mTabControl.getCurrentWebView();
1163 if (w != null) {
1164 w.resumeTimers();
1165 }
1166 return true;
1167 } else {
1168 return false;
1169 }
1170 }
1171
Mike Reed7bfa63b2009-05-28 11:08:32 -04001172 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001173 if (mActivityInPause && !mPageStarted) {
1174 CookieSyncManager.getInstance().stopSync();
1175 WebView w = mTabControl.getCurrentWebView();
1176 if (w != null) {
1177 w.pauseTimers();
1178 }
1179 return true;
1180 } else {
1181 return false;
1182 }
1183 }
1184
Leon Scroggins1f005d32009-08-10 17:36:42 -04001185 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001186 /*
1187 * This function is called when we are launching for the first time. We
1188 * are waiting for the login credentials before loading Google home
1189 * pages. This way the user will be logged in straight away.
1190 */
1191 private void waitForCredentials() {
1192 // Show a toast
1193 mCredsDlg = new ProgressDialog(this);
1194 mCredsDlg.setIndeterminate(true);
1195 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1196 // If the user cancels the operation, then cancel the Google
1197 // Credentials request.
1198 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1199 mCredsDlg.show();
1200
1201 // We set a timeout for the retrieval of credentials in onResume()
1202 // as that is when we have freed up some CPU time to get
1203 // the login credentials.
1204 }
1205
1206 /*
1207 * If we have received the credentials or we have timed out and we are
1208 * showing the credentials dialog, then it is time to move on.
1209 */
1210 private void resumeAfterCredentials() {
1211 if (mCredsDlg == null) {
1212 return;
1213 }
1214
1215 // Clear the toast
1216 if (mCredsDlg.isShowing()) {
1217 mCredsDlg.dismiss();
1218 }
1219 mCredsDlg = null;
1220
1221 // Clear any pending timeout
1222 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1223
1224 // Load the page
1225 WebView w = mTabControl.getCurrentWebView();
1226 if (w != null) {
1227 w.loadUrl(mSettings.getHomePage());
1228 }
1229
1230 // Update the settings, need to do this last as it can take a moment
1231 // to persist the settings. In the mean time we could be loading
1232 // content.
1233 mSettings.setLoginInitialized(this);
1234 }
1235
1236 // Open the icon database and retain all the icons for visited sites.
1237 private void retainIconsOnStartup() {
1238 final WebIconDatabase db = WebIconDatabase.getInstance();
1239 db.open(getDir("icons", 0).getPath());
1240 try {
1241 Cursor c = Browser.getAllBookmarks(mResolver);
1242 if (!c.moveToFirst()) {
1243 c.deactivate();
1244 return;
1245 }
1246 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1247 do {
1248 String url = c.getString(urlIndex);
1249 db.retainIconForPageUrl(url);
1250 } while (c.moveToNext());
1251 c.deactivate();
1252 } catch (IllegalStateException e) {
1253 Log.e(LOGTAG, "retainIconsOnStartup", e);
1254 }
1255 }
1256
1257 // Helper method for getting the top window.
1258 WebView getTopWindow() {
1259 return mTabControl.getCurrentTopWebView();
1260 }
1261
1262 @Override
1263 public boolean onCreateOptionsMenu(Menu menu) {
1264 super.onCreateOptionsMenu(menu);
1265
1266 MenuInflater inflater = getMenuInflater();
1267 inflater.inflate(R.menu.browser, menu);
1268 mMenu = menu;
1269 updateInLoadMenuItems();
1270 return true;
1271 }
1272
1273 /**
1274 * As the menu can be open when loading state changes
1275 * we must manually update the state of the stop/reload menu
1276 * item
1277 */
1278 private void updateInLoadMenuItems() {
1279 if (mMenu == null) {
1280 return;
1281 }
1282 MenuItem src = mInLoad ?
1283 mMenu.findItem(R.id.stop_menu_id):
1284 mMenu.findItem(R.id.reload_menu_id);
1285 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1286 dest.setIcon(src.getIcon());
1287 dest.setTitle(src.getTitle());
1288 }
1289
1290 @Override
1291 public boolean onContextItemSelected(MenuItem item) {
1292 // chording is not an issue with context menus, but we use the same
1293 // options selector, so set mCanChord to true so we can access them.
1294 mCanChord = true;
1295 int id = item.getItemId();
1296 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001297 if (null == webView) {
1298 return false;
1299 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001300 final HashMap hrefMap = new HashMap();
1301 hrefMap.put("webview", webView);
1302 final Message msg = mHandler.obtainMessage(
1303 FOCUS_NODE_HREF, id, 0, hrefMap);
1304 switch (id) {
1305 // -- Browser context menu
1306 case R.id.open_context_menu_id:
1307 case R.id.open_newtab_context_menu_id:
1308 case R.id.bookmark_context_menu_id:
1309 case R.id.save_link_context_menu_id:
1310 case R.id.share_link_context_menu_id:
1311 case R.id.copy_link_context_menu_id:
1312 webView.requestFocusNodeHref(msg);
1313 break;
1314
1315 default:
1316 // For other context menus
1317 return onOptionsItemSelected(item);
1318 }
1319 mCanChord = false;
1320 return true;
1321 }
1322
1323 private Bundle createGoogleSearchSourceBundle(String source) {
1324 Bundle bundle = new Bundle();
1325 bundle.putString(SearchManager.SOURCE, source);
1326 return bundle;
1327 }
1328
1329 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001330 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001331 */
1332 @Override
1333 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001334 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001335 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001336 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001337 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001338 return true;
1339 }
1340
1341 @Override
1342 public void startSearch(String initialQuery, boolean selectInitialQuery,
1343 Bundle appSearchData, boolean globalSearch) {
1344 if (appSearchData == null) {
1345 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1346 }
1347 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1348 }
1349
Leon Scroggins1f005d32009-08-10 17:36:42 -04001350 /**
1351 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1352 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001353 * @param index Index of the tab to change to, as defined by
1354 * mTabControl.getTabIndex(Tab t).
1355 * @return boolean True if we successfully switched to a different tab. If
1356 * the indexth tab is null, or if that tab is the same as
1357 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001358 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001359 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001360 TabControl.Tab tab = mTabControl.getTab(index);
1361 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1362 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001363 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001364 }
1365 if (currentTab != null) {
1366 // currentTab may be null if it was just removed. In that case,
1367 // we do not need to remove it
1368 removeTabFromContentView(currentTab);
1369 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001370 mTabControl.setCurrentTab(tab);
1371 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001372 resetTitleIconAndProgress();
1373 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001374 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001375 }
1376
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001377 /* package */ TabControl.Tab openTabToHomePage() {
1378 return openTabAndShow(mSettings.getHomePage(), false, null);
1379 }
1380
Leon Scroggins1f005d32009-08-10 17:36:42 -04001381 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001382 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001383 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001384 // This is the last tab. Open a new one, with the home
1385 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001386 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001387 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001388 return;
1389 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001390 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001391 int indexToShow = -1;
1392 if (parent != null) {
1393 indexToShow = mTabControl.getTabIndex(parent);
1394 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001395 final int currentIndex = mTabControl.getCurrentIndex();
1396 // Try to move to the tab to the right
1397 indexToShow = currentIndex + 1;
1398 if (indexToShow > mTabControl.getTabCount() - 1) {
1399 // Try to move to the tab to the left
1400 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001401 }
1402 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001403 if (switchToTab(indexToShow)) {
1404 // Close window
1405 closeTab(current);
1406 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001407 }
1408
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001409 private ActiveTabsPage mActiveTabsPage;
1410
1411 /**
1412 * Remove the active tabs page.
1413 * @param needToAttach If true, the active tabs page did not attach a tab
1414 * to the content view, so we need to do that here.
1415 */
1416 /* package */ void removeActiveTabPage(boolean needToAttach) {
1417 mContentView.removeView(mActiveTabsPage);
1418 mActiveTabsPage = null;
1419 mMenuState = R.id.MAIN_MENU;
1420 if (needToAttach) {
1421 attachTabToContentView(mTabControl.getCurrentTab());
1422 }
1423 getTopWindow().requestFocus();
1424 }
1425
The Android Open Source Project0c908882009-03-03 19:32:16 -08001426 @Override
1427 public boolean onOptionsItemSelected(MenuItem item) {
1428 if (!mCanChord) {
1429 // The user has already fired a shortcut with this hold down of the
1430 // menu key.
1431 return false;
1432 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001433 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001434 return false;
1435 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001436 if (mMenuIsDown) {
1437 // The shortcut action consumes the MENU. Even if it is still down,
1438 // it won't trigger the next shortcut action. In the case of the
1439 // shortcut action triggering a new activity, like Bookmarks, we
1440 // won't get onKeyUp for MENU. So it is important to reset it here.
1441 mMenuIsDown = false;
1442 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001443 switch (item.getItemId()) {
1444 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001445 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001446 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001447 break;
1448
Leon Scroggins64b80f32009-08-07 12:03:34 -04001449 case R.id.goto_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001450 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001451 break;
1452
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001453 case R.id.active_tabs_menu_id:
1454 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1455 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001456 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001457 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1458 mActiveTabsPage.requestFocus();
1459 mMenuState = EMPTY_MENU;
1460 break;
1461
Leon Scroggins1f005d32009-08-10 17:36:42 -04001462 case R.id.add_bookmark_menu_id:
1463 Intent i = new Intent(BrowserActivity.this,
1464 AddBookmarkPage.class);
1465 WebView w = getTopWindow();
1466 i.putExtra("url", w.getUrl());
1467 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001468 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001469 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001470 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001471 break;
1472
1473 case R.id.stop_reload_menu_id:
1474 if (mInLoad) {
1475 stopLoading();
1476 } else {
1477 getTopWindow().reload();
1478 }
1479 break;
1480
1481 case R.id.back_menu_id:
1482 getTopWindow().goBack();
1483 break;
1484
1485 case R.id.forward_menu_id:
1486 getTopWindow().goForward();
1487 break;
1488
1489 case R.id.close_menu_id:
1490 // Close the subwindow if it exists.
1491 if (mTabControl.getCurrentSubWindow() != null) {
1492 dismissSubWindow(mTabControl.getCurrentTab());
1493 break;
1494 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001495 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001496 break;
1497
1498 case R.id.homepage_menu_id:
1499 TabControl.Tab current = mTabControl.getCurrentTab();
1500 if (current != null) {
1501 dismissSubWindow(current);
1502 current.getWebView().loadUrl(mSettings.getHomePage());
1503 }
1504 break;
1505
1506 case R.id.preferences_menu_id:
1507 Intent intent = new Intent(this,
1508 BrowserPreferencesPage.class);
1509 startActivityForResult(intent, PREFERENCES_PAGE);
1510 break;
1511
1512 case R.id.find_menu_id:
1513 if (null == mFindDialog) {
1514 mFindDialog = new FindDialog(this);
1515 }
1516 mFindDialog.setWebView(getTopWindow());
1517 mFindDialog.show();
1518 mMenuState = EMPTY_MENU;
1519 break;
1520
1521 case R.id.select_text_id:
1522 getTopWindow().emulateShiftHeld();
1523 break;
1524 case R.id.page_info_menu_id:
1525 showPageInfo(mTabControl.getCurrentTab(), false);
1526 break;
1527
1528 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001529 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001530 break;
1531
1532 case R.id.share_page_menu_id:
1533 Browser.sendString(this, getTopWindow().getUrl());
1534 break;
1535
1536 case R.id.dump_nav_menu_id:
1537 getTopWindow().debugDump();
1538 break;
1539
1540 case R.id.zoom_in_menu_id:
1541 getTopWindow().zoomIn();
1542 break;
1543
1544 case R.id.zoom_out_menu_id:
1545 getTopWindow().zoomOut();
1546 break;
1547
1548 case R.id.view_downloads_menu_id:
1549 viewDownloads(null);
1550 break;
1551
The Android Open Source Project0c908882009-03-03 19:32:16 -08001552 case R.id.window_one_menu_id:
1553 case R.id.window_two_menu_id:
1554 case R.id.window_three_menu_id:
1555 case R.id.window_four_menu_id:
1556 case R.id.window_five_menu_id:
1557 case R.id.window_six_menu_id:
1558 case R.id.window_seven_menu_id:
1559 case R.id.window_eight_menu_id:
1560 {
1561 int menuid = item.getItemId();
1562 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1563 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1564 TabControl.Tab desiredTab = mTabControl.getTab(id);
1565 if (desiredTab != null &&
1566 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001567 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001568 }
1569 break;
1570 }
1571 }
1572 }
1573 break;
1574
1575 default:
1576 if (!super.onOptionsItemSelected(item)) {
1577 return false;
1578 }
1579 // Otherwise fall through.
1580 }
1581 mCanChord = false;
1582 return true;
1583 }
1584
1585 public void closeFind() {
1586 mMenuState = R.id.MAIN_MENU;
1587 }
1588
1589 @Override public boolean onPrepareOptionsMenu(Menu menu)
1590 {
1591 // This happens when the user begins to hold down the menu key, so
1592 // allow them to chord to get a shortcut.
1593 mCanChord = true;
1594 // Note: setVisible will decide whether an item is visible; while
1595 // setEnabled() will decide whether an item is enabled, which also means
1596 // whether the matching shortcut key will function.
1597 super.onPrepareOptionsMenu(menu);
1598 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001599 case EMPTY_MENU:
1600 if (mCurrentMenuState != mMenuState) {
1601 menu.setGroupVisible(R.id.MAIN_MENU, false);
1602 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1603 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001604 }
1605 break;
1606 default:
1607 if (mCurrentMenuState != mMenuState) {
1608 menu.setGroupVisible(R.id.MAIN_MENU, true);
1609 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1610 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001611 }
1612 final WebView w = getTopWindow();
1613 boolean canGoBack = false;
1614 boolean canGoForward = false;
1615 boolean isHome = false;
1616 if (w != null) {
1617 canGoBack = w.canGoBack();
1618 canGoForward = w.canGoForward();
1619 isHome = mSettings.getHomePage().equals(w.getUrl());
1620 }
1621 final MenuItem back = menu.findItem(R.id.back_menu_id);
1622 back.setEnabled(canGoBack);
1623
1624 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1625 home.setEnabled(!isHome);
1626
1627 menu.findItem(R.id.forward_menu_id)
1628 .setEnabled(canGoForward);
1629
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001630 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1631 mTabControl.getTabCount() < TabControl.MAX_TABS);
1632
The Android Open Source Project0c908882009-03-03 19:32:16 -08001633 // decide whether to show the share link option
1634 PackageManager pm = getPackageManager();
1635 Intent send = new Intent(Intent.ACTION_SEND);
1636 send.setType("text/plain");
1637 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1638 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1639
The Android Open Source Project0c908882009-03-03 19:32:16 -08001640 boolean isNavDump = mSettings.isNavDump();
1641 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1642 nav.setVisible(isNavDump);
1643 nav.setEnabled(isNavDump);
1644 break;
1645 }
1646 mCurrentMenuState = mMenuState;
1647 return true;
1648 }
1649
1650 @Override
1651 public void onCreateContextMenu(ContextMenu menu, View v,
1652 ContextMenuInfo menuInfo) {
1653 WebView webview = (WebView) v;
1654 WebView.HitTestResult result = webview.getHitTestResult();
1655 if (result == null) {
1656 return;
1657 }
1658
1659 int type = result.getType();
1660 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1661 Log.w(LOGTAG,
1662 "We should not show context menu when nothing is touched");
1663 return;
1664 }
1665 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1666 // let TextView handles context menu
1667 return;
1668 }
1669
1670 // Note, http://b/issue?id=1106666 is requesting that
1671 // an inflated menu can be used again. This is not available
1672 // yet, so inflate each time (yuk!)
1673 MenuInflater inflater = getMenuInflater();
1674 inflater.inflate(R.menu.browsercontext, menu);
1675
1676 // Show the correct menu group
1677 String extra = result.getExtra();
1678 menu.setGroupVisible(R.id.PHONE_MENU,
1679 type == WebView.HitTestResult.PHONE_TYPE);
1680 menu.setGroupVisible(R.id.EMAIL_MENU,
1681 type == WebView.HitTestResult.EMAIL_TYPE);
1682 menu.setGroupVisible(R.id.GEO_MENU,
1683 type == WebView.HitTestResult.GEO_TYPE);
1684 menu.setGroupVisible(R.id.IMAGE_MENU,
1685 type == WebView.HitTestResult.IMAGE_TYPE
1686 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1687 menu.setGroupVisible(R.id.ANCHOR_MENU,
1688 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1689 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1690
1691 // Setup custom handling depending on the type
1692 switch (type) {
1693 case WebView.HitTestResult.PHONE_TYPE:
1694 menu.setHeaderTitle(Uri.decode(extra));
1695 menu.findItem(R.id.dial_context_menu_id).setIntent(
1696 new Intent(Intent.ACTION_VIEW, Uri
1697 .parse(WebView.SCHEME_TEL + extra)));
1698 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1699 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1700 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1701 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1702 addIntent);
1703 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1704 new Copy(extra));
1705 break;
1706
1707 case WebView.HitTestResult.EMAIL_TYPE:
1708 menu.setHeaderTitle(extra);
1709 menu.findItem(R.id.email_context_menu_id).setIntent(
1710 new Intent(Intent.ACTION_VIEW, Uri
1711 .parse(WebView.SCHEME_MAILTO + extra)));
1712 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1713 new Copy(extra));
1714 break;
1715
1716 case WebView.HitTestResult.GEO_TYPE:
1717 menu.setHeaderTitle(extra);
1718 menu.findItem(R.id.map_context_menu_id).setIntent(
1719 new Intent(Intent.ACTION_VIEW, Uri
1720 .parse(WebView.SCHEME_GEO
1721 + URLEncoder.encode(extra))));
1722 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1723 new Copy(extra));
1724 break;
1725
1726 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1727 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1728 TextView titleView = (TextView) LayoutInflater.from(this)
1729 .inflate(android.R.layout.browser_link_context_header,
1730 null);
1731 titleView.setText(extra);
1732 menu.setHeaderView(titleView);
1733 // decide whether to show the open link in new tab option
1734 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1735 mTabControl.getTabCount() < TabControl.MAX_TABS);
1736 PackageManager pm = getPackageManager();
1737 Intent send = new Intent(Intent.ACTION_SEND);
1738 send.setType("text/plain");
1739 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1740 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1741 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1742 break;
1743 }
1744 // otherwise fall through to handle image part
1745 case WebView.HitTestResult.IMAGE_TYPE:
1746 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1747 menu.setHeaderTitle(extra);
1748 }
1749 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1750 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1751 menu.findItem(R.id.download_context_menu_id).
1752 setOnMenuItemClickListener(new Download(extra));
1753 break;
1754
1755 default:
1756 Log.w(LOGTAG, "We should not get here.");
1757 break;
1758 }
1759 }
1760
The Android Open Source Project0c908882009-03-03 19:32:16 -08001761 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001762 // this should only be called for the current tab.
The Android Open Source Project0c908882009-03-03 19:32:16 -08001763 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001764 // Attach the container that contains the main WebView and any other UI
1765 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001766 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001767
1768 if (mShouldShowErrorConsole) {
1769 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1770 if (errorConsole.numberOfErrors() == 0) {
1771 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1772 } else {
1773 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1774 }
1775
1776 mErrorConsoleContainer.addView(errorConsole,
1777 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1778 ViewGroup.LayoutParams.WRAP_CONTENT));
1779 }
1780
Grace Klobac928c302009-09-17 11:51:21 -07001781 setLockIconType(t.getLockIconType());
1782 setPrevLockType(t.getPrevLockIconType());
1783
1784 // this is to match the code in removeTabFromContentView()
1785 if (!mPageStarted && t.getTopWindow().getProgress() < 100) {
1786 mPageStarted = true;
Grace Klobaeb6eef42009-09-15 17:56:32 -07001787 }
1788
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001789 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001790 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001791 // Request focus on the top window.
1792 t.getTopWindow().requestFocus();
1793 }
1794
1795 // Attach a sub window to the main WebView of the given tab.
1796 private void attachSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001797 t.attachSubWindow(mContentView);
1798 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001799 }
1800
1801 // Remove the given tab from the content view.
1802 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001803 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001804 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001805
1806 if (mTabControl.getCurrentErrorConsole(false) != null) {
1807 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1808 }
1809
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001810 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001811 if (view != null) {
1812 view.setEmbeddedTitleBar(null);
1813 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001814
Grace Klobac928c302009-09-17 11:51:21 -07001815 // unlike attachTabToContentView(), removeTabFromContentView() can be
1816 // called for the non-current tab. Need to add the check.
Grace Klobaeb6eef42009-09-15 17:56:32 -07001817 if (t == mTabControl.getCurrentTab()) {
1818 t.setLockIconType(getLockIconType());
1819 t.setPrevLockIconType(getPrevLockType());
Grace Klobac928c302009-09-17 11:51:21 -07001820
1821 // this is not a perfect solution. But currently there is one
1822 // WebViewClient for all the WebView. if user switches from an
1823 // in-load window to an already loaded window, mPageStarted will not
1824 // be set to false. If user leaves the Browser, pauseWebViewTimers()
1825 // won't do anything and leaves the timer running even Browser is in
1826 // the background.
1827 if (mPageStarted) {
1828 mPageStarted = false;
1829 }
Grace Klobaeb6eef42009-09-15 17:56:32 -07001830 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001831 }
1832
1833 // Remove the sub window if it exists. Also called by TabControl when the
1834 // user clicks the 'X' to dismiss a sub window.
1835 /* package */ void dismissSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001836 t.removeSubWindow(mContentView);
1837 // Tell the TabControl to dismiss the subwindow. This will destroy
1838 // the WebView.
1839 mTabControl.dismissSubWindow(t);
1840 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001841 }
1842
Leon Scroggins1f005d32009-08-10 17:36:42 -04001843 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001844 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001845 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1846 String appId) {
1847 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001848 }
1849
1850 // This method does a ton of stuff. It will attempt to create a new tab
1851 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001852 // url isn't null, it will load the given url.
1853 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001854 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001855 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1856 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1857 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001858 final TabControl.Tab tab = mTabControl.createNewTab(
1859 closeOnExit, appId, urlData.mUrl);
1860 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001861 // If the last tab was removed from the active tabs page, currentTab
1862 // will be null.
1863 if (currentTab != null) {
1864 removeTabFromContentView(currentTab);
1865 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001866 // We must set the new tab as the current tab to reflect the old
1867 // animation behavior.
1868 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001869 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001870 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001871 urlData.loadIn(webview);
1872 }
1873 return tab;
1874 } else {
1875 // Get rid of the subwindow if it exists
1876 dismissSubWindow(currentTab);
1877 if (!urlData.isEmpty()) {
1878 // Load the given url.
1879 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001880 }
1881 }
Grace Klobac9181842009-04-14 08:53:22 -07001882 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001883 }
1884
Grace Klobac9181842009-04-14 08:53:22 -07001885 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001886 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001887 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001888 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001889 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001890 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001891 }
Grace Klobac9181842009-04-14 08:53:22 -07001892 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001893 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001894 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001895 }
1896 }
1897
1898 private class Copy implements OnMenuItemClickListener {
1899 private CharSequence mText;
1900
1901 public boolean onMenuItemClick(MenuItem item) {
1902 copy(mText);
1903 return true;
1904 }
1905
1906 public Copy(CharSequence toCopy) {
1907 mText = toCopy;
1908 }
1909 }
1910
1911 private class Download implements OnMenuItemClickListener {
1912 private String mText;
1913
1914 public boolean onMenuItemClick(MenuItem item) {
1915 onDownloadStartNoStream(mText, null, null, null, -1);
1916 return true;
1917 }
1918
1919 public Download(String toDownload) {
1920 mText = toDownload;
1921 }
1922 }
1923
1924 private void copy(CharSequence text) {
1925 try {
1926 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1927 if (clip != null) {
1928 clip.setClipboardText(text);
1929 }
1930 } catch (android.os.RemoteException e) {
1931 Log.e(LOGTAG, "Copy failed", e);
1932 }
1933 }
1934
1935 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001936 * Resets the browser title-view to whatever it must be
1937 * (for example, if we had a loading error)
1938 * When we have a new page, we call resetTitle, when we
1939 * have to reset the titlebar to whatever it used to be
1940 * (for example, if the user chose to stop loading), we
1941 * call resetTitleAndRevertLockIcon.
1942 */
1943 /* package */ void resetTitleAndRevertLockIcon() {
1944 revertLockIcon();
1945 resetTitleIconAndProgress();
1946 }
1947
1948 /**
1949 * Reset the title, favicon, and progress.
1950 */
1951 private void resetTitleIconAndProgress() {
1952 WebView current = mTabControl.getCurrentWebView();
1953 if (current == null) {
1954 return;
1955 }
1956 resetTitleAndIcon(current);
1957 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001958 mWebChromeClient.onProgressChanged(current, progress);
1959 }
1960
1961 // Reset the title and the icon based on the given item.
1962 private void resetTitleAndIcon(WebView view) {
1963 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1964 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001965 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001966 setFavicon(item.getFavicon());
1967 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001968 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001969 setFavicon(null);
1970 }
1971 }
1972
1973 /**
1974 * Sets a title composed of the URL and the title string.
1975 * @param url The URL of the site being loaded.
1976 * @param title The title of the site being loaded.
1977 */
Leon Scroggins68579392009-09-15 15:31:54 -04001978 private void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001979 mUrl = url;
1980 mTitle = title;
1981
Leon Scroggins68579392009-09-15 15:31:54 -04001982 mTitleBar.setTitleAndUrl(title, url);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001983 if (mFakeTitleBar != null) {
1984 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001985 }
1986 }
1987
1988 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001989 * @param url The URL to build a title version of the URL from.
1990 * @return The title version of the URL or null if fails.
1991 * The title version of the URL can be either the URL hostname,
1992 * or the hostname with an "https://" prefix (for secure URLs),
1993 * or an empty string if, for example, the URL in question is a
1994 * file:// URL with no hostname.
1995 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001996 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001997 String titleUrl = null;
1998
1999 if (url != null) {
2000 try {
2001 // parse the url string
2002 URL urlObj = new URL(url);
2003 if (urlObj != null) {
2004 titleUrl = "";
2005
2006 String protocol = urlObj.getProtocol();
2007 String host = urlObj.getHost();
2008
2009 if (host != null && 0 < host.length()) {
2010 titleUrl = host;
2011 if (protocol != null) {
2012 // if a secure site, add an "https://" prefix!
2013 if (protocol.equalsIgnoreCase("https")) {
2014 titleUrl = protocol + "://" + host;
2015 }
2016 }
2017 }
2018 }
2019 } catch (MalformedURLException e) {}
2020 }
2021
2022 return titleUrl;
2023 }
2024
2025 // Set the favicon in the title bar.
2026 private void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002027 mTitleBar.setFavicon(icon);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002028 if (mFakeTitleBar != null) {
2029 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002030 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002031 }
2032
2033 /**
2034 * Saves the current lock-icon state before resetting
2035 * the lock icon. If we have an error, we may need to
2036 * roll back to the previous state.
2037 */
2038 private void saveLockIcon() {
2039 mPrevLockType = mLockIconType;
2040 }
2041
2042 /**
2043 * Reverts the lock-icon state to the last saved state,
2044 * for example, if we had an error, and need to cancel
2045 * the load.
2046 */
2047 private void revertLockIcon() {
2048 mLockIconType = mPrevLockType;
2049
Dave Bort31a6d1c2009-04-13 15:56:49 -07002050 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002051 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2052 " revert lock icon to " + mLockIconType);
2053 }
2054
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002055 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002056 }
2057
Leon Scroggins1f005d32009-08-10 17:36:42 -04002058 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002059 * Close the tab, remove its associated title bar, and adjust mTabControl's
2060 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002061 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002062 /* package */ void closeTab(TabControl.Tab t) {
2063 int currentIndex = mTabControl.getCurrentIndex();
2064 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002065 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002066 if (currentIndex >= removeIndex && currentIndex != 0) {
2067 currentIndex--;
2068 }
2069 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
The Android Open Source Project0c908882009-03-03 19:32:16 -08002070 }
2071
2072 private void goBackOnePageOrQuit() {
2073 TabControl.Tab current = mTabControl.getCurrentTab();
2074 if (current == null) {
2075 /*
2076 * Instead of finishing the activity, simply push this to the back
2077 * of the stack and let ActivityManager to choose the foreground
2078 * activity. As BrowserActivity is singleTask, it will be always the
2079 * root of the task. So we can use either true or false for
2080 * moveTaskToBack().
2081 */
2082 moveTaskToBack(true);
2083 }
2084 WebView w = current.getWebView();
2085 if (w.canGoBack()) {
2086 w.goBack();
2087 } else {
2088 // Check to see if we are closing a window that was created by
2089 // another window. If so, we switch back to that window.
2090 TabControl.Tab parent = current.getParentTab();
2091 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002092 switchToTab(mTabControl.getTabIndex(parent));
2093 // Now we close the other tab
2094 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002095 } else {
2096 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002097 // force mPageStarted to be false as we are going to either
2098 // finish the activity or remove the tab. This will ensure
2099 // pauseWebView() taking action.
2100 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002101 if (mTabControl.getTabCount() == 1) {
2102 finish();
2103 return;
2104 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002105 // call pauseWebViewTimers() now, we won't be able to call
2106 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002107 // Temporarily change mActivityInPause to be true as
2108 // pauseWebViewTimers() will do nothing if mActivityInPause
2109 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002110 boolean savedState = mActivityInPause;
2111 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002112 Log.e(LOGTAG, "BrowserActivity is already paused "
2113 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002114 }
2115 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002116 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002117 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002118 removeTabFromContentView(current);
2119 mTabControl.removeTab(current);
2120 }
2121 /*
2122 * Instead of finishing the activity, simply push this to the back
2123 * of the stack and let ActivityManager to choose the foreground
2124 * activity. As BrowserActivity is singleTask, it will be always the
2125 * root of the task. So we can use either true or false for
2126 * moveTaskToBack().
2127 */
2128 moveTaskToBack(true);
2129 }
2130 }
2131 }
2132
Grace Kloba5942df02009-09-18 11:48:29 -07002133 @Override
2134 public boolean onKeyDown(int keyCode, KeyEvent event) {
2135 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2136 // still down, we don't want to trigger the search. Pretend to consume
2137 // the key and do nothing.
2138 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002139
Grace Kloba5942df02009-09-18 11:48:29 -07002140 switch(keyCode) {
2141 case KeyEvent.KEYCODE_MENU:
2142 mMenuIsDown = true;
2143 break;
2144 case KeyEvent.KEYCODE_SPACE:
2145 // Browser's hidden shortcut key. Don't call super so that
2146 // search won't be triggered.
2147 return true;
2148 case KeyEvent.KEYCODE_BACK:
2149 if (event.getRepeatCount() == 0) {
2150 event.startTracking();
2151 return true;
2152 } else if (mCustomView == null && mActiveTabsPage == null
2153 && event.isLongPress()) {
2154 bookmarksOrHistoryPicker(true);
2155 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002156 }
Grace Kloba5942df02009-09-18 11:48:29 -07002157 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002158 }
Grace Kloba5942df02009-09-18 11:48:29 -07002159 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002160 }
2161
Grace Kloba5942df02009-09-18 11:48:29 -07002162 @Override
2163 public boolean onKeyUp(int keyCode, KeyEvent event) {
2164 switch(keyCode) {
2165 case KeyEvent.KEYCODE_MENU:
2166 mMenuIsDown = false;
2167 break;
2168 case KeyEvent.KEYCODE_SPACE:
2169 if (event.isShiftPressed()) {
2170 getTopWindow().pageUp(false);
2171 } else {
2172 getTopWindow().pageDown(false);
2173 }
2174 return true;
2175 case KeyEvent.KEYCODE_BACK:
2176 if (event.isTracking() && !event.isCanceled()) {
2177 if (mCustomView != null) {
2178 // if a custom view is showing, hide it
2179 mWebChromeClient.onHideCustomView();
2180 } else if (mActiveTabsPage != null) {
2181 // if tab page is showing, hide it
2182 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002183 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002184 WebView subwindow = mTabControl.getCurrentSubWindow();
2185 if (subwindow != null) {
2186 if (subwindow.canGoBack()) {
2187 subwindow.goBack();
2188 } else {
2189 dismissSubWindow(mTabControl.getCurrentTab());
2190 }
2191 } else {
2192 goBackOnePageOrQuit();
2193 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002194 }
Grace Kloba5942df02009-09-18 11:48:29 -07002195 return true;
2196 }
2197 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002198 }
Grace Kloba5942df02009-09-18 11:48:29 -07002199 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002200 }
2201
Leon Scroggins68579392009-09-15 15:31:54 -04002202 /* package */ void stopLoading() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002203 resetTitleAndRevertLockIcon();
2204 WebView w = getTopWindow();
2205 w.stopLoading();
2206 mWebViewClient.onPageFinished(w, w.getUrl());
2207
2208 cancelStopToast();
2209 mStopToast = Toast
2210 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2211 mStopToast.show();
2212 }
2213
2214 private void cancelStopToast() {
2215 if (mStopToast != null) {
2216 mStopToast.cancel();
2217 mStopToast = null;
2218 }
2219 }
2220
2221 // called by a non-UI thread to post the message
2222 public void postMessage(int what, int arg1, int arg2, Object obj) {
2223 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2224 }
2225
2226 // public message ids
2227 public final static int LOAD_URL = 1001;
2228 public final static int STOP_LOAD = 1002;
2229
2230 // Message Ids
2231 private static final int FOCUS_NODE_HREF = 102;
2232 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002233 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002234
2235 // Private handler for handling javascript and saving passwords
2236 private Handler mHandler = new Handler() {
2237
2238 public void handleMessage(Message msg) {
2239 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002240 case FOCUS_NODE_HREF:
2241 String url = (String) msg.getData().get("url");
2242 if (url == null || url.length() == 0) {
2243 break;
2244 }
2245 HashMap focusNodeMap = (HashMap) msg.obj;
2246 WebView view = (WebView) focusNodeMap.get("webview");
2247 // Only apply the action if the top window did not change.
2248 if (getTopWindow() != view) {
2249 break;
2250 }
2251 switch (msg.arg1) {
2252 case R.id.open_context_menu_id:
2253 case R.id.view_image_context_menu_id:
2254 loadURL(getTopWindow(), url);
2255 break;
2256 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002257 final TabControl.Tab parent = mTabControl
2258 .getCurrentTab();
2259 final TabControl.Tab newTab = openTab(url);
2260 if (newTab != parent) {
2261 parent.addChildTab(newTab);
2262 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002263 break;
2264 case R.id.bookmark_context_menu_id:
2265 Intent intent = new Intent(BrowserActivity.this,
2266 AddBookmarkPage.class);
2267 intent.putExtra("url", url);
2268 startActivity(intent);
2269 break;
2270 case R.id.share_link_context_menu_id:
2271 Browser.sendString(BrowserActivity.this, url);
2272 break;
2273 case R.id.copy_link_context_menu_id:
2274 copy(url);
2275 break;
2276 case R.id.save_link_context_menu_id:
2277 case R.id.download_context_menu_id:
2278 onDownloadStartNoStream(url, null, null, null, -1);
2279 break;
2280 }
2281 break;
2282
2283 case LOAD_URL:
2284 loadURL(getTopWindow(), (String) msg.obj);
2285 break;
2286
2287 case STOP_LOAD:
2288 stopLoading();
2289 break;
2290
2291 case CANCEL_CREDS_REQUEST:
2292 resumeAfterCredentials();
2293 break;
2294
The Android Open Source Project0c908882009-03-03 19:32:16 -08002295 case RELEASE_WAKELOCK:
2296 if (mWakeLock.isHeld()) {
2297 mWakeLock.release();
2298 }
2299 break;
2300 }
2301 }
2302 };
2303
Leon Scroggins89c6d362009-07-15 16:54:37 -04002304 private void updateScreenshot(WebView view) {
2305 // If this is a bookmarked site, add a screenshot to the database.
2306 // FIXME: When should we update? Every time?
2307 // FIXME: Would like to make sure there is actually something to
2308 // draw, but the API for that (WebViewCore.pictureReady()) is not
2309 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002310 ContentResolver cr = getContentResolver();
2311 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002312 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002313 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002314 boolean succeed = c.moveToFirst();
2315 ContentValues values = null;
2316 while (succeed) {
2317 if (values == null) {
2318 final ByteArrayOutputStream os
2319 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002320 Bitmap bm = createScreenshot(view);
Leon Scroggins89c6d362009-07-15 16:54:37 -04002321 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2322 values = new ContentValues();
2323 values.put(Browser.BookmarkColumns.THUMBNAIL,
2324 os.toByteArray());
2325 }
2326 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2327 c.getInt(0)), values, null, null);
2328 succeed = c.moveToNext();
2329 }
2330 c.close();
2331 }
2332 }
2333
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002334 private Bitmap createScreenshot(WebView view) {
2335 Picture thumbnail = view.capturePicture();
2336 // Keep width and height in sync with BrowserBookmarksPage
2337 // and bookmark_thumb
2338 Bitmap bm = Bitmap.createBitmap(100, 80,
2339 Bitmap.Config.ARGB_4444);
2340 Canvas canvas = new Canvas(bm);
2341 // May need to tweak these values to determine what is the
2342 // best scale factor
2343 canvas.scale(.5f, .5f);
2344 thumbnail.draw(canvas);
2345 return bm;
2346 }
2347
The Android Open Source Project0c908882009-03-03 19:32:16 -08002348 // -------------------------------------------------------------------------
2349 // WebViewClient implementation.
2350 //-------------------------------------------------------------------------
2351
2352 // Use in overrideUrlLoading
2353 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2354 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2355 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2356 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2357
2358 /* package */ WebViewClient getWebViewClient() {
2359 return mWebViewClient;
2360 }
2361
Patrick Scott3918d442009-08-04 13:22:29 -04002362 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002363 if (icon != null) {
2364 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott3918d442009-08-04 13:22:29 -04002365 view, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002366 }
2367 setFavicon(icon);
2368 }
2369
2370 private final WebViewClient mWebViewClient = new WebViewClient() {
2371 @Override
2372 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2373 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002374 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002375
2376 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2377 if (errorConsole != null) {
2378 errorConsole.clearErrorMessages();
2379 if (mShouldShowErrorConsole) {
2380 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2381 }
2382 }
2383
The Android Open Source Project0c908882009-03-03 19:32:16 -08002384 // Call updateIcon instead of setFavicon so the bookmark
2385 // database can be updated.
Patrick Scott3918d442009-08-04 13:22:29 -04002386 updateIcon(view, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002387
Grace Kloba4d7880f2009-08-12 09:35:42 -07002388 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002389 String host;
2390 try {
2391 WebAddress uri = new WebAddress(url);
2392 host = uri.mHost;
2393 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002394 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002395 }
2396 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002397 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002398 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002399 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002400 }
2401
2402 // Performance probe
2403 if (false) {
2404 mStart = SystemClock.uptimeMillis();
2405 mProcessStart = Process.getElapsedCpuTime();
2406 long[] sysCpu = new long[7];
2407 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2408 sysCpu, null)) {
2409 mUserStart = sysCpu[0] + sysCpu[1];
2410 mSystemStart = sysCpu[2];
2411 mIdleStart = sysCpu[3];
2412 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2413 }
2414 mUiStart = SystemClock.currentThreadTimeMillis();
2415 }
2416
2417 if (!mPageStarted) {
2418 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002419 // if onResume() has been called, resumeWebViewTimers() does
2420 // nothing.
2421 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002422 }
2423
2424 // reset sync timer to avoid sync starts during loading a page
2425 CookieSyncManager.getInstance().resetSync();
2426
2427 mInLoad = true;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002428 WebView currentWebView = mTabControl.getCurrentWebView();
2429 if (currentWebView == null || currentWebView.getScrollY() != 0) {
2430 // This page has begun to load, so show the title bar
2431 showFakeTitleBar();
2432 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002433 updateInLoadMenuItems();
2434 if (!mIsNetworkUp) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04002435 createAndShowNetworkDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002436 if (view != null) {
2437 view.setNetworkAvailable(false);
2438 }
2439 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002440 }
2441
2442 @Override
2443 public void onPageFinished(WebView view, String url) {
2444 // Reset the title and icon in case we stopped a provisional
2445 // load.
2446 resetTitleAndIcon(view);
2447
2448 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002449 updateLockIconToLatest();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002450 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002451
The Android Open Source Project0c908882009-03-03 19:32:16 -08002452 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002453 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002454 long[] sysCpu = new long[7];
2455 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2456 sysCpu, null)) {
2457 String uiInfo = "UI thread used "
2458 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2459 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002460 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002461 Log.d(LOGTAG, uiInfo);
2462 }
2463 //The string that gets written to the log
2464 String performanceString = "It took total "
2465 + (SystemClock.uptimeMillis() - mStart)
2466 + " ms clock time to load the page."
2467 + "\nbrowser process used "
2468 + (Process.getElapsedCpuTime() - mProcessStart)
2469 + " ms, user processes used "
2470 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2471 + " ms, kernel used "
2472 + (sysCpu[2] - mSystemStart) * 10
2473 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2474 + " ms and irq took "
2475 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2476 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002477 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002478 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2479 }
2480 if (url != null) {
2481 // strip the url to maintain consistency
2482 String newUrl = new String(url);
2483 if (newUrl.startsWith("http://www.")) {
2484 newUrl = newUrl.substring(11);
2485 } else if (newUrl.startsWith("http://")) {
2486 newUrl = newUrl.substring(7);
2487 } else if (newUrl.startsWith("https://www.")) {
2488 newUrl = newUrl.substring(12);
2489 } else if (newUrl.startsWith("https://")) {
2490 newUrl = newUrl.substring(8);
2491 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002492 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002493 Log.d(LOGTAG, newUrl + " loaded");
2494 }
2495 /*
2496 if (sWhiteList.contains(newUrl)) {
2497 // The string that gets pushed to the statistcs
2498 // service
2499 performanceString = performanceString
2500 + "\nWebpage: "
2501 + newUrl
2502 + "\nCarrier: "
2503 + android.os.SystemProperties
2504 .get("gsm.sim.operator.alpha");
2505 if (mWebView != null
2506 && mWebView.getContext() != null
2507 && mWebView.getContext().getSystemService(
2508 Context.CONNECTIVITY_SERVICE) != null) {
2509 ConnectivityManager cManager =
2510 (ConnectivityManager) mWebView
2511 .getContext().getSystemService(
2512 Context.CONNECTIVITY_SERVICE);
2513 NetworkInfo nInfo = cManager
2514 .getActiveNetworkInfo();
2515 if (nInfo != null) {
2516 performanceString = performanceString
2517 + "\nNetwork Type: "
2518 + nInfo.getType().toString();
2519 }
2520 }
2521 Checkin.logEvent(mResolver,
2522 Checkin.Events.Tag.WEBPAGE_LOAD,
2523 performanceString);
2524 Log.w(LOGTAG, "pushed to the statistics service");
2525 }
2526 */
2527 }
2528 }
2529 }
2530
2531 if (mInTrace) {
2532 mInTrace = false;
2533 Debug.stopMethodTracing();
2534 }
2535
2536 if (mPageStarted) {
2537 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002538 // pauseWebViewTimers() will do nothing and return false if
2539 // onPause() is not called yet.
2540 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002541 if (mWakeLock.isHeld()) {
2542 mHandler.removeMessages(RELEASE_WAKELOCK);
2543 mWakeLock.release();
2544 }
2545 }
2546 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002547 }
2548
2549 // return true if want to hijack the url to let another app to handle it
2550 @Override
2551 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2552 if (url.startsWith(SCHEME_WTAI)) {
2553 // wtai://wp/mc;number
2554 // number=string(phone-number)
2555 if (url.startsWith(SCHEME_WTAI_MC)) {
2556 Intent intent = new Intent(Intent.ACTION_VIEW,
2557 Uri.parse(WebView.SCHEME_TEL +
2558 url.substring(SCHEME_WTAI_MC.length())));
2559 startActivity(intent);
2560 return true;
2561 }
2562 // wtai://wp/sd;dtmf
2563 // dtmf=string(dialstring)
2564 if (url.startsWith(SCHEME_WTAI_SD)) {
2565 // TODO
2566 // only send when there is active voice connection
2567 return false;
2568 }
2569 // wtai://wp/ap;number;name
2570 // number=string(phone-number)
2571 // name=string
2572 if (url.startsWith(SCHEME_WTAI_AP)) {
2573 // TODO
2574 return false;
2575 }
2576 }
2577
Dianne Hackborn99189432009-06-17 18:06:18 -07002578 // The "about:" schemes are internal to the browser; don't
2579 // want these to be dispatched to other apps.
2580 if (url.startsWith("about:")) {
2581 return false;
2582 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002583
Dianne Hackborn99189432009-06-17 18:06:18 -07002584 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002585
Dianne Hackborn99189432009-06-17 18:06:18 -07002586 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002587 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002588 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2589 } catch (URISyntaxException ex) {
2590 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002591 return false;
2592 }
2593
Grace Kloba5b078b52009-06-24 20:23:41 -07002594 // check whether the intent can be resolved. If not, we will see
2595 // whether we can download it from the Market.
2596 if (getPackageManager().resolveActivity(intent, 0) == null) {
2597 String packagename = intent.getPackage();
2598 if (packagename != null) {
2599 intent = new Intent(Intent.ACTION_VIEW, Uri
2600 .parse("market://search?q=pname:" + packagename));
2601 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2602 startActivity(intent);
2603 return true;
2604 } else {
2605 return false;
2606 }
2607 }
2608
Dianne Hackborn99189432009-06-17 18:06:18 -07002609 // sanitize the Intent, ensuring web pages can not bypass browser
2610 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002611 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002612 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002613 try {
2614 if (startActivityIfNeeded(intent, -1)) {
2615 return true;
2616 }
2617 } catch (ActivityNotFoundException ex) {
2618 // ignore the error. If no application can handle the URL,
2619 // eg about:blank, assume the browser can handle it.
2620 }
2621
2622 if (mMenuIsDown) {
2623 openTab(url);
2624 closeOptionsMenu();
2625 return true;
2626 }
2627
2628 return false;
2629 }
2630
2631 /**
2632 * Updates the lock icon. This method is called when we discover another
2633 * resource to be loaded for this page (for example, javascript). While
2634 * we update the icon type, we do not update the lock icon itself until
2635 * we are done loading, it is slightly more secure this way.
2636 */
2637 @Override
2638 public void onLoadResource(WebView view, String url) {
2639 if (url != null && url.length() > 0) {
2640 // It is only if the page claims to be secure
2641 // that we may have to update the lock:
2642 if (mLockIconType == LOCK_ICON_SECURE) {
2643 // If NOT a 'safe' url, change the lock to mixed content!
2644 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2645 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002646 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002647 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2648 " updated lock icon to " + mLockIconType + " due to " + url);
2649 }
2650 }
2651 }
2652 }
2653 }
2654
2655 /**
2656 * Show the dialog, asking the user if they would like to continue after
2657 * an excessive number of HTTP redirects.
2658 */
2659 @Override
2660 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2661 final Message continueMsg) {
2662 new AlertDialog.Builder(BrowserActivity.this)
2663 .setTitle(R.string.browserFrameRedirect)
2664 .setMessage(R.string.browserFrame307Post)
2665 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2666 public void onClick(DialogInterface dialog, int which) {
2667 continueMsg.sendToTarget();
2668 }})
2669 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2670 public void onClick(DialogInterface dialog, int which) {
2671 cancelMsg.sendToTarget();
2672 }})
2673 .setOnCancelListener(new OnCancelListener() {
2674 public void onCancel(DialogInterface dialog) {
2675 cancelMsg.sendToTarget();
2676 }})
2677 .show();
2678 }
2679
Patrick Scott37911c72009-03-24 18:02:58 -07002680 // Container class for the next error dialog that needs to be
2681 // displayed.
2682 class ErrorDialog {
2683 public final int mTitle;
2684 public final String mDescription;
2685 public final int mError;
2686 ErrorDialog(int title, String desc, int error) {
2687 mTitle = title;
2688 mDescription = desc;
2689 mError = error;
2690 }
2691 };
2692
2693 private void processNextError() {
2694 if (mQueuedErrors == null) {
2695 return;
2696 }
2697 // The first one is currently displayed so just remove it.
2698 mQueuedErrors.removeFirst();
2699 if (mQueuedErrors.size() == 0) {
2700 mQueuedErrors = null;
2701 return;
2702 }
2703 showError(mQueuedErrors.getFirst());
2704 }
2705
2706 private DialogInterface.OnDismissListener mDialogListener =
2707 new DialogInterface.OnDismissListener() {
2708 public void onDismiss(DialogInterface d) {
2709 processNextError();
2710 }
2711 };
2712 private LinkedList<ErrorDialog> mQueuedErrors;
2713
2714 private void queueError(int err, String desc) {
2715 if (mQueuedErrors == null) {
2716 mQueuedErrors = new LinkedList<ErrorDialog>();
2717 }
2718 for (ErrorDialog d : mQueuedErrors) {
2719 if (d.mError == err) {
2720 // Already saw a similar error, ignore the new one.
2721 return;
2722 }
2723 }
2724 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002725 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002726 R.string.browserFrameFileErrorLabel :
2727 R.string.browserFrameNetworkErrorLabel,
2728 desc, err);
2729 mQueuedErrors.addLast(errDialog);
2730
2731 // Show the dialog now if the queue was empty.
2732 if (mQueuedErrors.size() == 1) {
2733 showError(errDialog);
2734 }
2735 }
2736
2737 private void showError(ErrorDialog errDialog) {
2738 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2739 .setTitle(errDialog.mTitle)
2740 .setMessage(errDialog.mDescription)
2741 .setPositiveButton(R.string.ok, null)
2742 .create();
2743 d.setOnDismissListener(mDialogListener);
2744 d.show();
2745 }
2746
The Android Open Source Project0c908882009-03-03 19:32:16 -08002747 /**
2748 * Show a dialog informing the user of the network error reported by
2749 * WebCore.
2750 */
2751 @Override
2752 public void onReceivedError(WebView view, int errorCode,
2753 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002754 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2755 errorCode != WebViewClient.ERROR_CONNECT &&
2756 errorCode != WebViewClient.ERROR_BAD_URL &&
2757 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2758 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002759 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002760 }
Patrick Scott37911c72009-03-24 18:02:58 -07002761 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2762 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002763
2764 // We need to reset the title after an error.
2765 resetTitleAndRevertLockIcon();
2766 }
2767
2768 /**
2769 * Check with the user if it is ok to resend POST data as the page they
2770 * are trying to navigate to is the result of a POST.
2771 */
2772 @Override
2773 public void onFormResubmission(WebView view, final Message dontResend,
2774 final Message resend) {
2775 new AlertDialog.Builder(BrowserActivity.this)
2776 .setTitle(R.string.browserFrameFormResubmitLabel)
2777 .setMessage(R.string.browserFrameFormResubmitMessage)
2778 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2779 public void onClick(DialogInterface dialog, int which) {
2780 resend.sendToTarget();
2781 }})
2782 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2783 public void onClick(DialogInterface dialog, int which) {
2784 dontResend.sendToTarget();
2785 }})
2786 .setOnCancelListener(new OnCancelListener() {
2787 public void onCancel(DialogInterface dialog) {
2788 dontResend.sendToTarget();
2789 }})
2790 .show();
2791 }
2792
2793 /**
2794 * Insert the url into the visited history database.
2795 * @param url The url to be inserted.
2796 * @param isReload True if this url is being reloaded.
2797 * FIXME: Not sure what to do when reloading the page.
2798 */
2799 @Override
2800 public void doUpdateVisitedHistory(WebView view, String url,
2801 boolean isReload) {
2802 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2803 return;
2804 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002805 // remove "client" before updating it to the history so that it wont
2806 // show up in the auto-complete list.
2807 int index = url.indexOf("client=ms-");
2808 if (index > 0 && url.contains(".google.")) {
2809 int end = url.indexOf('&', index);
2810 if (end > 0) {
2811 url = url.substring(0, index-1).concat(url.substring(end));
2812 } else {
2813 url = url.substring(0, index-1);
2814 }
2815 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002816 Browser.updateVisitedHistory(mResolver, url, true);
2817 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2818 }
2819
2820 /**
2821 * Displays SSL error(s) dialog to the user.
2822 */
2823 @Override
2824 public void onReceivedSslError(
2825 final WebView view, final SslErrorHandler handler, final SslError error) {
2826
2827 if (mSettings.showSecurityWarnings()) {
2828 final LayoutInflater factory =
2829 LayoutInflater.from(BrowserActivity.this);
2830 final View warningsView =
2831 factory.inflate(R.layout.ssl_warnings, null);
2832 final LinearLayout placeholder =
2833 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2834
2835 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2836 LinearLayout ll = (LinearLayout)factory
2837 .inflate(R.layout.ssl_warning, null);
2838 ((TextView)ll.findViewById(R.id.warning))
2839 .setText(R.string.ssl_untrusted);
2840 placeholder.addView(ll);
2841 }
2842
2843 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2844 LinearLayout ll = (LinearLayout)factory
2845 .inflate(R.layout.ssl_warning, null);
2846 ((TextView)ll.findViewById(R.id.warning))
2847 .setText(R.string.ssl_mismatch);
2848 placeholder.addView(ll);
2849 }
2850
2851 if (error.hasError(SslError.SSL_EXPIRED)) {
2852 LinearLayout ll = (LinearLayout)factory
2853 .inflate(R.layout.ssl_warning, null);
2854 ((TextView)ll.findViewById(R.id.warning))
2855 .setText(R.string.ssl_expired);
2856 placeholder.addView(ll);
2857 }
2858
2859 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2860 LinearLayout ll = (LinearLayout)factory
2861 .inflate(R.layout.ssl_warning, null);
2862 ((TextView)ll.findViewById(R.id.warning))
2863 .setText(R.string.ssl_not_yet_valid);
2864 placeholder.addView(ll);
2865 }
2866
2867 new AlertDialog.Builder(BrowserActivity.this)
2868 .setTitle(R.string.security_warning)
2869 .setIcon(android.R.drawable.ic_dialog_alert)
2870 .setView(warningsView)
2871 .setPositiveButton(R.string.ssl_continue,
2872 new DialogInterface.OnClickListener() {
2873 public void onClick(DialogInterface dialog, int whichButton) {
2874 handler.proceed();
2875 }
2876 })
2877 .setNeutralButton(R.string.view_certificate,
2878 new DialogInterface.OnClickListener() {
2879 public void onClick(DialogInterface dialog, int whichButton) {
2880 showSSLCertificateOnError(view, handler, error);
2881 }
2882 })
2883 .setNegativeButton(R.string.cancel,
2884 new DialogInterface.OnClickListener() {
2885 public void onClick(DialogInterface dialog, int whichButton) {
2886 handler.cancel();
2887 BrowserActivity.this.resetTitleAndRevertLockIcon();
2888 }
2889 })
2890 .setOnCancelListener(
2891 new DialogInterface.OnCancelListener() {
2892 public void onCancel(DialogInterface dialog) {
2893 handler.cancel();
2894 BrowserActivity.this.resetTitleAndRevertLockIcon();
2895 }
2896 })
2897 .show();
2898 } else {
2899 handler.proceed();
2900 }
2901 }
2902
2903 /**
2904 * Handles an HTTP authentication request.
2905 *
2906 * @param handler The authentication handler
2907 * @param host The host
2908 * @param realm The realm
2909 */
2910 @Override
2911 public void onReceivedHttpAuthRequest(WebView view,
2912 final HttpAuthHandler handler, final String host, final String realm) {
2913 String username = null;
2914 String password = null;
2915
2916 boolean reuseHttpAuthUsernamePassword =
2917 handler.useHttpAuthUsernamePassword();
2918
2919 if (reuseHttpAuthUsernamePassword &&
2920 (mTabControl.getCurrentWebView() != null)) {
2921 String[] credentials =
2922 mTabControl.getCurrentWebView()
2923 .getHttpAuthUsernamePassword(host, realm);
2924 if (credentials != null && credentials.length == 2) {
2925 username = credentials[0];
2926 password = credentials[1];
2927 }
2928 }
2929
2930 if (username != null && password != null) {
2931 handler.proceed(username, password);
2932 } else {
2933 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2934 }
2935 }
2936
2937 @Override
2938 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2939 if (mMenuIsDown) {
2940 // only check shortcut key when MENU is held
2941 return getWindow().isShortcutKey(event.getKeyCode(), event);
2942 } else {
2943 return false;
2944 }
2945 }
2946
2947 @Override
2948 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2949 if (view != mTabControl.getCurrentTopWebView()) {
2950 return;
2951 }
2952 if (event.isDown()) {
2953 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2954 } else {
2955 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2956 }
2957 }
2958 };
2959
2960 //--------------------------------------------------------------------------
2961 // WebChromeClient implementation
2962 //--------------------------------------------------------------------------
2963
2964 /* package */ WebChromeClient getWebChromeClient() {
2965 return mWebChromeClient;
2966 }
2967
2968 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2969 // Helper method to create a new tab or sub window.
2970 private void createWindow(final boolean dialog, final Message msg) {
2971 if (dialog) {
2972 mTabControl.createSubWindow();
2973 final TabControl.Tab t = mTabControl.getCurrentTab();
2974 attachSubWindow(t);
2975 WebView.WebViewTransport transport =
2976 (WebView.WebViewTransport) msg.obj;
2977 transport.setWebView(t.getSubWebView());
2978 msg.sendToTarget();
2979 } else {
2980 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04002981 final TabControl.Tab newTab
2982 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07002983 if (newTab != parent) {
2984 parent.addChildTab(newTab);
2985 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002986 WebView.WebViewTransport transport =
2987 (WebView.WebViewTransport) msg.obj;
2988 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04002989 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002990 }
2991 }
2992
2993 @Override
2994 public boolean onCreateWindow(WebView view, final boolean dialog,
2995 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002996 // Short-circuit if we can't create any more tabs or sub windows.
2997 if (dialog && mTabControl.getCurrentSubWindow() != null) {
2998 new AlertDialog.Builder(BrowserActivity.this)
2999 .setTitle(R.string.too_many_subwindows_dialog_title)
3000 .setIcon(android.R.drawable.ic_dialog_alert)
3001 .setMessage(R.string.too_many_subwindows_dialog_message)
3002 .setPositiveButton(R.string.ok, null)
3003 .show();
3004 return false;
3005 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3006 new AlertDialog.Builder(BrowserActivity.this)
3007 .setTitle(R.string.too_many_windows_dialog_title)
3008 .setIcon(android.R.drawable.ic_dialog_alert)
3009 .setMessage(R.string.too_many_windows_dialog_message)
3010 .setPositiveButton(R.string.ok, null)
3011 .show();
3012 return false;
3013 }
3014
3015 // Short-circuit if this was a user gesture.
3016 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003017 createWindow(dialog, resultMsg);
3018 return true;
3019 }
3020
3021 // Allow the popup and create the appropriate window.
3022 final AlertDialog.OnClickListener allowListener =
3023 new AlertDialog.OnClickListener() {
3024 public void onClick(DialogInterface d,
3025 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003026 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003027 }
3028 };
3029
3030 // Block the popup by returning a null WebView.
3031 final AlertDialog.OnClickListener blockListener =
3032 new AlertDialog.OnClickListener() {
3033 public void onClick(DialogInterface d, int which) {
3034 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003035 }
3036 };
3037
3038 // Build a confirmation dialog to display to the user.
3039 final AlertDialog d =
3040 new AlertDialog.Builder(BrowserActivity.this)
3041 .setTitle(R.string.attention)
3042 .setIcon(android.R.drawable.ic_dialog_alert)
3043 .setMessage(R.string.popup_window_attempt)
3044 .setPositiveButton(R.string.allow, allowListener)
3045 .setNegativeButton(R.string.block, blockListener)
3046 .setCancelable(false)
3047 .create();
3048
3049 // Show the confirmation dialog.
3050 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003051 return true;
3052 }
3053
3054 @Override
3055 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003056 final TabControl.Tab current = mTabControl.getCurrentTab();
3057 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003058 if (parent != null) {
3059 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003060 switchToTab(mTabControl.getTabIndex(parent));
3061 // Now we need to close the window
3062 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003063 }
3064 }
3065
3066 @Override
3067 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003068 mTitleBar.setProgress(newProgress);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003069 if (mFakeTitleBar != null) {
3070 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003071 }
3072
3073 if (newProgress == 100) {
3074 // onProgressChanged() is called for sub-frame too while
3075 // onPageFinished() is only called for the main frame. sync
3076 // cookie and cache promptly here.
3077 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003078 if (mInLoad) {
3079 mInLoad = false;
3080 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003081 // If the options menu is open, leave the title bar
3082 if (!mOptionsMenuOpen || !mIconView) {
3083 hideFakeTitleBar();
3084 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003085 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003086 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003087 // onPageFinished may have already been called but a subframe
3088 // is still loading and updating the progress. Reset mInLoad
3089 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003090 mInLoad = true;
3091 updateInLoadMenuItems();
3092 WebView currentWebView = mTabControl.getCurrentWebView();
3093 if ((currentWebView == null || currentWebView.getScrollY() != 0)
3094 && (!mOptionsMenuOpen || mIconView)) {
3095 // This page has begun to load, so show the title bar
3096 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003097 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003098 }
3099 }
3100
3101 @Override
3102 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003103 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003104
3105 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003106 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003107
3108 if (url == null ||
3109 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3110 return;
3111 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003112 // See if we can find the current url in our history database and
3113 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003114 if (url.startsWith("http://www.")) {
3115 url = url.substring(11);
3116 } else if (url.startsWith("http://")) {
3117 url = url.substring(4);
3118 }
3119 try {
3120 url = "%" + url;
3121 String [] selArgs = new String[] { url };
3122
3123 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3124 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3125 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3126 Browser.HISTORY_PROJECTION, where, selArgs, null);
3127 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003128 // Current implementation of database only has one entry per
3129 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003130 ContentValues map = new ContentValues();
3131 map.put(Browser.BookmarkColumns.TITLE, title);
3132 mResolver.update(Browser.BOOKMARKS_URI, map,
3133 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003134 }
3135 c.close();
3136 } catch (IllegalStateException e) {
3137 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3138 } catch (SQLiteException ex) {
3139 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3140 }
3141 }
3142
3143 @Override
3144 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003145 updateIcon(view, icon);
3146 }
3147
3148 @Override
3149 public void onReceivedTouchIconUrl(WebView view, String url) {
3150 final ContentResolver cr = getContentResolver();
3151 final Cursor c =
3152 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003153 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003154 if (c != null) {
3155 if (c.getCount() > 0) {
3156 new DownloadTouchIcon(cr, c, view).execute(url);
3157 } else {
3158 c.close();
3159 }
3160 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003161 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003162
Andrei Popescuadc008d2009-06-26 14:11:30 +01003163 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003164 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003165 if (mCustomView != null)
3166 return;
3167
3168 // Add the custom view to its container.
3169 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3170 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003171 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003172 // Save the menu state and set it to empty while the custom
3173 // view is showing.
3174 mOldMenuState = mMenuState;
3175 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003176 // Hide the content view.
3177 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003178 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003179 mCustomViewContainer.setVisibility(View.VISIBLE);
3180 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003181 }
3182
3183 @Override
3184 public void onHideCustomView() {
3185 if (mCustomView == null)
3186 return;
3187
Andrei Popescuc9b55562009-07-07 10:51:15 +01003188 // Hide the custom view.
3189 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003190 // Remove the custom view from its container.
3191 mCustomViewContainer.removeView(mCustomView);
3192 mCustomView = null;
3193 // Reset the old menu state.
3194 mMenuState = mOldMenuState;
3195 mOldMenuState = EMPTY_MENU;
3196 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003197 mCustomViewCallback.onCustomViewHidden();
3198 // Show the content view.
3199 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003200 }
3201
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003202 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003203 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003204 * @param url the URL that exceeded the quota
3205 * @param databaseIdentifier the identifier of the database on
3206 * which the transaction that caused the quota overflow was run
3207 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003208 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003209 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003210 * @param quotaUpdater The callback to run when a decision to allow or
3211 * deny quota has been made. Don't forget to call this!
3212 */
3213 @Override
3214 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003215 String databaseIdentifier, long currentQuota, long estimatedSize,
3216 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003217 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003218 url, databaseIdentifier, currentQuota, estimatedSize,
3219 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003220 }
3221
3222 /**
3223 * The Application Cache has exceeded its max size.
3224 * @param spaceNeeded is the amount of disk space that would be needed
3225 * in order for the last appcache operation to succeed.
3226 * @param totalUsedQuota is the sum of all origins' quota.
3227 * @param quotaUpdater A callback to inform the WebCore thread that a new
3228 * app cache size is available. This callback must always be executed at
3229 * some point to ensure that the sleeping WebCore thread is woken up.
3230 */
3231 @Override
3232 public void onReachedMaxAppCacheSize(long spaceNeeded,
3233 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3234 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3235 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003236 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003237
Steve Block2bc69912009-07-30 14:45:13 +01003238 /**
3239 * Instructs the browser to show a prompt to ask the user to set the
3240 * Geolocation permission state for the specified origin.
3241 * @param origin The origin for which Geolocation permissions are
3242 * requested.
3243 * @param callback The callback to call once the user has set the
3244 * Geolocation permission state.
3245 */
3246 @Override
3247 public void onGeolocationPermissionsShowPrompt(String origin,
3248 GeolocationPermissions.Callback callback) {
3249 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3250 origin, callback);
3251 }
3252
3253 /**
3254 * Instructs the browser to hide the Geolocation permissions prompt.
3255 */
3256 @Override
3257 public void onGeolocationPermissionsHidePrompt() {
3258 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3259 }
3260
Ben Murdoch7db26342009-06-03 18:21:19 +01003261 /* Adds a JavaScript error message to the system log.
3262 * @param message The error message to report.
3263 * @param lineNumber The line number of the error.
3264 * @param sourceID The name of the source file that caused the error.
3265 */
3266 @Override
3267 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003268 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3269 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3270 if (mShouldShowErrorConsole &&
3271 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3272 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3273 }
3274 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003275 }
Andrei Popescu540035d2009-09-18 18:59:20 +01003276
3277 /**
3278 * Ask the browser for an icon to represent a <video> element.
3279 * This icon will be used if the Web page did not specify a poster attribute.
3280 *
3281 * @return Bitmap The icon or null if no such icon is available.
3282 * @hide pending API Council approval
3283 */
3284 @Override
3285 public Bitmap getDefaultVideoPoster() {
3286 if (mDefaultVideoPoster == null) {
3287 mDefaultVideoPoster = BitmapFactory.decodeResource(
3288 getResources(), R.drawable.default_video_poster);
3289 }
3290 return mDefaultVideoPoster;
3291 }
3292
3293 /**
3294 * Ask the host application for a custom progress view to show while
3295 * a <video> is loading.
3296 *
3297 * @return View The progress view.
3298 * @hide pending API Council approval
3299 */
3300 @Override
3301 public View getVideoLoadingProgressView() {
3302 if (mVideoProgressView == null) {
3303 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
3304 mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
3305 }
3306 return mVideoProgressView;
3307 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003308 };
3309
3310 /**
3311 * Notify the host application a download should be done, or that
3312 * the data should be streamed if a streaming viewer is available.
3313 * @param url The full url to the content that should be downloaded
3314 * @param contentDisposition Content-disposition http header, if
3315 * present.
3316 * @param mimetype The mimetype of the content reported by the server
3317 * @param contentLength The file size reported by the server
3318 */
3319 public void onDownloadStart(String url, String userAgent,
3320 String contentDisposition, String mimetype, long contentLength) {
3321 // if we're dealing wih A/V content that's not explicitly marked
3322 // for download, check if it's streamable.
3323 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003324 || !contentDisposition.regionMatches(
3325 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003326 // query the package manager to see if there's a registered handler
3327 // that matches.
3328 Intent intent = new Intent(Intent.ACTION_VIEW);
3329 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003330 ResolveInfo info = getPackageManager().resolveActivity(intent,
3331 PackageManager.MATCH_DEFAULT_ONLY);
3332 if (info != null) {
3333 ComponentName myName = getComponentName();
3334 // If we resolved to ourselves, we don't want to attempt to
3335 // load the url only to try and download it again.
3336 if (!myName.getPackageName().equals(
3337 info.activityInfo.packageName)
3338 || !myName.getClassName().equals(
3339 info.activityInfo.name)) {
3340 // someone (other than us) knows how to handle this mime
3341 // type with this scheme, don't download.
3342 try {
3343 startActivity(intent);
3344 return;
3345 } catch (ActivityNotFoundException ex) {
3346 if (LOGD_ENABLED) {
3347 Log.d(LOGTAG, "activity not found for " + mimetype
3348 + " over " + Uri.parse(url).getScheme(),
3349 ex);
3350 }
3351 // Best behavior is to fall back to a download in this
3352 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003353 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003354 }
3355 }
3356 }
3357 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3358 }
3359
3360 /**
3361 * Notify the host application a download should be done, even if there
3362 * is a streaming viewer available for thise type.
3363 * @param url The full url to the content that should be downloaded
3364 * @param contentDisposition Content-disposition http header, if
3365 * present.
3366 * @param mimetype The mimetype of the content reported by the server
3367 * @param contentLength The file size reported by the server
3368 */
3369 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3370 String contentDisposition, String mimetype, long contentLength) {
3371
3372 String filename = URLUtil.guessFileName(url,
3373 contentDisposition, mimetype);
3374
3375 // Check to see if we have an SDCard
3376 String status = Environment.getExternalStorageState();
3377 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3378 int title;
3379 String msg;
3380
3381 // Check to see if the SDCard is busy, same as the music app
3382 if (status.equals(Environment.MEDIA_SHARED)) {
3383 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3384 title = R.string.download_sdcard_busy_dlg_title;
3385 } else {
3386 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3387 title = R.string.download_no_sdcard_dlg_title;
3388 }
3389
3390 new AlertDialog.Builder(this)
3391 .setTitle(title)
3392 .setIcon(android.R.drawable.ic_dialog_alert)
3393 .setMessage(msg)
3394 .setPositiveButton(R.string.ok, null)
3395 .show();
3396 return;
3397 }
3398
3399 // java.net.URI is a lot stricter than KURL so we have to undo
3400 // KURL's percent-encoding and redo the encoding using java.net.URI.
3401 URI uri = null;
3402 try {
3403 // Undo the percent-encoding that KURL may have done.
3404 String newUrl = new String(URLUtil.decode(url.getBytes()));
3405 // Parse the url into pieces
3406 WebAddress w = new WebAddress(newUrl);
3407 String frag = null;
3408 String query = null;
3409 String path = w.mPath;
3410 // Break the path into path, query, and fragment
3411 if (path.length() > 0) {
3412 // Strip the fragment
3413 int idx = path.lastIndexOf('#');
3414 if (idx != -1) {
3415 frag = path.substring(idx + 1);
3416 path = path.substring(0, idx);
3417 }
3418 idx = path.lastIndexOf('?');
3419 if (idx != -1) {
3420 query = path.substring(idx + 1);
3421 path = path.substring(0, idx);
3422 }
3423 }
3424 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3425 query, frag);
3426 } catch (Exception e) {
3427 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3428 return;
3429 }
3430
3431 // XXX: Have to use the old url since the cookies were stored using the
3432 // old percent-encoded url.
3433 String cookies = CookieManager.getInstance().getCookie(url);
3434
3435 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003436 values.put(Downloads.COLUMN_URI, uri.toString());
3437 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3438 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3439 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003440 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003441 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003442 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003443 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3444 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3445 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3446 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003447 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003448 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003449 }
3450 if (mimetype == null) {
3451 // We must have long pressed on a link or image to download it. We
3452 // are not sure of the mimetype in this case, so do a head request
3453 new FetchUrlMimeType(this).execute(values);
3454 } else {
3455 final Uri contentUri =
3456 getContentResolver().insert(Downloads.CONTENT_URI, values);
3457 viewDownloads(contentUri);
3458 }
3459
3460 }
3461
3462 /**
3463 * Resets the lock icon. This method is called when we start a new load and
3464 * know the url to be loaded.
3465 */
3466 private void resetLockIcon(String url) {
3467 // Save the lock-icon state (we revert to it if the load gets cancelled)
3468 saveLockIcon();
3469
3470 mLockIconType = LOCK_ICON_UNSECURE;
3471 if (URLUtil.isHttpsUrl(url)) {
3472 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003473 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003474 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3475 " reset lock icon to " + mLockIconType);
3476 }
3477 }
3478
3479 updateLockIconImage(LOCK_ICON_UNSECURE);
3480 }
3481
Grace Klobaeb6eef42009-09-15 17:56:32 -07003482 /* package */ void setLockIconType(int type) {
3483 mLockIconType = type;
3484 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003485
Grace Klobaeb6eef42009-09-15 17:56:32 -07003486 /* package */ int getLockIconType() {
3487 return mLockIconType;
3488 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003489
Grace Klobaeb6eef42009-09-15 17:56:32 -07003490 /* package */ void setPrevLockType(int type) {
3491 mPrevLockType = type;
3492 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003493
Grace Klobaeb6eef42009-09-15 17:56:32 -07003494 /* package */ int getPrevLockType() {
3495 return mPrevLockType;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003496 }
3497
3498 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003499 * Update the lock icon to correspond to our latest state.
3500 */
3501 /* package */ void updateLockIconToLatest() {
3502 updateLockIconImage(mLockIconType);
3503 }
3504
3505 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003506 * Updates the lock-icon image in the title-bar.
3507 */
3508 private void updateLockIconImage(int lockIconType) {
3509 Drawable d = null;
3510 if (lockIconType == LOCK_ICON_SECURE) {
3511 d = mSecLockIcon;
3512 } else if (lockIconType == LOCK_ICON_MIXED) {
3513 d = mMixLockIcon;
3514 }
Leon Scroggins68579392009-09-15 15:31:54 -04003515 mTitleBar.setLock(d);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003516 if (mFakeTitleBar != null) {
3517 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003518 }
3519 }
3520
3521 /**
3522 * Displays a page-info dialog.
3523 * @param tab The tab to show info about
3524 * @param fromShowSSLCertificateOnError The flag that indicates whether
3525 * this dialog was opened from the SSL-certificate-on-error dialog or
3526 * not. This is important, since we need to know whether to return to
3527 * the parent dialog or simply dismiss.
3528 */
3529 private void showPageInfo(final TabControl.Tab tab,
3530 final boolean fromShowSSLCertificateOnError) {
3531 final LayoutInflater factory = LayoutInflater
3532 .from(this);
3533
3534 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3535
3536 final WebView view = tab.getWebView();
3537
3538 String url = null;
3539 String title = null;
3540
3541 if (view == null) {
3542 url = tab.getUrl();
3543 title = tab.getTitle();
3544 } else if (view == mTabControl.getCurrentWebView()) {
3545 // Use the cached title and url if this is the current WebView
3546 url = mUrl;
3547 title = mTitle;
3548 } else {
3549 url = view.getUrl();
3550 title = view.getTitle();
3551 }
3552
3553 if (url == null) {
3554 url = "";
3555 }
3556 if (title == null) {
3557 title = "";
3558 }
3559
3560 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3561 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3562
3563 mPageInfoView = tab;
3564 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3565
3566 AlertDialog.Builder alertDialogBuilder =
3567 new AlertDialog.Builder(this)
3568 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3569 .setView(pageInfoView)
3570 .setPositiveButton(
3571 R.string.ok,
3572 new DialogInterface.OnClickListener() {
3573 public void onClick(DialogInterface dialog,
3574 int whichButton) {
3575 mPageInfoDialog = null;
3576 mPageInfoView = null;
3577 mPageInfoFromShowSSLCertificateOnError = null;
3578
3579 // if we came here from the SSL error dialog
3580 if (fromShowSSLCertificateOnError) {
3581 // go back to the SSL error dialog
3582 showSSLCertificateOnError(
3583 mSSLCertificateOnErrorView,
3584 mSSLCertificateOnErrorHandler,
3585 mSSLCertificateOnErrorError);
3586 }
3587 }
3588 })
3589 .setOnCancelListener(
3590 new DialogInterface.OnCancelListener() {
3591 public void onCancel(DialogInterface dialog) {
3592 mPageInfoDialog = null;
3593 mPageInfoView = null;
3594 mPageInfoFromShowSSLCertificateOnError = null;
3595
3596 // if we came here from the SSL error dialog
3597 if (fromShowSSLCertificateOnError) {
3598 // go back to the SSL error dialog
3599 showSSLCertificateOnError(
3600 mSSLCertificateOnErrorView,
3601 mSSLCertificateOnErrorHandler,
3602 mSSLCertificateOnErrorError);
3603 }
3604 }
3605 });
3606
3607 // if we have a main top-level page SSL certificate set or a certificate
3608 // error
3609 if (fromShowSSLCertificateOnError ||
3610 (view != null && view.getCertificate() != null)) {
3611 // add a 'View Certificate' button
3612 alertDialogBuilder.setNeutralButton(
3613 R.string.view_certificate,
3614 new DialogInterface.OnClickListener() {
3615 public void onClick(DialogInterface dialog,
3616 int whichButton) {
3617 mPageInfoDialog = null;
3618 mPageInfoView = null;
3619 mPageInfoFromShowSSLCertificateOnError = null;
3620
3621 // if we came here from the SSL error dialog
3622 if (fromShowSSLCertificateOnError) {
3623 // go back to the SSL error dialog
3624 showSSLCertificateOnError(
3625 mSSLCertificateOnErrorView,
3626 mSSLCertificateOnErrorHandler,
3627 mSSLCertificateOnErrorError);
3628 } else {
3629 // otherwise, display the top-most certificate from
3630 // the chain
3631 if (view.getCertificate() != null) {
3632 showSSLCertificate(tab);
3633 }
3634 }
3635 }
3636 });
3637 }
3638
3639 mPageInfoDialog = alertDialogBuilder.show();
3640 }
3641
3642 /**
3643 * Displays the main top-level page SSL certificate dialog
3644 * (accessible from the Page-Info dialog).
3645 * @param tab The tab to show certificate for.
3646 */
3647 private void showSSLCertificate(final TabControl.Tab tab) {
3648 final View certificateView =
3649 inflateCertificateView(tab.getWebView().getCertificate());
3650 if (certificateView == null) {
3651 return;
3652 }
3653
3654 LayoutInflater factory = LayoutInflater.from(this);
3655
3656 final LinearLayout placeholder =
3657 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3658
3659 LinearLayout ll = (LinearLayout) factory.inflate(
3660 R.layout.ssl_success, placeholder);
3661 ((TextView)ll.findViewById(R.id.success))
3662 .setText(R.string.ssl_certificate_is_valid);
3663
3664 mSSLCertificateView = tab;
3665 mSSLCertificateDialog =
3666 new AlertDialog.Builder(this)
3667 .setTitle(R.string.ssl_certificate).setIcon(
3668 R.drawable.ic_dialog_browser_certificate_secure)
3669 .setView(certificateView)
3670 .setPositiveButton(R.string.ok,
3671 new DialogInterface.OnClickListener() {
3672 public void onClick(DialogInterface dialog,
3673 int whichButton) {
3674 mSSLCertificateDialog = null;
3675 mSSLCertificateView = null;
3676
3677 showPageInfo(tab, false);
3678 }
3679 })
3680 .setOnCancelListener(
3681 new DialogInterface.OnCancelListener() {
3682 public void onCancel(DialogInterface dialog) {
3683 mSSLCertificateDialog = null;
3684 mSSLCertificateView = null;
3685
3686 showPageInfo(tab, false);
3687 }
3688 })
3689 .show();
3690 }
3691
3692 /**
3693 * Displays the SSL error certificate dialog.
3694 * @param view The target web-view.
3695 * @param handler The SSL error handler responsible for cancelling the
3696 * connection that resulted in an SSL error or proceeding per user request.
3697 * @param error The SSL error object.
3698 */
3699 private void showSSLCertificateOnError(
3700 final WebView view, final SslErrorHandler handler, final SslError error) {
3701
3702 final View certificateView =
3703 inflateCertificateView(error.getCertificate());
3704 if (certificateView == null) {
3705 return;
3706 }
3707
3708 LayoutInflater factory = LayoutInflater.from(this);
3709
3710 final LinearLayout placeholder =
3711 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3712
3713 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3714 LinearLayout ll = (LinearLayout)factory
3715 .inflate(R.layout.ssl_warning, placeholder);
3716 ((TextView)ll.findViewById(R.id.warning))
3717 .setText(R.string.ssl_untrusted);
3718 }
3719
3720 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3721 LinearLayout ll = (LinearLayout)factory
3722 .inflate(R.layout.ssl_warning, placeholder);
3723 ((TextView)ll.findViewById(R.id.warning))
3724 .setText(R.string.ssl_mismatch);
3725 }
3726
3727 if (error.hasError(SslError.SSL_EXPIRED)) {
3728 LinearLayout ll = (LinearLayout)factory
3729 .inflate(R.layout.ssl_warning, placeholder);
3730 ((TextView)ll.findViewById(R.id.warning))
3731 .setText(R.string.ssl_expired);
3732 }
3733
3734 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3735 LinearLayout ll = (LinearLayout)factory
3736 .inflate(R.layout.ssl_warning, placeholder);
3737 ((TextView)ll.findViewById(R.id.warning))
3738 .setText(R.string.ssl_not_yet_valid);
3739 }
3740
3741 mSSLCertificateOnErrorHandler = handler;
3742 mSSLCertificateOnErrorView = view;
3743 mSSLCertificateOnErrorError = error;
3744 mSSLCertificateOnErrorDialog =
3745 new AlertDialog.Builder(this)
3746 .setTitle(R.string.ssl_certificate).setIcon(
3747 R.drawable.ic_dialog_browser_certificate_partially_secure)
3748 .setView(certificateView)
3749 .setPositiveButton(R.string.ok,
3750 new DialogInterface.OnClickListener() {
3751 public void onClick(DialogInterface dialog,
3752 int whichButton) {
3753 mSSLCertificateOnErrorDialog = null;
3754 mSSLCertificateOnErrorView = null;
3755 mSSLCertificateOnErrorHandler = null;
3756 mSSLCertificateOnErrorError = null;
3757
3758 mWebViewClient.onReceivedSslError(
3759 view, handler, error);
3760 }
3761 })
3762 .setNeutralButton(R.string.page_info_view,
3763 new DialogInterface.OnClickListener() {
3764 public void onClick(DialogInterface dialog,
3765 int whichButton) {
3766 mSSLCertificateOnErrorDialog = null;
3767
3768 // do not clear the dialog state: we will
3769 // need to show the dialog again once the
3770 // user is done exploring the page-info details
3771
3772 showPageInfo(mTabControl.getTabFromView(view),
3773 true);
3774 }
3775 })
3776 .setOnCancelListener(
3777 new DialogInterface.OnCancelListener() {
3778 public void onCancel(DialogInterface dialog) {
3779 mSSLCertificateOnErrorDialog = null;
3780 mSSLCertificateOnErrorView = null;
3781 mSSLCertificateOnErrorHandler = null;
3782 mSSLCertificateOnErrorError = null;
3783
3784 mWebViewClient.onReceivedSslError(
3785 view, handler, error);
3786 }
3787 })
3788 .show();
3789 }
3790
3791 /**
3792 * Inflates the SSL certificate view (helper method).
3793 * @param certificate The SSL certificate.
3794 * @return The resultant certificate view with issued-to, issued-by,
3795 * issued-on, expires-on, and possibly other fields set.
3796 * If the input certificate is null, returns null.
3797 */
3798 private View inflateCertificateView(SslCertificate certificate) {
3799 if (certificate == null) {
3800 return null;
3801 }
3802
3803 LayoutInflater factory = LayoutInflater.from(this);
3804
3805 View certificateView = factory.inflate(
3806 R.layout.ssl_certificate, null);
3807
3808 // issued to:
3809 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3810 if (issuedTo != null) {
3811 ((TextView) certificateView.findViewById(R.id.to_common))
3812 .setText(issuedTo.getCName());
3813 ((TextView) certificateView.findViewById(R.id.to_org))
3814 .setText(issuedTo.getOName());
3815 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3816 .setText(issuedTo.getUName());
3817 }
3818
3819 // issued by:
3820 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3821 if (issuedBy != null) {
3822 ((TextView) certificateView.findViewById(R.id.by_common))
3823 .setText(issuedBy.getCName());
3824 ((TextView) certificateView.findViewById(R.id.by_org))
3825 .setText(issuedBy.getOName());
3826 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3827 .setText(issuedBy.getUName());
3828 }
3829
3830 // issued on:
3831 String issuedOn = reformatCertificateDate(
3832 certificate.getValidNotBefore());
3833 ((TextView) certificateView.findViewById(R.id.issued_on))
3834 .setText(issuedOn);
3835
3836 // expires on:
3837 String expiresOn = reformatCertificateDate(
3838 certificate.getValidNotAfter());
3839 ((TextView) certificateView.findViewById(R.id.expires_on))
3840 .setText(expiresOn);
3841
3842 return certificateView;
3843 }
3844
3845 /**
3846 * Re-formats the certificate date (Date.toString()) string to
3847 * a properly localized date string.
3848 * @return Properly localized version of the certificate date string and
3849 * the original certificate date string if fails to localize.
3850 * If the original string is null, returns an empty string "".
3851 */
3852 private String reformatCertificateDate(String certificateDate) {
3853 String reformattedDate = null;
3854
3855 if (certificateDate != null) {
3856 Date date = null;
3857 try {
3858 date = java.text.DateFormat.getInstance().parse(certificateDate);
3859 } catch (ParseException e) {
3860 date = null;
3861 }
3862
3863 if (date != null) {
3864 reformattedDate =
3865 DateFormat.getDateFormat(this).format(date);
3866 }
3867 }
3868
3869 return reformattedDate != null ? reformattedDate :
3870 (certificateDate != null ? certificateDate : "");
3871 }
3872
3873 /**
3874 * Displays an http-authentication dialog.
3875 */
3876 private void showHttpAuthentication(final HttpAuthHandler handler,
3877 final String host, final String realm, final String title,
3878 final String name, final String password, int focusId) {
3879 LayoutInflater factory = LayoutInflater.from(this);
3880 final View v = factory
3881 .inflate(R.layout.http_authentication, null);
3882 if (name != null) {
3883 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3884 }
3885 if (password != null) {
3886 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3887 }
3888
3889 String titleText = title;
3890 if (titleText == null) {
3891 titleText = getText(R.string.sign_in_to).toString().replace(
3892 "%s1", host).replace("%s2", realm);
3893 }
3894
3895 mHttpAuthHandler = handler;
3896 AlertDialog dialog = new AlertDialog.Builder(this)
3897 .setTitle(titleText)
3898 .setIcon(android.R.drawable.ic_dialog_alert)
3899 .setView(v)
3900 .setPositiveButton(R.string.action,
3901 new DialogInterface.OnClickListener() {
3902 public void onClick(DialogInterface dialog,
3903 int whichButton) {
3904 String nm = ((EditText) v
3905 .findViewById(R.id.username_edit))
3906 .getText().toString();
3907 String pw = ((EditText) v
3908 .findViewById(R.id.password_edit))
3909 .getText().toString();
3910 BrowserActivity.this.setHttpAuthUsernamePassword
3911 (host, realm, nm, pw);
3912 handler.proceed(nm, pw);
3913 mHttpAuthenticationDialog = null;
3914 mHttpAuthHandler = null;
3915 }})
3916 .setNegativeButton(R.string.cancel,
3917 new DialogInterface.OnClickListener() {
3918 public void onClick(DialogInterface dialog,
3919 int whichButton) {
3920 handler.cancel();
3921 BrowserActivity.this.resetTitleAndRevertLockIcon();
3922 mHttpAuthenticationDialog = null;
3923 mHttpAuthHandler = null;
3924 }})
3925 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3926 public void onCancel(DialogInterface dialog) {
3927 handler.cancel();
3928 BrowserActivity.this.resetTitleAndRevertLockIcon();
3929 mHttpAuthenticationDialog = null;
3930 mHttpAuthHandler = null;
3931 }})
3932 .create();
3933 // Make the IME appear when the dialog is displayed if applicable.
3934 dialog.getWindow().setSoftInputMode(
3935 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3936 dialog.show();
3937 if (focusId != 0) {
3938 dialog.findViewById(focusId).requestFocus();
3939 } else {
3940 v.findViewById(R.id.username_edit).requestFocus();
3941 }
3942 mHttpAuthenticationDialog = dialog;
3943 }
3944
3945 public int getProgress() {
3946 WebView w = mTabControl.getCurrentWebView();
3947 if (w != null) {
3948 return w.getProgress();
3949 } else {
3950 return 100;
3951 }
3952 }
3953
3954 /**
3955 * Set HTTP authentication password.
3956 *
3957 * @param host The host for the password
3958 * @param realm The realm for the password
3959 * @param username The username for the password. If it is null, it means
3960 * password can't be saved.
3961 * @param password The password
3962 */
3963 public void setHttpAuthUsernamePassword(String host, String realm,
3964 String username,
3965 String password) {
3966 WebView w = mTabControl.getCurrentWebView();
3967 if (w != null) {
3968 w.setHttpAuthUsernamePassword(host, realm, username, password);
3969 }
3970 }
3971
3972 /**
3973 * connectivity manager says net has come or gone... inform the user
3974 * @param up true if net has come up, false if net has gone down
3975 */
3976 public void onNetworkToggle(boolean up) {
3977 if (up == mIsNetworkUp) {
3978 return;
3979 } else if (up) {
3980 mIsNetworkUp = true;
3981 if (mAlertDialog != null) {
3982 mAlertDialog.cancel();
3983 mAlertDialog = null;
3984 }
3985 } else {
3986 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003987 if (mInLoad) {
3988 createAndShowNetworkDialog();
3989 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003990 }
3991 WebView w = mTabControl.getCurrentWebView();
3992 if (w != null) {
3993 w.setNetworkAvailable(up);
3994 }
3995 }
3996
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003997 // This method shows the network dialog alerting the user that the net is
3998 // down. It will only show the dialog if mAlertDialog is null.
3999 private void createAndShowNetworkDialog() {
4000 if (mAlertDialog == null) {
4001 mAlertDialog = new AlertDialog.Builder(this)
4002 .setTitle(R.string.loadSuspendedTitle)
4003 .setMessage(R.string.loadSuspended)
4004 .setPositiveButton(R.string.ok, null)
4005 .show();
4006 }
4007 }
4008
The Android Open Source Project0c908882009-03-03 19:32:16 -08004009 @Override
4010 protected void onActivityResult(int requestCode, int resultCode,
4011 Intent intent) {
4012 switch (requestCode) {
4013 case COMBO_PAGE:
4014 if (resultCode == RESULT_OK && intent != null) {
4015 String data = intent.getAction();
4016 Bundle extras = intent.getExtras();
4017 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04004018 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004019 } else {
4020 final TabControl.Tab currentTab =
4021 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04004022 dismissSubWindow(currentTab);
4023 if (data != null && data.length() != 0) {
4024 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004025 }
4026 }
4027 }
4028 break;
4029 default:
4030 break;
4031 }
Leon Scroggins30444232009-09-04 18:36:20 -04004032 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004033 }
4034
4035 /*
4036 * This method is called as a result of the user selecting the options
4037 * menu to see the download window, or when a download changes state. It
4038 * shows the download window ontop of the current window.
4039 */
4040 /* package */ void viewDownloads(Uri downloadRecord) {
4041 Intent intent = new Intent(this,
4042 BrowserDownloadPage.class);
4043 intent.setData(downloadRecord);
4044 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4045
4046 }
4047
Leon Scroggins160a7e72009-08-14 18:28:01 -04004048 /**
4049 * Open the Go page.
4050 * @param startWithHistory If true, open starting on the history tab.
4051 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004052 */
Leon Scroggins30444232009-09-04 18:36:20 -04004053 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004054 WebView current = mTabControl.getCurrentWebView();
4055 if (current == null) {
4056 return;
4057 }
4058 Intent intent = new Intent(this,
4059 CombinedBookmarkHistoryActivity.class);
4060 String title = current.getTitle();
4061 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004062 Bitmap thumbnail = createScreenshot(current);
4063
The Android Open Source Project0c908882009-03-03 19:32:16 -08004064 // Just in case the user opens bookmarks before a page finishes loading
4065 // so the current history item, and therefore the page, is null.
4066 if (null == url) {
4067 url = mLastEnteredUrl;
4068 // This can happen.
4069 if (null == url) {
4070 url = mSettings.getHomePage();
4071 }
4072 }
4073 // In case the web page has not yet received its associated title.
4074 if (title == null) {
4075 title = url;
4076 }
4077 intent.putExtra("title", title);
4078 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004079 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04004080 // Disable opening in a new window if we have maxed out the windows
4081 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4082 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004083 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004084 if (startWithHistory) {
4085 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4086 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4087 }
4088 startActivityForResult(intent, COMBO_PAGE);
4089 }
4090
4091 // Called when loading from context menu or LOAD_URL message
4092 private void loadURL(WebView view, String url) {
4093 // In case the user enters nothing.
4094 if (url != null && url.length() != 0 && view != null) {
4095 url = smartUrlFilter(url);
4096 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4097 view.loadUrl(url);
4098 }
4099 }
4100 }
4101
The Android Open Source Project0c908882009-03-03 19:32:16 -08004102 private String smartUrlFilter(Uri inUri) {
4103 if (inUri != null) {
4104 return smartUrlFilter(inUri.toString());
4105 }
4106 return null;
4107 }
4108
4109
4110 // get window count
4111
4112 int getWindowCount(){
4113 if(mTabControl != null){
4114 return mTabControl.getTabCount();
4115 }
4116 return 0;
4117 }
4118
Feng Qianb34f87a2009-03-24 21:27:26 -07004119 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004120 "(?i)" + // switch on case insensitive matching
4121 "(" + // begin group for schema
4122 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004123 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004124 ")" +
4125 "(.*)" );
4126
4127 /**
4128 * Attempts to determine whether user input is a URL or search
4129 * terms. Anything with a space is passed to search.
4130 *
4131 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4132 * "Http://" converts to "http://"
4133 *
4134 * @return Original or modified URL
4135 *
4136 */
4137 String smartUrlFilter(String url) {
4138
4139 String inUrl = url.trim();
4140 boolean hasSpace = inUrl.indexOf(' ') != -1;
4141
4142 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4143 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004144 // force scheme to lowercase
4145 String scheme = matcher.group(1);
4146 String lcScheme = scheme.toLowerCase();
4147 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004148 inUrl = lcScheme + matcher.group(2);
4149 }
4150 if (hasSpace) {
4151 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004152 }
4153 return inUrl;
4154 }
4155 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004156 // FIXME: Is this the correct place to add to searches?
4157 // what if someone else calls this function?
4158 int shortcut = parseUrlShortcut(inUrl);
4159 if (shortcut != SHORTCUT_INVALID) {
4160 Browser.addSearchUrl(mResolver, inUrl);
4161 String query = inUrl.substring(2);
4162 switch (shortcut) {
4163 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004164 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004165 case SHORTCUT_WIKIPEDIA_SEARCH:
4166 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4167 case SHORTCUT_DICTIONARY_SEARCH:
4168 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4169 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004170 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004171 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004172 }
4173 }
4174 } else {
4175 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4176 return URLUtil.guessUrl(inUrl);
4177 }
4178 }
4179
4180 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004181 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004182 }
4183
Ben Murdochbff2d602009-07-01 20:19:05 +01004184 /* package */ void setShouldShowErrorConsole(boolean flag) {
4185 if (flag == mShouldShowErrorConsole) {
4186 // Nothing to do.
4187 return;
4188 }
4189
4190 mShouldShowErrorConsole = flag;
4191
4192 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4193
4194 if (flag) {
4195 // Setting the show state of the console will cause it's the layout to be inflated.
4196 if (errorConsole.numberOfErrors() > 0) {
4197 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4198 } else {
4199 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4200 }
4201
4202 // Now we can add it to the main view.
4203 mErrorConsoleContainer.addView(errorConsole,
4204 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4205 ViewGroup.LayoutParams.WRAP_CONTENT));
4206 } else {
4207 mErrorConsoleContainer.removeView(errorConsole);
4208 }
4209
4210 }
4211
Grace Klobaeb6eef42009-09-15 17:56:32 -07004212 final static int LOCK_ICON_UNSECURE = 0;
4213 final static int LOCK_ICON_SECURE = 1;
4214 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004215
4216 private int mLockIconType = LOCK_ICON_UNSECURE;
4217 private int mPrevLockType = LOCK_ICON_UNSECURE;
4218
4219 private BrowserSettings mSettings;
4220 private TabControl mTabControl;
4221 private ContentResolver mResolver;
4222 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004223 private View mCustomView;
4224 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004225 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004226
4227 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4228 // view, we should rewrite this.
4229 private int mCurrentMenuState = 0;
4230 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004231 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004232 private static final int EMPTY_MENU = -1;
4233 private Menu mMenu;
4234
4235 private FindDialog mFindDialog;
4236 // Used to prevent chording to result in firing two shortcuts immediately
4237 // one after another. Fixes bug 1211714.
4238 boolean mCanChord;
4239
4240 private boolean mInLoad;
4241 private boolean mIsNetworkUp;
4242
4243 private boolean mPageStarted;
4244 private boolean mActivityInPause = true;
4245
4246 private boolean mMenuIsDown;
4247
The Android Open Source Project0c908882009-03-03 19:32:16 -08004248 private static boolean mInTrace;
4249
4250 // Performance probe
4251 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4252 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4253 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4254 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4255 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4256 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4257 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4258 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4259 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4260 };
4261
4262 private long mStart;
4263 private long mProcessStart;
4264 private long mUserStart;
4265 private long mSystemStart;
4266 private long mIdleStart;
4267 private long mIrqStart;
4268
4269 private long mUiStart;
4270
4271 private Drawable mMixLockIcon;
4272 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004273
4274 /* hold a ref so we can auto-cancel if necessary */
4275 private AlertDialog mAlertDialog;
4276
4277 // Wait for credentials before loading google.com
4278 private ProgressDialog mCredsDlg;
4279
4280 // The up-to-date URL and title (these can be different from those stored
4281 // in WebView, since it takes some time for the information in WebView to
4282 // get updated)
4283 private String mUrl;
4284 private String mTitle;
4285
4286 // As PageInfo has different style for landscape / portrait, we have
4287 // to re-open it when configuration changed
4288 private AlertDialog mPageInfoDialog;
4289 private TabControl.Tab mPageInfoView;
4290 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4291 // dialog, we should not just dismiss it, but should get back to the
4292 // SSL-certificate-on-error dialog. This flag is used to store this state
4293 private Boolean mPageInfoFromShowSSLCertificateOnError;
4294
4295 // as SSLCertificateOnError has different style for landscape / portrait,
4296 // we have to re-open it when configuration changed
4297 private AlertDialog mSSLCertificateOnErrorDialog;
4298 private WebView mSSLCertificateOnErrorView;
4299 private SslErrorHandler mSSLCertificateOnErrorHandler;
4300 private SslError mSSLCertificateOnErrorError;
4301
4302 // as SSLCertificate has different style for landscape / portrait, we
4303 // have to re-open it when configuration changed
4304 private AlertDialog mSSLCertificateDialog;
4305 private TabControl.Tab mSSLCertificateView;
4306
4307 // as HttpAuthentication has different style for landscape / portrait, we
4308 // have to re-open it when configuration changed
4309 private AlertDialog mHttpAuthenticationDialog;
4310 private HttpAuthHandler mHttpAuthHandler;
4311
4312 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4313 new FrameLayout.LayoutParams(
4314 ViewGroup.LayoutParams.FILL_PARENT,
4315 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004316 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4317 new FrameLayout.LayoutParams(
4318 ViewGroup.LayoutParams.FILL_PARENT,
4319 ViewGroup.LayoutParams.FILL_PARENT,
4320 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004321 // Google search
4322 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004323 // Wikipedia search
4324 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4325 // Dictionary search
4326 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4327 // Google Mobile Local search
4328 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4329
4330 final static String QUERY_PLACE_HOLDER = "%s";
4331
4332 // "source" parameter for Google search through search key
4333 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4334 // "source" parameter for Google search through goto menu
4335 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4336 // "source" parameter for Google search through simplily type
4337 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4338 // "source" parameter for Google search suggested by the browser
4339 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4340 // "source" parameter for Google search from unknown source
4341 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4342
4343 private final static String LOGTAG = "browser";
4344
The Android Open Source Project0c908882009-03-03 19:32:16 -08004345 private String mLastEnteredUrl;
4346
4347 private PowerManager.WakeLock mWakeLock;
4348 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4349
4350 private Toast mStopToast;
4351
Leon Scroggins68579392009-09-15 15:31:54 -04004352 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004353
Ben Murdochbff2d602009-07-01 20:19:05 +01004354 private LinearLayout mErrorConsoleContainer = null;
4355 private boolean mShouldShowErrorConsole = false;
4356
The Android Open Source Project0c908882009-03-03 19:32:16 -08004357 // As the ids are dynamically created, we can't guarantee that they will
4358 // be in sequence, so this static array maps ids to a window number.
4359 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4360 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4361 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4362 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4363
4364 // monitor platform changes
4365 private IntentFilter mNetworkStateChangedFilter;
4366 private BroadcastReceiver mNetworkStateIntentReceiver;
4367
Grace Klobab4da0ad2009-05-14 14:45:40 -07004368 private BroadcastReceiver mPackageInstallationReceiver;
4369
The Android Open Source Project0c908882009-03-03 19:32:16 -08004370 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004371 final static int COMBO_PAGE = 1;
4372 final static int DOWNLOAD_PAGE = 2;
4373 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004374
Andrei Popescu540035d2009-09-18 18:59:20 +01004375 // the default <video> poster
4376 private Bitmap mDefaultVideoPoster;
4377 // the video progress view
4378 private View mVideoProgressView;
4379
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004380 /**
4381 * A UrlData class to abstract how the content will be set to WebView.
4382 * This base class uses loadUrl to show the content.
4383 */
4384 private static class UrlData {
4385 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004386 byte[] mPostData;
4387
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004388 UrlData(String url) {
4389 this.mUrl = url;
4390 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004391
4392 void setPostData(byte[] postData) {
4393 mPostData = postData;
4394 }
4395
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004396 boolean isEmpty() {
4397 return mUrl == null || mUrl.length() == 0;
4398 }
4399
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004400 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004401 if (mPostData != null) {
4402 webView.postUrl(mUrl, mPostData);
4403 } else {
4404 webView.loadUrl(mUrl);
4405 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004406 }
4407 };
4408
4409 /**
4410 * A subclass of UrlData class that can display inlined content using
4411 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4412 */
4413 private static class InlinedUrlData extends UrlData {
4414 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4415 super(failUrl);
4416 mInlined = inlined;
4417 mMimeType = mimeType;
4418 mEncoding = encoding;
4419 }
4420 String mMimeType;
4421 String mInlined;
4422 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004423 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004424 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004425 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004426 }
4427
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004428 @Override
4429 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004430 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4431 }
4432 }
4433
Leon Scroggins1f005d32009-08-10 17:36:42 -04004434 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004435}