blob: dc85ec02ff6af1b4f0fe207f80bfba7552f7e2ab [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 Scott15525d42009-09-21 13:39:37 -04002365 view.getOriginalUrl(), view.getUrl(), icon);
2366 }
2367 setFavicon(icon);
2368 }
2369
2370 private void updateIcon(String url, Bitmap icon) {
2371 if (icon != null) {
2372 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2373 null, url, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002374 }
2375 setFavicon(icon);
2376 }
2377
2378 private final WebViewClient mWebViewClient = new WebViewClient() {
2379 @Override
2380 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2381 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002382 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002383
2384 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2385 if (errorConsole != null) {
2386 errorConsole.clearErrorMessages();
2387 if (mShouldShowErrorConsole) {
2388 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2389 }
2390 }
2391
The Android Open Source Project0c908882009-03-03 19:32:16 -08002392 // Call updateIcon instead of setFavicon so the bookmark
2393 // database can be updated.
Patrick Scott15525d42009-09-21 13:39:37 -04002394 updateIcon(url, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002395
Grace Kloba4d7880f2009-08-12 09:35:42 -07002396 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002397 String host;
2398 try {
2399 WebAddress uri = new WebAddress(url);
2400 host = uri.mHost;
2401 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002402 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002403 }
2404 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002405 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002406 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002407 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002408 }
2409
2410 // Performance probe
2411 if (false) {
2412 mStart = SystemClock.uptimeMillis();
2413 mProcessStart = Process.getElapsedCpuTime();
2414 long[] sysCpu = new long[7];
2415 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2416 sysCpu, null)) {
2417 mUserStart = sysCpu[0] + sysCpu[1];
2418 mSystemStart = sysCpu[2];
2419 mIdleStart = sysCpu[3];
2420 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2421 }
2422 mUiStart = SystemClock.currentThreadTimeMillis();
2423 }
2424
2425 if (!mPageStarted) {
2426 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002427 // if onResume() has been called, resumeWebViewTimers() does
2428 // nothing.
2429 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002430 }
2431
2432 // reset sync timer to avoid sync starts during loading a page
2433 CookieSyncManager.getInstance().resetSync();
2434
2435 mInLoad = true;
Leon Scroggins184f5e32009-09-21 10:38:24 -04002436 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002437 updateInLoadMenuItems();
2438 if (!mIsNetworkUp) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04002439 createAndShowNetworkDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002440 if (view != null) {
2441 view.setNetworkAvailable(false);
2442 }
2443 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002444 }
2445
2446 @Override
2447 public void onPageFinished(WebView view, String url) {
2448 // Reset the title and icon in case we stopped a provisional
2449 // load.
2450 resetTitleAndIcon(view);
2451
2452 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002453 updateLockIconToLatest();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002454 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002455
The Android Open Source Project0c908882009-03-03 19:32:16 -08002456 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002457 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002458 long[] sysCpu = new long[7];
2459 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2460 sysCpu, null)) {
2461 String uiInfo = "UI thread used "
2462 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2463 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002464 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002465 Log.d(LOGTAG, uiInfo);
2466 }
2467 //The string that gets written to the log
2468 String performanceString = "It took total "
2469 + (SystemClock.uptimeMillis() - mStart)
2470 + " ms clock time to load the page."
2471 + "\nbrowser process used "
2472 + (Process.getElapsedCpuTime() - mProcessStart)
2473 + " ms, user processes used "
2474 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2475 + " ms, kernel used "
2476 + (sysCpu[2] - mSystemStart) * 10
2477 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2478 + " ms and irq took "
2479 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2480 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002481 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002482 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2483 }
2484 if (url != null) {
2485 // strip the url to maintain consistency
2486 String newUrl = new String(url);
2487 if (newUrl.startsWith("http://www.")) {
2488 newUrl = newUrl.substring(11);
2489 } else if (newUrl.startsWith("http://")) {
2490 newUrl = newUrl.substring(7);
2491 } else if (newUrl.startsWith("https://www.")) {
2492 newUrl = newUrl.substring(12);
2493 } else if (newUrl.startsWith("https://")) {
2494 newUrl = newUrl.substring(8);
2495 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002496 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002497 Log.d(LOGTAG, newUrl + " loaded");
2498 }
2499 /*
2500 if (sWhiteList.contains(newUrl)) {
2501 // The string that gets pushed to the statistcs
2502 // service
2503 performanceString = performanceString
2504 + "\nWebpage: "
2505 + newUrl
2506 + "\nCarrier: "
2507 + android.os.SystemProperties
2508 .get("gsm.sim.operator.alpha");
2509 if (mWebView != null
2510 && mWebView.getContext() != null
2511 && mWebView.getContext().getSystemService(
2512 Context.CONNECTIVITY_SERVICE) != null) {
2513 ConnectivityManager cManager =
2514 (ConnectivityManager) mWebView
2515 .getContext().getSystemService(
2516 Context.CONNECTIVITY_SERVICE);
2517 NetworkInfo nInfo = cManager
2518 .getActiveNetworkInfo();
2519 if (nInfo != null) {
2520 performanceString = performanceString
2521 + "\nNetwork Type: "
2522 + nInfo.getType().toString();
2523 }
2524 }
2525 Checkin.logEvent(mResolver,
2526 Checkin.Events.Tag.WEBPAGE_LOAD,
2527 performanceString);
2528 Log.w(LOGTAG, "pushed to the statistics service");
2529 }
2530 */
2531 }
2532 }
2533 }
2534
2535 if (mInTrace) {
2536 mInTrace = false;
2537 Debug.stopMethodTracing();
2538 }
2539
2540 if (mPageStarted) {
2541 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002542 // pauseWebViewTimers() will do nothing and return false if
2543 // onPause() is not called yet.
2544 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002545 if (mWakeLock.isHeld()) {
2546 mHandler.removeMessages(RELEASE_WAKELOCK);
2547 mWakeLock.release();
2548 }
2549 }
2550 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002551 }
2552
2553 // return true if want to hijack the url to let another app to handle it
2554 @Override
2555 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2556 if (url.startsWith(SCHEME_WTAI)) {
2557 // wtai://wp/mc;number
2558 // number=string(phone-number)
2559 if (url.startsWith(SCHEME_WTAI_MC)) {
2560 Intent intent = new Intent(Intent.ACTION_VIEW,
2561 Uri.parse(WebView.SCHEME_TEL +
2562 url.substring(SCHEME_WTAI_MC.length())));
2563 startActivity(intent);
2564 return true;
2565 }
2566 // wtai://wp/sd;dtmf
2567 // dtmf=string(dialstring)
2568 if (url.startsWith(SCHEME_WTAI_SD)) {
2569 // TODO
2570 // only send when there is active voice connection
2571 return false;
2572 }
2573 // wtai://wp/ap;number;name
2574 // number=string(phone-number)
2575 // name=string
2576 if (url.startsWith(SCHEME_WTAI_AP)) {
2577 // TODO
2578 return false;
2579 }
2580 }
2581
Dianne Hackborn99189432009-06-17 18:06:18 -07002582 // The "about:" schemes are internal to the browser; don't
2583 // want these to be dispatched to other apps.
2584 if (url.startsWith("about:")) {
2585 return false;
2586 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002587
Dianne Hackborn99189432009-06-17 18:06:18 -07002588 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002589
Dianne Hackborn99189432009-06-17 18:06:18 -07002590 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002591 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002592 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2593 } catch (URISyntaxException ex) {
2594 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002595 return false;
2596 }
2597
Grace Kloba5b078b52009-06-24 20:23:41 -07002598 // check whether the intent can be resolved. If not, we will see
2599 // whether we can download it from the Market.
2600 if (getPackageManager().resolveActivity(intent, 0) == null) {
2601 String packagename = intent.getPackage();
2602 if (packagename != null) {
2603 intent = new Intent(Intent.ACTION_VIEW, Uri
2604 .parse("market://search?q=pname:" + packagename));
2605 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2606 startActivity(intent);
2607 return true;
2608 } else {
2609 return false;
2610 }
2611 }
2612
Dianne Hackborn99189432009-06-17 18:06:18 -07002613 // sanitize the Intent, ensuring web pages can not bypass browser
2614 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002615 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002616 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002617 try {
2618 if (startActivityIfNeeded(intent, -1)) {
2619 return true;
2620 }
2621 } catch (ActivityNotFoundException ex) {
2622 // ignore the error. If no application can handle the URL,
2623 // eg about:blank, assume the browser can handle it.
2624 }
2625
2626 if (mMenuIsDown) {
2627 openTab(url);
2628 closeOptionsMenu();
2629 return true;
2630 }
2631
2632 return false;
2633 }
2634
2635 /**
2636 * Updates the lock icon. This method is called when we discover another
2637 * resource to be loaded for this page (for example, javascript). While
2638 * we update the icon type, we do not update the lock icon itself until
2639 * we are done loading, it is slightly more secure this way.
2640 */
2641 @Override
2642 public void onLoadResource(WebView view, String url) {
2643 if (url != null && url.length() > 0) {
2644 // It is only if the page claims to be secure
2645 // that we may have to update the lock:
2646 if (mLockIconType == LOCK_ICON_SECURE) {
2647 // If NOT a 'safe' url, change the lock to mixed content!
2648 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2649 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002650 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002651 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2652 " updated lock icon to " + mLockIconType + " due to " + url);
2653 }
2654 }
2655 }
2656 }
2657 }
2658
2659 /**
2660 * Show the dialog, asking the user if they would like to continue after
2661 * an excessive number of HTTP redirects.
2662 */
2663 @Override
2664 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2665 final Message continueMsg) {
2666 new AlertDialog.Builder(BrowserActivity.this)
2667 .setTitle(R.string.browserFrameRedirect)
2668 .setMessage(R.string.browserFrame307Post)
2669 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2670 public void onClick(DialogInterface dialog, int which) {
2671 continueMsg.sendToTarget();
2672 }})
2673 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2674 public void onClick(DialogInterface dialog, int which) {
2675 cancelMsg.sendToTarget();
2676 }})
2677 .setOnCancelListener(new OnCancelListener() {
2678 public void onCancel(DialogInterface dialog) {
2679 cancelMsg.sendToTarget();
2680 }})
2681 .show();
2682 }
2683
Patrick Scott37911c72009-03-24 18:02:58 -07002684 // Container class for the next error dialog that needs to be
2685 // displayed.
2686 class ErrorDialog {
2687 public final int mTitle;
2688 public final String mDescription;
2689 public final int mError;
2690 ErrorDialog(int title, String desc, int error) {
2691 mTitle = title;
2692 mDescription = desc;
2693 mError = error;
2694 }
2695 };
2696
2697 private void processNextError() {
2698 if (mQueuedErrors == null) {
2699 return;
2700 }
2701 // The first one is currently displayed so just remove it.
2702 mQueuedErrors.removeFirst();
2703 if (mQueuedErrors.size() == 0) {
2704 mQueuedErrors = null;
2705 return;
2706 }
2707 showError(mQueuedErrors.getFirst());
2708 }
2709
2710 private DialogInterface.OnDismissListener mDialogListener =
2711 new DialogInterface.OnDismissListener() {
2712 public void onDismiss(DialogInterface d) {
2713 processNextError();
2714 }
2715 };
2716 private LinkedList<ErrorDialog> mQueuedErrors;
2717
2718 private void queueError(int err, String desc) {
2719 if (mQueuedErrors == null) {
2720 mQueuedErrors = new LinkedList<ErrorDialog>();
2721 }
2722 for (ErrorDialog d : mQueuedErrors) {
2723 if (d.mError == err) {
2724 // Already saw a similar error, ignore the new one.
2725 return;
2726 }
2727 }
2728 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002729 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002730 R.string.browserFrameFileErrorLabel :
2731 R.string.browserFrameNetworkErrorLabel,
2732 desc, err);
2733 mQueuedErrors.addLast(errDialog);
2734
2735 // Show the dialog now if the queue was empty.
2736 if (mQueuedErrors.size() == 1) {
2737 showError(errDialog);
2738 }
2739 }
2740
2741 private void showError(ErrorDialog errDialog) {
2742 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2743 .setTitle(errDialog.mTitle)
2744 .setMessage(errDialog.mDescription)
2745 .setPositiveButton(R.string.ok, null)
2746 .create();
2747 d.setOnDismissListener(mDialogListener);
2748 d.show();
2749 }
2750
The Android Open Source Project0c908882009-03-03 19:32:16 -08002751 /**
2752 * Show a dialog informing the user of the network error reported by
2753 * WebCore.
2754 */
2755 @Override
2756 public void onReceivedError(WebView view, int errorCode,
2757 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002758 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2759 errorCode != WebViewClient.ERROR_CONNECT &&
2760 errorCode != WebViewClient.ERROR_BAD_URL &&
2761 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2762 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002763 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002764 }
Patrick Scott37911c72009-03-24 18:02:58 -07002765 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2766 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002767
2768 // We need to reset the title after an error.
2769 resetTitleAndRevertLockIcon();
2770 }
2771
2772 /**
2773 * Check with the user if it is ok to resend POST data as the page they
2774 * are trying to navigate to is the result of a POST.
2775 */
2776 @Override
2777 public void onFormResubmission(WebView view, final Message dontResend,
2778 final Message resend) {
2779 new AlertDialog.Builder(BrowserActivity.this)
2780 .setTitle(R.string.browserFrameFormResubmitLabel)
2781 .setMessage(R.string.browserFrameFormResubmitMessage)
2782 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2783 public void onClick(DialogInterface dialog, int which) {
2784 resend.sendToTarget();
2785 }})
2786 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2787 public void onClick(DialogInterface dialog, int which) {
2788 dontResend.sendToTarget();
2789 }})
2790 .setOnCancelListener(new OnCancelListener() {
2791 public void onCancel(DialogInterface dialog) {
2792 dontResend.sendToTarget();
2793 }})
2794 .show();
2795 }
2796
2797 /**
2798 * Insert the url into the visited history database.
2799 * @param url The url to be inserted.
2800 * @param isReload True if this url is being reloaded.
2801 * FIXME: Not sure what to do when reloading the page.
2802 */
2803 @Override
2804 public void doUpdateVisitedHistory(WebView view, String url,
2805 boolean isReload) {
2806 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2807 return;
2808 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002809 // remove "client" before updating it to the history so that it wont
2810 // show up in the auto-complete list.
2811 int index = url.indexOf("client=ms-");
2812 if (index > 0 && url.contains(".google.")) {
2813 int end = url.indexOf('&', index);
2814 if (end > 0) {
2815 url = url.substring(0, index-1).concat(url.substring(end));
2816 } else {
2817 url = url.substring(0, index-1);
2818 }
2819 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002820 Browser.updateVisitedHistory(mResolver, url, true);
2821 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2822 }
2823
2824 /**
2825 * Displays SSL error(s) dialog to the user.
2826 */
2827 @Override
2828 public void onReceivedSslError(
2829 final WebView view, final SslErrorHandler handler, final SslError error) {
2830
2831 if (mSettings.showSecurityWarnings()) {
2832 final LayoutInflater factory =
2833 LayoutInflater.from(BrowserActivity.this);
2834 final View warningsView =
2835 factory.inflate(R.layout.ssl_warnings, null);
2836 final LinearLayout placeholder =
2837 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2838
2839 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2840 LinearLayout ll = (LinearLayout)factory
2841 .inflate(R.layout.ssl_warning, null);
2842 ((TextView)ll.findViewById(R.id.warning))
2843 .setText(R.string.ssl_untrusted);
2844 placeholder.addView(ll);
2845 }
2846
2847 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2848 LinearLayout ll = (LinearLayout)factory
2849 .inflate(R.layout.ssl_warning, null);
2850 ((TextView)ll.findViewById(R.id.warning))
2851 .setText(R.string.ssl_mismatch);
2852 placeholder.addView(ll);
2853 }
2854
2855 if (error.hasError(SslError.SSL_EXPIRED)) {
2856 LinearLayout ll = (LinearLayout)factory
2857 .inflate(R.layout.ssl_warning, null);
2858 ((TextView)ll.findViewById(R.id.warning))
2859 .setText(R.string.ssl_expired);
2860 placeholder.addView(ll);
2861 }
2862
2863 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2864 LinearLayout ll = (LinearLayout)factory
2865 .inflate(R.layout.ssl_warning, null);
2866 ((TextView)ll.findViewById(R.id.warning))
2867 .setText(R.string.ssl_not_yet_valid);
2868 placeholder.addView(ll);
2869 }
2870
2871 new AlertDialog.Builder(BrowserActivity.this)
2872 .setTitle(R.string.security_warning)
2873 .setIcon(android.R.drawable.ic_dialog_alert)
2874 .setView(warningsView)
2875 .setPositiveButton(R.string.ssl_continue,
2876 new DialogInterface.OnClickListener() {
2877 public void onClick(DialogInterface dialog, int whichButton) {
2878 handler.proceed();
2879 }
2880 })
2881 .setNeutralButton(R.string.view_certificate,
2882 new DialogInterface.OnClickListener() {
2883 public void onClick(DialogInterface dialog, int whichButton) {
2884 showSSLCertificateOnError(view, handler, error);
2885 }
2886 })
2887 .setNegativeButton(R.string.cancel,
2888 new DialogInterface.OnClickListener() {
2889 public void onClick(DialogInterface dialog, int whichButton) {
2890 handler.cancel();
2891 BrowserActivity.this.resetTitleAndRevertLockIcon();
2892 }
2893 })
2894 .setOnCancelListener(
2895 new DialogInterface.OnCancelListener() {
2896 public void onCancel(DialogInterface dialog) {
2897 handler.cancel();
2898 BrowserActivity.this.resetTitleAndRevertLockIcon();
2899 }
2900 })
2901 .show();
2902 } else {
2903 handler.proceed();
2904 }
2905 }
2906
2907 /**
2908 * Handles an HTTP authentication request.
2909 *
2910 * @param handler The authentication handler
2911 * @param host The host
2912 * @param realm The realm
2913 */
2914 @Override
2915 public void onReceivedHttpAuthRequest(WebView view,
2916 final HttpAuthHandler handler, final String host, final String realm) {
2917 String username = null;
2918 String password = null;
2919
2920 boolean reuseHttpAuthUsernamePassword =
2921 handler.useHttpAuthUsernamePassword();
2922
2923 if (reuseHttpAuthUsernamePassword &&
2924 (mTabControl.getCurrentWebView() != null)) {
2925 String[] credentials =
2926 mTabControl.getCurrentWebView()
2927 .getHttpAuthUsernamePassword(host, realm);
2928 if (credentials != null && credentials.length == 2) {
2929 username = credentials[0];
2930 password = credentials[1];
2931 }
2932 }
2933
2934 if (username != null && password != null) {
2935 handler.proceed(username, password);
2936 } else {
2937 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2938 }
2939 }
2940
2941 @Override
2942 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2943 if (mMenuIsDown) {
2944 // only check shortcut key when MENU is held
2945 return getWindow().isShortcutKey(event.getKeyCode(), event);
2946 } else {
2947 return false;
2948 }
2949 }
2950
2951 @Override
2952 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2953 if (view != mTabControl.getCurrentTopWebView()) {
2954 return;
2955 }
2956 if (event.isDown()) {
2957 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2958 } else {
2959 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2960 }
2961 }
2962 };
2963
2964 //--------------------------------------------------------------------------
2965 // WebChromeClient implementation
2966 //--------------------------------------------------------------------------
2967
2968 /* package */ WebChromeClient getWebChromeClient() {
2969 return mWebChromeClient;
2970 }
2971
2972 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2973 // Helper method to create a new tab or sub window.
2974 private void createWindow(final boolean dialog, final Message msg) {
2975 if (dialog) {
2976 mTabControl.createSubWindow();
2977 final TabControl.Tab t = mTabControl.getCurrentTab();
2978 attachSubWindow(t);
2979 WebView.WebViewTransport transport =
2980 (WebView.WebViewTransport) msg.obj;
2981 transport.setWebView(t.getSubWebView());
2982 msg.sendToTarget();
2983 } else {
2984 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04002985 final TabControl.Tab newTab
2986 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07002987 if (newTab != parent) {
2988 parent.addChildTab(newTab);
2989 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002990 WebView.WebViewTransport transport =
2991 (WebView.WebViewTransport) msg.obj;
2992 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04002993 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002994 }
2995 }
2996
2997 @Override
2998 public boolean onCreateWindow(WebView view, final boolean dialog,
2999 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003000 // Short-circuit if we can't create any more tabs or sub windows.
3001 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3002 new AlertDialog.Builder(BrowserActivity.this)
3003 .setTitle(R.string.too_many_subwindows_dialog_title)
3004 .setIcon(android.R.drawable.ic_dialog_alert)
3005 .setMessage(R.string.too_many_subwindows_dialog_message)
3006 .setPositiveButton(R.string.ok, null)
3007 .show();
3008 return false;
3009 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3010 new AlertDialog.Builder(BrowserActivity.this)
3011 .setTitle(R.string.too_many_windows_dialog_title)
3012 .setIcon(android.R.drawable.ic_dialog_alert)
3013 .setMessage(R.string.too_many_windows_dialog_message)
3014 .setPositiveButton(R.string.ok, null)
3015 .show();
3016 return false;
3017 }
3018
3019 // Short-circuit if this was a user gesture.
3020 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003021 createWindow(dialog, resultMsg);
3022 return true;
3023 }
3024
3025 // Allow the popup and create the appropriate window.
3026 final AlertDialog.OnClickListener allowListener =
3027 new AlertDialog.OnClickListener() {
3028 public void onClick(DialogInterface d,
3029 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003030 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003031 }
3032 };
3033
3034 // Block the popup by returning a null WebView.
3035 final AlertDialog.OnClickListener blockListener =
3036 new AlertDialog.OnClickListener() {
3037 public void onClick(DialogInterface d, int which) {
3038 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003039 }
3040 };
3041
3042 // Build a confirmation dialog to display to the user.
3043 final AlertDialog d =
3044 new AlertDialog.Builder(BrowserActivity.this)
3045 .setTitle(R.string.attention)
3046 .setIcon(android.R.drawable.ic_dialog_alert)
3047 .setMessage(R.string.popup_window_attempt)
3048 .setPositiveButton(R.string.allow, allowListener)
3049 .setNegativeButton(R.string.block, blockListener)
3050 .setCancelable(false)
3051 .create();
3052
3053 // Show the confirmation dialog.
3054 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003055 return true;
3056 }
3057
3058 @Override
3059 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003060 final TabControl.Tab current = mTabControl.getCurrentTab();
3061 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003062 if (parent != null) {
3063 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003064 switchToTab(mTabControl.getTabIndex(parent));
3065 // Now we need to close the window
3066 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003067 }
3068 }
3069
3070 @Override
3071 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003072 mTitleBar.setProgress(newProgress);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003073 if (mFakeTitleBar != null) {
3074 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003075 }
3076
3077 if (newProgress == 100) {
3078 // onProgressChanged() is called for sub-frame too while
3079 // onPageFinished() is only called for the main frame. sync
3080 // cookie and cache promptly here.
3081 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003082 if (mInLoad) {
3083 mInLoad = false;
3084 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003085 // If the options menu is open, leave the title bar
3086 if (!mOptionsMenuOpen || !mIconView) {
3087 hideFakeTitleBar();
3088 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003089 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003090 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003091 // onPageFinished may have already been called but a subframe
3092 // is still loading and updating the progress. Reset mInLoad
3093 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003094 mInLoad = true;
3095 updateInLoadMenuItems();
Leon Scroggins184f5e32009-09-21 10:38:24 -04003096 if (!mOptionsMenuOpen || mIconView) {
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003097 // This page has begun to load, so show the title bar
3098 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003099 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003100 }
3101 }
3102
3103 @Override
3104 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003105 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003106
3107 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003108 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003109
3110 if (url == null ||
3111 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3112 return;
3113 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003114 // See if we can find the current url in our history database and
3115 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003116 if (url.startsWith("http://www.")) {
3117 url = url.substring(11);
3118 } else if (url.startsWith("http://")) {
3119 url = url.substring(4);
3120 }
3121 try {
3122 url = "%" + url;
3123 String [] selArgs = new String[] { url };
3124
3125 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3126 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3127 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3128 Browser.HISTORY_PROJECTION, where, selArgs, null);
3129 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003130 // Current implementation of database only has one entry per
3131 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003132 ContentValues map = new ContentValues();
3133 map.put(Browser.BookmarkColumns.TITLE, title);
3134 mResolver.update(Browser.BOOKMARKS_URI, map,
3135 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003136 }
3137 c.close();
3138 } catch (IllegalStateException e) {
3139 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3140 } catch (SQLiteException ex) {
3141 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3142 }
3143 }
3144
3145 @Override
3146 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003147 updateIcon(view, icon);
3148 }
3149
3150 @Override
3151 public void onReceivedTouchIconUrl(WebView view, String url) {
3152 final ContentResolver cr = getContentResolver();
3153 final Cursor c =
3154 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003155 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003156 if (c != null) {
3157 if (c.getCount() > 0) {
3158 new DownloadTouchIcon(cr, c, view).execute(url);
3159 } else {
3160 c.close();
3161 }
3162 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003163 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003164
Andrei Popescuadc008d2009-06-26 14:11:30 +01003165 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003166 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003167 if (mCustomView != null)
3168 return;
3169
3170 // Add the custom view to its container.
3171 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3172 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003173 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003174 // Save the menu state and set it to empty while the custom
3175 // view is showing.
3176 mOldMenuState = mMenuState;
3177 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003178 // Hide the content view.
3179 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003180 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003181 mCustomViewContainer.setVisibility(View.VISIBLE);
3182 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003183 }
3184
3185 @Override
3186 public void onHideCustomView() {
3187 if (mCustomView == null)
3188 return;
3189
Andrei Popescuc9b55562009-07-07 10:51:15 +01003190 // Hide the custom view.
3191 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003192 // Remove the custom view from its container.
3193 mCustomViewContainer.removeView(mCustomView);
3194 mCustomView = null;
3195 // Reset the old menu state.
3196 mMenuState = mOldMenuState;
3197 mOldMenuState = EMPTY_MENU;
3198 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003199 mCustomViewCallback.onCustomViewHidden();
3200 // Show the content view.
3201 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003202 }
3203
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003204 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003205 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003206 * @param url the URL that exceeded the quota
3207 * @param databaseIdentifier the identifier of the database on
3208 * which the transaction that caused the quota overflow was run
3209 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003210 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003211 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003212 * @param quotaUpdater The callback to run when a decision to allow or
3213 * deny quota has been made. Don't forget to call this!
3214 */
3215 @Override
3216 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003217 String databaseIdentifier, long currentQuota, long estimatedSize,
3218 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003219 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003220 url, databaseIdentifier, currentQuota, estimatedSize,
3221 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003222 }
3223
3224 /**
3225 * The Application Cache has exceeded its max size.
3226 * @param spaceNeeded is the amount of disk space that would be needed
3227 * in order for the last appcache operation to succeed.
3228 * @param totalUsedQuota is the sum of all origins' quota.
3229 * @param quotaUpdater A callback to inform the WebCore thread that a new
3230 * app cache size is available. This callback must always be executed at
3231 * some point to ensure that the sleeping WebCore thread is woken up.
3232 */
3233 @Override
3234 public void onReachedMaxAppCacheSize(long spaceNeeded,
3235 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3236 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3237 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003238 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003239
Steve Block2bc69912009-07-30 14:45:13 +01003240 /**
3241 * Instructs the browser to show a prompt to ask the user to set the
3242 * Geolocation permission state for the specified origin.
3243 * @param origin The origin for which Geolocation permissions are
3244 * requested.
3245 * @param callback The callback to call once the user has set the
3246 * Geolocation permission state.
3247 */
3248 @Override
3249 public void onGeolocationPermissionsShowPrompt(String origin,
3250 GeolocationPermissions.Callback callback) {
3251 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3252 origin, callback);
3253 }
3254
3255 /**
3256 * Instructs the browser to hide the Geolocation permissions prompt.
3257 */
3258 @Override
3259 public void onGeolocationPermissionsHidePrompt() {
3260 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3261 }
3262
Ben Murdoch7db26342009-06-03 18:21:19 +01003263 /* Adds a JavaScript error message to the system log.
3264 * @param message The error message to report.
3265 * @param lineNumber The line number of the error.
3266 * @param sourceID The name of the source file that caused the error.
3267 */
3268 @Override
3269 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003270 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3271 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3272 if (mShouldShowErrorConsole &&
3273 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3274 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3275 }
3276 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003277 }
Andrei Popescu540035d2009-09-18 18:59:20 +01003278
3279 /**
3280 * Ask the browser for an icon to represent a <video> element.
3281 * This icon will be used if the Web page did not specify a poster attribute.
3282 *
3283 * @return Bitmap The icon or null if no such icon is available.
3284 * @hide pending API Council approval
3285 */
3286 @Override
3287 public Bitmap getDefaultVideoPoster() {
3288 if (mDefaultVideoPoster == null) {
3289 mDefaultVideoPoster = BitmapFactory.decodeResource(
3290 getResources(), R.drawable.default_video_poster);
3291 }
3292 return mDefaultVideoPoster;
3293 }
3294
3295 /**
3296 * Ask the host application for a custom progress view to show while
3297 * a <video> is loading.
3298 *
3299 * @return View The progress view.
3300 * @hide pending API Council approval
3301 */
3302 @Override
3303 public View getVideoLoadingProgressView() {
3304 if (mVideoProgressView == null) {
3305 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
3306 mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
3307 }
3308 return mVideoProgressView;
3309 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003310 };
3311
3312 /**
3313 * Notify the host application a download should be done, or that
3314 * the data should be streamed if a streaming viewer is available.
3315 * @param url The full url to the content that should be downloaded
3316 * @param contentDisposition Content-disposition http header, if
3317 * present.
3318 * @param mimetype The mimetype of the content reported by the server
3319 * @param contentLength The file size reported by the server
3320 */
3321 public void onDownloadStart(String url, String userAgent,
3322 String contentDisposition, String mimetype, long contentLength) {
3323 // if we're dealing wih A/V content that's not explicitly marked
3324 // for download, check if it's streamable.
3325 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003326 || !contentDisposition.regionMatches(
3327 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003328 // query the package manager to see if there's a registered handler
3329 // that matches.
3330 Intent intent = new Intent(Intent.ACTION_VIEW);
3331 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003332 ResolveInfo info = getPackageManager().resolveActivity(intent,
3333 PackageManager.MATCH_DEFAULT_ONLY);
3334 if (info != null) {
3335 ComponentName myName = getComponentName();
3336 // If we resolved to ourselves, we don't want to attempt to
3337 // load the url only to try and download it again.
3338 if (!myName.getPackageName().equals(
3339 info.activityInfo.packageName)
3340 || !myName.getClassName().equals(
3341 info.activityInfo.name)) {
3342 // someone (other than us) knows how to handle this mime
3343 // type with this scheme, don't download.
3344 try {
3345 startActivity(intent);
3346 return;
3347 } catch (ActivityNotFoundException ex) {
3348 if (LOGD_ENABLED) {
3349 Log.d(LOGTAG, "activity not found for " + mimetype
3350 + " over " + Uri.parse(url).getScheme(),
3351 ex);
3352 }
3353 // Best behavior is to fall back to a download in this
3354 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003355 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003356 }
3357 }
3358 }
3359 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3360 }
3361
3362 /**
3363 * Notify the host application a download should be done, even if there
3364 * is a streaming viewer available for thise type.
3365 * @param url The full url to the content that should be downloaded
3366 * @param contentDisposition Content-disposition http header, if
3367 * present.
3368 * @param mimetype The mimetype of the content reported by the server
3369 * @param contentLength The file size reported by the server
3370 */
3371 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3372 String contentDisposition, String mimetype, long contentLength) {
3373
3374 String filename = URLUtil.guessFileName(url,
3375 contentDisposition, mimetype);
3376
3377 // Check to see if we have an SDCard
3378 String status = Environment.getExternalStorageState();
3379 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3380 int title;
3381 String msg;
3382
3383 // Check to see if the SDCard is busy, same as the music app
3384 if (status.equals(Environment.MEDIA_SHARED)) {
3385 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3386 title = R.string.download_sdcard_busy_dlg_title;
3387 } else {
3388 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3389 title = R.string.download_no_sdcard_dlg_title;
3390 }
3391
3392 new AlertDialog.Builder(this)
3393 .setTitle(title)
3394 .setIcon(android.R.drawable.ic_dialog_alert)
3395 .setMessage(msg)
3396 .setPositiveButton(R.string.ok, null)
3397 .show();
3398 return;
3399 }
3400
3401 // java.net.URI is a lot stricter than KURL so we have to undo
3402 // KURL's percent-encoding and redo the encoding using java.net.URI.
3403 URI uri = null;
3404 try {
3405 // Undo the percent-encoding that KURL may have done.
3406 String newUrl = new String(URLUtil.decode(url.getBytes()));
3407 // Parse the url into pieces
3408 WebAddress w = new WebAddress(newUrl);
3409 String frag = null;
3410 String query = null;
3411 String path = w.mPath;
3412 // Break the path into path, query, and fragment
3413 if (path.length() > 0) {
3414 // Strip the fragment
3415 int idx = path.lastIndexOf('#');
3416 if (idx != -1) {
3417 frag = path.substring(idx + 1);
3418 path = path.substring(0, idx);
3419 }
3420 idx = path.lastIndexOf('?');
3421 if (idx != -1) {
3422 query = path.substring(idx + 1);
3423 path = path.substring(0, idx);
3424 }
3425 }
3426 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3427 query, frag);
3428 } catch (Exception e) {
3429 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3430 return;
3431 }
3432
3433 // XXX: Have to use the old url since the cookies were stored using the
3434 // old percent-encoded url.
3435 String cookies = CookieManager.getInstance().getCookie(url);
3436
3437 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003438 values.put(Downloads.COLUMN_URI, uri.toString());
3439 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3440 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3441 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003442 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003443 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003444 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003445 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3446 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3447 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3448 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003449 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003450 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003451 }
3452 if (mimetype == null) {
3453 // We must have long pressed on a link or image to download it. We
3454 // are not sure of the mimetype in this case, so do a head request
3455 new FetchUrlMimeType(this).execute(values);
3456 } else {
3457 final Uri contentUri =
3458 getContentResolver().insert(Downloads.CONTENT_URI, values);
3459 viewDownloads(contentUri);
3460 }
3461
3462 }
3463
3464 /**
3465 * Resets the lock icon. This method is called when we start a new load and
3466 * know the url to be loaded.
3467 */
3468 private void resetLockIcon(String url) {
3469 // Save the lock-icon state (we revert to it if the load gets cancelled)
3470 saveLockIcon();
3471
3472 mLockIconType = LOCK_ICON_UNSECURE;
3473 if (URLUtil.isHttpsUrl(url)) {
3474 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003475 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003476 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3477 " reset lock icon to " + mLockIconType);
3478 }
3479 }
3480
3481 updateLockIconImage(LOCK_ICON_UNSECURE);
3482 }
3483
Grace Klobaeb6eef42009-09-15 17:56:32 -07003484 /* package */ void setLockIconType(int type) {
3485 mLockIconType = type;
3486 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003487
Grace Klobaeb6eef42009-09-15 17:56:32 -07003488 /* package */ int getLockIconType() {
3489 return mLockIconType;
3490 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003491
Grace Klobaeb6eef42009-09-15 17:56:32 -07003492 /* package */ void setPrevLockType(int type) {
3493 mPrevLockType = type;
3494 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003495
Grace Klobaeb6eef42009-09-15 17:56:32 -07003496 /* package */ int getPrevLockType() {
3497 return mPrevLockType;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003498 }
3499
3500 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003501 * Update the lock icon to correspond to our latest state.
3502 */
3503 /* package */ void updateLockIconToLatest() {
3504 updateLockIconImage(mLockIconType);
3505 }
3506
3507 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003508 * Updates the lock-icon image in the title-bar.
3509 */
3510 private void updateLockIconImage(int lockIconType) {
3511 Drawable d = null;
3512 if (lockIconType == LOCK_ICON_SECURE) {
3513 d = mSecLockIcon;
3514 } else if (lockIconType == LOCK_ICON_MIXED) {
3515 d = mMixLockIcon;
3516 }
Leon Scroggins68579392009-09-15 15:31:54 -04003517 mTitleBar.setLock(d);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003518 if (mFakeTitleBar != null) {
3519 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003520 }
3521 }
3522
3523 /**
3524 * Displays a page-info dialog.
3525 * @param tab The tab to show info about
3526 * @param fromShowSSLCertificateOnError The flag that indicates whether
3527 * this dialog was opened from the SSL-certificate-on-error dialog or
3528 * not. This is important, since we need to know whether to return to
3529 * the parent dialog or simply dismiss.
3530 */
3531 private void showPageInfo(final TabControl.Tab tab,
3532 final boolean fromShowSSLCertificateOnError) {
3533 final LayoutInflater factory = LayoutInflater
3534 .from(this);
3535
3536 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3537
3538 final WebView view = tab.getWebView();
3539
3540 String url = null;
3541 String title = null;
3542
3543 if (view == null) {
3544 url = tab.getUrl();
3545 title = tab.getTitle();
3546 } else if (view == mTabControl.getCurrentWebView()) {
3547 // Use the cached title and url if this is the current WebView
3548 url = mUrl;
3549 title = mTitle;
3550 } else {
3551 url = view.getUrl();
3552 title = view.getTitle();
3553 }
3554
3555 if (url == null) {
3556 url = "";
3557 }
3558 if (title == null) {
3559 title = "";
3560 }
3561
3562 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3563 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3564
3565 mPageInfoView = tab;
3566 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3567
3568 AlertDialog.Builder alertDialogBuilder =
3569 new AlertDialog.Builder(this)
3570 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3571 .setView(pageInfoView)
3572 .setPositiveButton(
3573 R.string.ok,
3574 new DialogInterface.OnClickListener() {
3575 public void onClick(DialogInterface dialog,
3576 int whichButton) {
3577 mPageInfoDialog = null;
3578 mPageInfoView = null;
3579 mPageInfoFromShowSSLCertificateOnError = null;
3580
3581 // if we came here from the SSL error dialog
3582 if (fromShowSSLCertificateOnError) {
3583 // go back to the SSL error dialog
3584 showSSLCertificateOnError(
3585 mSSLCertificateOnErrorView,
3586 mSSLCertificateOnErrorHandler,
3587 mSSLCertificateOnErrorError);
3588 }
3589 }
3590 })
3591 .setOnCancelListener(
3592 new DialogInterface.OnCancelListener() {
3593 public void onCancel(DialogInterface dialog) {
3594 mPageInfoDialog = null;
3595 mPageInfoView = null;
3596 mPageInfoFromShowSSLCertificateOnError = null;
3597
3598 // if we came here from the SSL error dialog
3599 if (fromShowSSLCertificateOnError) {
3600 // go back to the SSL error dialog
3601 showSSLCertificateOnError(
3602 mSSLCertificateOnErrorView,
3603 mSSLCertificateOnErrorHandler,
3604 mSSLCertificateOnErrorError);
3605 }
3606 }
3607 });
3608
3609 // if we have a main top-level page SSL certificate set or a certificate
3610 // error
3611 if (fromShowSSLCertificateOnError ||
3612 (view != null && view.getCertificate() != null)) {
3613 // add a 'View Certificate' button
3614 alertDialogBuilder.setNeutralButton(
3615 R.string.view_certificate,
3616 new DialogInterface.OnClickListener() {
3617 public void onClick(DialogInterface dialog,
3618 int whichButton) {
3619 mPageInfoDialog = null;
3620 mPageInfoView = null;
3621 mPageInfoFromShowSSLCertificateOnError = null;
3622
3623 // if we came here from the SSL error dialog
3624 if (fromShowSSLCertificateOnError) {
3625 // go back to the SSL error dialog
3626 showSSLCertificateOnError(
3627 mSSLCertificateOnErrorView,
3628 mSSLCertificateOnErrorHandler,
3629 mSSLCertificateOnErrorError);
3630 } else {
3631 // otherwise, display the top-most certificate from
3632 // the chain
3633 if (view.getCertificate() != null) {
3634 showSSLCertificate(tab);
3635 }
3636 }
3637 }
3638 });
3639 }
3640
3641 mPageInfoDialog = alertDialogBuilder.show();
3642 }
3643
3644 /**
3645 * Displays the main top-level page SSL certificate dialog
3646 * (accessible from the Page-Info dialog).
3647 * @param tab The tab to show certificate for.
3648 */
3649 private void showSSLCertificate(final TabControl.Tab tab) {
3650 final View certificateView =
3651 inflateCertificateView(tab.getWebView().getCertificate());
3652 if (certificateView == null) {
3653 return;
3654 }
3655
3656 LayoutInflater factory = LayoutInflater.from(this);
3657
3658 final LinearLayout placeholder =
3659 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3660
3661 LinearLayout ll = (LinearLayout) factory.inflate(
3662 R.layout.ssl_success, placeholder);
3663 ((TextView)ll.findViewById(R.id.success))
3664 .setText(R.string.ssl_certificate_is_valid);
3665
3666 mSSLCertificateView = tab;
3667 mSSLCertificateDialog =
3668 new AlertDialog.Builder(this)
3669 .setTitle(R.string.ssl_certificate).setIcon(
3670 R.drawable.ic_dialog_browser_certificate_secure)
3671 .setView(certificateView)
3672 .setPositiveButton(R.string.ok,
3673 new DialogInterface.OnClickListener() {
3674 public void onClick(DialogInterface dialog,
3675 int whichButton) {
3676 mSSLCertificateDialog = null;
3677 mSSLCertificateView = null;
3678
3679 showPageInfo(tab, false);
3680 }
3681 })
3682 .setOnCancelListener(
3683 new DialogInterface.OnCancelListener() {
3684 public void onCancel(DialogInterface dialog) {
3685 mSSLCertificateDialog = null;
3686 mSSLCertificateView = null;
3687
3688 showPageInfo(tab, false);
3689 }
3690 })
3691 .show();
3692 }
3693
3694 /**
3695 * Displays the SSL error certificate dialog.
3696 * @param view The target web-view.
3697 * @param handler The SSL error handler responsible for cancelling the
3698 * connection that resulted in an SSL error or proceeding per user request.
3699 * @param error The SSL error object.
3700 */
3701 private void showSSLCertificateOnError(
3702 final WebView view, final SslErrorHandler handler, final SslError error) {
3703
3704 final View certificateView =
3705 inflateCertificateView(error.getCertificate());
3706 if (certificateView == null) {
3707 return;
3708 }
3709
3710 LayoutInflater factory = LayoutInflater.from(this);
3711
3712 final LinearLayout placeholder =
3713 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3714
3715 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3716 LinearLayout ll = (LinearLayout)factory
3717 .inflate(R.layout.ssl_warning, placeholder);
3718 ((TextView)ll.findViewById(R.id.warning))
3719 .setText(R.string.ssl_untrusted);
3720 }
3721
3722 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3723 LinearLayout ll = (LinearLayout)factory
3724 .inflate(R.layout.ssl_warning, placeholder);
3725 ((TextView)ll.findViewById(R.id.warning))
3726 .setText(R.string.ssl_mismatch);
3727 }
3728
3729 if (error.hasError(SslError.SSL_EXPIRED)) {
3730 LinearLayout ll = (LinearLayout)factory
3731 .inflate(R.layout.ssl_warning, placeholder);
3732 ((TextView)ll.findViewById(R.id.warning))
3733 .setText(R.string.ssl_expired);
3734 }
3735
3736 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3737 LinearLayout ll = (LinearLayout)factory
3738 .inflate(R.layout.ssl_warning, placeholder);
3739 ((TextView)ll.findViewById(R.id.warning))
3740 .setText(R.string.ssl_not_yet_valid);
3741 }
3742
3743 mSSLCertificateOnErrorHandler = handler;
3744 mSSLCertificateOnErrorView = view;
3745 mSSLCertificateOnErrorError = error;
3746 mSSLCertificateOnErrorDialog =
3747 new AlertDialog.Builder(this)
3748 .setTitle(R.string.ssl_certificate).setIcon(
3749 R.drawable.ic_dialog_browser_certificate_partially_secure)
3750 .setView(certificateView)
3751 .setPositiveButton(R.string.ok,
3752 new DialogInterface.OnClickListener() {
3753 public void onClick(DialogInterface dialog,
3754 int whichButton) {
3755 mSSLCertificateOnErrorDialog = null;
3756 mSSLCertificateOnErrorView = null;
3757 mSSLCertificateOnErrorHandler = null;
3758 mSSLCertificateOnErrorError = null;
3759
3760 mWebViewClient.onReceivedSslError(
3761 view, handler, error);
3762 }
3763 })
3764 .setNeutralButton(R.string.page_info_view,
3765 new DialogInterface.OnClickListener() {
3766 public void onClick(DialogInterface dialog,
3767 int whichButton) {
3768 mSSLCertificateOnErrorDialog = null;
3769
3770 // do not clear the dialog state: we will
3771 // need to show the dialog again once the
3772 // user is done exploring the page-info details
3773
3774 showPageInfo(mTabControl.getTabFromView(view),
3775 true);
3776 }
3777 })
3778 .setOnCancelListener(
3779 new DialogInterface.OnCancelListener() {
3780 public void onCancel(DialogInterface dialog) {
3781 mSSLCertificateOnErrorDialog = null;
3782 mSSLCertificateOnErrorView = null;
3783 mSSLCertificateOnErrorHandler = null;
3784 mSSLCertificateOnErrorError = null;
3785
3786 mWebViewClient.onReceivedSslError(
3787 view, handler, error);
3788 }
3789 })
3790 .show();
3791 }
3792
3793 /**
3794 * Inflates the SSL certificate view (helper method).
3795 * @param certificate The SSL certificate.
3796 * @return The resultant certificate view with issued-to, issued-by,
3797 * issued-on, expires-on, and possibly other fields set.
3798 * If the input certificate is null, returns null.
3799 */
3800 private View inflateCertificateView(SslCertificate certificate) {
3801 if (certificate == null) {
3802 return null;
3803 }
3804
3805 LayoutInflater factory = LayoutInflater.from(this);
3806
3807 View certificateView = factory.inflate(
3808 R.layout.ssl_certificate, null);
3809
3810 // issued to:
3811 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3812 if (issuedTo != null) {
3813 ((TextView) certificateView.findViewById(R.id.to_common))
3814 .setText(issuedTo.getCName());
3815 ((TextView) certificateView.findViewById(R.id.to_org))
3816 .setText(issuedTo.getOName());
3817 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3818 .setText(issuedTo.getUName());
3819 }
3820
3821 // issued by:
3822 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3823 if (issuedBy != null) {
3824 ((TextView) certificateView.findViewById(R.id.by_common))
3825 .setText(issuedBy.getCName());
3826 ((TextView) certificateView.findViewById(R.id.by_org))
3827 .setText(issuedBy.getOName());
3828 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3829 .setText(issuedBy.getUName());
3830 }
3831
3832 // issued on:
3833 String issuedOn = reformatCertificateDate(
3834 certificate.getValidNotBefore());
3835 ((TextView) certificateView.findViewById(R.id.issued_on))
3836 .setText(issuedOn);
3837
3838 // expires on:
3839 String expiresOn = reformatCertificateDate(
3840 certificate.getValidNotAfter());
3841 ((TextView) certificateView.findViewById(R.id.expires_on))
3842 .setText(expiresOn);
3843
3844 return certificateView;
3845 }
3846
3847 /**
3848 * Re-formats the certificate date (Date.toString()) string to
3849 * a properly localized date string.
3850 * @return Properly localized version of the certificate date string and
3851 * the original certificate date string if fails to localize.
3852 * If the original string is null, returns an empty string "".
3853 */
3854 private String reformatCertificateDate(String certificateDate) {
3855 String reformattedDate = null;
3856
3857 if (certificateDate != null) {
3858 Date date = null;
3859 try {
3860 date = java.text.DateFormat.getInstance().parse(certificateDate);
3861 } catch (ParseException e) {
3862 date = null;
3863 }
3864
3865 if (date != null) {
3866 reformattedDate =
3867 DateFormat.getDateFormat(this).format(date);
3868 }
3869 }
3870
3871 return reformattedDate != null ? reformattedDate :
3872 (certificateDate != null ? certificateDate : "");
3873 }
3874
3875 /**
3876 * Displays an http-authentication dialog.
3877 */
3878 private void showHttpAuthentication(final HttpAuthHandler handler,
3879 final String host, final String realm, final String title,
3880 final String name, final String password, int focusId) {
3881 LayoutInflater factory = LayoutInflater.from(this);
3882 final View v = factory
3883 .inflate(R.layout.http_authentication, null);
3884 if (name != null) {
3885 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3886 }
3887 if (password != null) {
3888 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3889 }
3890
3891 String titleText = title;
3892 if (titleText == null) {
3893 titleText = getText(R.string.sign_in_to).toString().replace(
3894 "%s1", host).replace("%s2", realm);
3895 }
3896
3897 mHttpAuthHandler = handler;
3898 AlertDialog dialog = new AlertDialog.Builder(this)
3899 .setTitle(titleText)
3900 .setIcon(android.R.drawable.ic_dialog_alert)
3901 .setView(v)
3902 .setPositiveButton(R.string.action,
3903 new DialogInterface.OnClickListener() {
3904 public void onClick(DialogInterface dialog,
3905 int whichButton) {
3906 String nm = ((EditText) v
3907 .findViewById(R.id.username_edit))
3908 .getText().toString();
3909 String pw = ((EditText) v
3910 .findViewById(R.id.password_edit))
3911 .getText().toString();
3912 BrowserActivity.this.setHttpAuthUsernamePassword
3913 (host, realm, nm, pw);
3914 handler.proceed(nm, pw);
3915 mHttpAuthenticationDialog = null;
3916 mHttpAuthHandler = null;
3917 }})
3918 .setNegativeButton(R.string.cancel,
3919 new DialogInterface.OnClickListener() {
3920 public void onClick(DialogInterface dialog,
3921 int whichButton) {
3922 handler.cancel();
3923 BrowserActivity.this.resetTitleAndRevertLockIcon();
3924 mHttpAuthenticationDialog = null;
3925 mHttpAuthHandler = null;
3926 }})
3927 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3928 public void onCancel(DialogInterface dialog) {
3929 handler.cancel();
3930 BrowserActivity.this.resetTitleAndRevertLockIcon();
3931 mHttpAuthenticationDialog = null;
3932 mHttpAuthHandler = null;
3933 }})
3934 .create();
3935 // Make the IME appear when the dialog is displayed if applicable.
3936 dialog.getWindow().setSoftInputMode(
3937 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3938 dialog.show();
3939 if (focusId != 0) {
3940 dialog.findViewById(focusId).requestFocus();
3941 } else {
3942 v.findViewById(R.id.username_edit).requestFocus();
3943 }
3944 mHttpAuthenticationDialog = dialog;
3945 }
3946
3947 public int getProgress() {
3948 WebView w = mTabControl.getCurrentWebView();
3949 if (w != null) {
3950 return w.getProgress();
3951 } else {
3952 return 100;
3953 }
3954 }
3955
3956 /**
3957 * Set HTTP authentication password.
3958 *
3959 * @param host The host for the password
3960 * @param realm The realm for the password
3961 * @param username The username for the password. If it is null, it means
3962 * password can't be saved.
3963 * @param password The password
3964 */
3965 public void setHttpAuthUsernamePassword(String host, String realm,
3966 String username,
3967 String password) {
3968 WebView w = mTabControl.getCurrentWebView();
3969 if (w != null) {
3970 w.setHttpAuthUsernamePassword(host, realm, username, password);
3971 }
3972 }
3973
3974 /**
3975 * connectivity manager says net has come or gone... inform the user
3976 * @param up true if net has come up, false if net has gone down
3977 */
3978 public void onNetworkToggle(boolean up) {
3979 if (up == mIsNetworkUp) {
3980 return;
3981 } else if (up) {
3982 mIsNetworkUp = true;
3983 if (mAlertDialog != null) {
3984 mAlertDialog.cancel();
3985 mAlertDialog = null;
3986 }
3987 } else {
3988 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003989 if (mInLoad) {
3990 createAndShowNetworkDialog();
3991 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003992 }
3993 WebView w = mTabControl.getCurrentWebView();
3994 if (w != null) {
3995 w.setNetworkAvailable(up);
3996 }
3997 }
3998
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003999 // This method shows the network dialog alerting the user that the net is
4000 // down. It will only show the dialog if mAlertDialog is null.
4001 private void createAndShowNetworkDialog() {
4002 if (mAlertDialog == null) {
4003 mAlertDialog = new AlertDialog.Builder(this)
4004 .setTitle(R.string.loadSuspendedTitle)
4005 .setMessage(R.string.loadSuspended)
4006 .setPositiveButton(R.string.ok, null)
4007 .show();
4008 }
4009 }
4010
The Android Open Source Project0c908882009-03-03 19:32:16 -08004011 @Override
4012 protected void onActivityResult(int requestCode, int resultCode,
4013 Intent intent) {
4014 switch (requestCode) {
4015 case COMBO_PAGE:
4016 if (resultCode == RESULT_OK && intent != null) {
4017 String data = intent.getAction();
4018 Bundle extras = intent.getExtras();
4019 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04004020 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004021 } else {
4022 final TabControl.Tab currentTab =
4023 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04004024 dismissSubWindow(currentTab);
4025 if (data != null && data.length() != 0) {
4026 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004027 }
4028 }
4029 }
4030 break;
4031 default:
4032 break;
4033 }
Leon Scroggins30444232009-09-04 18:36:20 -04004034 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004035 }
4036
4037 /*
4038 * This method is called as a result of the user selecting the options
4039 * menu to see the download window, or when a download changes state. It
4040 * shows the download window ontop of the current window.
4041 */
4042 /* package */ void viewDownloads(Uri downloadRecord) {
4043 Intent intent = new Intent(this,
4044 BrowserDownloadPage.class);
4045 intent.setData(downloadRecord);
4046 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4047
4048 }
4049
Leon Scroggins160a7e72009-08-14 18:28:01 -04004050 /**
4051 * Open the Go page.
4052 * @param startWithHistory If true, open starting on the history tab.
4053 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004054 */
Leon Scroggins30444232009-09-04 18:36:20 -04004055 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004056 WebView current = mTabControl.getCurrentWebView();
4057 if (current == null) {
4058 return;
4059 }
4060 Intent intent = new Intent(this,
4061 CombinedBookmarkHistoryActivity.class);
4062 String title = current.getTitle();
4063 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004064 Bitmap thumbnail = createScreenshot(current);
4065
The Android Open Source Project0c908882009-03-03 19:32:16 -08004066 // Just in case the user opens bookmarks before a page finishes loading
4067 // so the current history item, and therefore the page, is null.
4068 if (null == url) {
4069 url = mLastEnteredUrl;
4070 // This can happen.
4071 if (null == url) {
4072 url = mSettings.getHomePage();
4073 }
4074 }
4075 // In case the web page has not yet received its associated title.
4076 if (title == null) {
4077 title = url;
4078 }
4079 intent.putExtra("title", title);
4080 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004081 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04004082 // Disable opening in a new window if we have maxed out the windows
4083 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4084 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004085 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004086 if (startWithHistory) {
4087 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4088 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4089 }
4090 startActivityForResult(intent, COMBO_PAGE);
4091 }
4092
4093 // Called when loading from context menu or LOAD_URL message
4094 private void loadURL(WebView view, String url) {
4095 // In case the user enters nothing.
4096 if (url != null && url.length() != 0 && view != null) {
4097 url = smartUrlFilter(url);
4098 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4099 view.loadUrl(url);
4100 }
4101 }
4102 }
4103
The Android Open Source Project0c908882009-03-03 19:32:16 -08004104 private String smartUrlFilter(Uri inUri) {
4105 if (inUri != null) {
4106 return smartUrlFilter(inUri.toString());
4107 }
4108 return null;
4109 }
4110
4111
4112 // get window count
4113
4114 int getWindowCount(){
4115 if(mTabControl != null){
4116 return mTabControl.getTabCount();
4117 }
4118 return 0;
4119 }
4120
Feng Qianb34f87a2009-03-24 21:27:26 -07004121 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004122 "(?i)" + // switch on case insensitive matching
4123 "(" + // begin group for schema
4124 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004125 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004126 ")" +
4127 "(.*)" );
4128
4129 /**
4130 * Attempts to determine whether user input is a URL or search
4131 * terms. Anything with a space is passed to search.
4132 *
4133 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4134 * "Http://" converts to "http://"
4135 *
4136 * @return Original or modified URL
4137 *
4138 */
4139 String smartUrlFilter(String url) {
4140
4141 String inUrl = url.trim();
4142 boolean hasSpace = inUrl.indexOf(' ') != -1;
4143
4144 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4145 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004146 // force scheme to lowercase
4147 String scheme = matcher.group(1);
4148 String lcScheme = scheme.toLowerCase();
4149 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004150 inUrl = lcScheme + matcher.group(2);
4151 }
4152 if (hasSpace) {
4153 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004154 }
4155 return inUrl;
4156 }
4157 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004158 // FIXME: Is this the correct place to add to searches?
4159 // what if someone else calls this function?
4160 int shortcut = parseUrlShortcut(inUrl);
4161 if (shortcut != SHORTCUT_INVALID) {
4162 Browser.addSearchUrl(mResolver, inUrl);
4163 String query = inUrl.substring(2);
4164 switch (shortcut) {
4165 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004166 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004167 case SHORTCUT_WIKIPEDIA_SEARCH:
4168 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4169 case SHORTCUT_DICTIONARY_SEARCH:
4170 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4171 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004172 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004173 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004174 }
4175 }
4176 } else {
4177 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4178 return URLUtil.guessUrl(inUrl);
4179 }
4180 }
4181
4182 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004183 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004184 }
4185
Ben Murdochbff2d602009-07-01 20:19:05 +01004186 /* package */ void setShouldShowErrorConsole(boolean flag) {
4187 if (flag == mShouldShowErrorConsole) {
4188 // Nothing to do.
4189 return;
4190 }
4191
4192 mShouldShowErrorConsole = flag;
4193
4194 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4195
4196 if (flag) {
4197 // Setting the show state of the console will cause it's the layout to be inflated.
4198 if (errorConsole.numberOfErrors() > 0) {
4199 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4200 } else {
4201 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4202 }
4203
4204 // Now we can add it to the main view.
4205 mErrorConsoleContainer.addView(errorConsole,
4206 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4207 ViewGroup.LayoutParams.WRAP_CONTENT));
4208 } else {
4209 mErrorConsoleContainer.removeView(errorConsole);
4210 }
4211
4212 }
4213
Grace Klobaeb6eef42009-09-15 17:56:32 -07004214 final static int LOCK_ICON_UNSECURE = 0;
4215 final static int LOCK_ICON_SECURE = 1;
4216 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004217
4218 private int mLockIconType = LOCK_ICON_UNSECURE;
4219 private int mPrevLockType = LOCK_ICON_UNSECURE;
4220
4221 private BrowserSettings mSettings;
4222 private TabControl mTabControl;
4223 private ContentResolver mResolver;
4224 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004225 private View mCustomView;
4226 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004227 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004228
4229 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4230 // view, we should rewrite this.
4231 private int mCurrentMenuState = 0;
4232 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004233 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004234 private static final int EMPTY_MENU = -1;
4235 private Menu mMenu;
4236
4237 private FindDialog mFindDialog;
4238 // Used to prevent chording to result in firing two shortcuts immediately
4239 // one after another. Fixes bug 1211714.
4240 boolean mCanChord;
4241
4242 private boolean mInLoad;
4243 private boolean mIsNetworkUp;
4244
4245 private boolean mPageStarted;
4246 private boolean mActivityInPause = true;
4247
4248 private boolean mMenuIsDown;
4249
The Android Open Source Project0c908882009-03-03 19:32:16 -08004250 private static boolean mInTrace;
4251
4252 // Performance probe
4253 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4254 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4255 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4256 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4257 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4258 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4259 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4260 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4261 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4262 };
4263
4264 private long mStart;
4265 private long mProcessStart;
4266 private long mUserStart;
4267 private long mSystemStart;
4268 private long mIdleStart;
4269 private long mIrqStart;
4270
4271 private long mUiStart;
4272
4273 private Drawable mMixLockIcon;
4274 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004275
4276 /* hold a ref so we can auto-cancel if necessary */
4277 private AlertDialog mAlertDialog;
4278
4279 // Wait for credentials before loading google.com
4280 private ProgressDialog mCredsDlg;
4281
4282 // The up-to-date URL and title (these can be different from those stored
4283 // in WebView, since it takes some time for the information in WebView to
4284 // get updated)
4285 private String mUrl;
4286 private String mTitle;
4287
4288 // As PageInfo has different style for landscape / portrait, we have
4289 // to re-open it when configuration changed
4290 private AlertDialog mPageInfoDialog;
4291 private TabControl.Tab mPageInfoView;
4292 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4293 // dialog, we should not just dismiss it, but should get back to the
4294 // SSL-certificate-on-error dialog. This flag is used to store this state
4295 private Boolean mPageInfoFromShowSSLCertificateOnError;
4296
4297 // as SSLCertificateOnError has different style for landscape / portrait,
4298 // we have to re-open it when configuration changed
4299 private AlertDialog mSSLCertificateOnErrorDialog;
4300 private WebView mSSLCertificateOnErrorView;
4301 private SslErrorHandler mSSLCertificateOnErrorHandler;
4302 private SslError mSSLCertificateOnErrorError;
4303
4304 // as SSLCertificate has different style for landscape / portrait, we
4305 // have to re-open it when configuration changed
4306 private AlertDialog mSSLCertificateDialog;
4307 private TabControl.Tab mSSLCertificateView;
4308
4309 // as HttpAuthentication has different style for landscape / portrait, we
4310 // have to re-open it when configuration changed
4311 private AlertDialog mHttpAuthenticationDialog;
4312 private HttpAuthHandler mHttpAuthHandler;
4313
4314 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4315 new FrameLayout.LayoutParams(
4316 ViewGroup.LayoutParams.FILL_PARENT,
4317 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004318 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4319 new FrameLayout.LayoutParams(
4320 ViewGroup.LayoutParams.FILL_PARENT,
4321 ViewGroup.LayoutParams.FILL_PARENT,
4322 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004323 // Google search
4324 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004325 // Wikipedia search
4326 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4327 // Dictionary search
4328 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4329 // Google Mobile Local search
4330 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4331
4332 final static String QUERY_PLACE_HOLDER = "%s";
4333
4334 // "source" parameter for Google search through search key
4335 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4336 // "source" parameter for Google search through goto menu
4337 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4338 // "source" parameter for Google search through simplily type
4339 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4340 // "source" parameter for Google search suggested by the browser
4341 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4342 // "source" parameter for Google search from unknown source
4343 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4344
4345 private final static String LOGTAG = "browser";
4346
The Android Open Source Project0c908882009-03-03 19:32:16 -08004347 private String mLastEnteredUrl;
4348
4349 private PowerManager.WakeLock mWakeLock;
4350 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4351
4352 private Toast mStopToast;
4353
Leon Scroggins68579392009-09-15 15:31:54 -04004354 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004355
Ben Murdochbff2d602009-07-01 20:19:05 +01004356 private LinearLayout mErrorConsoleContainer = null;
4357 private boolean mShouldShowErrorConsole = false;
4358
The Android Open Source Project0c908882009-03-03 19:32:16 -08004359 // As the ids are dynamically created, we can't guarantee that they will
4360 // be in sequence, so this static array maps ids to a window number.
4361 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4362 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4363 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4364 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4365
4366 // monitor platform changes
4367 private IntentFilter mNetworkStateChangedFilter;
4368 private BroadcastReceiver mNetworkStateIntentReceiver;
4369
Grace Klobab4da0ad2009-05-14 14:45:40 -07004370 private BroadcastReceiver mPackageInstallationReceiver;
4371
The Android Open Source Project0c908882009-03-03 19:32:16 -08004372 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004373 final static int COMBO_PAGE = 1;
4374 final static int DOWNLOAD_PAGE = 2;
4375 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004376
Andrei Popescu540035d2009-09-18 18:59:20 +01004377 // the default <video> poster
4378 private Bitmap mDefaultVideoPoster;
4379 // the video progress view
4380 private View mVideoProgressView;
4381
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004382 /**
4383 * A UrlData class to abstract how the content will be set to WebView.
4384 * This base class uses loadUrl to show the content.
4385 */
4386 private static class UrlData {
4387 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004388 byte[] mPostData;
4389
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004390 UrlData(String url) {
4391 this.mUrl = url;
4392 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004393
4394 void setPostData(byte[] postData) {
4395 mPostData = postData;
4396 }
4397
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004398 boolean isEmpty() {
4399 return mUrl == null || mUrl.length() == 0;
4400 }
4401
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004402 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004403 if (mPostData != null) {
4404 webView.postUrl(mUrl, mPostData);
4405 } else {
4406 webView.loadUrl(mUrl);
4407 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004408 }
4409 };
4410
4411 /**
4412 * A subclass of UrlData class that can display inlined content using
4413 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4414 */
4415 private static class InlinedUrlData extends UrlData {
4416 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4417 super(failUrl);
4418 mInlined = inlined;
4419 mMimeType = mimeType;
4420 mEncoding = encoding;
4421 }
4422 String mMimeType;
4423 String mInlined;
4424 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004425 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004426 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004427 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004428 }
4429
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004430 @Override
4431 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004432 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4433 }
4434 }
4435
Leon Scroggins1f005d32009-08-10 17:36:42 -04004436 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004437}