blob: 42bc1ab5c3eb767658622cd39b809ec3364ddd75 [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;
48import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.DrawFilter;
50import android.graphics.Paint;
51import android.graphics.PaintFlagsDrawFilter;
52import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040053import android.graphics.PixelFormat;
54import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080055import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080056import android.hardware.SensorListener;
57import android.hardware.SensorManager;
58import android.net.ConnectivityManager;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -040059import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080060import android.net.Uri;
61import android.net.WebAddress;
62import android.net.http.EventHandler;
63import android.net.http.SslCertificate;
64import android.net.http.SslError;
65import android.os.AsyncTask;
66import android.os.Bundle;
67import android.os.Debug;
68import android.os.Environment;
69import android.os.Handler;
70import android.os.IBinder;
71import android.os.Message;
72import android.os.PowerManager;
73import android.os.Process;
74import android.os.RemoteException;
75import android.os.ServiceManager;
76import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080077import android.provider.Browser;
78import android.provider.Contacts;
79import android.provider.Downloads;
80import android.provider.MediaStore;
81import android.provider.Contacts.Intents.Insert;
82import android.text.IClipboard;
83import android.text.TextUtils;
84import android.text.format.DateFormat;
85import android.text.util.Regex;
The Android Open Source Project0c908882009-03-03 19:32:16 -080086import android.util.Log;
87import android.view.ContextMenu;
88import android.view.Gravity;
89import android.view.KeyEvent;
90import android.view.LayoutInflater;
91import android.view.Menu;
92import android.view.MenuInflater;
93import android.view.MenuItem;
94import android.view.View;
95import android.view.ViewGroup;
96import android.view.Window;
97import android.view.WindowManager;
98import android.view.ContextMenu.ContextMenuInfo;
99import android.view.MenuItem.OnMenuItemClickListener;
100import android.view.animation.AlphaAnimation;
101import android.view.animation.Animation;
102import android.view.animation.AnimationSet;
103import android.view.animation.DecelerateInterpolator;
104import android.view.animation.ScaleAnimation;
105import android.view.animation.TranslateAnimation;
106import android.webkit.CookieManager;
107import android.webkit.CookieSyncManager;
108import android.webkit.DownloadListener;
Steve Block2bc69912009-07-30 14:45:13 +0100109import android.webkit.GeolocationPermissions;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800110import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -0700111import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800112import android.webkit.SslErrorHandler;
113import android.webkit.URLUtil;
114import android.webkit.WebChromeClient;
Andrei Popescuc9b55562009-07-07 10:51:15 +0100115import android.webkit.WebChromeClient.CustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800116import android.webkit.WebHistoryItem;
117import android.webkit.WebIconDatabase;
Ben Murdoch092dd5d2009-04-22 12:34:12 +0100118import android.webkit.WebStorage;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800119import android.webkit.WebView;
120import android.webkit.WebViewClient;
121import android.widget.EditText;
122import android.widget.FrameLayout;
123import android.widget.LinearLayout;
124import android.widget.TextView;
125import android.widget.Toast;
126
127import java.io.BufferedOutputStream;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400128import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800129import java.io.File;
130import java.io.FileInputStream;
131import java.io.FileOutputStream;
132import java.io.IOException;
133import java.io.InputStream;
134import java.net.MalformedURLException;
135import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700136import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800137import java.net.URL;
138import java.net.URLEncoder;
139import java.text.ParseException;
140import java.util.Date;
141import java.util.Enumeration;
142import java.util.HashMap;
Patrick Scott37911c72009-03-24 18:02:58 -0700143import java.util.LinkedList;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800144import java.util.Vector;
145import java.util.regex.Matcher;
146import java.util.regex.Pattern;
147import java.util.zip.ZipEntry;
148import java.util.zip.ZipFile;
149
150public class BrowserActivity extends Activity
151 implements KeyTracker.OnKeyTracker,
152 View.OnCreateContextMenuListener,
153 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());
Leon Scroggins1f005d32009-08-10 17:36:42 -04001469 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001470 break;
1471
1472 case R.id.stop_reload_menu_id:
1473 if (mInLoad) {
1474 stopLoading();
1475 } else {
1476 getTopWindow().reload();
1477 }
1478 break;
1479
1480 case R.id.back_menu_id:
1481 getTopWindow().goBack();
1482 break;
1483
1484 case R.id.forward_menu_id:
1485 getTopWindow().goForward();
1486 break;
1487
1488 case R.id.close_menu_id:
1489 // Close the subwindow if it exists.
1490 if (mTabControl.getCurrentSubWindow() != null) {
1491 dismissSubWindow(mTabControl.getCurrentTab());
1492 break;
1493 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001494 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001495 break;
1496
1497 case R.id.homepage_menu_id:
1498 TabControl.Tab current = mTabControl.getCurrentTab();
1499 if (current != null) {
1500 dismissSubWindow(current);
1501 current.getWebView().loadUrl(mSettings.getHomePage());
1502 }
1503 break;
1504
1505 case R.id.preferences_menu_id:
1506 Intent intent = new Intent(this,
1507 BrowserPreferencesPage.class);
1508 startActivityForResult(intent, PREFERENCES_PAGE);
1509 break;
1510
1511 case R.id.find_menu_id:
1512 if (null == mFindDialog) {
1513 mFindDialog = new FindDialog(this);
1514 }
1515 mFindDialog.setWebView(getTopWindow());
1516 mFindDialog.show();
1517 mMenuState = EMPTY_MENU;
1518 break;
1519
1520 case R.id.select_text_id:
1521 getTopWindow().emulateShiftHeld();
1522 break;
1523 case R.id.page_info_menu_id:
1524 showPageInfo(mTabControl.getCurrentTab(), false);
1525 break;
1526
1527 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001528 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001529 break;
1530
1531 case R.id.share_page_menu_id:
1532 Browser.sendString(this, getTopWindow().getUrl());
1533 break;
1534
1535 case R.id.dump_nav_menu_id:
1536 getTopWindow().debugDump();
1537 break;
1538
1539 case R.id.zoom_in_menu_id:
1540 getTopWindow().zoomIn();
1541 break;
1542
1543 case R.id.zoom_out_menu_id:
1544 getTopWindow().zoomOut();
1545 break;
1546
1547 case R.id.view_downloads_menu_id:
1548 viewDownloads(null);
1549 break;
1550
The Android Open Source Project0c908882009-03-03 19:32:16 -08001551 case R.id.window_one_menu_id:
1552 case R.id.window_two_menu_id:
1553 case R.id.window_three_menu_id:
1554 case R.id.window_four_menu_id:
1555 case R.id.window_five_menu_id:
1556 case R.id.window_six_menu_id:
1557 case R.id.window_seven_menu_id:
1558 case R.id.window_eight_menu_id:
1559 {
1560 int menuid = item.getItemId();
1561 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1562 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1563 TabControl.Tab desiredTab = mTabControl.getTab(id);
1564 if (desiredTab != null &&
1565 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001566 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001567 }
1568 break;
1569 }
1570 }
1571 }
1572 break;
1573
1574 default:
1575 if (!super.onOptionsItemSelected(item)) {
1576 return false;
1577 }
1578 // Otherwise fall through.
1579 }
1580 mCanChord = false;
1581 return true;
1582 }
1583
1584 public void closeFind() {
1585 mMenuState = R.id.MAIN_MENU;
1586 }
1587
1588 @Override public boolean onPrepareOptionsMenu(Menu menu)
1589 {
1590 // This happens when the user begins to hold down the menu key, so
1591 // allow them to chord to get a shortcut.
1592 mCanChord = true;
1593 // Note: setVisible will decide whether an item is visible; while
1594 // setEnabled() will decide whether an item is enabled, which also means
1595 // whether the matching shortcut key will function.
1596 super.onPrepareOptionsMenu(menu);
1597 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001598 case EMPTY_MENU:
1599 if (mCurrentMenuState != mMenuState) {
1600 menu.setGroupVisible(R.id.MAIN_MENU, false);
1601 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1602 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001603 }
1604 break;
1605 default:
1606 if (mCurrentMenuState != mMenuState) {
1607 menu.setGroupVisible(R.id.MAIN_MENU, true);
1608 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1609 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001610 }
1611 final WebView w = getTopWindow();
1612 boolean canGoBack = false;
1613 boolean canGoForward = false;
1614 boolean isHome = false;
1615 if (w != null) {
1616 canGoBack = w.canGoBack();
1617 canGoForward = w.canGoForward();
1618 isHome = mSettings.getHomePage().equals(w.getUrl());
1619 }
1620 final MenuItem back = menu.findItem(R.id.back_menu_id);
1621 back.setEnabled(canGoBack);
1622
1623 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1624 home.setEnabled(!isHome);
1625
1626 menu.findItem(R.id.forward_menu_id)
1627 .setEnabled(canGoForward);
1628
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001629 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1630 mTabControl.getTabCount() < TabControl.MAX_TABS);
1631
The Android Open Source Project0c908882009-03-03 19:32:16 -08001632 // decide whether to show the share link option
1633 PackageManager pm = getPackageManager();
1634 Intent send = new Intent(Intent.ACTION_SEND);
1635 send.setType("text/plain");
1636 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1637 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1638
The Android Open Source Project0c908882009-03-03 19:32:16 -08001639 boolean isNavDump = mSettings.isNavDump();
1640 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1641 nav.setVisible(isNavDump);
1642 nav.setEnabled(isNavDump);
1643 break;
1644 }
1645 mCurrentMenuState = mMenuState;
1646 return true;
1647 }
1648
1649 @Override
1650 public void onCreateContextMenu(ContextMenu menu, View v,
1651 ContextMenuInfo menuInfo) {
1652 WebView webview = (WebView) v;
1653 WebView.HitTestResult result = webview.getHitTestResult();
1654 if (result == null) {
1655 return;
1656 }
1657
1658 int type = result.getType();
1659 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1660 Log.w(LOGTAG,
1661 "We should not show context menu when nothing is touched");
1662 return;
1663 }
1664 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1665 // let TextView handles context menu
1666 return;
1667 }
1668
1669 // Note, http://b/issue?id=1106666 is requesting that
1670 // an inflated menu can be used again. This is not available
1671 // yet, so inflate each time (yuk!)
1672 MenuInflater inflater = getMenuInflater();
1673 inflater.inflate(R.menu.browsercontext, menu);
1674
1675 // Show the correct menu group
1676 String extra = result.getExtra();
1677 menu.setGroupVisible(R.id.PHONE_MENU,
1678 type == WebView.HitTestResult.PHONE_TYPE);
1679 menu.setGroupVisible(R.id.EMAIL_MENU,
1680 type == WebView.HitTestResult.EMAIL_TYPE);
1681 menu.setGroupVisible(R.id.GEO_MENU,
1682 type == WebView.HitTestResult.GEO_TYPE);
1683 menu.setGroupVisible(R.id.IMAGE_MENU,
1684 type == WebView.HitTestResult.IMAGE_TYPE
1685 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1686 menu.setGroupVisible(R.id.ANCHOR_MENU,
1687 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1688 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1689
1690 // Setup custom handling depending on the type
1691 switch (type) {
1692 case WebView.HitTestResult.PHONE_TYPE:
1693 menu.setHeaderTitle(Uri.decode(extra));
1694 menu.findItem(R.id.dial_context_menu_id).setIntent(
1695 new Intent(Intent.ACTION_VIEW, Uri
1696 .parse(WebView.SCHEME_TEL + extra)));
1697 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1698 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1699 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1700 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1701 addIntent);
1702 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1703 new Copy(extra));
1704 break;
1705
1706 case WebView.HitTestResult.EMAIL_TYPE:
1707 menu.setHeaderTitle(extra);
1708 menu.findItem(R.id.email_context_menu_id).setIntent(
1709 new Intent(Intent.ACTION_VIEW, Uri
1710 .parse(WebView.SCHEME_MAILTO + extra)));
1711 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1712 new Copy(extra));
1713 break;
1714
1715 case WebView.HitTestResult.GEO_TYPE:
1716 menu.setHeaderTitle(extra);
1717 menu.findItem(R.id.map_context_menu_id).setIntent(
1718 new Intent(Intent.ACTION_VIEW, Uri
1719 .parse(WebView.SCHEME_GEO
1720 + URLEncoder.encode(extra))));
1721 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1722 new Copy(extra));
1723 break;
1724
1725 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1726 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1727 TextView titleView = (TextView) LayoutInflater.from(this)
1728 .inflate(android.R.layout.browser_link_context_header,
1729 null);
1730 titleView.setText(extra);
1731 menu.setHeaderView(titleView);
1732 // decide whether to show the open link in new tab option
1733 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1734 mTabControl.getTabCount() < TabControl.MAX_TABS);
1735 PackageManager pm = getPackageManager();
1736 Intent send = new Intent(Intent.ACTION_SEND);
1737 send.setType("text/plain");
1738 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1739 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1740 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1741 break;
1742 }
1743 // otherwise fall through to handle image part
1744 case WebView.HitTestResult.IMAGE_TYPE:
1745 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1746 menu.setHeaderTitle(extra);
1747 }
1748 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1749 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1750 menu.findItem(R.id.download_context_menu_id).
1751 setOnMenuItemClickListener(new Download(extra));
1752 break;
1753
1754 default:
1755 Log.w(LOGTAG, "We should not get here.");
1756 break;
1757 }
1758 }
1759
The Android Open Source Project0c908882009-03-03 19:32:16 -08001760 // Attach the given tab to the content view.
1761 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001762 // Attach the container that contains the main WebView and any other UI
1763 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001764 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001765
1766 if (mShouldShowErrorConsole) {
1767 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1768 if (errorConsole.numberOfErrors() == 0) {
1769 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1770 } else {
1771 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1772 }
1773
1774 mErrorConsoleContainer.addView(errorConsole,
1775 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1776 ViewGroup.LayoutParams.WRAP_CONTENT));
1777 }
1778
Grace Klobaeb6eef42009-09-15 17:56:32 -07001779 if (t == mTabControl.getCurrentTab()) {
1780 setLockIconType(t.getLockIconType());
1781 setPrevLockType(t.getPrevLockIconType());
1782 }
1783
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001784 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001785 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001786 // Request focus on the top window.
1787 t.getTopWindow().requestFocus();
1788 }
1789
1790 // Attach a sub window to the main WebView of the given tab.
1791 private void attachSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001792 t.attachSubWindow(mContentView);
1793 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001794 }
1795
1796 // Remove the given tab from the content view.
1797 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001798 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001799 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001800
1801 if (mTabControl.getCurrentErrorConsole(false) != null) {
1802 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1803 }
1804
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001805 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001806 if (view != null) {
1807 view.setEmbeddedTitleBar(null);
1808 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001809
Grace Klobaeb6eef42009-09-15 17:56:32 -07001810 if (t == mTabControl.getCurrentTab()) {
1811 t.setLockIconType(getLockIconType());
1812 t.setPrevLockIconType(getPrevLockType());
1813 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001814 }
1815
1816 // Remove the sub window if it exists. Also called by TabControl when the
1817 // user clicks the 'X' to dismiss a sub window.
1818 /* package */ void dismissSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001819 t.removeSubWindow(mContentView);
1820 // Tell the TabControl to dismiss the subwindow. This will destroy
1821 // the WebView.
1822 mTabControl.dismissSubWindow(t);
1823 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001824 }
1825
Leon Scroggins1f005d32009-08-10 17:36:42 -04001826 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001827 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001828 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1829 String appId) {
1830 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001831 }
1832
1833 // This method does a ton of stuff. It will attempt to create a new tab
1834 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001835 // url isn't null, it will load the given url.
1836 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001837 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001838 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1839 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1840 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001841 final TabControl.Tab tab = mTabControl.createNewTab(
1842 closeOnExit, appId, urlData.mUrl);
1843 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001844 // If the last tab was removed from the active tabs page, currentTab
1845 // will be null.
1846 if (currentTab != null) {
1847 removeTabFromContentView(currentTab);
1848 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001849 // We must set the new tab as the current tab to reflect the old
1850 // animation behavior.
1851 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001852 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001853 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001854 urlData.loadIn(webview);
1855 }
1856 return tab;
1857 } else {
1858 // Get rid of the subwindow if it exists
1859 dismissSubWindow(currentTab);
1860 if (!urlData.isEmpty()) {
1861 // Load the given url.
1862 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001863 }
1864 }
Grace Klobac9181842009-04-14 08:53:22 -07001865 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001866 }
1867
Grace Klobac9181842009-04-14 08:53:22 -07001868 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001869 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001870 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001871 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001872 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001873 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001874 }
Grace Klobac9181842009-04-14 08:53:22 -07001875 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001876 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001877 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001878 }
1879 }
1880
1881 private class Copy implements OnMenuItemClickListener {
1882 private CharSequence mText;
1883
1884 public boolean onMenuItemClick(MenuItem item) {
1885 copy(mText);
1886 return true;
1887 }
1888
1889 public Copy(CharSequence toCopy) {
1890 mText = toCopy;
1891 }
1892 }
1893
1894 private class Download implements OnMenuItemClickListener {
1895 private String mText;
1896
1897 public boolean onMenuItemClick(MenuItem item) {
1898 onDownloadStartNoStream(mText, null, null, null, -1);
1899 return true;
1900 }
1901
1902 public Download(String toDownload) {
1903 mText = toDownload;
1904 }
1905 }
1906
1907 private void copy(CharSequence text) {
1908 try {
1909 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1910 if (clip != null) {
1911 clip.setClipboardText(text);
1912 }
1913 } catch (android.os.RemoteException e) {
1914 Log.e(LOGTAG, "Copy failed", e);
1915 }
1916 }
1917
1918 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001919 * Resets the browser title-view to whatever it must be
1920 * (for example, if we had a loading error)
1921 * When we have a new page, we call resetTitle, when we
1922 * have to reset the titlebar to whatever it used to be
1923 * (for example, if the user chose to stop loading), we
1924 * call resetTitleAndRevertLockIcon.
1925 */
1926 /* package */ void resetTitleAndRevertLockIcon() {
1927 revertLockIcon();
1928 resetTitleIconAndProgress();
1929 }
1930
1931 /**
1932 * Reset the title, favicon, and progress.
1933 */
1934 private void resetTitleIconAndProgress() {
1935 WebView current = mTabControl.getCurrentWebView();
1936 if (current == null) {
1937 return;
1938 }
1939 resetTitleAndIcon(current);
1940 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001941 mWebChromeClient.onProgressChanged(current, progress);
1942 }
1943
1944 // Reset the title and the icon based on the given item.
1945 private void resetTitleAndIcon(WebView view) {
1946 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1947 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001948 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001949 setFavicon(item.getFavicon());
1950 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001951 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001952 setFavicon(null);
1953 }
1954 }
1955
1956 /**
1957 * Sets a title composed of the URL and the title string.
1958 * @param url The URL of the site being loaded.
1959 * @param title The title of the site being loaded.
1960 */
Leon Scroggins68579392009-09-15 15:31:54 -04001961 private void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001962 mUrl = url;
1963 mTitle = title;
1964
Leon Scroggins68579392009-09-15 15:31:54 -04001965 mTitleBar.setTitleAndUrl(title, url);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001966 if (mFakeTitleBar != null) {
1967 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001968 }
1969 }
1970
1971 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001972 * @param url The URL to build a title version of the URL from.
1973 * @return The title version of the URL or null if fails.
1974 * The title version of the URL can be either the URL hostname,
1975 * or the hostname with an "https://" prefix (for secure URLs),
1976 * or an empty string if, for example, the URL in question is a
1977 * file:// URL with no hostname.
1978 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001979 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001980 String titleUrl = null;
1981
1982 if (url != null) {
1983 try {
1984 // parse the url string
1985 URL urlObj = new URL(url);
1986 if (urlObj != null) {
1987 titleUrl = "";
1988
1989 String protocol = urlObj.getProtocol();
1990 String host = urlObj.getHost();
1991
1992 if (host != null && 0 < host.length()) {
1993 titleUrl = host;
1994 if (protocol != null) {
1995 // if a secure site, add an "https://" prefix!
1996 if (protocol.equalsIgnoreCase("https")) {
1997 titleUrl = protocol + "://" + host;
1998 }
1999 }
2000 }
2001 }
2002 } catch (MalformedURLException e) {}
2003 }
2004
2005 return titleUrl;
2006 }
2007
2008 // Set the favicon in the title bar.
2009 private void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002010 mTitleBar.setFavicon(icon);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002011 if (mFakeTitleBar != null) {
2012 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002013 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002014 }
2015
2016 /**
2017 * Saves the current lock-icon state before resetting
2018 * the lock icon. If we have an error, we may need to
2019 * roll back to the previous state.
2020 */
2021 private void saveLockIcon() {
2022 mPrevLockType = mLockIconType;
2023 }
2024
2025 /**
2026 * Reverts the lock-icon state to the last saved state,
2027 * for example, if we had an error, and need to cancel
2028 * the load.
2029 */
2030 private void revertLockIcon() {
2031 mLockIconType = mPrevLockType;
2032
Dave Bort31a6d1c2009-04-13 15:56:49 -07002033 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002034 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2035 " revert lock icon to " + mLockIconType);
2036 }
2037
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002038 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002039 }
2040
Leon Scroggins1f005d32009-08-10 17:36:42 -04002041 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002042 * Close the tab, remove its associated title bar, and adjust mTabControl's
2043 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002044 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002045 /* package */ void closeTab(TabControl.Tab t) {
2046 int currentIndex = mTabControl.getCurrentIndex();
2047 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002048 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002049 if (currentIndex >= removeIndex && currentIndex != 0) {
2050 currentIndex--;
2051 }
2052 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
The Android Open Source Project0c908882009-03-03 19:32:16 -08002053 }
2054
2055 private void goBackOnePageOrQuit() {
2056 TabControl.Tab current = mTabControl.getCurrentTab();
2057 if (current == null) {
2058 /*
2059 * Instead of finishing the activity, simply push this to the back
2060 * of the stack and let ActivityManager to choose the foreground
2061 * activity. As BrowserActivity is singleTask, it will be always the
2062 * root of the task. So we can use either true or false for
2063 * moveTaskToBack().
2064 */
2065 moveTaskToBack(true);
2066 }
2067 WebView w = current.getWebView();
2068 if (w.canGoBack()) {
2069 w.goBack();
2070 } else {
2071 // Check to see if we are closing a window that was created by
2072 // another window. If so, we switch back to that window.
2073 TabControl.Tab parent = current.getParentTab();
2074 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002075 switchToTab(mTabControl.getTabIndex(parent));
2076 // Now we close the other tab
2077 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002078 } else {
2079 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002080 // force mPageStarted to be false as we are going to either
2081 // finish the activity or remove the tab. This will ensure
2082 // pauseWebView() taking action.
2083 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002084 if (mTabControl.getTabCount() == 1) {
2085 finish();
2086 return;
2087 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002088 // call pauseWebViewTimers() now, we won't be able to call
2089 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002090 // Temporarily change mActivityInPause to be true as
2091 // pauseWebViewTimers() will do nothing if mActivityInPause
2092 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002093 boolean savedState = mActivityInPause;
2094 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002095 Log.e(LOGTAG, "BrowserActivity is already paused "
2096 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002097 }
2098 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002099 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002100 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002101 removeTabFromContentView(current);
2102 mTabControl.removeTab(current);
2103 }
2104 /*
2105 * Instead of finishing the activity, simply push this to the back
2106 * of the stack and let ActivityManager to choose the foreground
2107 * activity. As BrowserActivity is singleTask, it will be always the
2108 * root of the task. So we can use either true or false for
2109 * moveTaskToBack().
2110 */
2111 moveTaskToBack(true);
2112 }
2113 }
2114 }
2115
2116 public KeyTracker.State onKeyTracker(int keyCode,
2117 KeyEvent event,
2118 KeyTracker.Stage stage,
2119 int duration) {
2120 // if onKeyTracker() is called after activity onStop()
2121 // because of accumulated key events,
2122 // we should ignore it as browser is not active any more.
2123 WebView topWindow = getTopWindow();
Andrei Popescuadc008d2009-06-26 14:11:30 +01002124 if (topWindow == null && mCustomView == null)
The Android Open Source Project0c908882009-03-03 19:32:16 -08002125 return KeyTracker.State.NOT_TRACKING;
2126
2127 if (keyCode == KeyEvent.KEYCODE_BACK) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01002128 // Check if a custom view is currently showing and, if it is, hide it.
2129 if (mCustomView != null) {
2130 mWebChromeClient.onHideCustomView();
2131 return KeyTracker.State.DONE_TRACKING;
2132 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002133 if (stage == KeyTracker.Stage.LONG_REPEAT) {
Leon Scroggins30444232009-09-04 18:36:20 -04002134 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002135 return KeyTracker.State.DONE_TRACKING;
2136 } else if (stage == KeyTracker.Stage.UP) {
2137 // FIXME: Currently, we do not have a notion of the
2138 // history picker for the subwindow, but maybe we
2139 // should?
2140 WebView subwindow = mTabControl.getCurrentSubWindow();
2141 if (subwindow != null) {
2142 if (subwindow.canGoBack()) {
2143 subwindow.goBack();
2144 } else {
2145 dismissSubWindow(mTabControl.getCurrentTab());
2146 }
2147 } else {
2148 goBackOnePageOrQuit();
2149 }
2150 return KeyTracker.State.DONE_TRACKING;
2151 }
2152 return KeyTracker.State.KEEP_TRACKING;
2153 }
2154 return KeyTracker.State.NOT_TRACKING;
2155 }
2156
2157 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2158 if (keyCode == KeyEvent.KEYCODE_MENU) {
2159 mMenuIsDown = true;
Grace Kloba6ee9c492009-07-13 10:04:34 -07002160 } else if (mMenuIsDown) {
2161 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2162 // still down, we don't want to trigger the search. Pretend to
2163 // consume the key and do nothing.
2164 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002165 }
2166 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2167 if (!handled) {
2168 switch (keyCode) {
2169 case KeyEvent.KEYCODE_SPACE:
2170 if (event.isShiftPressed()) {
2171 getTopWindow().pageUp(false);
2172 } else {
2173 getTopWindow().pageDown(false);
2174 }
2175 handled = true;
2176 break;
2177
2178 default:
2179 break;
2180 }
2181 }
2182 return handled || super.onKeyDown(keyCode, event);
2183 }
2184
2185 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2186 if (keyCode == KeyEvent.KEYCODE_MENU) {
2187 mMenuIsDown = false;
2188 }
2189 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2190 }
2191
Leon Scroggins68579392009-09-15 15:31:54 -04002192 /* package */ void stopLoading() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002193 resetTitleAndRevertLockIcon();
2194 WebView w = getTopWindow();
2195 w.stopLoading();
2196 mWebViewClient.onPageFinished(w, w.getUrl());
2197
2198 cancelStopToast();
2199 mStopToast = Toast
2200 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2201 mStopToast.show();
2202 }
2203
2204 private void cancelStopToast() {
2205 if (mStopToast != null) {
2206 mStopToast.cancel();
2207 mStopToast = null;
2208 }
2209 }
2210
2211 // called by a non-UI thread to post the message
2212 public void postMessage(int what, int arg1, int arg2, Object obj) {
2213 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2214 }
2215
2216 // public message ids
2217 public final static int LOAD_URL = 1001;
2218 public final static int STOP_LOAD = 1002;
2219
2220 // Message Ids
2221 private static final int FOCUS_NODE_HREF = 102;
2222 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002223 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002224
2225 // Private handler for handling javascript and saving passwords
2226 private Handler mHandler = new Handler() {
2227
2228 public void handleMessage(Message msg) {
2229 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002230 case FOCUS_NODE_HREF:
2231 String url = (String) msg.getData().get("url");
2232 if (url == null || url.length() == 0) {
2233 break;
2234 }
2235 HashMap focusNodeMap = (HashMap) msg.obj;
2236 WebView view = (WebView) focusNodeMap.get("webview");
2237 // Only apply the action if the top window did not change.
2238 if (getTopWindow() != view) {
2239 break;
2240 }
2241 switch (msg.arg1) {
2242 case R.id.open_context_menu_id:
2243 case R.id.view_image_context_menu_id:
2244 loadURL(getTopWindow(), url);
2245 break;
2246 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002247 final TabControl.Tab parent = mTabControl
2248 .getCurrentTab();
2249 final TabControl.Tab newTab = openTab(url);
2250 if (newTab != parent) {
2251 parent.addChildTab(newTab);
2252 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002253 break;
2254 case R.id.bookmark_context_menu_id:
2255 Intent intent = new Intent(BrowserActivity.this,
2256 AddBookmarkPage.class);
2257 intent.putExtra("url", url);
2258 startActivity(intent);
2259 break;
2260 case R.id.share_link_context_menu_id:
2261 Browser.sendString(BrowserActivity.this, url);
2262 break;
2263 case R.id.copy_link_context_menu_id:
2264 copy(url);
2265 break;
2266 case R.id.save_link_context_menu_id:
2267 case R.id.download_context_menu_id:
2268 onDownloadStartNoStream(url, null, null, null, -1);
2269 break;
2270 }
2271 break;
2272
2273 case LOAD_URL:
2274 loadURL(getTopWindow(), (String) msg.obj);
2275 break;
2276
2277 case STOP_LOAD:
2278 stopLoading();
2279 break;
2280
2281 case CANCEL_CREDS_REQUEST:
2282 resumeAfterCredentials();
2283 break;
2284
The Android Open Source Project0c908882009-03-03 19:32:16 -08002285 case RELEASE_WAKELOCK:
2286 if (mWakeLock.isHeld()) {
2287 mWakeLock.release();
2288 }
2289 break;
2290 }
2291 }
2292 };
2293
Leon Scroggins89c6d362009-07-15 16:54:37 -04002294 private void updateScreenshot(WebView view) {
2295 // If this is a bookmarked site, add a screenshot to the database.
2296 // FIXME: When should we update? Every time?
2297 // FIXME: Would like to make sure there is actually something to
2298 // draw, but the API for that (WebViewCore.pictureReady()) is not
2299 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002300 ContentResolver cr = getContentResolver();
2301 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002302 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002303 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002304 boolean succeed = c.moveToFirst();
2305 ContentValues values = null;
2306 while (succeed) {
2307 if (values == null) {
2308 final ByteArrayOutputStream os
2309 = new ByteArrayOutputStream();
2310 Picture thumbnail = view.capturePicture();
2311 // Keep width and height in sync with BrowserBookmarksPage
2312 // and bookmark_thumb
2313 Bitmap bm = Bitmap.createBitmap(100, 80,
2314 Bitmap.Config.ARGB_4444);
2315 Canvas canvas = new Canvas(bm);
2316 // May need to tweak these values to determine what is the
2317 // best scale factor
2318 canvas.scale(.5f, .5f);
2319 thumbnail.draw(canvas);
2320 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2321 values = new ContentValues();
2322 values.put(Browser.BookmarkColumns.THUMBNAIL,
2323 os.toByteArray());
2324 }
2325 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2326 c.getInt(0)), values, null, null);
2327 succeed = c.moveToNext();
2328 }
2329 c.close();
2330 }
2331 }
2332
The Android Open Source Project0c908882009-03-03 19:32:16 -08002333 // -------------------------------------------------------------------------
2334 // WebViewClient implementation.
2335 //-------------------------------------------------------------------------
2336
2337 // Use in overrideUrlLoading
2338 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2339 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2340 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2341 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2342
2343 /* package */ WebViewClient getWebViewClient() {
2344 return mWebViewClient;
2345 }
2346
Patrick Scott3918d442009-08-04 13:22:29 -04002347 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002348 if (icon != null) {
2349 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott3918d442009-08-04 13:22:29 -04002350 view, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002351 }
2352 setFavicon(icon);
2353 }
2354
2355 private final WebViewClient mWebViewClient = new WebViewClient() {
2356 @Override
2357 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2358 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002359 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002360
2361 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2362 if (errorConsole != null) {
2363 errorConsole.clearErrorMessages();
2364 if (mShouldShowErrorConsole) {
2365 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2366 }
2367 }
2368
The Android Open Source Project0c908882009-03-03 19:32:16 -08002369 // Call updateIcon instead of setFavicon so the bookmark
2370 // database can be updated.
Patrick Scott3918d442009-08-04 13:22:29 -04002371 updateIcon(view, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002372
Grace Kloba4d7880f2009-08-12 09:35:42 -07002373 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002374 String host;
2375 try {
2376 WebAddress uri = new WebAddress(url);
2377 host = uri.mHost;
2378 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002379 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002380 }
2381 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002382 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002383 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002384 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002385 }
2386
2387 // Performance probe
2388 if (false) {
2389 mStart = SystemClock.uptimeMillis();
2390 mProcessStart = Process.getElapsedCpuTime();
2391 long[] sysCpu = new long[7];
2392 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2393 sysCpu, null)) {
2394 mUserStart = sysCpu[0] + sysCpu[1];
2395 mSystemStart = sysCpu[2];
2396 mIdleStart = sysCpu[3];
2397 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2398 }
2399 mUiStart = SystemClock.currentThreadTimeMillis();
2400 }
2401
2402 if (!mPageStarted) {
2403 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002404 // if onResume() has been called, resumeWebViewTimers() does
2405 // nothing.
2406 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002407 }
2408
2409 // reset sync timer to avoid sync starts during loading a page
2410 CookieSyncManager.getInstance().resetSync();
2411
2412 mInLoad = true;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002413 WebView currentWebView = mTabControl.getCurrentWebView();
2414 if (currentWebView == null || currentWebView.getScrollY() != 0) {
2415 // This page has begun to load, so show the title bar
2416 showFakeTitleBar();
2417 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002418 updateInLoadMenuItems();
2419 if (!mIsNetworkUp) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04002420 createAndShowNetworkDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002421 if (view != null) {
2422 view.setNetworkAvailable(false);
2423 }
2424 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002425 }
2426
2427 @Override
2428 public void onPageFinished(WebView view, String url) {
2429 // Reset the title and icon in case we stopped a provisional
2430 // load.
2431 resetTitleAndIcon(view);
2432
2433 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002434 updateLockIconToLatest();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002435 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002436
The Android Open Source Project0c908882009-03-03 19:32:16 -08002437 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002438 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002439 long[] sysCpu = new long[7];
2440 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2441 sysCpu, null)) {
2442 String uiInfo = "UI thread used "
2443 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2444 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002445 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002446 Log.d(LOGTAG, uiInfo);
2447 }
2448 //The string that gets written to the log
2449 String performanceString = "It took total "
2450 + (SystemClock.uptimeMillis() - mStart)
2451 + " ms clock time to load the page."
2452 + "\nbrowser process used "
2453 + (Process.getElapsedCpuTime() - mProcessStart)
2454 + " ms, user processes used "
2455 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2456 + " ms, kernel used "
2457 + (sysCpu[2] - mSystemStart) * 10
2458 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2459 + " ms and irq took "
2460 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2461 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002462 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002463 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2464 }
2465 if (url != null) {
2466 // strip the url to maintain consistency
2467 String newUrl = new String(url);
2468 if (newUrl.startsWith("http://www.")) {
2469 newUrl = newUrl.substring(11);
2470 } else if (newUrl.startsWith("http://")) {
2471 newUrl = newUrl.substring(7);
2472 } else if (newUrl.startsWith("https://www.")) {
2473 newUrl = newUrl.substring(12);
2474 } else if (newUrl.startsWith("https://")) {
2475 newUrl = newUrl.substring(8);
2476 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002477 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002478 Log.d(LOGTAG, newUrl + " loaded");
2479 }
2480 /*
2481 if (sWhiteList.contains(newUrl)) {
2482 // The string that gets pushed to the statistcs
2483 // service
2484 performanceString = performanceString
2485 + "\nWebpage: "
2486 + newUrl
2487 + "\nCarrier: "
2488 + android.os.SystemProperties
2489 .get("gsm.sim.operator.alpha");
2490 if (mWebView != null
2491 && mWebView.getContext() != null
2492 && mWebView.getContext().getSystemService(
2493 Context.CONNECTIVITY_SERVICE) != null) {
2494 ConnectivityManager cManager =
2495 (ConnectivityManager) mWebView
2496 .getContext().getSystemService(
2497 Context.CONNECTIVITY_SERVICE);
2498 NetworkInfo nInfo = cManager
2499 .getActiveNetworkInfo();
2500 if (nInfo != null) {
2501 performanceString = performanceString
2502 + "\nNetwork Type: "
2503 + nInfo.getType().toString();
2504 }
2505 }
2506 Checkin.logEvent(mResolver,
2507 Checkin.Events.Tag.WEBPAGE_LOAD,
2508 performanceString);
2509 Log.w(LOGTAG, "pushed to the statistics service");
2510 }
2511 */
2512 }
2513 }
2514 }
2515
2516 if (mInTrace) {
2517 mInTrace = false;
2518 Debug.stopMethodTracing();
2519 }
2520
2521 if (mPageStarted) {
2522 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002523 // pauseWebViewTimers() will do nothing and return false if
2524 // onPause() is not called yet.
2525 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002526 if (mWakeLock.isHeld()) {
2527 mHandler.removeMessages(RELEASE_WAKELOCK);
2528 mWakeLock.release();
2529 }
2530 }
2531 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002532 }
2533
2534 // return true if want to hijack the url to let another app to handle it
2535 @Override
2536 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2537 if (url.startsWith(SCHEME_WTAI)) {
2538 // wtai://wp/mc;number
2539 // number=string(phone-number)
2540 if (url.startsWith(SCHEME_WTAI_MC)) {
2541 Intent intent = new Intent(Intent.ACTION_VIEW,
2542 Uri.parse(WebView.SCHEME_TEL +
2543 url.substring(SCHEME_WTAI_MC.length())));
2544 startActivity(intent);
2545 return true;
2546 }
2547 // wtai://wp/sd;dtmf
2548 // dtmf=string(dialstring)
2549 if (url.startsWith(SCHEME_WTAI_SD)) {
2550 // TODO
2551 // only send when there is active voice connection
2552 return false;
2553 }
2554 // wtai://wp/ap;number;name
2555 // number=string(phone-number)
2556 // name=string
2557 if (url.startsWith(SCHEME_WTAI_AP)) {
2558 // TODO
2559 return false;
2560 }
2561 }
2562
Dianne Hackborn99189432009-06-17 18:06:18 -07002563 // The "about:" schemes are internal to the browser; don't
2564 // want these to be dispatched to other apps.
2565 if (url.startsWith("about:")) {
2566 return false;
2567 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002568
Dianne Hackborn99189432009-06-17 18:06:18 -07002569 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002570
Dianne Hackborn99189432009-06-17 18:06:18 -07002571 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002572 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002573 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2574 } catch (URISyntaxException ex) {
2575 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002576 return false;
2577 }
2578
Grace Kloba5b078b52009-06-24 20:23:41 -07002579 // check whether the intent can be resolved. If not, we will see
2580 // whether we can download it from the Market.
2581 if (getPackageManager().resolveActivity(intent, 0) == null) {
2582 String packagename = intent.getPackage();
2583 if (packagename != null) {
2584 intent = new Intent(Intent.ACTION_VIEW, Uri
2585 .parse("market://search?q=pname:" + packagename));
2586 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2587 startActivity(intent);
2588 return true;
2589 } else {
2590 return false;
2591 }
2592 }
2593
Dianne Hackborn99189432009-06-17 18:06:18 -07002594 // sanitize the Intent, ensuring web pages can not bypass browser
2595 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002596 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002597 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002598 try {
2599 if (startActivityIfNeeded(intent, -1)) {
2600 return true;
2601 }
2602 } catch (ActivityNotFoundException ex) {
2603 // ignore the error. If no application can handle the URL,
2604 // eg about:blank, assume the browser can handle it.
2605 }
2606
2607 if (mMenuIsDown) {
2608 openTab(url);
2609 closeOptionsMenu();
2610 return true;
2611 }
2612
2613 return false;
2614 }
2615
2616 /**
2617 * Updates the lock icon. This method is called when we discover another
2618 * resource to be loaded for this page (for example, javascript). While
2619 * we update the icon type, we do not update the lock icon itself until
2620 * we are done loading, it is slightly more secure this way.
2621 */
2622 @Override
2623 public void onLoadResource(WebView view, String url) {
2624 if (url != null && url.length() > 0) {
2625 // It is only if the page claims to be secure
2626 // that we may have to update the lock:
2627 if (mLockIconType == LOCK_ICON_SECURE) {
2628 // If NOT a 'safe' url, change the lock to mixed content!
2629 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2630 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002631 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002632 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2633 " updated lock icon to " + mLockIconType + " due to " + url);
2634 }
2635 }
2636 }
2637 }
2638 }
2639
2640 /**
2641 * Show the dialog, asking the user if they would like to continue after
2642 * an excessive number of HTTP redirects.
2643 */
2644 @Override
2645 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2646 final Message continueMsg) {
2647 new AlertDialog.Builder(BrowserActivity.this)
2648 .setTitle(R.string.browserFrameRedirect)
2649 .setMessage(R.string.browserFrame307Post)
2650 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2651 public void onClick(DialogInterface dialog, int which) {
2652 continueMsg.sendToTarget();
2653 }})
2654 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2655 public void onClick(DialogInterface dialog, int which) {
2656 cancelMsg.sendToTarget();
2657 }})
2658 .setOnCancelListener(new OnCancelListener() {
2659 public void onCancel(DialogInterface dialog) {
2660 cancelMsg.sendToTarget();
2661 }})
2662 .show();
2663 }
2664
Patrick Scott37911c72009-03-24 18:02:58 -07002665 // Container class for the next error dialog that needs to be
2666 // displayed.
2667 class ErrorDialog {
2668 public final int mTitle;
2669 public final String mDescription;
2670 public final int mError;
2671 ErrorDialog(int title, String desc, int error) {
2672 mTitle = title;
2673 mDescription = desc;
2674 mError = error;
2675 }
2676 };
2677
2678 private void processNextError() {
2679 if (mQueuedErrors == null) {
2680 return;
2681 }
2682 // The first one is currently displayed so just remove it.
2683 mQueuedErrors.removeFirst();
2684 if (mQueuedErrors.size() == 0) {
2685 mQueuedErrors = null;
2686 return;
2687 }
2688 showError(mQueuedErrors.getFirst());
2689 }
2690
2691 private DialogInterface.OnDismissListener mDialogListener =
2692 new DialogInterface.OnDismissListener() {
2693 public void onDismiss(DialogInterface d) {
2694 processNextError();
2695 }
2696 };
2697 private LinkedList<ErrorDialog> mQueuedErrors;
2698
2699 private void queueError(int err, String desc) {
2700 if (mQueuedErrors == null) {
2701 mQueuedErrors = new LinkedList<ErrorDialog>();
2702 }
2703 for (ErrorDialog d : mQueuedErrors) {
2704 if (d.mError == err) {
2705 // Already saw a similar error, ignore the new one.
2706 return;
2707 }
2708 }
2709 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002710 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002711 R.string.browserFrameFileErrorLabel :
2712 R.string.browserFrameNetworkErrorLabel,
2713 desc, err);
2714 mQueuedErrors.addLast(errDialog);
2715
2716 // Show the dialog now if the queue was empty.
2717 if (mQueuedErrors.size() == 1) {
2718 showError(errDialog);
2719 }
2720 }
2721
2722 private void showError(ErrorDialog errDialog) {
2723 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2724 .setTitle(errDialog.mTitle)
2725 .setMessage(errDialog.mDescription)
2726 .setPositiveButton(R.string.ok, null)
2727 .create();
2728 d.setOnDismissListener(mDialogListener);
2729 d.show();
2730 }
2731
The Android Open Source Project0c908882009-03-03 19:32:16 -08002732 /**
2733 * Show a dialog informing the user of the network error reported by
2734 * WebCore.
2735 */
2736 @Override
2737 public void onReceivedError(WebView view, int errorCode,
2738 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002739 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2740 errorCode != WebViewClient.ERROR_CONNECT &&
2741 errorCode != WebViewClient.ERROR_BAD_URL &&
2742 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2743 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002744 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002745 }
Patrick Scott37911c72009-03-24 18:02:58 -07002746 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2747 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002748
2749 // We need to reset the title after an error.
2750 resetTitleAndRevertLockIcon();
2751 }
2752
2753 /**
2754 * Check with the user if it is ok to resend POST data as the page they
2755 * are trying to navigate to is the result of a POST.
2756 */
2757 @Override
2758 public void onFormResubmission(WebView view, final Message dontResend,
2759 final Message resend) {
2760 new AlertDialog.Builder(BrowserActivity.this)
2761 .setTitle(R.string.browserFrameFormResubmitLabel)
2762 .setMessage(R.string.browserFrameFormResubmitMessage)
2763 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2764 public void onClick(DialogInterface dialog, int which) {
2765 resend.sendToTarget();
2766 }})
2767 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2768 public void onClick(DialogInterface dialog, int which) {
2769 dontResend.sendToTarget();
2770 }})
2771 .setOnCancelListener(new OnCancelListener() {
2772 public void onCancel(DialogInterface dialog) {
2773 dontResend.sendToTarget();
2774 }})
2775 .show();
2776 }
2777
2778 /**
2779 * Insert the url into the visited history database.
2780 * @param url The url to be inserted.
2781 * @param isReload True if this url is being reloaded.
2782 * FIXME: Not sure what to do when reloading the page.
2783 */
2784 @Override
2785 public void doUpdateVisitedHistory(WebView view, String url,
2786 boolean isReload) {
2787 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2788 return;
2789 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002790 // remove "client" before updating it to the history so that it wont
2791 // show up in the auto-complete list.
2792 int index = url.indexOf("client=ms-");
2793 if (index > 0 && url.contains(".google.")) {
2794 int end = url.indexOf('&', index);
2795 if (end > 0) {
2796 url = url.substring(0, index-1).concat(url.substring(end));
2797 } else {
2798 url = url.substring(0, index-1);
2799 }
2800 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002801 Browser.updateVisitedHistory(mResolver, url, true);
2802 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2803 }
2804
2805 /**
2806 * Displays SSL error(s) dialog to the user.
2807 */
2808 @Override
2809 public void onReceivedSslError(
2810 final WebView view, final SslErrorHandler handler, final SslError error) {
2811
2812 if (mSettings.showSecurityWarnings()) {
2813 final LayoutInflater factory =
2814 LayoutInflater.from(BrowserActivity.this);
2815 final View warningsView =
2816 factory.inflate(R.layout.ssl_warnings, null);
2817 final LinearLayout placeholder =
2818 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2819
2820 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2821 LinearLayout ll = (LinearLayout)factory
2822 .inflate(R.layout.ssl_warning, null);
2823 ((TextView)ll.findViewById(R.id.warning))
2824 .setText(R.string.ssl_untrusted);
2825 placeholder.addView(ll);
2826 }
2827
2828 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2829 LinearLayout ll = (LinearLayout)factory
2830 .inflate(R.layout.ssl_warning, null);
2831 ((TextView)ll.findViewById(R.id.warning))
2832 .setText(R.string.ssl_mismatch);
2833 placeholder.addView(ll);
2834 }
2835
2836 if (error.hasError(SslError.SSL_EXPIRED)) {
2837 LinearLayout ll = (LinearLayout)factory
2838 .inflate(R.layout.ssl_warning, null);
2839 ((TextView)ll.findViewById(R.id.warning))
2840 .setText(R.string.ssl_expired);
2841 placeholder.addView(ll);
2842 }
2843
2844 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2845 LinearLayout ll = (LinearLayout)factory
2846 .inflate(R.layout.ssl_warning, null);
2847 ((TextView)ll.findViewById(R.id.warning))
2848 .setText(R.string.ssl_not_yet_valid);
2849 placeholder.addView(ll);
2850 }
2851
2852 new AlertDialog.Builder(BrowserActivity.this)
2853 .setTitle(R.string.security_warning)
2854 .setIcon(android.R.drawable.ic_dialog_alert)
2855 .setView(warningsView)
2856 .setPositiveButton(R.string.ssl_continue,
2857 new DialogInterface.OnClickListener() {
2858 public void onClick(DialogInterface dialog, int whichButton) {
2859 handler.proceed();
2860 }
2861 })
2862 .setNeutralButton(R.string.view_certificate,
2863 new DialogInterface.OnClickListener() {
2864 public void onClick(DialogInterface dialog, int whichButton) {
2865 showSSLCertificateOnError(view, handler, error);
2866 }
2867 })
2868 .setNegativeButton(R.string.cancel,
2869 new DialogInterface.OnClickListener() {
2870 public void onClick(DialogInterface dialog, int whichButton) {
2871 handler.cancel();
2872 BrowserActivity.this.resetTitleAndRevertLockIcon();
2873 }
2874 })
2875 .setOnCancelListener(
2876 new DialogInterface.OnCancelListener() {
2877 public void onCancel(DialogInterface dialog) {
2878 handler.cancel();
2879 BrowserActivity.this.resetTitleAndRevertLockIcon();
2880 }
2881 })
2882 .show();
2883 } else {
2884 handler.proceed();
2885 }
2886 }
2887
2888 /**
2889 * Handles an HTTP authentication request.
2890 *
2891 * @param handler The authentication handler
2892 * @param host The host
2893 * @param realm The realm
2894 */
2895 @Override
2896 public void onReceivedHttpAuthRequest(WebView view,
2897 final HttpAuthHandler handler, final String host, final String realm) {
2898 String username = null;
2899 String password = null;
2900
2901 boolean reuseHttpAuthUsernamePassword =
2902 handler.useHttpAuthUsernamePassword();
2903
2904 if (reuseHttpAuthUsernamePassword &&
2905 (mTabControl.getCurrentWebView() != null)) {
2906 String[] credentials =
2907 mTabControl.getCurrentWebView()
2908 .getHttpAuthUsernamePassword(host, realm);
2909 if (credentials != null && credentials.length == 2) {
2910 username = credentials[0];
2911 password = credentials[1];
2912 }
2913 }
2914
2915 if (username != null && password != null) {
2916 handler.proceed(username, password);
2917 } else {
2918 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2919 }
2920 }
2921
2922 @Override
2923 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2924 if (mMenuIsDown) {
2925 // only check shortcut key when MENU is held
2926 return getWindow().isShortcutKey(event.getKeyCode(), event);
2927 } else {
2928 return false;
2929 }
2930 }
2931
2932 @Override
2933 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2934 if (view != mTabControl.getCurrentTopWebView()) {
2935 return;
2936 }
2937 if (event.isDown()) {
2938 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2939 } else {
2940 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2941 }
2942 }
2943 };
2944
2945 //--------------------------------------------------------------------------
2946 // WebChromeClient implementation
2947 //--------------------------------------------------------------------------
2948
2949 /* package */ WebChromeClient getWebChromeClient() {
2950 return mWebChromeClient;
2951 }
2952
2953 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2954 // Helper method to create a new tab or sub window.
2955 private void createWindow(final boolean dialog, final Message msg) {
2956 if (dialog) {
2957 mTabControl.createSubWindow();
2958 final TabControl.Tab t = mTabControl.getCurrentTab();
2959 attachSubWindow(t);
2960 WebView.WebViewTransport transport =
2961 (WebView.WebViewTransport) msg.obj;
2962 transport.setWebView(t.getSubWebView());
2963 msg.sendToTarget();
2964 } else {
2965 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04002966 final TabControl.Tab newTab
2967 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07002968 if (newTab != parent) {
2969 parent.addChildTab(newTab);
2970 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002971 WebView.WebViewTransport transport =
2972 (WebView.WebViewTransport) msg.obj;
2973 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04002974 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002975 }
2976 }
2977
2978 @Override
2979 public boolean onCreateWindow(WebView view, final boolean dialog,
2980 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002981 // Short-circuit if we can't create any more tabs or sub windows.
2982 if (dialog && mTabControl.getCurrentSubWindow() != null) {
2983 new AlertDialog.Builder(BrowserActivity.this)
2984 .setTitle(R.string.too_many_subwindows_dialog_title)
2985 .setIcon(android.R.drawable.ic_dialog_alert)
2986 .setMessage(R.string.too_many_subwindows_dialog_message)
2987 .setPositiveButton(R.string.ok, null)
2988 .show();
2989 return false;
2990 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
2991 new AlertDialog.Builder(BrowserActivity.this)
2992 .setTitle(R.string.too_many_windows_dialog_title)
2993 .setIcon(android.R.drawable.ic_dialog_alert)
2994 .setMessage(R.string.too_many_windows_dialog_message)
2995 .setPositiveButton(R.string.ok, null)
2996 .show();
2997 return false;
2998 }
2999
3000 // Short-circuit if this was a user gesture.
3001 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003002 createWindow(dialog, resultMsg);
3003 return true;
3004 }
3005
3006 // Allow the popup and create the appropriate window.
3007 final AlertDialog.OnClickListener allowListener =
3008 new AlertDialog.OnClickListener() {
3009 public void onClick(DialogInterface d,
3010 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003011 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003012 }
3013 };
3014
3015 // Block the popup by returning a null WebView.
3016 final AlertDialog.OnClickListener blockListener =
3017 new AlertDialog.OnClickListener() {
3018 public void onClick(DialogInterface d, int which) {
3019 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003020 }
3021 };
3022
3023 // Build a confirmation dialog to display to the user.
3024 final AlertDialog d =
3025 new AlertDialog.Builder(BrowserActivity.this)
3026 .setTitle(R.string.attention)
3027 .setIcon(android.R.drawable.ic_dialog_alert)
3028 .setMessage(R.string.popup_window_attempt)
3029 .setPositiveButton(R.string.allow, allowListener)
3030 .setNegativeButton(R.string.block, blockListener)
3031 .setCancelable(false)
3032 .create();
3033
3034 // Show the confirmation dialog.
3035 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003036 return true;
3037 }
3038
3039 @Override
3040 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003041 final TabControl.Tab current = mTabControl.getCurrentTab();
3042 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003043 if (parent != null) {
3044 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003045 switchToTab(mTabControl.getTabIndex(parent));
3046 // Now we need to close the window
3047 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003048 }
3049 }
3050
3051 @Override
3052 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003053 mTitleBar.setProgress(newProgress);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003054 if (mFakeTitleBar != null) {
3055 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003056 }
3057
3058 if (newProgress == 100) {
3059 // onProgressChanged() is called for sub-frame too while
3060 // onPageFinished() is only called for the main frame. sync
3061 // cookie and cache promptly here.
3062 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003063 if (mInLoad) {
3064 mInLoad = false;
3065 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003066 // If the options menu is open, leave the title bar
3067 if (!mOptionsMenuOpen || !mIconView) {
3068 hideFakeTitleBar();
3069 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003070 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003071 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003072 // onPageFinished may have already been called but a subframe
3073 // is still loading and updating the progress. Reset mInLoad
3074 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003075 mInLoad = true;
3076 updateInLoadMenuItems();
3077 WebView currentWebView = mTabControl.getCurrentWebView();
3078 if ((currentWebView == null || currentWebView.getScrollY() != 0)
3079 && (!mOptionsMenuOpen || mIconView)) {
3080 // This page has begun to load, so show the title bar
3081 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003082 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003083 }
3084 }
3085
3086 @Override
3087 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003088 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003089
3090 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003091 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003092
3093 if (url == null ||
3094 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3095 return;
3096 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003097 // See if we can find the current url in our history database and
3098 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003099 if (url.startsWith("http://www.")) {
3100 url = url.substring(11);
3101 } else if (url.startsWith("http://")) {
3102 url = url.substring(4);
3103 }
3104 try {
3105 url = "%" + url;
3106 String [] selArgs = new String[] { url };
3107
3108 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3109 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3110 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3111 Browser.HISTORY_PROJECTION, where, selArgs, null);
3112 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003113 // Current implementation of database only has one entry per
3114 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003115 ContentValues map = new ContentValues();
3116 map.put(Browser.BookmarkColumns.TITLE, title);
3117 mResolver.update(Browser.BOOKMARKS_URI, map,
3118 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003119 }
3120 c.close();
3121 } catch (IllegalStateException e) {
3122 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3123 } catch (SQLiteException ex) {
3124 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3125 }
3126 }
3127
3128 @Override
3129 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003130 updateIcon(view, icon);
3131 }
3132
3133 @Override
3134 public void onReceivedTouchIconUrl(WebView view, String url) {
3135 final ContentResolver cr = getContentResolver();
3136 final Cursor c =
3137 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003138 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003139 if (c != null) {
3140 if (c.getCount() > 0) {
3141 new DownloadTouchIcon(cr, c, view).execute(url);
3142 } else {
3143 c.close();
3144 }
3145 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003146 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003147
Andrei Popescuadc008d2009-06-26 14:11:30 +01003148 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003149 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003150 if (mCustomView != null)
3151 return;
3152
3153 // Add the custom view to its container.
3154 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3155 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003156 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003157 // Save the menu state and set it to empty while the custom
3158 // view is showing.
3159 mOldMenuState = mMenuState;
3160 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003161 // Hide the content view.
3162 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003163 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003164 mCustomViewContainer.setVisibility(View.VISIBLE);
3165 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003166 }
3167
3168 @Override
3169 public void onHideCustomView() {
3170 if (mCustomView == null)
3171 return;
3172
Andrei Popescuc9b55562009-07-07 10:51:15 +01003173 // Hide the custom view.
3174 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003175 // Remove the custom view from its container.
3176 mCustomViewContainer.removeView(mCustomView);
3177 mCustomView = null;
3178 // Reset the old menu state.
3179 mMenuState = mOldMenuState;
3180 mOldMenuState = EMPTY_MENU;
3181 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003182 mCustomViewCallback.onCustomViewHidden();
3183 // Show the content view.
3184 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003185 }
3186
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003187 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003188 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003189 * @param url the URL that exceeded the quota
3190 * @param databaseIdentifier the identifier of the database on
3191 * which the transaction that caused the quota overflow was run
3192 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003193 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003194 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003195 * @param quotaUpdater The callback to run when a decision to allow or
3196 * deny quota has been made. Don't forget to call this!
3197 */
3198 @Override
3199 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003200 String databaseIdentifier, long currentQuota, long estimatedSize,
3201 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003202 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003203 url, databaseIdentifier, currentQuota, estimatedSize,
3204 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003205 }
3206
3207 /**
3208 * The Application Cache has exceeded its max size.
3209 * @param spaceNeeded is the amount of disk space that would be needed
3210 * in order for the last appcache operation to succeed.
3211 * @param totalUsedQuota is the sum of all origins' quota.
3212 * @param quotaUpdater A callback to inform the WebCore thread that a new
3213 * app cache size is available. This callback must always be executed at
3214 * some point to ensure that the sleeping WebCore thread is woken up.
3215 */
3216 @Override
3217 public void onReachedMaxAppCacheSize(long spaceNeeded,
3218 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3219 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3220 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003221 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003222
Steve Block2bc69912009-07-30 14:45:13 +01003223 /**
3224 * Instructs the browser to show a prompt to ask the user to set the
3225 * Geolocation permission state for the specified origin.
3226 * @param origin The origin for which Geolocation permissions are
3227 * requested.
3228 * @param callback The callback to call once the user has set the
3229 * Geolocation permission state.
3230 */
3231 @Override
3232 public void onGeolocationPermissionsShowPrompt(String origin,
3233 GeolocationPermissions.Callback callback) {
3234 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3235 origin, callback);
3236 }
3237
3238 /**
3239 * Instructs the browser to hide the Geolocation permissions prompt.
3240 */
3241 @Override
3242 public void onGeolocationPermissionsHidePrompt() {
3243 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3244 }
3245
Ben Murdoch7db26342009-06-03 18:21:19 +01003246 /* Adds a JavaScript error message to the system log.
3247 * @param message The error message to report.
3248 * @param lineNumber The line number of the error.
3249 * @param sourceID The name of the source file that caused the error.
3250 */
3251 @Override
3252 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003253 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3254 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3255 if (mShouldShowErrorConsole &&
3256 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3257 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3258 }
3259 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003260 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003261 };
3262
3263 /**
3264 * Notify the host application a download should be done, or that
3265 * the data should be streamed if a streaming viewer is available.
3266 * @param url The full url to the content that should be downloaded
3267 * @param contentDisposition Content-disposition http header, if
3268 * present.
3269 * @param mimetype The mimetype of the content reported by the server
3270 * @param contentLength The file size reported by the server
3271 */
3272 public void onDownloadStart(String url, String userAgent,
3273 String contentDisposition, String mimetype, long contentLength) {
3274 // if we're dealing wih A/V content that's not explicitly marked
3275 // for download, check if it's streamable.
3276 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003277 || !contentDisposition.regionMatches(
3278 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003279 // query the package manager to see if there's a registered handler
3280 // that matches.
3281 Intent intent = new Intent(Intent.ACTION_VIEW);
3282 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003283 ResolveInfo info = getPackageManager().resolveActivity(intent,
3284 PackageManager.MATCH_DEFAULT_ONLY);
3285 if (info != null) {
3286 ComponentName myName = getComponentName();
3287 // If we resolved to ourselves, we don't want to attempt to
3288 // load the url only to try and download it again.
3289 if (!myName.getPackageName().equals(
3290 info.activityInfo.packageName)
3291 || !myName.getClassName().equals(
3292 info.activityInfo.name)) {
3293 // someone (other than us) knows how to handle this mime
3294 // type with this scheme, don't download.
3295 try {
3296 startActivity(intent);
3297 return;
3298 } catch (ActivityNotFoundException ex) {
3299 if (LOGD_ENABLED) {
3300 Log.d(LOGTAG, "activity not found for " + mimetype
3301 + " over " + Uri.parse(url).getScheme(),
3302 ex);
3303 }
3304 // Best behavior is to fall back to a download in this
3305 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003306 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003307 }
3308 }
3309 }
3310 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3311 }
3312
3313 /**
3314 * Notify the host application a download should be done, even if there
3315 * is a streaming viewer available for thise type.
3316 * @param url The full url to the content that should be downloaded
3317 * @param contentDisposition Content-disposition http header, if
3318 * present.
3319 * @param mimetype The mimetype of the content reported by the server
3320 * @param contentLength The file size reported by the server
3321 */
3322 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3323 String contentDisposition, String mimetype, long contentLength) {
3324
3325 String filename = URLUtil.guessFileName(url,
3326 contentDisposition, mimetype);
3327
3328 // Check to see if we have an SDCard
3329 String status = Environment.getExternalStorageState();
3330 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3331 int title;
3332 String msg;
3333
3334 // Check to see if the SDCard is busy, same as the music app
3335 if (status.equals(Environment.MEDIA_SHARED)) {
3336 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3337 title = R.string.download_sdcard_busy_dlg_title;
3338 } else {
3339 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3340 title = R.string.download_no_sdcard_dlg_title;
3341 }
3342
3343 new AlertDialog.Builder(this)
3344 .setTitle(title)
3345 .setIcon(android.R.drawable.ic_dialog_alert)
3346 .setMessage(msg)
3347 .setPositiveButton(R.string.ok, null)
3348 .show();
3349 return;
3350 }
3351
3352 // java.net.URI is a lot stricter than KURL so we have to undo
3353 // KURL's percent-encoding and redo the encoding using java.net.URI.
3354 URI uri = null;
3355 try {
3356 // Undo the percent-encoding that KURL may have done.
3357 String newUrl = new String(URLUtil.decode(url.getBytes()));
3358 // Parse the url into pieces
3359 WebAddress w = new WebAddress(newUrl);
3360 String frag = null;
3361 String query = null;
3362 String path = w.mPath;
3363 // Break the path into path, query, and fragment
3364 if (path.length() > 0) {
3365 // Strip the fragment
3366 int idx = path.lastIndexOf('#');
3367 if (idx != -1) {
3368 frag = path.substring(idx + 1);
3369 path = path.substring(0, idx);
3370 }
3371 idx = path.lastIndexOf('?');
3372 if (idx != -1) {
3373 query = path.substring(idx + 1);
3374 path = path.substring(0, idx);
3375 }
3376 }
3377 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3378 query, frag);
3379 } catch (Exception e) {
3380 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3381 return;
3382 }
3383
3384 // XXX: Have to use the old url since the cookies were stored using the
3385 // old percent-encoded url.
3386 String cookies = CookieManager.getInstance().getCookie(url);
3387
3388 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003389 values.put(Downloads.COLUMN_URI, uri.toString());
3390 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3391 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3392 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003393 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003394 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003395 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003396 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3397 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3398 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3399 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003400 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003401 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003402 }
3403 if (mimetype == null) {
3404 // We must have long pressed on a link or image to download it. We
3405 // are not sure of the mimetype in this case, so do a head request
3406 new FetchUrlMimeType(this).execute(values);
3407 } else {
3408 final Uri contentUri =
3409 getContentResolver().insert(Downloads.CONTENT_URI, values);
3410 viewDownloads(contentUri);
3411 }
3412
3413 }
3414
3415 /**
3416 * Resets the lock icon. This method is called when we start a new load and
3417 * know the url to be loaded.
3418 */
3419 private void resetLockIcon(String url) {
3420 // Save the lock-icon state (we revert to it if the load gets cancelled)
3421 saveLockIcon();
3422
3423 mLockIconType = LOCK_ICON_UNSECURE;
3424 if (URLUtil.isHttpsUrl(url)) {
3425 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003426 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003427 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3428 " reset lock icon to " + mLockIconType);
3429 }
3430 }
3431
3432 updateLockIconImage(LOCK_ICON_UNSECURE);
3433 }
3434
Grace Klobaeb6eef42009-09-15 17:56:32 -07003435 /* package */ void setLockIconType(int type) {
3436 mLockIconType = type;
3437 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003438
Grace Klobaeb6eef42009-09-15 17:56:32 -07003439 /* package */ int getLockIconType() {
3440 return mLockIconType;
3441 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003442
Grace Klobaeb6eef42009-09-15 17:56:32 -07003443 /* package */ void setPrevLockType(int type) {
3444 mPrevLockType = type;
3445 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003446
Grace Klobaeb6eef42009-09-15 17:56:32 -07003447 /* package */ int getPrevLockType() {
3448 return mPrevLockType;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003449 }
3450
3451 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003452 * Update the lock icon to correspond to our latest state.
3453 */
3454 /* package */ void updateLockIconToLatest() {
3455 updateLockIconImage(mLockIconType);
3456 }
3457
3458 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003459 * Updates the lock-icon image in the title-bar.
3460 */
3461 private void updateLockIconImage(int lockIconType) {
3462 Drawable d = null;
3463 if (lockIconType == LOCK_ICON_SECURE) {
3464 d = mSecLockIcon;
3465 } else if (lockIconType == LOCK_ICON_MIXED) {
3466 d = mMixLockIcon;
3467 }
Leon Scroggins68579392009-09-15 15:31:54 -04003468 mTitleBar.setLock(d);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003469 if (mFakeTitleBar != null) {
3470 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003471 }
3472 }
3473
3474 /**
3475 * Displays a page-info dialog.
3476 * @param tab The tab to show info about
3477 * @param fromShowSSLCertificateOnError The flag that indicates whether
3478 * this dialog was opened from the SSL-certificate-on-error dialog or
3479 * not. This is important, since we need to know whether to return to
3480 * the parent dialog or simply dismiss.
3481 */
3482 private void showPageInfo(final TabControl.Tab tab,
3483 final boolean fromShowSSLCertificateOnError) {
3484 final LayoutInflater factory = LayoutInflater
3485 .from(this);
3486
3487 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3488
3489 final WebView view = tab.getWebView();
3490
3491 String url = null;
3492 String title = null;
3493
3494 if (view == null) {
3495 url = tab.getUrl();
3496 title = tab.getTitle();
3497 } else if (view == mTabControl.getCurrentWebView()) {
3498 // Use the cached title and url if this is the current WebView
3499 url = mUrl;
3500 title = mTitle;
3501 } else {
3502 url = view.getUrl();
3503 title = view.getTitle();
3504 }
3505
3506 if (url == null) {
3507 url = "";
3508 }
3509 if (title == null) {
3510 title = "";
3511 }
3512
3513 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3514 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3515
3516 mPageInfoView = tab;
3517 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3518
3519 AlertDialog.Builder alertDialogBuilder =
3520 new AlertDialog.Builder(this)
3521 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3522 .setView(pageInfoView)
3523 .setPositiveButton(
3524 R.string.ok,
3525 new DialogInterface.OnClickListener() {
3526 public void onClick(DialogInterface dialog,
3527 int whichButton) {
3528 mPageInfoDialog = null;
3529 mPageInfoView = null;
3530 mPageInfoFromShowSSLCertificateOnError = null;
3531
3532 // if we came here from the SSL error dialog
3533 if (fromShowSSLCertificateOnError) {
3534 // go back to the SSL error dialog
3535 showSSLCertificateOnError(
3536 mSSLCertificateOnErrorView,
3537 mSSLCertificateOnErrorHandler,
3538 mSSLCertificateOnErrorError);
3539 }
3540 }
3541 })
3542 .setOnCancelListener(
3543 new DialogInterface.OnCancelListener() {
3544 public void onCancel(DialogInterface dialog) {
3545 mPageInfoDialog = null;
3546 mPageInfoView = null;
3547 mPageInfoFromShowSSLCertificateOnError = null;
3548
3549 // if we came here from the SSL error dialog
3550 if (fromShowSSLCertificateOnError) {
3551 // go back to the SSL error dialog
3552 showSSLCertificateOnError(
3553 mSSLCertificateOnErrorView,
3554 mSSLCertificateOnErrorHandler,
3555 mSSLCertificateOnErrorError);
3556 }
3557 }
3558 });
3559
3560 // if we have a main top-level page SSL certificate set or a certificate
3561 // error
3562 if (fromShowSSLCertificateOnError ||
3563 (view != null && view.getCertificate() != null)) {
3564 // add a 'View Certificate' button
3565 alertDialogBuilder.setNeutralButton(
3566 R.string.view_certificate,
3567 new DialogInterface.OnClickListener() {
3568 public void onClick(DialogInterface dialog,
3569 int whichButton) {
3570 mPageInfoDialog = null;
3571 mPageInfoView = null;
3572 mPageInfoFromShowSSLCertificateOnError = null;
3573
3574 // if we came here from the SSL error dialog
3575 if (fromShowSSLCertificateOnError) {
3576 // go back to the SSL error dialog
3577 showSSLCertificateOnError(
3578 mSSLCertificateOnErrorView,
3579 mSSLCertificateOnErrorHandler,
3580 mSSLCertificateOnErrorError);
3581 } else {
3582 // otherwise, display the top-most certificate from
3583 // the chain
3584 if (view.getCertificate() != null) {
3585 showSSLCertificate(tab);
3586 }
3587 }
3588 }
3589 });
3590 }
3591
3592 mPageInfoDialog = alertDialogBuilder.show();
3593 }
3594
3595 /**
3596 * Displays the main top-level page SSL certificate dialog
3597 * (accessible from the Page-Info dialog).
3598 * @param tab The tab to show certificate for.
3599 */
3600 private void showSSLCertificate(final TabControl.Tab tab) {
3601 final View certificateView =
3602 inflateCertificateView(tab.getWebView().getCertificate());
3603 if (certificateView == null) {
3604 return;
3605 }
3606
3607 LayoutInflater factory = LayoutInflater.from(this);
3608
3609 final LinearLayout placeholder =
3610 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3611
3612 LinearLayout ll = (LinearLayout) factory.inflate(
3613 R.layout.ssl_success, placeholder);
3614 ((TextView)ll.findViewById(R.id.success))
3615 .setText(R.string.ssl_certificate_is_valid);
3616
3617 mSSLCertificateView = tab;
3618 mSSLCertificateDialog =
3619 new AlertDialog.Builder(this)
3620 .setTitle(R.string.ssl_certificate).setIcon(
3621 R.drawable.ic_dialog_browser_certificate_secure)
3622 .setView(certificateView)
3623 .setPositiveButton(R.string.ok,
3624 new DialogInterface.OnClickListener() {
3625 public void onClick(DialogInterface dialog,
3626 int whichButton) {
3627 mSSLCertificateDialog = null;
3628 mSSLCertificateView = null;
3629
3630 showPageInfo(tab, false);
3631 }
3632 })
3633 .setOnCancelListener(
3634 new DialogInterface.OnCancelListener() {
3635 public void onCancel(DialogInterface dialog) {
3636 mSSLCertificateDialog = null;
3637 mSSLCertificateView = null;
3638
3639 showPageInfo(tab, false);
3640 }
3641 })
3642 .show();
3643 }
3644
3645 /**
3646 * Displays the SSL error certificate dialog.
3647 * @param view The target web-view.
3648 * @param handler The SSL error handler responsible for cancelling the
3649 * connection that resulted in an SSL error or proceeding per user request.
3650 * @param error The SSL error object.
3651 */
3652 private void showSSLCertificateOnError(
3653 final WebView view, final SslErrorHandler handler, final SslError error) {
3654
3655 final View certificateView =
3656 inflateCertificateView(error.getCertificate());
3657 if (certificateView == null) {
3658 return;
3659 }
3660
3661 LayoutInflater factory = LayoutInflater.from(this);
3662
3663 final LinearLayout placeholder =
3664 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3665
3666 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3667 LinearLayout ll = (LinearLayout)factory
3668 .inflate(R.layout.ssl_warning, placeholder);
3669 ((TextView)ll.findViewById(R.id.warning))
3670 .setText(R.string.ssl_untrusted);
3671 }
3672
3673 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3674 LinearLayout ll = (LinearLayout)factory
3675 .inflate(R.layout.ssl_warning, placeholder);
3676 ((TextView)ll.findViewById(R.id.warning))
3677 .setText(R.string.ssl_mismatch);
3678 }
3679
3680 if (error.hasError(SslError.SSL_EXPIRED)) {
3681 LinearLayout ll = (LinearLayout)factory
3682 .inflate(R.layout.ssl_warning, placeholder);
3683 ((TextView)ll.findViewById(R.id.warning))
3684 .setText(R.string.ssl_expired);
3685 }
3686
3687 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3688 LinearLayout ll = (LinearLayout)factory
3689 .inflate(R.layout.ssl_warning, placeholder);
3690 ((TextView)ll.findViewById(R.id.warning))
3691 .setText(R.string.ssl_not_yet_valid);
3692 }
3693
3694 mSSLCertificateOnErrorHandler = handler;
3695 mSSLCertificateOnErrorView = view;
3696 mSSLCertificateOnErrorError = error;
3697 mSSLCertificateOnErrorDialog =
3698 new AlertDialog.Builder(this)
3699 .setTitle(R.string.ssl_certificate).setIcon(
3700 R.drawable.ic_dialog_browser_certificate_partially_secure)
3701 .setView(certificateView)
3702 .setPositiveButton(R.string.ok,
3703 new DialogInterface.OnClickListener() {
3704 public void onClick(DialogInterface dialog,
3705 int whichButton) {
3706 mSSLCertificateOnErrorDialog = null;
3707 mSSLCertificateOnErrorView = null;
3708 mSSLCertificateOnErrorHandler = null;
3709 mSSLCertificateOnErrorError = null;
3710
3711 mWebViewClient.onReceivedSslError(
3712 view, handler, error);
3713 }
3714 })
3715 .setNeutralButton(R.string.page_info_view,
3716 new DialogInterface.OnClickListener() {
3717 public void onClick(DialogInterface dialog,
3718 int whichButton) {
3719 mSSLCertificateOnErrorDialog = null;
3720
3721 // do not clear the dialog state: we will
3722 // need to show the dialog again once the
3723 // user is done exploring the page-info details
3724
3725 showPageInfo(mTabControl.getTabFromView(view),
3726 true);
3727 }
3728 })
3729 .setOnCancelListener(
3730 new DialogInterface.OnCancelListener() {
3731 public void onCancel(DialogInterface dialog) {
3732 mSSLCertificateOnErrorDialog = null;
3733 mSSLCertificateOnErrorView = null;
3734 mSSLCertificateOnErrorHandler = null;
3735 mSSLCertificateOnErrorError = null;
3736
3737 mWebViewClient.onReceivedSslError(
3738 view, handler, error);
3739 }
3740 })
3741 .show();
3742 }
3743
3744 /**
3745 * Inflates the SSL certificate view (helper method).
3746 * @param certificate The SSL certificate.
3747 * @return The resultant certificate view with issued-to, issued-by,
3748 * issued-on, expires-on, and possibly other fields set.
3749 * If the input certificate is null, returns null.
3750 */
3751 private View inflateCertificateView(SslCertificate certificate) {
3752 if (certificate == null) {
3753 return null;
3754 }
3755
3756 LayoutInflater factory = LayoutInflater.from(this);
3757
3758 View certificateView = factory.inflate(
3759 R.layout.ssl_certificate, null);
3760
3761 // issued to:
3762 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3763 if (issuedTo != null) {
3764 ((TextView) certificateView.findViewById(R.id.to_common))
3765 .setText(issuedTo.getCName());
3766 ((TextView) certificateView.findViewById(R.id.to_org))
3767 .setText(issuedTo.getOName());
3768 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3769 .setText(issuedTo.getUName());
3770 }
3771
3772 // issued by:
3773 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3774 if (issuedBy != null) {
3775 ((TextView) certificateView.findViewById(R.id.by_common))
3776 .setText(issuedBy.getCName());
3777 ((TextView) certificateView.findViewById(R.id.by_org))
3778 .setText(issuedBy.getOName());
3779 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3780 .setText(issuedBy.getUName());
3781 }
3782
3783 // issued on:
3784 String issuedOn = reformatCertificateDate(
3785 certificate.getValidNotBefore());
3786 ((TextView) certificateView.findViewById(R.id.issued_on))
3787 .setText(issuedOn);
3788
3789 // expires on:
3790 String expiresOn = reformatCertificateDate(
3791 certificate.getValidNotAfter());
3792 ((TextView) certificateView.findViewById(R.id.expires_on))
3793 .setText(expiresOn);
3794
3795 return certificateView;
3796 }
3797
3798 /**
3799 * Re-formats the certificate date (Date.toString()) string to
3800 * a properly localized date string.
3801 * @return Properly localized version of the certificate date string and
3802 * the original certificate date string if fails to localize.
3803 * If the original string is null, returns an empty string "".
3804 */
3805 private String reformatCertificateDate(String certificateDate) {
3806 String reformattedDate = null;
3807
3808 if (certificateDate != null) {
3809 Date date = null;
3810 try {
3811 date = java.text.DateFormat.getInstance().parse(certificateDate);
3812 } catch (ParseException e) {
3813 date = null;
3814 }
3815
3816 if (date != null) {
3817 reformattedDate =
3818 DateFormat.getDateFormat(this).format(date);
3819 }
3820 }
3821
3822 return reformattedDate != null ? reformattedDate :
3823 (certificateDate != null ? certificateDate : "");
3824 }
3825
3826 /**
3827 * Displays an http-authentication dialog.
3828 */
3829 private void showHttpAuthentication(final HttpAuthHandler handler,
3830 final String host, final String realm, final String title,
3831 final String name, final String password, int focusId) {
3832 LayoutInflater factory = LayoutInflater.from(this);
3833 final View v = factory
3834 .inflate(R.layout.http_authentication, null);
3835 if (name != null) {
3836 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3837 }
3838 if (password != null) {
3839 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3840 }
3841
3842 String titleText = title;
3843 if (titleText == null) {
3844 titleText = getText(R.string.sign_in_to).toString().replace(
3845 "%s1", host).replace("%s2", realm);
3846 }
3847
3848 mHttpAuthHandler = handler;
3849 AlertDialog dialog = new AlertDialog.Builder(this)
3850 .setTitle(titleText)
3851 .setIcon(android.R.drawable.ic_dialog_alert)
3852 .setView(v)
3853 .setPositiveButton(R.string.action,
3854 new DialogInterface.OnClickListener() {
3855 public void onClick(DialogInterface dialog,
3856 int whichButton) {
3857 String nm = ((EditText) v
3858 .findViewById(R.id.username_edit))
3859 .getText().toString();
3860 String pw = ((EditText) v
3861 .findViewById(R.id.password_edit))
3862 .getText().toString();
3863 BrowserActivity.this.setHttpAuthUsernamePassword
3864 (host, realm, nm, pw);
3865 handler.proceed(nm, pw);
3866 mHttpAuthenticationDialog = null;
3867 mHttpAuthHandler = null;
3868 }})
3869 .setNegativeButton(R.string.cancel,
3870 new DialogInterface.OnClickListener() {
3871 public void onClick(DialogInterface dialog,
3872 int whichButton) {
3873 handler.cancel();
3874 BrowserActivity.this.resetTitleAndRevertLockIcon();
3875 mHttpAuthenticationDialog = null;
3876 mHttpAuthHandler = null;
3877 }})
3878 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3879 public void onCancel(DialogInterface dialog) {
3880 handler.cancel();
3881 BrowserActivity.this.resetTitleAndRevertLockIcon();
3882 mHttpAuthenticationDialog = null;
3883 mHttpAuthHandler = null;
3884 }})
3885 .create();
3886 // Make the IME appear when the dialog is displayed if applicable.
3887 dialog.getWindow().setSoftInputMode(
3888 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3889 dialog.show();
3890 if (focusId != 0) {
3891 dialog.findViewById(focusId).requestFocus();
3892 } else {
3893 v.findViewById(R.id.username_edit).requestFocus();
3894 }
3895 mHttpAuthenticationDialog = dialog;
3896 }
3897
3898 public int getProgress() {
3899 WebView w = mTabControl.getCurrentWebView();
3900 if (w != null) {
3901 return w.getProgress();
3902 } else {
3903 return 100;
3904 }
3905 }
3906
3907 /**
3908 * Set HTTP authentication password.
3909 *
3910 * @param host The host for the password
3911 * @param realm The realm for the password
3912 * @param username The username for the password. If it is null, it means
3913 * password can't be saved.
3914 * @param password The password
3915 */
3916 public void setHttpAuthUsernamePassword(String host, String realm,
3917 String username,
3918 String password) {
3919 WebView w = mTabControl.getCurrentWebView();
3920 if (w != null) {
3921 w.setHttpAuthUsernamePassword(host, realm, username, password);
3922 }
3923 }
3924
3925 /**
3926 * connectivity manager says net has come or gone... inform the user
3927 * @param up true if net has come up, false if net has gone down
3928 */
3929 public void onNetworkToggle(boolean up) {
3930 if (up == mIsNetworkUp) {
3931 return;
3932 } else if (up) {
3933 mIsNetworkUp = true;
3934 if (mAlertDialog != null) {
3935 mAlertDialog.cancel();
3936 mAlertDialog = null;
3937 }
3938 } else {
3939 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003940 if (mInLoad) {
3941 createAndShowNetworkDialog();
3942 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003943 }
3944 WebView w = mTabControl.getCurrentWebView();
3945 if (w != null) {
3946 w.setNetworkAvailable(up);
3947 }
3948 }
3949
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003950 // This method shows the network dialog alerting the user that the net is
3951 // down. It will only show the dialog if mAlertDialog is null.
3952 private void createAndShowNetworkDialog() {
3953 if (mAlertDialog == null) {
3954 mAlertDialog = new AlertDialog.Builder(this)
3955 .setTitle(R.string.loadSuspendedTitle)
3956 .setMessage(R.string.loadSuspended)
3957 .setPositiveButton(R.string.ok, null)
3958 .show();
3959 }
3960 }
3961
The Android Open Source Project0c908882009-03-03 19:32:16 -08003962 @Override
3963 protected void onActivityResult(int requestCode, int resultCode,
3964 Intent intent) {
3965 switch (requestCode) {
3966 case COMBO_PAGE:
3967 if (resultCode == RESULT_OK && intent != null) {
3968 String data = intent.getAction();
3969 Bundle extras = intent.getExtras();
3970 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003971 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003972 } else {
3973 final TabControl.Tab currentTab =
3974 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003975 dismissSubWindow(currentTab);
3976 if (data != null && data.length() != 0) {
3977 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003978 }
3979 }
3980 }
3981 break;
3982 default:
3983 break;
3984 }
Leon Scroggins30444232009-09-04 18:36:20 -04003985 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003986 }
3987
3988 /*
3989 * This method is called as a result of the user selecting the options
3990 * menu to see the download window, or when a download changes state. It
3991 * shows the download window ontop of the current window.
3992 */
3993 /* package */ void viewDownloads(Uri downloadRecord) {
3994 Intent intent = new Intent(this,
3995 BrowserDownloadPage.class);
3996 intent.setData(downloadRecord);
3997 startActivityForResult(intent, this.DOWNLOAD_PAGE);
3998
3999 }
4000
Leon Scroggins160a7e72009-08-14 18:28:01 -04004001 /**
4002 * Open the Go page.
4003 * @param startWithHistory If true, open starting on the history tab.
4004 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004005 */
Leon Scroggins30444232009-09-04 18:36:20 -04004006 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004007 WebView current = mTabControl.getCurrentWebView();
4008 if (current == null) {
4009 return;
4010 }
4011 Intent intent = new Intent(this,
4012 CombinedBookmarkHistoryActivity.class);
4013 String title = current.getTitle();
4014 String url = current.getUrl();
4015 // Just in case the user opens bookmarks before a page finishes loading
4016 // so the current history item, and therefore the page, is null.
4017 if (null == url) {
4018 url = mLastEnteredUrl;
4019 // This can happen.
4020 if (null == url) {
4021 url = mSettings.getHomePage();
4022 }
4023 }
4024 // In case the web page has not yet received its associated title.
4025 if (title == null) {
4026 title = url;
4027 }
4028 intent.putExtra("title", title);
4029 intent.putExtra("url", url);
Leon Scroggins30444232009-09-04 18:36:20 -04004030 // Disable opening in a new window if we have maxed out the windows
4031 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4032 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004033 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004034 if (startWithHistory) {
4035 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4036 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4037 }
4038 startActivityForResult(intent, COMBO_PAGE);
4039 }
4040
4041 // Called when loading from context menu or LOAD_URL message
4042 private void loadURL(WebView view, String url) {
4043 // In case the user enters nothing.
4044 if (url != null && url.length() != 0 && view != null) {
4045 url = smartUrlFilter(url);
4046 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4047 view.loadUrl(url);
4048 }
4049 }
4050 }
4051
The Android Open Source Project0c908882009-03-03 19:32:16 -08004052 private String smartUrlFilter(Uri inUri) {
4053 if (inUri != null) {
4054 return smartUrlFilter(inUri.toString());
4055 }
4056 return null;
4057 }
4058
4059
4060 // get window count
4061
4062 int getWindowCount(){
4063 if(mTabControl != null){
4064 return mTabControl.getTabCount();
4065 }
4066 return 0;
4067 }
4068
Feng Qianb34f87a2009-03-24 21:27:26 -07004069 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004070 "(?i)" + // switch on case insensitive matching
4071 "(" + // begin group for schema
4072 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004073 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004074 ")" +
4075 "(.*)" );
4076
4077 /**
4078 * Attempts to determine whether user input is a URL or search
4079 * terms. Anything with a space is passed to search.
4080 *
4081 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4082 * "Http://" converts to "http://"
4083 *
4084 * @return Original or modified URL
4085 *
4086 */
4087 String smartUrlFilter(String url) {
4088
4089 String inUrl = url.trim();
4090 boolean hasSpace = inUrl.indexOf(' ') != -1;
4091
4092 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4093 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004094 // force scheme to lowercase
4095 String scheme = matcher.group(1);
4096 String lcScheme = scheme.toLowerCase();
4097 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004098 inUrl = lcScheme + matcher.group(2);
4099 }
4100 if (hasSpace) {
4101 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004102 }
4103 return inUrl;
4104 }
4105 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004106 // FIXME: Is this the correct place to add to searches?
4107 // what if someone else calls this function?
4108 int shortcut = parseUrlShortcut(inUrl);
4109 if (shortcut != SHORTCUT_INVALID) {
4110 Browser.addSearchUrl(mResolver, inUrl);
4111 String query = inUrl.substring(2);
4112 switch (shortcut) {
4113 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004114 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004115 case SHORTCUT_WIKIPEDIA_SEARCH:
4116 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4117 case SHORTCUT_DICTIONARY_SEARCH:
4118 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4119 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004120 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004121 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004122 }
4123 }
4124 } else {
4125 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4126 return URLUtil.guessUrl(inUrl);
4127 }
4128 }
4129
4130 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004131 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004132 }
4133
Ben Murdochbff2d602009-07-01 20:19:05 +01004134 /* package */ void setShouldShowErrorConsole(boolean flag) {
4135 if (flag == mShouldShowErrorConsole) {
4136 // Nothing to do.
4137 return;
4138 }
4139
4140 mShouldShowErrorConsole = flag;
4141
4142 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4143
4144 if (flag) {
4145 // Setting the show state of the console will cause it's the layout to be inflated.
4146 if (errorConsole.numberOfErrors() > 0) {
4147 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4148 } else {
4149 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4150 }
4151
4152 // Now we can add it to the main view.
4153 mErrorConsoleContainer.addView(errorConsole,
4154 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4155 ViewGroup.LayoutParams.WRAP_CONTENT));
4156 } else {
4157 mErrorConsoleContainer.removeView(errorConsole);
4158 }
4159
4160 }
4161
Grace Klobaeb6eef42009-09-15 17:56:32 -07004162 final static int LOCK_ICON_UNSECURE = 0;
4163 final static int LOCK_ICON_SECURE = 1;
4164 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004165
4166 private int mLockIconType = LOCK_ICON_UNSECURE;
4167 private int mPrevLockType = LOCK_ICON_UNSECURE;
4168
4169 private BrowserSettings mSettings;
4170 private TabControl mTabControl;
4171 private ContentResolver mResolver;
4172 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004173 private View mCustomView;
4174 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004175 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004176
4177 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4178 // view, we should rewrite this.
4179 private int mCurrentMenuState = 0;
4180 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004181 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004182 private static final int EMPTY_MENU = -1;
4183 private Menu mMenu;
4184
4185 private FindDialog mFindDialog;
4186 // Used to prevent chording to result in firing two shortcuts immediately
4187 // one after another. Fixes bug 1211714.
4188 boolean mCanChord;
4189
4190 private boolean mInLoad;
4191 private boolean mIsNetworkUp;
4192
4193 private boolean mPageStarted;
4194 private boolean mActivityInPause = true;
4195
4196 private boolean mMenuIsDown;
4197
4198 private final KeyTracker mKeyTracker = new KeyTracker(this);
4199
4200 // As trackball doesn't send repeat down, we have to track it ourselves
4201 private boolean mTrackTrackball;
4202
4203 private static boolean mInTrace;
4204
4205 // Performance probe
4206 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4207 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4208 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4209 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4210 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4211 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4212 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4213 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4214 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4215 };
4216
4217 private long mStart;
4218 private long mProcessStart;
4219 private long mUserStart;
4220 private long mSystemStart;
4221 private long mIdleStart;
4222 private long mIrqStart;
4223
4224 private long mUiStart;
4225
4226 private Drawable mMixLockIcon;
4227 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004228
4229 /* hold a ref so we can auto-cancel if necessary */
4230 private AlertDialog mAlertDialog;
4231
4232 // Wait for credentials before loading google.com
4233 private ProgressDialog mCredsDlg;
4234
4235 // The up-to-date URL and title (these can be different from those stored
4236 // in WebView, since it takes some time for the information in WebView to
4237 // get updated)
4238 private String mUrl;
4239 private String mTitle;
4240
4241 // As PageInfo has different style for landscape / portrait, we have
4242 // to re-open it when configuration changed
4243 private AlertDialog mPageInfoDialog;
4244 private TabControl.Tab mPageInfoView;
4245 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4246 // dialog, we should not just dismiss it, but should get back to the
4247 // SSL-certificate-on-error dialog. This flag is used to store this state
4248 private Boolean mPageInfoFromShowSSLCertificateOnError;
4249
4250 // as SSLCertificateOnError has different style for landscape / portrait,
4251 // we have to re-open it when configuration changed
4252 private AlertDialog mSSLCertificateOnErrorDialog;
4253 private WebView mSSLCertificateOnErrorView;
4254 private SslErrorHandler mSSLCertificateOnErrorHandler;
4255 private SslError mSSLCertificateOnErrorError;
4256
4257 // as SSLCertificate has different style for landscape / portrait, we
4258 // have to re-open it when configuration changed
4259 private AlertDialog mSSLCertificateDialog;
4260 private TabControl.Tab mSSLCertificateView;
4261
4262 // as HttpAuthentication has different style for landscape / portrait, we
4263 // have to re-open it when configuration changed
4264 private AlertDialog mHttpAuthenticationDialog;
4265 private HttpAuthHandler mHttpAuthHandler;
4266
4267 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4268 new FrameLayout.LayoutParams(
4269 ViewGroup.LayoutParams.FILL_PARENT,
4270 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004271 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4272 new FrameLayout.LayoutParams(
4273 ViewGroup.LayoutParams.FILL_PARENT,
4274 ViewGroup.LayoutParams.FILL_PARENT,
4275 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004276 // Google search
4277 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004278 // Wikipedia search
4279 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4280 // Dictionary search
4281 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4282 // Google Mobile Local search
4283 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4284
4285 final static String QUERY_PLACE_HOLDER = "%s";
4286
4287 // "source" parameter for Google search through search key
4288 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4289 // "source" parameter for Google search through goto menu
4290 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4291 // "source" parameter for Google search through simplily type
4292 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4293 // "source" parameter for Google search suggested by the browser
4294 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4295 // "source" parameter for Google search from unknown source
4296 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4297
4298 private final static String LOGTAG = "browser";
4299
The Android Open Source Project0c908882009-03-03 19:32:16 -08004300 private String mLastEnteredUrl;
4301
4302 private PowerManager.WakeLock mWakeLock;
4303 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4304
4305 private Toast mStopToast;
4306
Leon Scroggins68579392009-09-15 15:31:54 -04004307 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004308
Ben Murdochbff2d602009-07-01 20:19:05 +01004309 private LinearLayout mErrorConsoleContainer = null;
4310 private boolean mShouldShowErrorConsole = false;
4311
The Android Open Source Project0c908882009-03-03 19:32:16 -08004312 // As the ids are dynamically created, we can't guarantee that they will
4313 // be in sequence, so this static array maps ids to a window number.
4314 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4315 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4316 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4317 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4318
4319 // monitor platform changes
4320 private IntentFilter mNetworkStateChangedFilter;
4321 private BroadcastReceiver mNetworkStateIntentReceiver;
4322
Grace Klobab4da0ad2009-05-14 14:45:40 -07004323 private BroadcastReceiver mPackageInstallationReceiver;
4324
The Android Open Source Project0c908882009-03-03 19:32:16 -08004325 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004326 final static int COMBO_PAGE = 1;
4327 final static int DOWNLOAD_PAGE = 2;
4328 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004329
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004330 /**
4331 * A UrlData class to abstract how the content will be set to WebView.
4332 * This base class uses loadUrl to show the content.
4333 */
4334 private static class UrlData {
4335 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004336 byte[] mPostData;
4337
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004338 UrlData(String url) {
4339 this.mUrl = url;
4340 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004341
4342 void setPostData(byte[] postData) {
4343 mPostData = postData;
4344 }
4345
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004346 boolean isEmpty() {
4347 return mUrl == null || mUrl.length() == 0;
4348 }
4349
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004350 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004351 if (mPostData != null) {
4352 webView.postUrl(mUrl, mPostData);
4353 } else {
4354 webView.loadUrl(mUrl);
4355 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004356 }
4357 };
4358
4359 /**
4360 * A subclass of UrlData class that can display inlined content using
4361 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4362 */
4363 private static class InlinedUrlData extends UrlData {
4364 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4365 super(failUrl);
4366 mInlined = inlined;
4367 mMimeType = mimeType;
4368 mEncoding = encoding;
4369 }
4370 String mMimeType;
4371 String mInlined;
4372 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004373 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004374 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004375 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004376 }
4377
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004378 @Override
4379 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004380 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4381 }
4382 }
4383
Leon Scroggins1f005d32009-08-10 17:36:42 -04004384 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004385}