blob: 0cecd85d5046eb5938590fd4d8b86b7f2cb61576 [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;
59import android.net.Uri;
60import android.net.WebAddress;
61import android.net.http.EventHandler;
62import android.net.http.SslCertificate;
63import android.net.http.SslError;
64import android.os.AsyncTask;
65import android.os.Bundle;
66import android.os.Debug;
67import android.os.Environment;
68import android.os.Handler;
69import android.os.IBinder;
70import android.os.Message;
71import android.os.PowerManager;
72import android.os.Process;
73import android.os.RemoteException;
74import android.os.ServiceManager;
75import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080076import android.provider.Browser;
77import android.provider.Contacts;
78import android.provider.Downloads;
79import android.provider.MediaStore;
80import android.provider.Contacts.Intents.Insert;
81import android.text.IClipboard;
82import android.text.TextUtils;
83import android.text.format.DateFormat;
84import android.text.util.Regex;
The Android Open Source Project0c908882009-03-03 19:32:16 -080085import android.util.Log;
86import android.view.ContextMenu;
87import android.view.Gravity;
88import android.view.KeyEvent;
89import android.view.LayoutInflater;
90import android.view.Menu;
91import android.view.MenuInflater;
92import android.view.MenuItem;
93import android.view.View;
94import android.view.ViewGroup;
95import android.view.Window;
96import android.view.WindowManager;
97import android.view.ContextMenu.ContextMenuInfo;
98import android.view.MenuItem.OnMenuItemClickListener;
99import android.view.animation.AlphaAnimation;
100import android.view.animation.Animation;
101import android.view.animation.AnimationSet;
102import android.view.animation.DecelerateInterpolator;
103import android.view.animation.ScaleAnimation;
104import android.view.animation.TranslateAnimation;
105import android.webkit.CookieManager;
106import android.webkit.CookieSyncManager;
107import android.webkit.DownloadListener;
Steve Block2bc69912009-07-30 14:45:13 +0100108import android.webkit.GeolocationPermissions;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800109import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -0700110import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800111import android.webkit.SslErrorHandler;
112import android.webkit.URLUtil;
113import android.webkit.WebChromeClient;
Andrei Popescuc9b55562009-07-07 10:51:15 +0100114import android.webkit.WebChromeClient.CustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800115import android.webkit.WebHistoryItem;
116import android.webkit.WebIconDatabase;
Ben Murdoch092dd5d2009-04-22 12:34:12 +0100117import android.webkit.WebStorage;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import android.webkit.WebView;
119import android.webkit.WebViewClient;
120import android.widget.EditText;
121import android.widget.FrameLayout;
122import android.widget.LinearLayout;
123import android.widget.TextView;
124import android.widget.Toast;
125
126import java.io.BufferedOutputStream;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400127import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128import java.io.File;
129import java.io.FileInputStream;
130import java.io.FileOutputStream;
131import java.io.IOException;
132import java.io.InputStream;
133import java.net.MalformedURLException;
134import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700135import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800136import java.net.URL;
137import java.net.URLEncoder;
138import java.text.ParseException;
139import java.util.Date;
140import java.util.Enumeration;
141import java.util.HashMap;
Patrick Scott37911c72009-03-24 18:02:58 -0700142import java.util.LinkedList;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800143import java.util.Vector;
144import java.util.regex.Matcher;
145import java.util.regex.Pattern;
146import java.util.zip.ZipEntry;
147import java.util.zip.ZipFile;
148
149public class BrowserActivity extends Activity
150 implements KeyTracker.OnKeyTracker,
151 View.OnCreateContextMenuListener,
152 DownloadListener {
153
Dave Bort31a6d1c2009-04-13 15:56:49 -0700154 /* Define some aliases to make these debugging flags easier to refer to.
155 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
156 */
157 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
158 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
159 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
160
The Android Open Source Project0c908882009-03-03 19:32:16 -0800161 private IGoogleLoginService mGls = null;
162 private ServiceConnection mGlsConnection = null;
163
164 private SensorManager mSensorManager = null;
165
Satish Sampath565505b2009-05-29 15:37:27 +0100166 // These are single-character shortcuts for searching popular sources.
167 private static final int SHORTCUT_INVALID = 0;
168 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
169 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
170 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
171 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
172
The Android Open Source Project0c908882009-03-03 19:32:16 -0800173 /* Whitelisted webpages
174 private static HashSet<String> sWhiteList;
175
176 static {
177 sWhiteList = new HashSet<String>();
178 sWhiteList.add("cnn.com/");
179 sWhiteList.add("espn.go.com/");
180 sWhiteList.add("nytimes.com/");
181 sWhiteList.add("engadget.com/");
182 sWhiteList.add("yahoo.com/");
183 sWhiteList.add("msn.com/");
184 sWhiteList.add("amazon.com/");
185 sWhiteList.add("consumerist.com/");
186 sWhiteList.add("google.com/m/news");
187 }
188 */
189
190 private void setupHomePage() {
191 final Runnable getAccount = new Runnable() {
192 public void run() {
193 // Lower priority
194 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
195 // get the default home page
196 String homepage = mSettings.getHomePage();
197
198 try {
199 if (mGls == null) return;
200
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700201 if (!homepage.startsWith("http://www.google.")) return;
202 if (homepage.indexOf('?') == -1) return;
203
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
205 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
206
207 // three cases:
208 //
209 // hostedUser == googleUser
210 // The device has only a google account
211 //
212 // hostedUser != googleUser
213 // The device has a hosted account and a google account
214 //
215 // hostedUser != null, googleUser == null
216 // The device has only a hosted account (so far)
217
218 // developers might have no accounts at all
219 if (hostedUser == null) return;
220
221 if (googleUser == null || !hostedUser.equals(googleUser)) {
222 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700223 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800224 }
225 } catch (RemoteException ignore) {
226 // Login service died; carry on
227 } catch (RuntimeException ignore) {
228 // Login service died; carry on
229 } finally {
230 finish(homepage);
231 }
232 }
233
234 private void finish(final String homepage) {
235 mHandler.post(new Runnable() {
236 public void run() {
237 mSettings.setHomePage(BrowserActivity.this, homepage);
238 resumeAfterCredentials();
239
240 // as this is running in a separate thread,
241 // BrowserActivity's onDestroy() may have been called,
242 // which also calls unbindService().
243 if (mGlsConnection != null) {
244 // we no longer need to keep GLS open
245 unbindService(mGlsConnection);
246 mGlsConnection = null;
247 }
248 } });
249 } };
250
251 final boolean[] done = { false };
252
253 // Open a connection to the Google Login Service. The first
254 // time the connection is established, set up the homepage depending on
255 // the account in a background thread.
256 mGlsConnection = new ServiceConnection() {
257 public void onServiceConnected(ComponentName className, IBinder service) {
258 mGls = IGoogleLoginService.Stub.asInterface(service);
259 if (done[0] == false) {
260 done[0] = true;
261 Thread account = new Thread(getAccount);
262 account.setName("GLSAccount");
263 account.start();
264 }
265 }
266 public void onServiceDisconnected(ComponentName className) {
267 mGls = null;
268 }
269 };
270
271 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
272 mGlsConnection, Context.BIND_AUTO_CREATE);
273 }
274
Cary Clarka9771242009-08-11 16:42:26 -0400275 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800276 @Override
277 public Void doInBackground(File... files) {
278 if (files != null) {
279 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400280 if (!f.delete()) {
281 Log.e(LOGTAG, f.getPath() + " was not deleted");
282 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800283 }
284 }
285 return null;
286 }
287 }
288
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400289 /**
290 * This layout holds everything you see below the status bar, including the
291 * error console, the custom view container, and the webviews.
292 */
293 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400294
The Android Open Source Project0c908882009-03-03 19:32:16 -0800295 @Override public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700296 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800297 Log.v(LOGTAG, this + " onStart");
298 }
299 super.onCreate(icicle);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400300 this.requestWindowFeature(Window.FEATURE_NO_TITLE);
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)) {
360 boolean down = intent.getBooleanExtra(
361 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
362 onNetworkToggle(!down);
363 }
364 }
365 };
366
Grace Kloba615c6c92009-08-03 10:22:44 -0700367 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
368 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
369 filter.addDataScheme("package");
370 mPackageInstallationReceiver = new BroadcastReceiver() {
371 @Override
372 public void onReceive(Context context, Intent intent) {
373 final String action = intent.getAction();
374 final String packageName = intent.getData()
375 .getSchemeSpecificPart();
376 final boolean replacing = intent.getBooleanExtra(
377 Intent.EXTRA_REPLACING, false);
378 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
379 // if it is replacing, refreshPlugins() when adding
380 return;
381 }
382 PackageManager pm = BrowserActivity.this.getPackageManager();
383 PackageInfo pkgInfo = null;
384 try {
385 pkgInfo = pm.getPackageInfo(packageName,
386 PackageManager.GET_PERMISSIONS);
387 } catch (PackageManager.NameNotFoundException e) {
388 return;
389 }
390 if (pkgInfo != null) {
391 String permissions[] = pkgInfo.requestedPermissions;
392 if (permissions == null) {
393 return;
394 }
395 boolean permissionOk = false;
396 for (String permit : permissions) {
397 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
398 permissionOk = true;
399 break;
400 }
401 }
402 if (permissionOk) {
403 PluginManager.getInstance(BrowserActivity.this)
404 .refreshPlugins(
405 Intent.ACTION_PACKAGE_ADDED
406 .equals(action));
407 }
408 }
409 }
410 };
411 registerReceiver(mPackageInstallationReceiver, filter);
412
Satish Sampath565505b2009-05-29 15:37:27 +0100413 // If this was a web search request, pass it on to the default web search provider.
414 if (handleWebSearchIntent(getIntent())) {
415 moveTaskToBack(true);
416 return;
417 }
418
The Android Open Source Project0c908882009-03-03 19:32:16 -0800419 if (!mTabControl.restoreState(icicle)) {
420 // clear up the thumbnail directory if we can't restore the state as
421 // none of the files in the directory are referenced any more.
422 new ClearThumbnails().execute(
423 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700424 // there is no quit on Android. But if we can't restore the state,
425 // we can treat it as a new Browser, remove the old session cookies.
426 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800427 final Intent intent = getIntent();
428 final Bundle extra = intent.getExtras();
429 // Create an initial tab.
430 // If the intent is ACTION_VIEW and data is not null, the Browser is
431 // invoked to view the content by another application. In this case,
432 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700433 UrlData urlData = getUrlDataFromIntent(intent);
434
The Android Open Source Project0c908882009-03-03 19:32:16 -0800435 final TabControl.Tab t = mTabControl.createNewTab(
436 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700437 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700438 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800439 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800440 attachTabToContentView(t);
441 WebView webView = t.getWebView();
442 if (extra != null) {
443 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
444 if (scale > 0 && scale <= 1000) {
445 webView.setInitialScale(scale);
446 }
447 }
448 // If we are not restoring from an icicle, then there is a high
449 // likely hood this is the first run. So, check to see if the
450 // homepage needs to be configured and copy any plugins from our
451 // asset directory to the data partition.
452 if ((extra == null || !extra.getBoolean("testing"))
453 && !mSettings.isLoginInitialized()) {
454 setupHomePage();
455 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800456
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700457 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400458 if (mSettings.isLoginInitialized()) {
459 webView.loadUrl(mSettings.getHomePage());
460 } else {
461 waitForCredentials();
462 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800463 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700464 if (extra != null) {
465 urlData.setPostData(extra
466 .getByteArray(Browser.EXTRA_POST_DATA));
467 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700468 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800469 }
470 } else {
471 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400472 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800473 attachTabToContentView(mTabControl.getCurrentTab());
474 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700475
Feng Qianb3c02da2009-06-29 15:58:08 -0700476 // Read JavaScript flags if it exists.
477 String jsFlags = mSettings.getJsFlags();
478 if (jsFlags.trim().length() != 0) {
479 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
480 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800481 }
482
483 @Override
484 protected void onNewIntent(Intent intent) {
485 TabControl.Tab current = mTabControl.getCurrentTab();
486 // When a tab is closed on exit, the current tab index is set to -1.
487 // Reset before proceed as Browser requires the current tab to be set.
488 if (current == null) {
489 // Try to reset the tab in case the index was incorrect.
490 current = mTabControl.getTab(0);
491 if (current == null) {
492 // No tabs at all so just ignore this intent.
493 return;
494 }
495 mTabControl.setCurrentTab(current);
496 attachTabToContentView(current);
497 resetTitleAndIcon(current.getWebView());
498 }
499 final String action = intent.getAction();
500 final int flags = intent.getFlags();
501 if (Intent.ACTION_MAIN.equals(action) ||
502 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
503 // just resume the browser
504 return;
505 }
506 if (Intent.ACTION_VIEW.equals(action)
507 || Intent.ACTION_SEARCH.equals(action)
508 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
509 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100510 // If this was a search request (e.g. search query directly typed into the address bar),
511 // pass it on to the default web search provider.
512 if (handleWebSearchIntent(intent)) {
513 return;
514 }
515
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700516 UrlData urlData = getUrlDataFromIntent(intent);
517 if (urlData.isEmpty()) {
518 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800519 }
Grace Kloba81678d92009-06-30 07:09:56 -0700520 urlData.setPostData(intent
521 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700522
Grace Klobacc634032009-07-28 15:58:19 -0700523 final String appId = intent
524 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
525 if (Intent.ACTION_VIEW.equals(action)
526 && !getPackageName().equals(appId)
527 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Patrick Scottcd115892009-07-16 09:42:58 -0400528 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700529 if (appTab != null) {
530 Log.i(LOGTAG, "Reusing tab for " + appId);
531 // Dismiss the subwindow if applicable.
532 dismissSubWindow(appTab);
533 // Since we might kill the WebView, remove it from the
534 // content view first.
535 removeTabFromContentView(appTab);
536 // Recreate the main WebView after destroying the old one.
537 // If the WebView has the same original url and is on that
538 // page, it can be reused.
539 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700540 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100541
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700542 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400543 switchToTab(mTabControl.getTabIndex(appTab));
544 if (needsLoad) {
545 urlData.loadIn(appTab.getWebView());
546 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700547 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400548 // If the tab was the current tab, we have to attach
549 // it to the view system again.
550 attachTabToContentView(appTab);
551 if (needsLoad) {
552 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700553 }
554 }
555 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400556 } else {
557 // No matching application tab, try to find a regular tab
558 // with a matching url.
559 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400560 if (appTab != null) {
561 if (current != appTab) {
562 switchToTab(mTabControl.getTabIndex(appTab));
563 }
564 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400565 } else {
566 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
567 // will be opened in a new tab unless we have reached
568 // MAX_TABS. Then the url will be opened in the current
569 // tab. If a new tab is created, it will have "true" for
570 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400571 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400572 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700573 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800574 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700575 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800576 mSettings.toggleDebugSettings();
577 return;
578 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400579 // Get rid of the subwindow if it exists
580 dismissSubWindow(current);
581 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800582 }
583 }
584 }
585
Satish Sampath565505b2009-05-29 15:37:27 +0100586 private int parseUrlShortcut(String url) {
587 if (url == null) return SHORTCUT_INVALID;
588
589 // FIXME: quick search, need to be customized by setting
590 if (url.length() > 2 && url.charAt(1) == ' ') {
591 switch (url.charAt(0)) {
592 case 'g': return SHORTCUT_GOOGLE_SEARCH;
593 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
594 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
595 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
596 }
597 }
598 return SHORTCUT_INVALID;
599 }
600
601 /**
602 * Launches the default web search activity with the query parameters if the given intent's data
603 * are identified as plain search terms and not URLs/shortcuts.
604 * @return true if the intent was handled and web search activity was launched, false if not.
605 */
606 private boolean handleWebSearchIntent(Intent intent) {
607 if (intent == null) return false;
608
609 String url = null;
610 final String action = intent.getAction();
611 if (Intent.ACTION_VIEW.equals(action)) {
612 url = intent.getData().toString();
613 } else if (Intent.ACTION_SEARCH.equals(action)
614 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
615 || Intent.ACTION_WEB_SEARCH.equals(action)) {
616 url = intent.getStringExtra(SearchManager.QUERY);
617 }
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100618 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA));
Satish Sampath565505b2009-05-29 15:37:27 +0100619 }
620
621 /**
622 * Launches the default web search activity with the query parameters if the given url string
623 * was identified as plain search terms and not URL/shortcut.
624 * @return true if the request was handled and web search activity was launched, false if not.
625 */
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100626 private boolean handleWebSearchRequest(String inUrl, Bundle appData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100627 if (inUrl == null) return false;
628
629 // In general, we shouldn't modify URL from Intent.
630 // But currently, we get the user-typed URL from search box as well.
631 String url = fixUrl(inUrl).trim();
632
633 // URLs and site specific search shortcuts are handled by the regular flow of control, so
634 // return early.
635 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100636 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100637 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
638 return false;
639 }
640
641 Browser.updateVisitedHistory(mResolver, url, false);
642 Browser.addSearchUrl(mResolver, url);
643
644 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
645 intent.addCategory(Intent.CATEGORY_DEFAULT);
646 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100647 if (appData != null) {
648 intent.putExtra(SearchManager.APP_DATA, appData);
649 }
Grace Klobacc634032009-07-28 15:58:19 -0700650 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100651 startActivity(intent);
652
653 return true;
654 }
655
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700656 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800657 String url = null;
658 if (intent != null) {
659 final String action = intent.getAction();
660 if (Intent.ACTION_VIEW.equals(action)) {
661 url = smartUrlFilter(intent.getData());
662 if (url != null && url.startsWith("content:")) {
663 /* Append mimetype so webview knows how to display */
664 String mimeType = intent.resolveType(getContentResolver());
665 if (mimeType != null) {
666 url += "?" + mimeType;
667 }
668 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700669 if ("inline:".equals(url)) {
670 return new InlinedUrlData(
671 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
672 intent.getType(),
673 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
674 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
675 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800676 } else if (Intent.ACTION_SEARCH.equals(action)
677 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
678 || Intent.ACTION_WEB_SEARCH.equals(action)) {
679 url = intent.getStringExtra(SearchManager.QUERY);
680 if (url != null) {
681 mLastEnteredUrl = url;
682 // Don't add Urls, just search terms.
683 // Urls will get added when the page is loaded.
684 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
685 Browser.updateVisitedHistory(mResolver, url, false);
686 }
687 // In general, we shouldn't modify URL from Intent.
688 // But currently, we get the user-typed URL from search box as well.
689 url = fixUrl(url);
690 url = smartUrlFilter(url);
691 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
692 if (url.contains(searchSource)) {
693 String source = null;
694 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
695 if (appData != null) {
696 source = appData.getString(SearchManager.SOURCE);
697 }
698 if (TextUtils.isEmpty(source)) {
699 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
700 }
701 url = url.replace(searchSource, "&source=android-"+source+"&");
702 }
703 }
704 }
705 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700706 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800707 }
708
709 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400710 // FIXME: Converting the url to lower case
711 // duplicates functionality in smartUrlFilter().
712 // However, changing all current callers of fixUrl to
713 // call smartUrlFilter in addition may have unwanted
714 // consequences, and is deferred for now.
715 int colon = inUrl.indexOf(':');
716 boolean allLower = true;
717 for (int index = 0; index < colon; index++) {
718 char ch = inUrl.charAt(index);
719 if (!Character.isLetter(ch)) {
720 break;
721 }
722 allLower &= Character.isLowerCase(ch);
723 if (index == colon - 1 && !allLower) {
724 inUrl = inUrl.substring(0, colon).toLowerCase()
725 + inUrl.substring(colon);
726 }
727 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800728 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
729 return inUrl;
730 if (inUrl.startsWith("http:") ||
731 inUrl.startsWith("https:")) {
732 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
733 inUrl = inUrl.replaceFirst("/", "//");
734 } else inUrl = inUrl.replaceFirst(":", "://");
735 }
736 return inUrl;
737 }
738
739 /**
740 * Looking for the pattern like this
741 *
742 * *
743 * * *
744 * *** * *******
745 * * *
746 * * *
747 * *
748 */
749 private final SensorListener mSensorListener = new SensorListener() {
750 private long mLastGestureTime;
751 private float[] mPrev = new float[3];
752 private float[] mPrevDiff = new float[3];
753 private float[] mDiff = new float[3];
754 private float[] mRevertDiff = new float[3];
755
756 public void onSensorChanged(int sensor, float[] values) {
757 boolean show = false;
758 float[] diff = new float[3];
759
760 for (int i = 0; i < 3; i++) {
761 diff[i] = values[i] - mPrev[i];
762 if (Math.abs(diff[i]) > 1) {
763 show = true;
764 }
765 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
766 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
767 // start track when there is a big move, or revert
768 mRevertDiff[i] = mDiff[i];
769 mDiff[i] = 0;
770 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
771 // reset when it is flat
772 mDiff[i] = mRevertDiff[i] = 0;
773 }
774 mDiff[i] += diff[i];
775 mPrevDiff[i] = diff[i];
776 mPrev[i] = values[i];
777 }
778
779 if (false) {
780 // only shows if we think the delta is big enough, in an attempt
781 // to detect "serious" moves left/right or up/down
782 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
783 + values[0] + ", " + values[1] + ", " + values[2] + ")"
784 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
785 + ")");
786 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
787 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
788 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
789 + mRevertDiff[2] + ")");
790 }
791
792 long now = android.os.SystemClock.uptimeMillis();
793 if (now - mLastGestureTime > 1000) {
794 mLastGestureTime = 0;
795
796 float y = mDiff[1];
797 float z = mDiff[2];
798 float ay = Math.abs(y);
799 float az = Math.abs(z);
800 float ry = mRevertDiff[1];
801 float rz = mRevertDiff[2];
802 float ary = Math.abs(ry);
803 float arz = Math.abs(rz);
804 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
805 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
806
807 if ((gestY || gestZ) && !(gestY && gestZ)) {
808 WebView view = mTabControl.getCurrentWebView();
809
810 if (view != null) {
811 if (gestZ) {
812 if (z < 0) {
813 view.zoomOut();
814 } else {
815 view.zoomIn();
816 }
817 } else {
818 view.flingScroll(0, Math.round(y * 100));
819 }
820 }
821 mLastGestureTime = now;
822 }
823 }
824 }
825
826 public void onAccuracyChanged(int sensor, int accuracy) {
827 // TODO Auto-generated method stub
828
829 }
830 };
831
832 @Override protected void onResume() {
833 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700834 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800835 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
836 }
837
838 if (!mActivityInPause) {
839 Log.e(LOGTAG, "BrowserActivity is already resumed.");
840 return;
841 }
842
Mike Reed7bfa63b2009-05-28 11:08:32 -0400843 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800844 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400845 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800846
847 if (mWakeLock.isHeld()) {
848 mHandler.removeMessages(RELEASE_WAKELOCK);
849 mWakeLock.release();
850 }
851
852 if (mCredsDlg != null) {
853 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
854 // In case credential request never comes back
855 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
856 }
857 }
858
859 registerReceiver(mNetworkStateIntentReceiver,
860 mNetworkStateChangedFilter);
861 WebView.enablePlatformNotifications();
862
863 if (mSettings.doFlick()) {
864 if (mSensorManager == null) {
865 mSensorManager = (SensorManager) getSystemService(
866 Context.SENSOR_SERVICE);
867 }
868 mSensorManager.registerListener(mSensorListener,
869 SensorManager.SENSOR_ACCELEROMETER,
870 SensorManager.SENSOR_DELAY_FASTEST);
871 } else {
872 mSensorManager = null;
873 }
874 }
875
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400876 /**
877 * Since the actual title bar is embedded in the WebView, and removing it
878 * would change its appearance, create a temporary title bar to go at
879 * the top of the screen while the menu is open.
880 */
881 private TitleBar mFakeTitleBar;
882
883 /**
884 * Keeps track of whether the options menu is open. This is important in
885 * determining whether to show or hide the title bar overlay.
886 */
887 private boolean mOptionsMenuOpen;
888
889 /**
890 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
891 * of whether the configuration has changed. The first onMenuOpened call
892 * after a configuration change is simply a reopening of the same menu
893 * (i.e. mIconView did not change).
894 */
895 private boolean mConfigChanged;
896
897 /**
898 * Whether or not the options menu is in its smaller, icon menu form. When
899 * true, we want the title bar overlay to be up. When false, we do not.
900 * Only meaningful if mOptionsMenuOpen is true.
901 */
902 private boolean mIconView;
903
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400904 @Override
905 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400906 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
907 if (mOptionsMenuOpen) {
908 if (mConfigChanged) {
909 // We do not need to make any changes to the state of the
910 // title bar, since the only thing that happened was a
911 // change in orientation
912 mConfigChanged = false;
913 } else {
914 if (mIconView) {
915 // Switching the menu to expanded view, so hide the
916 // title bar.
917 hideFakeTitleBar();
918 mIconView = false;
919 } else {
920 // Switching the menu back to icon view, so show the
921 // title bar once again.
922 showFakeTitleBar();
923 mIconView = true;
924 }
925 }
926 } else {
927 // The options menu is closed, so open it, and show the title
928 showFakeTitleBar();
929 mOptionsMenuOpen = true;
930 mConfigChanged = false;
931 mIconView = true;
932 }
933 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400934 return true;
935 }
936
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400937 private void showFakeTitleBar() {
Leon Scroggins43de6162009-09-14 19:59:58 -0400938 if (mFakeTitleBar == null || mActiveTabsPage != null) {
Leon Scrogginsf4bb18a2009-09-11 18:37:53 -0400939 final WebView webView = getTopWindow();
Leon Scroggins68579392009-09-15 15:31:54 -0400940 mFakeTitleBar = new TitleBar(this);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400941 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
942 mFakeTitleBar.setProgress(webView.getProgress());
943 mFakeTitleBar.setFavicon(webView.getFavicon());
944 updateLockIconToLatest();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400945
946 WindowManager manager
947 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
948
949 // Add the title bar to the window manager so it can receive touches
950 // while the menu is up
951 WindowManager.LayoutParams params
952 = new WindowManager.LayoutParams(
953 ViewGroup.LayoutParams.FILL_PARENT,
954 ViewGroup.LayoutParams.WRAP_CONTENT,
955 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
956 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
957 PixelFormat.OPAQUE);
958 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400959 WebView mainView = mTabControl.getCurrentWebView();
960 params.windowAnimations = mainView == null
961 || mainView.getScrollY() != 0
962 ? com.android.internal.R.style.Animation_DropDownDown : 0;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400963 // XXX : Without providing an offset, the fake title bar will be
964 // placed underneath the status bar. Use the global visible rect
965 // of mBrowserFrameLayout to determine the bottom of the status bar
966 Rect rectangle = new Rect();
967 mBrowserFrameLayout.getGlobalVisibleRect(rectangle);
968 params.y = rectangle.top;
969 manager.addView(mFakeTitleBar, params);
970 }
971 }
972
973 @Override
974 public void onOptionsMenuClosed(Menu menu) {
975 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400976 if (!mInLoad) {
977 hideFakeTitleBar();
978 } else if (!mIconView) {
979 // The page is currently loading, and we are in expanded mode, so
980 // we were not showing the menu. Show it once again. It will be
981 // removed when the page finishes.
982 showFakeTitleBar();
983 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400984 }
985 private void hideFakeTitleBar() {
986 if (mFakeTitleBar == null) return;
987 WindowManager manager
988 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
989 manager.removeView(mFakeTitleBar);
990 mFakeTitleBar = null;
991 }
992
The Android Open Source Project0c908882009-03-03 19:32:16 -0800993 /**
994 * onSaveInstanceState(Bundle map)
995 * onSaveInstanceState is called right before onStop(). The map contains
996 * the saved state.
997 */
998 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700999 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001000 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1001 }
1002 // the default implementation requires each view to have an id. As the
1003 // browser handles the state itself and it doesn't use id for the views,
1004 // don't call the default implementation. Otherwise it will trigger the
1005 // warning like this, "couldn't save which view has focus because the
1006 // focused view XXX has no id".
1007
1008 // Save all the tabs
1009 mTabControl.saveState(outState);
1010 }
1011
1012 @Override protected void onPause() {
1013 super.onPause();
1014
1015 if (mActivityInPause) {
1016 Log.e(LOGTAG, "BrowserActivity is already paused.");
1017 return;
1018 }
1019
Mike Reed7bfa63b2009-05-28 11:08:32 -04001020 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001021 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001022 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001023 mWakeLock.acquire();
1024 mHandler.sendMessageDelayed(mHandler
1025 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1026 }
1027
1028 // Clear the credentials toast if it is up
1029 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1030 mCredsDlg.dismiss();
1031 }
1032 mCredsDlg = null;
1033
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001034 // FIXME: This removes the active tabs page and resets the menu to
1035 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1036 // but then we would need to save it in onSaveInstanceState and restore
1037 // it in onCreate/onRestoreInstanceState
1038 if (mActiveTabsPage != null) {
1039 removeActiveTabPage(true);
1040 }
1041
The Android Open Source Project0c908882009-03-03 19:32:16 -08001042 cancelStopToast();
1043
1044 // unregister network state listener
1045 unregisterReceiver(mNetworkStateIntentReceiver);
1046 WebView.disablePlatformNotifications();
1047
1048 if (mSensorManager != null) {
1049 mSensorManager.unregisterListener(mSensorListener);
1050 }
1051 }
1052
1053 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001054 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001055 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1056 }
1057 super.onDestroy();
1058 // Remove the current tab and sub window
1059 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001060 if (t != null) {
1061 dismissSubWindow(t);
1062 removeTabFromContentView(t);
1063 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001064 // Destroy all the tabs
1065 mTabControl.destroy();
1066 WebIconDatabase.getInstance().close();
1067 if (mGlsConnection != null) {
1068 unbindService(mGlsConnection);
1069 mGlsConnection = null;
1070 }
1071
1072 //
1073 // stop MASF proxy service
1074 //
1075 //Intent proxyServiceIntent = new Intent();
1076 //proxyServiceIntent.setComponent
1077 // (new ComponentName(
1078 // "com.android.masfproxyservice",
1079 // "com.android.masfproxyservice.MasfProxyService"));
1080 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001081
1082 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001083 }
1084
1085 @Override
1086 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001087 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001088 super.onConfigurationChanged(newConfig);
1089
1090 if (mPageInfoDialog != null) {
1091 mPageInfoDialog.dismiss();
1092 showPageInfo(
1093 mPageInfoView,
1094 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1095 }
1096 if (mSSLCertificateDialog != null) {
1097 mSSLCertificateDialog.dismiss();
1098 showSSLCertificate(
1099 mSSLCertificateView);
1100 }
1101 if (mSSLCertificateOnErrorDialog != null) {
1102 mSSLCertificateOnErrorDialog.dismiss();
1103 showSSLCertificateOnError(
1104 mSSLCertificateOnErrorView,
1105 mSSLCertificateOnErrorHandler,
1106 mSSLCertificateOnErrorError);
1107 }
1108 if (mHttpAuthenticationDialog != null) {
1109 String title = ((TextView) mHttpAuthenticationDialog
1110 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1111 .toString();
1112 String name = ((TextView) mHttpAuthenticationDialog
1113 .findViewById(R.id.username_edit)).getText().toString();
1114 String password = ((TextView) mHttpAuthenticationDialog
1115 .findViewById(R.id.password_edit)).getText().toString();
1116 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1117 .getId();
1118 mHttpAuthenticationDialog.dismiss();
1119 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1120 name, password, focusId);
1121 }
1122 if (mFindDialog != null && mFindDialog.isShowing()) {
1123 mFindDialog.onConfigurationChanged(newConfig);
1124 }
1125 }
1126
1127 @Override public void onLowMemory() {
1128 super.onLowMemory();
1129 mTabControl.freeMemory();
1130 }
1131
Mike Reed7bfa63b2009-05-28 11:08:32 -04001132 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001133 if ((!mActivityInPause && !mPageStarted) ||
1134 (mActivityInPause && mPageStarted)) {
1135 CookieSyncManager.getInstance().startSync();
1136 WebView w = mTabControl.getCurrentWebView();
1137 if (w != null) {
1138 w.resumeTimers();
1139 }
1140 return true;
1141 } else {
1142 return false;
1143 }
1144 }
1145
Mike Reed7bfa63b2009-05-28 11:08:32 -04001146 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001147 if (mActivityInPause && !mPageStarted) {
1148 CookieSyncManager.getInstance().stopSync();
1149 WebView w = mTabControl.getCurrentWebView();
1150 if (w != null) {
1151 w.pauseTimers();
1152 }
1153 return true;
1154 } else {
1155 return false;
1156 }
1157 }
1158
Leon Scroggins1f005d32009-08-10 17:36:42 -04001159 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001160 /*
1161 * This function is called when we are launching for the first time. We
1162 * are waiting for the login credentials before loading Google home
1163 * pages. This way the user will be logged in straight away.
1164 */
1165 private void waitForCredentials() {
1166 // Show a toast
1167 mCredsDlg = new ProgressDialog(this);
1168 mCredsDlg.setIndeterminate(true);
1169 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1170 // If the user cancels the operation, then cancel the Google
1171 // Credentials request.
1172 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1173 mCredsDlg.show();
1174
1175 // We set a timeout for the retrieval of credentials in onResume()
1176 // as that is when we have freed up some CPU time to get
1177 // the login credentials.
1178 }
1179
1180 /*
1181 * If we have received the credentials or we have timed out and we are
1182 * showing the credentials dialog, then it is time to move on.
1183 */
1184 private void resumeAfterCredentials() {
1185 if (mCredsDlg == null) {
1186 return;
1187 }
1188
1189 // Clear the toast
1190 if (mCredsDlg.isShowing()) {
1191 mCredsDlg.dismiss();
1192 }
1193 mCredsDlg = null;
1194
1195 // Clear any pending timeout
1196 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1197
1198 // Load the page
1199 WebView w = mTabControl.getCurrentWebView();
1200 if (w != null) {
1201 w.loadUrl(mSettings.getHomePage());
1202 }
1203
1204 // Update the settings, need to do this last as it can take a moment
1205 // to persist the settings. In the mean time we could be loading
1206 // content.
1207 mSettings.setLoginInitialized(this);
1208 }
1209
1210 // Open the icon database and retain all the icons for visited sites.
1211 private void retainIconsOnStartup() {
1212 final WebIconDatabase db = WebIconDatabase.getInstance();
1213 db.open(getDir("icons", 0).getPath());
1214 try {
1215 Cursor c = Browser.getAllBookmarks(mResolver);
1216 if (!c.moveToFirst()) {
1217 c.deactivate();
1218 return;
1219 }
1220 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1221 do {
1222 String url = c.getString(urlIndex);
1223 db.retainIconForPageUrl(url);
1224 } while (c.moveToNext());
1225 c.deactivate();
1226 } catch (IllegalStateException e) {
1227 Log.e(LOGTAG, "retainIconsOnStartup", e);
1228 }
1229 }
1230
1231 // Helper method for getting the top window.
1232 WebView getTopWindow() {
1233 return mTabControl.getCurrentTopWebView();
1234 }
1235
1236 @Override
1237 public boolean onCreateOptionsMenu(Menu menu) {
1238 super.onCreateOptionsMenu(menu);
1239
1240 MenuInflater inflater = getMenuInflater();
1241 inflater.inflate(R.menu.browser, menu);
1242 mMenu = menu;
1243 updateInLoadMenuItems();
1244 return true;
1245 }
1246
1247 /**
1248 * As the menu can be open when loading state changes
1249 * we must manually update the state of the stop/reload menu
1250 * item
1251 */
1252 private void updateInLoadMenuItems() {
1253 if (mMenu == null) {
1254 return;
1255 }
1256 MenuItem src = mInLoad ?
1257 mMenu.findItem(R.id.stop_menu_id):
1258 mMenu.findItem(R.id.reload_menu_id);
1259 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1260 dest.setIcon(src.getIcon());
1261 dest.setTitle(src.getTitle());
1262 }
1263
1264 @Override
1265 public boolean onContextItemSelected(MenuItem item) {
1266 // chording is not an issue with context menus, but we use the same
1267 // options selector, so set mCanChord to true so we can access them.
1268 mCanChord = true;
1269 int id = item.getItemId();
1270 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001271 if (null == webView) {
1272 return false;
1273 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001274 final HashMap hrefMap = new HashMap();
1275 hrefMap.put("webview", webView);
1276 final Message msg = mHandler.obtainMessage(
1277 FOCUS_NODE_HREF, id, 0, hrefMap);
1278 switch (id) {
1279 // -- Browser context menu
1280 case R.id.open_context_menu_id:
1281 case R.id.open_newtab_context_menu_id:
1282 case R.id.bookmark_context_menu_id:
1283 case R.id.save_link_context_menu_id:
1284 case R.id.share_link_context_menu_id:
1285 case R.id.copy_link_context_menu_id:
1286 webView.requestFocusNodeHref(msg);
1287 break;
1288
1289 default:
1290 // For other context menus
1291 return onOptionsItemSelected(item);
1292 }
1293 mCanChord = false;
1294 return true;
1295 }
1296
1297 private Bundle createGoogleSearchSourceBundle(String source) {
1298 Bundle bundle = new Bundle();
1299 bundle.putString(SearchManager.SOURCE, source);
1300 return bundle;
1301 }
1302
1303 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001304 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001305 */
1306 @Override
1307 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001308 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001309 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001310 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001311 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001312 return true;
1313 }
1314
1315 @Override
1316 public void startSearch(String initialQuery, boolean selectInitialQuery,
1317 Bundle appSearchData, boolean globalSearch) {
1318 if (appSearchData == null) {
1319 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1320 }
1321 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1322 }
1323
Leon Scroggins1f005d32009-08-10 17:36:42 -04001324 /**
1325 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1326 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001327 * @param index Index of the tab to change to, as defined by
1328 * mTabControl.getTabIndex(Tab t).
1329 * @return boolean True if we successfully switched to a different tab. If
1330 * the indexth tab is null, or if that tab is the same as
1331 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001332 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001333 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001334 TabControl.Tab tab = mTabControl.getTab(index);
1335 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1336 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001337 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001338 }
1339 if (currentTab != null) {
1340 // currentTab may be null if it was just removed. In that case,
1341 // we do not need to remove it
1342 removeTabFromContentView(currentTab);
1343 }
1344 removeTabFromContentView(tab);
1345 mTabControl.setCurrentTab(tab);
1346 attachTabToContentView(tab);
Patrick Scottdb22ea72009-09-15 10:57:22 -04001347 resetTitle();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001348 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001349 }
1350
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001351 /* package */ TabControl.Tab openTabToHomePage() {
1352 return openTabAndShow(mSettings.getHomePage(), false, null);
1353 }
1354
Leon Scroggins1f005d32009-08-10 17:36:42 -04001355 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001356 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001357 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001358 // This is the last tab. Open a new one, with the home
1359 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001360 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001361 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001362 return;
1363 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001364 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001365 int indexToShow = -1;
1366 if (parent != null) {
1367 indexToShow = mTabControl.getTabIndex(parent);
1368 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001369 final int currentIndex = mTabControl.getCurrentIndex();
1370 // Try to move to the tab to the right
1371 indexToShow = currentIndex + 1;
1372 if (indexToShow > mTabControl.getTabCount() - 1) {
1373 // Try to move to the tab to the left
1374 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001375 }
1376 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001377 if (switchToTab(indexToShow)) {
1378 // Close window
1379 closeTab(current);
1380 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001381 }
1382
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001383 private ActiveTabsPage mActiveTabsPage;
1384
1385 /**
1386 * Remove the active tabs page.
1387 * @param needToAttach If true, the active tabs page did not attach a tab
1388 * to the content view, so we need to do that here.
1389 */
1390 /* package */ void removeActiveTabPage(boolean needToAttach) {
1391 mContentView.removeView(mActiveTabsPage);
1392 mActiveTabsPage = null;
1393 mMenuState = R.id.MAIN_MENU;
1394 if (needToAttach) {
1395 attachTabToContentView(mTabControl.getCurrentTab());
1396 }
1397 getTopWindow().requestFocus();
1398 }
1399
The Android Open Source Project0c908882009-03-03 19:32:16 -08001400 @Override
1401 public boolean onOptionsItemSelected(MenuItem item) {
1402 if (!mCanChord) {
1403 // The user has already fired a shortcut with this hold down of the
1404 // menu key.
1405 return false;
1406 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001407 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001408 return false;
1409 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001410 if (mMenuIsDown) {
1411 // The shortcut action consumes the MENU. Even if it is still down,
1412 // it won't trigger the next shortcut action. In the case of the
1413 // shortcut action triggering a new activity, like Bookmarks, we
1414 // won't get onKeyUp for MENU. So it is important to reset it here.
1415 mMenuIsDown = false;
1416 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001417 switch (item.getItemId()) {
1418 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001419 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001420 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001421 break;
1422
Leon Scroggins64b80f32009-08-07 12:03:34 -04001423 case R.id.goto_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001424 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001425 break;
1426
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001427 case R.id.active_tabs_menu_id:
1428 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1429 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001430 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001431 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1432 mActiveTabsPage.requestFocus();
1433 mMenuState = EMPTY_MENU;
1434 break;
1435
Leon Scroggins1f005d32009-08-10 17:36:42 -04001436 case R.id.add_bookmark_menu_id:
1437 Intent i = new Intent(BrowserActivity.this,
1438 AddBookmarkPage.class);
1439 WebView w = getTopWindow();
1440 i.putExtra("url", w.getUrl());
1441 i.putExtra("title", w.getTitle());
1442 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001443 break;
1444
1445 case R.id.stop_reload_menu_id:
1446 if (mInLoad) {
1447 stopLoading();
1448 } else {
1449 getTopWindow().reload();
1450 }
1451 break;
1452
1453 case R.id.back_menu_id:
1454 getTopWindow().goBack();
1455 break;
1456
1457 case R.id.forward_menu_id:
1458 getTopWindow().goForward();
1459 break;
1460
1461 case R.id.close_menu_id:
1462 // Close the subwindow if it exists.
1463 if (mTabControl.getCurrentSubWindow() != null) {
1464 dismissSubWindow(mTabControl.getCurrentTab());
1465 break;
1466 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001467 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001468 break;
1469
1470 case R.id.homepage_menu_id:
1471 TabControl.Tab current = mTabControl.getCurrentTab();
1472 if (current != null) {
1473 dismissSubWindow(current);
1474 current.getWebView().loadUrl(mSettings.getHomePage());
1475 }
1476 break;
1477
1478 case R.id.preferences_menu_id:
1479 Intent intent = new Intent(this,
1480 BrowserPreferencesPage.class);
1481 startActivityForResult(intent, PREFERENCES_PAGE);
1482 break;
1483
1484 case R.id.find_menu_id:
1485 if (null == mFindDialog) {
1486 mFindDialog = new FindDialog(this);
1487 }
1488 mFindDialog.setWebView(getTopWindow());
1489 mFindDialog.show();
1490 mMenuState = EMPTY_MENU;
1491 break;
1492
1493 case R.id.select_text_id:
1494 getTopWindow().emulateShiftHeld();
1495 break;
1496 case R.id.page_info_menu_id:
1497 showPageInfo(mTabControl.getCurrentTab(), false);
1498 break;
1499
1500 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001501 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001502 break;
1503
1504 case R.id.share_page_menu_id:
1505 Browser.sendString(this, getTopWindow().getUrl());
1506 break;
1507
1508 case R.id.dump_nav_menu_id:
1509 getTopWindow().debugDump();
1510 break;
1511
1512 case R.id.zoom_in_menu_id:
1513 getTopWindow().zoomIn();
1514 break;
1515
1516 case R.id.zoom_out_menu_id:
1517 getTopWindow().zoomOut();
1518 break;
1519
1520 case R.id.view_downloads_menu_id:
1521 viewDownloads(null);
1522 break;
1523
The Android Open Source Project0c908882009-03-03 19:32:16 -08001524 case R.id.window_one_menu_id:
1525 case R.id.window_two_menu_id:
1526 case R.id.window_three_menu_id:
1527 case R.id.window_four_menu_id:
1528 case R.id.window_five_menu_id:
1529 case R.id.window_six_menu_id:
1530 case R.id.window_seven_menu_id:
1531 case R.id.window_eight_menu_id:
1532 {
1533 int menuid = item.getItemId();
1534 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1535 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1536 TabControl.Tab desiredTab = mTabControl.getTab(id);
1537 if (desiredTab != null &&
1538 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001539 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001540 }
1541 break;
1542 }
1543 }
1544 }
1545 break;
1546
1547 default:
1548 if (!super.onOptionsItemSelected(item)) {
1549 return false;
1550 }
1551 // Otherwise fall through.
1552 }
1553 mCanChord = false;
1554 return true;
1555 }
1556
1557 public void closeFind() {
1558 mMenuState = R.id.MAIN_MENU;
1559 }
1560
1561 @Override public boolean onPrepareOptionsMenu(Menu menu)
1562 {
1563 // This happens when the user begins to hold down the menu key, so
1564 // allow them to chord to get a shortcut.
1565 mCanChord = true;
1566 // Note: setVisible will decide whether an item is visible; while
1567 // setEnabled() will decide whether an item is enabled, which also means
1568 // whether the matching shortcut key will function.
1569 super.onPrepareOptionsMenu(menu);
1570 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001571 case EMPTY_MENU:
1572 if (mCurrentMenuState != mMenuState) {
1573 menu.setGroupVisible(R.id.MAIN_MENU, false);
1574 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1575 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001576 }
1577 break;
1578 default:
1579 if (mCurrentMenuState != mMenuState) {
1580 menu.setGroupVisible(R.id.MAIN_MENU, true);
1581 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1582 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001583 }
1584 final WebView w = getTopWindow();
1585 boolean canGoBack = false;
1586 boolean canGoForward = false;
1587 boolean isHome = false;
1588 if (w != null) {
1589 canGoBack = w.canGoBack();
1590 canGoForward = w.canGoForward();
1591 isHome = mSettings.getHomePage().equals(w.getUrl());
1592 }
1593 final MenuItem back = menu.findItem(R.id.back_menu_id);
1594 back.setEnabled(canGoBack);
1595
1596 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1597 home.setEnabled(!isHome);
1598
1599 menu.findItem(R.id.forward_menu_id)
1600 .setEnabled(canGoForward);
1601
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001602 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1603 mTabControl.getTabCount() < TabControl.MAX_TABS);
1604
The Android Open Source Project0c908882009-03-03 19:32:16 -08001605 // decide whether to show the share link option
1606 PackageManager pm = getPackageManager();
1607 Intent send = new Intent(Intent.ACTION_SEND);
1608 send.setType("text/plain");
1609 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1610 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1611
The Android Open Source Project0c908882009-03-03 19:32:16 -08001612 boolean isNavDump = mSettings.isNavDump();
1613 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1614 nav.setVisible(isNavDump);
1615 nav.setEnabled(isNavDump);
1616 break;
1617 }
1618 mCurrentMenuState = mMenuState;
1619 return true;
1620 }
1621
1622 @Override
1623 public void onCreateContextMenu(ContextMenu menu, View v,
1624 ContextMenuInfo menuInfo) {
1625 WebView webview = (WebView) v;
1626 WebView.HitTestResult result = webview.getHitTestResult();
1627 if (result == null) {
1628 return;
1629 }
1630
1631 int type = result.getType();
1632 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1633 Log.w(LOGTAG,
1634 "We should not show context menu when nothing is touched");
1635 return;
1636 }
1637 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1638 // let TextView handles context menu
1639 return;
1640 }
1641
1642 // Note, http://b/issue?id=1106666 is requesting that
1643 // an inflated menu can be used again. This is not available
1644 // yet, so inflate each time (yuk!)
1645 MenuInflater inflater = getMenuInflater();
1646 inflater.inflate(R.menu.browsercontext, menu);
1647
1648 // Show the correct menu group
1649 String extra = result.getExtra();
1650 menu.setGroupVisible(R.id.PHONE_MENU,
1651 type == WebView.HitTestResult.PHONE_TYPE);
1652 menu.setGroupVisible(R.id.EMAIL_MENU,
1653 type == WebView.HitTestResult.EMAIL_TYPE);
1654 menu.setGroupVisible(R.id.GEO_MENU,
1655 type == WebView.HitTestResult.GEO_TYPE);
1656 menu.setGroupVisible(R.id.IMAGE_MENU,
1657 type == WebView.HitTestResult.IMAGE_TYPE
1658 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1659 menu.setGroupVisible(R.id.ANCHOR_MENU,
1660 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1661 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1662
1663 // Setup custom handling depending on the type
1664 switch (type) {
1665 case WebView.HitTestResult.PHONE_TYPE:
1666 menu.setHeaderTitle(Uri.decode(extra));
1667 menu.findItem(R.id.dial_context_menu_id).setIntent(
1668 new Intent(Intent.ACTION_VIEW, Uri
1669 .parse(WebView.SCHEME_TEL + extra)));
1670 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1671 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1672 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1673 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1674 addIntent);
1675 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1676 new Copy(extra));
1677 break;
1678
1679 case WebView.HitTestResult.EMAIL_TYPE:
1680 menu.setHeaderTitle(extra);
1681 menu.findItem(R.id.email_context_menu_id).setIntent(
1682 new Intent(Intent.ACTION_VIEW, Uri
1683 .parse(WebView.SCHEME_MAILTO + extra)));
1684 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1685 new Copy(extra));
1686 break;
1687
1688 case WebView.HitTestResult.GEO_TYPE:
1689 menu.setHeaderTitle(extra);
1690 menu.findItem(R.id.map_context_menu_id).setIntent(
1691 new Intent(Intent.ACTION_VIEW, Uri
1692 .parse(WebView.SCHEME_GEO
1693 + URLEncoder.encode(extra))));
1694 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1695 new Copy(extra));
1696 break;
1697
1698 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1699 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1700 TextView titleView = (TextView) LayoutInflater.from(this)
1701 .inflate(android.R.layout.browser_link_context_header,
1702 null);
1703 titleView.setText(extra);
1704 menu.setHeaderView(titleView);
1705 // decide whether to show the open link in new tab option
1706 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1707 mTabControl.getTabCount() < TabControl.MAX_TABS);
1708 PackageManager pm = getPackageManager();
1709 Intent send = new Intent(Intent.ACTION_SEND);
1710 send.setType("text/plain");
1711 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1712 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1713 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1714 break;
1715 }
1716 // otherwise fall through to handle image part
1717 case WebView.HitTestResult.IMAGE_TYPE:
1718 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1719 menu.setHeaderTitle(extra);
1720 }
1721 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1722 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1723 menu.findItem(R.id.download_context_menu_id).
1724 setOnMenuItemClickListener(new Download(extra));
1725 break;
1726
1727 default:
1728 Log.w(LOGTAG, "We should not get here.");
1729 break;
1730 }
1731 }
1732
The Android Open Source Project0c908882009-03-03 19:32:16 -08001733 // Attach the given tab to the content view.
1734 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001735 // Attach the container that contains the main WebView and any other UI
1736 // associated with the tab.
1737 mContentView.addView(t.getContainer(), COVER_SCREEN_PARAMS);
Ben Murdochbff2d602009-07-01 20:19:05 +01001738
1739 if (mShouldShowErrorConsole) {
1740 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1741 if (errorConsole.numberOfErrors() == 0) {
1742 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1743 } else {
1744 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1745 }
1746
1747 mErrorConsoleContainer.addView(errorConsole,
1748 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1749 ViewGroup.LayoutParams.WRAP_CONTENT));
1750 }
1751
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001752 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001753 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001754 // Attach the sub window if necessary
1755 attachSubWindow(t);
1756 // Request focus on the top window.
1757 t.getTopWindow().requestFocus();
1758 }
1759
1760 // Attach a sub window to the main WebView of the given tab.
1761 private void attachSubWindow(TabControl.Tab t) {
1762 // If a sub window exists, attach it to the content view.
1763 final WebView subView = t.getSubWebView();
1764 if (subView != null) {
1765 final View container = t.getSubWebViewContainer();
1766 mContentView.addView(container, COVER_SCREEN_PARAMS);
1767 subView.requestFocus();
1768 }
1769 }
1770
1771 // Remove the given tab from the content view.
1772 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001773 // Remove the container that contains the main WebView.
1774 mContentView.removeView(t.getContainer());
Ben Murdochbff2d602009-07-01 20:19:05 +01001775
1776 if (mTabControl.getCurrentErrorConsole(false) != null) {
1777 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1778 }
1779
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001780 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001781 if (view != null) {
1782 view.setEmbeddedTitleBar(null);
1783 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001784
The Android Open Source Project0c908882009-03-03 19:32:16 -08001785 // Remove the sub window if it exists.
1786 if (t.getSubWebView() != null) {
1787 mContentView.removeView(t.getSubWebViewContainer());
1788 }
1789 }
1790
1791 // Remove the sub window if it exists. Also called by TabControl when the
1792 // user clicks the 'X' to dismiss a sub window.
1793 /* package */ void dismissSubWindow(TabControl.Tab t) {
1794 final WebView mainView = t.getWebView();
1795 if (t.getSubWebView() != null) {
1796 // Remove the container view and request focus on the main WebView.
1797 mContentView.removeView(t.getSubWebViewContainer());
1798 mainView.requestFocus();
1799 // Tell the TabControl to dismiss the subwindow. This will destroy
1800 // the WebView.
1801 mTabControl.dismissSubWindow(t);
1802 }
1803 }
1804
Leon Scroggins1f005d32009-08-10 17:36:42 -04001805 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001806 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001807 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1808 String appId) {
1809 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001810 }
1811
1812 // This method does a ton of stuff. It will attempt to create a new tab
1813 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001814 // url isn't null, it will load the given url.
1815 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001816 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001817 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1818 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1819 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001820 final TabControl.Tab tab = mTabControl.createNewTab(
1821 closeOnExit, appId, urlData.mUrl);
1822 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001823 // If the last tab was removed from the active tabs page, currentTab
1824 // will be null.
1825 if (currentTab != null) {
1826 removeTabFromContentView(currentTab);
1827 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001828 attachTabToContentView(tab);
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001829 // We must set the new tab as the current tab to reflect the old
1830 // animation behavior.
1831 mTabControl.setCurrentTab(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001832 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001833 urlData.loadIn(webview);
1834 }
1835 return tab;
1836 } else {
1837 // Get rid of the subwindow if it exists
1838 dismissSubWindow(currentTab);
1839 if (!urlData.isEmpty()) {
1840 // Load the given url.
1841 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001842 }
1843 }
Grace Klobac9181842009-04-14 08:53:22 -07001844 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001845 }
1846
Grace Klobac9181842009-04-14 08:53:22 -07001847 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001848 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001849 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001850 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001851 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001852 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001853 }
Grace Klobac9181842009-04-14 08:53:22 -07001854 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001855 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001856 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001857 }
1858 }
1859
1860 private class Copy implements OnMenuItemClickListener {
1861 private CharSequence mText;
1862
1863 public boolean onMenuItemClick(MenuItem item) {
1864 copy(mText);
1865 return true;
1866 }
1867
1868 public Copy(CharSequence toCopy) {
1869 mText = toCopy;
1870 }
1871 }
1872
1873 private class Download implements OnMenuItemClickListener {
1874 private String mText;
1875
1876 public boolean onMenuItemClick(MenuItem item) {
1877 onDownloadStartNoStream(mText, null, null, null, -1);
1878 return true;
1879 }
1880
1881 public Download(String toDownload) {
1882 mText = toDownload;
1883 }
1884 }
1885
1886 private void copy(CharSequence text) {
1887 try {
1888 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1889 if (clip != null) {
1890 clip.setClipboardText(text);
1891 }
1892 } catch (android.os.RemoteException e) {
1893 Log.e(LOGTAG, "Copy failed", e);
1894 }
1895 }
1896
1897 /**
1898 * Resets the browser title-view to whatever it must be (for example, if we
1899 * load a page from history).
1900 */
1901 private void resetTitle() {
1902 resetLockIcon();
1903 resetTitleIconAndProgress();
1904 }
1905
1906 /**
1907 * Resets the browser title-view to whatever it must be
1908 * (for example, if we had a loading error)
1909 * When we have a new page, we call resetTitle, when we
1910 * have to reset the titlebar to whatever it used to be
1911 * (for example, if the user chose to stop loading), we
1912 * call resetTitleAndRevertLockIcon.
1913 */
1914 /* package */ void resetTitleAndRevertLockIcon() {
1915 revertLockIcon();
1916 resetTitleIconAndProgress();
1917 }
1918
1919 /**
1920 * Reset the title, favicon, and progress.
1921 */
1922 private void resetTitleIconAndProgress() {
1923 WebView current = mTabControl.getCurrentWebView();
1924 if (current == null) {
1925 return;
1926 }
1927 resetTitleAndIcon(current);
1928 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001929 mWebChromeClient.onProgressChanged(current, progress);
1930 }
1931
1932 // Reset the title and the icon based on the given item.
1933 private void resetTitleAndIcon(WebView view) {
1934 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1935 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001936 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001937 setFavicon(item.getFavicon());
1938 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001939 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001940 setFavicon(null);
1941 }
1942 }
1943
1944 /**
1945 * Sets a title composed of the URL and the title string.
1946 * @param url The URL of the site being loaded.
1947 * @param title The title of the site being loaded.
1948 */
Leon Scroggins68579392009-09-15 15:31:54 -04001949 private void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001950 mUrl = url;
1951 mTitle = title;
1952
Leon Scroggins68579392009-09-15 15:31:54 -04001953 mTitleBar.setTitleAndUrl(title, url);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001954 if (mFakeTitleBar != null) {
1955 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001956 }
1957 }
1958
1959 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001960 * @param url The URL to build a title version of the URL from.
1961 * @return The title version of the URL or null if fails.
1962 * The title version of the URL can be either the URL hostname,
1963 * or the hostname with an "https://" prefix (for secure URLs),
1964 * or an empty string if, for example, the URL in question is a
1965 * file:// URL with no hostname.
1966 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001967 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001968 String titleUrl = null;
1969
1970 if (url != null) {
1971 try {
1972 // parse the url string
1973 URL urlObj = new URL(url);
1974 if (urlObj != null) {
1975 titleUrl = "";
1976
1977 String protocol = urlObj.getProtocol();
1978 String host = urlObj.getHost();
1979
1980 if (host != null && 0 < host.length()) {
1981 titleUrl = host;
1982 if (protocol != null) {
1983 // if a secure site, add an "https://" prefix!
1984 if (protocol.equalsIgnoreCase("https")) {
1985 titleUrl = protocol + "://" + host;
1986 }
1987 }
1988 }
1989 }
1990 } catch (MalformedURLException e) {}
1991 }
1992
1993 return titleUrl;
1994 }
1995
1996 // Set the favicon in the title bar.
1997 private void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04001998 mTitleBar.setFavicon(icon);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001999 if (mFakeTitleBar != null) {
2000 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002001 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002002 }
2003
2004 /**
2005 * Saves the current lock-icon state before resetting
2006 * the lock icon. If we have an error, we may need to
2007 * roll back to the previous state.
2008 */
2009 private void saveLockIcon() {
2010 mPrevLockType = mLockIconType;
2011 }
2012
2013 /**
2014 * Reverts the lock-icon state to the last saved state,
2015 * for example, if we had an error, and need to cancel
2016 * the load.
2017 */
2018 private void revertLockIcon() {
2019 mLockIconType = mPrevLockType;
2020
Dave Bort31a6d1c2009-04-13 15:56:49 -07002021 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002022 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2023 " revert lock icon to " + mLockIconType);
2024 }
2025
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002026 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002027 }
2028
Leon Scroggins1f005d32009-08-10 17:36:42 -04002029 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002030 * Close the tab, remove its associated title bar, and adjust mTabControl's
2031 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002032 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002033 /* package */ void closeTab(TabControl.Tab t) {
2034 int currentIndex = mTabControl.getCurrentIndex();
2035 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002036 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002037 if (currentIndex >= removeIndex && currentIndex != 0) {
2038 currentIndex--;
2039 }
2040 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
The Android Open Source Project0c908882009-03-03 19:32:16 -08002041 }
2042
2043 private void goBackOnePageOrQuit() {
2044 TabControl.Tab current = mTabControl.getCurrentTab();
2045 if (current == null) {
2046 /*
2047 * Instead of finishing the activity, simply push this to the back
2048 * of the stack and let ActivityManager to choose the foreground
2049 * activity. As BrowserActivity is singleTask, it will be always the
2050 * root of the task. So we can use either true or false for
2051 * moveTaskToBack().
2052 */
2053 moveTaskToBack(true);
2054 }
2055 WebView w = current.getWebView();
2056 if (w.canGoBack()) {
2057 w.goBack();
2058 } else {
2059 // Check to see if we are closing a window that was created by
2060 // another window. If so, we switch back to that window.
2061 TabControl.Tab parent = current.getParentTab();
2062 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002063 switchToTab(mTabControl.getTabIndex(parent));
2064 // Now we close the other tab
2065 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002066 } else {
2067 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002068 // force mPageStarted to be false as we are going to either
2069 // finish the activity or remove the tab. This will ensure
2070 // pauseWebView() taking action.
2071 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002072 if (mTabControl.getTabCount() == 1) {
2073 finish();
2074 return;
2075 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002076 // call pauseWebViewTimers() now, we won't be able to call
2077 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002078 // Temporarily change mActivityInPause to be true as
2079 // pauseWebViewTimers() will do nothing if mActivityInPause
2080 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002081 boolean savedState = mActivityInPause;
2082 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002083 Log.e(LOGTAG, "BrowserActivity is already paused "
2084 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002085 }
2086 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002087 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002088 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002089 removeTabFromContentView(current);
2090 mTabControl.removeTab(current);
2091 }
2092 /*
2093 * Instead of finishing the activity, simply push this to the back
2094 * of the stack and let ActivityManager to choose the foreground
2095 * activity. As BrowserActivity is singleTask, it will be always the
2096 * root of the task. So we can use either true or false for
2097 * moveTaskToBack().
2098 */
2099 moveTaskToBack(true);
2100 }
2101 }
2102 }
2103
2104 public KeyTracker.State onKeyTracker(int keyCode,
2105 KeyEvent event,
2106 KeyTracker.Stage stage,
2107 int duration) {
2108 // if onKeyTracker() is called after activity onStop()
2109 // because of accumulated key events,
2110 // we should ignore it as browser is not active any more.
2111 WebView topWindow = getTopWindow();
Andrei Popescuadc008d2009-06-26 14:11:30 +01002112 if (topWindow == null && mCustomView == null)
The Android Open Source Project0c908882009-03-03 19:32:16 -08002113 return KeyTracker.State.NOT_TRACKING;
2114
2115 if (keyCode == KeyEvent.KEYCODE_BACK) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01002116 // Check if a custom view is currently showing and, if it is, hide it.
2117 if (mCustomView != null) {
2118 mWebChromeClient.onHideCustomView();
2119 return KeyTracker.State.DONE_TRACKING;
2120 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002121 if (stage == KeyTracker.Stage.LONG_REPEAT) {
Leon Scroggins30444232009-09-04 18:36:20 -04002122 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002123 return KeyTracker.State.DONE_TRACKING;
2124 } else if (stage == KeyTracker.Stage.UP) {
2125 // FIXME: Currently, we do not have a notion of the
2126 // history picker for the subwindow, but maybe we
2127 // should?
2128 WebView subwindow = mTabControl.getCurrentSubWindow();
2129 if (subwindow != null) {
2130 if (subwindow.canGoBack()) {
2131 subwindow.goBack();
2132 } else {
2133 dismissSubWindow(mTabControl.getCurrentTab());
2134 }
2135 } else {
2136 goBackOnePageOrQuit();
2137 }
2138 return KeyTracker.State.DONE_TRACKING;
2139 }
2140 return KeyTracker.State.KEEP_TRACKING;
2141 }
2142 return KeyTracker.State.NOT_TRACKING;
2143 }
2144
2145 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2146 if (keyCode == KeyEvent.KEYCODE_MENU) {
2147 mMenuIsDown = true;
Grace Kloba6ee9c492009-07-13 10:04:34 -07002148 } else if (mMenuIsDown) {
2149 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2150 // still down, we don't want to trigger the search. Pretend to
2151 // consume the key and do nothing.
2152 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002153 }
2154 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2155 if (!handled) {
2156 switch (keyCode) {
2157 case KeyEvent.KEYCODE_SPACE:
2158 if (event.isShiftPressed()) {
2159 getTopWindow().pageUp(false);
2160 } else {
2161 getTopWindow().pageDown(false);
2162 }
2163 handled = true;
2164 break;
2165
2166 default:
2167 break;
2168 }
2169 }
2170 return handled || super.onKeyDown(keyCode, event);
2171 }
2172
2173 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2174 if (keyCode == KeyEvent.KEYCODE_MENU) {
2175 mMenuIsDown = false;
2176 }
2177 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2178 }
2179
Leon Scroggins68579392009-09-15 15:31:54 -04002180 /* package */ void stopLoading() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002181 resetTitleAndRevertLockIcon();
2182 WebView w = getTopWindow();
2183 w.stopLoading();
2184 mWebViewClient.onPageFinished(w, w.getUrl());
2185
2186 cancelStopToast();
2187 mStopToast = Toast
2188 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2189 mStopToast.show();
2190 }
2191
2192 private void cancelStopToast() {
2193 if (mStopToast != null) {
2194 mStopToast.cancel();
2195 mStopToast = null;
2196 }
2197 }
2198
2199 // called by a non-UI thread to post the message
2200 public void postMessage(int what, int arg1, int arg2, Object obj) {
2201 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2202 }
2203
2204 // public message ids
2205 public final static int LOAD_URL = 1001;
2206 public final static int STOP_LOAD = 1002;
2207
2208 // Message Ids
2209 private static final int FOCUS_NODE_HREF = 102;
2210 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002211 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002212
2213 // Private handler for handling javascript and saving passwords
2214 private Handler mHandler = new Handler() {
2215
2216 public void handleMessage(Message msg) {
2217 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002218 case FOCUS_NODE_HREF:
2219 String url = (String) msg.getData().get("url");
2220 if (url == null || url.length() == 0) {
2221 break;
2222 }
2223 HashMap focusNodeMap = (HashMap) msg.obj;
2224 WebView view = (WebView) focusNodeMap.get("webview");
2225 // Only apply the action if the top window did not change.
2226 if (getTopWindow() != view) {
2227 break;
2228 }
2229 switch (msg.arg1) {
2230 case R.id.open_context_menu_id:
2231 case R.id.view_image_context_menu_id:
2232 loadURL(getTopWindow(), url);
2233 break;
2234 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002235 final TabControl.Tab parent = mTabControl
2236 .getCurrentTab();
2237 final TabControl.Tab newTab = openTab(url);
2238 if (newTab != parent) {
2239 parent.addChildTab(newTab);
2240 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002241 break;
2242 case R.id.bookmark_context_menu_id:
2243 Intent intent = new Intent(BrowserActivity.this,
2244 AddBookmarkPage.class);
2245 intent.putExtra("url", url);
2246 startActivity(intent);
2247 break;
2248 case R.id.share_link_context_menu_id:
2249 Browser.sendString(BrowserActivity.this, url);
2250 break;
2251 case R.id.copy_link_context_menu_id:
2252 copy(url);
2253 break;
2254 case R.id.save_link_context_menu_id:
2255 case R.id.download_context_menu_id:
2256 onDownloadStartNoStream(url, null, null, null, -1);
2257 break;
2258 }
2259 break;
2260
2261 case LOAD_URL:
2262 loadURL(getTopWindow(), (String) msg.obj);
2263 break;
2264
2265 case STOP_LOAD:
2266 stopLoading();
2267 break;
2268
2269 case CANCEL_CREDS_REQUEST:
2270 resumeAfterCredentials();
2271 break;
2272
The Android Open Source Project0c908882009-03-03 19:32:16 -08002273 case RELEASE_WAKELOCK:
2274 if (mWakeLock.isHeld()) {
2275 mWakeLock.release();
2276 }
2277 break;
2278 }
2279 }
2280 };
2281
Leon Scroggins89c6d362009-07-15 16:54:37 -04002282 private void updateScreenshot(WebView view) {
2283 // If this is a bookmarked site, add a screenshot to the database.
2284 // FIXME: When should we update? Every time?
2285 // FIXME: Would like to make sure there is actually something to
2286 // draw, but the API for that (WebViewCore.pictureReady()) is not
2287 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002288 ContentResolver cr = getContentResolver();
2289 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002290 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002291 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002292 boolean succeed = c.moveToFirst();
2293 ContentValues values = null;
2294 while (succeed) {
2295 if (values == null) {
2296 final ByteArrayOutputStream os
2297 = new ByteArrayOutputStream();
2298 Picture thumbnail = view.capturePicture();
2299 // Keep width and height in sync with BrowserBookmarksPage
2300 // and bookmark_thumb
2301 Bitmap bm = Bitmap.createBitmap(100, 80,
2302 Bitmap.Config.ARGB_4444);
2303 Canvas canvas = new Canvas(bm);
2304 // May need to tweak these values to determine what is the
2305 // best scale factor
2306 canvas.scale(.5f, .5f);
2307 thumbnail.draw(canvas);
2308 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2309 values = new ContentValues();
2310 values.put(Browser.BookmarkColumns.THUMBNAIL,
2311 os.toByteArray());
2312 }
2313 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2314 c.getInt(0)), values, null, null);
2315 succeed = c.moveToNext();
2316 }
2317 c.close();
2318 }
2319 }
2320
The Android Open Source Project0c908882009-03-03 19:32:16 -08002321 // -------------------------------------------------------------------------
2322 // WebViewClient implementation.
2323 //-------------------------------------------------------------------------
2324
2325 // Use in overrideUrlLoading
2326 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2327 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2328 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2329 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2330
2331 /* package */ WebViewClient getWebViewClient() {
2332 return mWebViewClient;
2333 }
2334
Patrick Scott3918d442009-08-04 13:22:29 -04002335 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002336 if (icon != null) {
2337 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott3918d442009-08-04 13:22:29 -04002338 view, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002339 }
2340 setFavicon(icon);
2341 }
2342
2343 private final WebViewClient mWebViewClient = new WebViewClient() {
2344 @Override
2345 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2346 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002347 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002348
2349 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2350 if (errorConsole != null) {
2351 errorConsole.clearErrorMessages();
2352 if (mShouldShowErrorConsole) {
2353 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2354 }
2355 }
2356
The Android Open Source Project0c908882009-03-03 19:32:16 -08002357 // Call updateIcon instead of setFavicon so the bookmark
2358 // database can be updated.
Patrick Scott3918d442009-08-04 13:22:29 -04002359 updateIcon(view, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002360
Grace Kloba4d7880f2009-08-12 09:35:42 -07002361 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002362 String host;
2363 try {
2364 WebAddress uri = new WebAddress(url);
2365 host = uri.mHost;
2366 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002367 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002368 }
2369 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002370 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002371 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002372 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002373 }
2374
2375 // Performance probe
2376 if (false) {
2377 mStart = SystemClock.uptimeMillis();
2378 mProcessStart = Process.getElapsedCpuTime();
2379 long[] sysCpu = new long[7];
2380 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2381 sysCpu, null)) {
2382 mUserStart = sysCpu[0] + sysCpu[1];
2383 mSystemStart = sysCpu[2];
2384 mIdleStart = sysCpu[3];
2385 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2386 }
2387 mUiStart = SystemClock.currentThreadTimeMillis();
2388 }
2389
2390 if (!mPageStarted) {
2391 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002392 // if onResume() has been called, resumeWebViewTimers() does
2393 // nothing.
2394 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002395 }
2396
2397 // reset sync timer to avoid sync starts during loading a page
2398 CookieSyncManager.getInstance().resetSync();
2399
2400 mInLoad = true;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002401 WebView currentWebView = mTabControl.getCurrentWebView();
2402 if (currentWebView == null || currentWebView.getScrollY() != 0) {
2403 // This page has begun to load, so show the title bar
2404 showFakeTitleBar();
2405 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002406 updateInLoadMenuItems();
2407 if (!mIsNetworkUp) {
2408 if ( mAlertDialog == null) {
2409 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2410 .setTitle(R.string.loadSuspendedTitle)
2411 .setMessage(R.string.loadSuspended)
2412 .setPositiveButton(R.string.ok, null)
2413 .show();
2414 }
2415 if (view != null) {
2416 view.setNetworkAvailable(false);
2417 }
2418 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002419 }
2420
2421 @Override
2422 public void onPageFinished(WebView view, String url) {
2423 // Reset the title and icon in case we stopped a provisional
2424 // load.
2425 resetTitleAndIcon(view);
2426
2427 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002428 updateLockIconToLatest();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002429 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002430
The Android Open Source Project0c908882009-03-03 19:32:16 -08002431 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002432 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002433 long[] sysCpu = new long[7];
2434 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2435 sysCpu, null)) {
2436 String uiInfo = "UI thread used "
2437 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2438 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002439 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002440 Log.d(LOGTAG, uiInfo);
2441 }
2442 //The string that gets written to the log
2443 String performanceString = "It took total "
2444 + (SystemClock.uptimeMillis() - mStart)
2445 + " ms clock time to load the page."
2446 + "\nbrowser process used "
2447 + (Process.getElapsedCpuTime() - mProcessStart)
2448 + " ms, user processes used "
2449 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2450 + " ms, kernel used "
2451 + (sysCpu[2] - mSystemStart) * 10
2452 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2453 + " ms and irq took "
2454 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2455 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002456 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002457 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2458 }
2459 if (url != null) {
2460 // strip the url to maintain consistency
2461 String newUrl = new String(url);
2462 if (newUrl.startsWith("http://www.")) {
2463 newUrl = newUrl.substring(11);
2464 } else if (newUrl.startsWith("http://")) {
2465 newUrl = newUrl.substring(7);
2466 } else if (newUrl.startsWith("https://www.")) {
2467 newUrl = newUrl.substring(12);
2468 } else if (newUrl.startsWith("https://")) {
2469 newUrl = newUrl.substring(8);
2470 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002471 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002472 Log.d(LOGTAG, newUrl + " loaded");
2473 }
2474 /*
2475 if (sWhiteList.contains(newUrl)) {
2476 // The string that gets pushed to the statistcs
2477 // service
2478 performanceString = performanceString
2479 + "\nWebpage: "
2480 + newUrl
2481 + "\nCarrier: "
2482 + android.os.SystemProperties
2483 .get("gsm.sim.operator.alpha");
2484 if (mWebView != null
2485 && mWebView.getContext() != null
2486 && mWebView.getContext().getSystemService(
2487 Context.CONNECTIVITY_SERVICE) != null) {
2488 ConnectivityManager cManager =
2489 (ConnectivityManager) mWebView
2490 .getContext().getSystemService(
2491 Context.CONNECTIVITY_SERVICE);
2492 NetworkInfo nInfo = cManager
2493 .getActiveNetworkInfo();
2494 if (nInfo != null) {
2495 performanceString = performanceString
2496 + "\nNetwork Type: "
2497 + nInfo.getType().toString();
2498 }
2499 }
2500 Checkin.logEvent(mResolver,
2501 Checkin.Events.Tag.WEBPAGE_LOAD,
2502 performanceString);
2503 Log.w(LOGTAG, "pushed to the statistics service");
2504 }
2505 */
2506 }
2507 }
2508 }
2509
2510 if (mInTrace) {
2511 mInTrace = false;
2512 Debug.stopMethodTracing();
2513 }
2514
2515 if (mPageStarted) {
2516 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002517 // pauseWebViewTimers() will do nothing and return false if
2518 // onPause() is not called yet.
2519 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002520 if (mWakeLock.isHeld()) {
2521 mHandler.removeMessages(RELEASE_WAKELOCK);
2522 mWakeLock.release();
2523 }
2524 }
2525 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002526 }
2527
2528 // return true if want to hijack the url to let another app to handle it
2529 @Override
2530 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2531 if (url.startsWith(SCHEME_WTAI)) {
2532 // wtai://wp/mc;number
2533 // number=string(phone-number)
2534 if (url.startsWith(SCHEME_WTAI_MC)) {
2535 Intent intent = new Intent(Intent.ACTION_VIEW,
2536 Uri.parse(WebView.SCHEME_TEL +
2537 url.substring(SCHEME_WTAI_MC.length())));
2538 startActivity(intent);
2539 return true;
2540 }
2541 // wtai://wp/sd;dtmf
2542 // dtmf=string(dialstring)
2543 if (url.startsWith(SCHEME_WTAI_SD)) {
2544 // TODO
2545 // only send when there is active voice connection
2546 return false;
2547 }
2548 // wtai://wp/ap;number;name
2549 // number=string(phone-number)
2550 // name=string
2551 if (url.startsWith(SCHEME_WTAI_AP)) {
2552 // TODO
2553 return false;
2554 }
2555 }
2556
Dianne Hackborn99189432009-06-17 18:06:18 -07002557 // The "about:" schemes are internal to the browser; don't
2558 // want these to be dispatched to other apps.
2559 if (url.startsWith("about:")) {
2560 return false;
2561 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002562
Dianne Hackborn99189432009-06-17 18:06:18 -07002563 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002564
Dianne Hackborn99189432009-06-17 18:06:18 -07002565 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002566 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002567 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2568 } catch (URISyntaxException ex) {
2569 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002570 return false;
2571 }
2572
Grace Kloba5b078b52009-06-24 20:23:41 -07002573 // check whether the intent can be resolved. If not, we will see
2574 // whether we can download it from the Market.
2575 if (getPackageManager().resolveActivity(intent, 0) == null) {
2576 String packagename = intent.getPackage();
2577 if (packagename != null) {
2578 intent = new Intent(Intent.ACTION_VIEW, Uri
2579 .parse("market://search?q=pname:" + packagename));
2580 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2581 startActivity(intent);
2582 return true;
2583 } else {
2584 return false;
2585 }
2586 }
2587
Dianne Hackborn99189432009-06-17 18:06:18 -07002588 // sanitize the Intent, ensuring web pages can not bypass browser
2589 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002590 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002591 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002592 try {
2593 if (startActivityIfNeeded(intent, -1)) {
2594 return true;
2595 }
2596 } catch (ActivityNotFoundException ex) {
2597 // ignore the error. If no application can handle the URL,
2598 // eg about:blank, assume the browser can handle it.
2599 }
2600
2601 if (mMenuIsDown) {
2602 openTab(url);
2603 closeOptionsMenu();
2604 return true;
2605 }
2606
2607 return false;
2608 }
2609
2610 /**
2611 * Updates the lock icon. This method is called when we discover another
2612 * resource to be loaded for this page (for example, javascript). While
2613 * we update the icon type, we do not update the lock icon itself until
2614 * we are done loading, it is slightly more secure this way.
2615 */
2616 @Override
2617 public void onLoadResource(WebView view, String url) {
2618 if (url != null && url.length() > 0) {
2619 // It is only if the page claims to be secure
2620 // that we may have to update the lock:
2621 if (mLockIconType == LOCK_ICON_SECURE) {
2622 // If NOT a 'safe' url, change the lock to mixed content!
2623 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2624 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002625 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002626 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2627 " updated lock icon to " + mLockIconType + " due to " + url);
2628 }
2629 }
2630 }
2631 }
2632 }
2633
2634 /**
2635 * Show the dialog, asking the user if they would like to continue after
2636 * an excessive number of HTTP redirects.
2637 */
2638 @Override
2639 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2640 final Message continueMsg) {
2641 new AlertDialog.Builder(BrowserActivity.this)
2642 .setTitle(R.string.browserFrameRedirect)
2643 .setMessage(R.string.browserFrame307Post)
2644 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2645 public void onClick(DialogInterface dialog, int which) {
2646 continueMsg.sendToTarget();
2647 }})
2648 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2649 public void onClick(DialogInterface dialog, int which) {
2650 cancelMsg.sendToTarget();
2651 }})
2652 .setOnCancelListener(new OnCancelListener() {
2653 public void onCancel(DialogInterface dialog) {
2654 cancelMsg.sendToTarget();
2655 }})
2656 .show();
2657 }
2658
Patrick Scott37911c72009-03-24 18:02:58 -07002659 // Container class for the next error dialog that needs to be
2660 // displayed.
2661 class ErrorDialog {
2662 public final int mTitle;
2663 public final String mDescription;
2664 public final int mError;
2665 ErrorDialog(int title, String desc, int error) {
2666 mTitle = title;
2667 mDescription = desc;
2668 mError = error;
2669 }
2670 };
2671
2672 private void processNextError() {
2673 if (mQueuedErrors == null) {
2674 return;
2675 }
2676 // The first one is currently displayed so just remove it.
2677 mQueuedErrors.removeFirst();
2678 if (mQueuedErrors.size() == 0) {
2679 mQueuedErrors = null;
2680 return;
2681 }
2682 showError(mQueuedErrors.getFirst());
2683 }
2684
2685 private DialogInterface.OnDismissListener mDialogListener =
2686 new DialogInterface.OnDismissListener() {
2687 public void onDismiss(DialogInterface d) {
2688 processNextError();
2689 }
2690 };
2691 private LinkedList<ErrorDialog> mQueuedErrors;
2692
2693 private void queueError(int err, String desc) {
2694 if (mQueuedErrors == null) {
2695 mQueuedErrors = new LinkedList<ErrorDialog>();
2696 }
2697 for (ErrorDialog d : mQueuedErrors) {
2698 if (d.mError == err) {
2699 // Already saw a similar error, ignore the new one.
2700 return;
2701 }
2702 }
2703 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002704 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002705 R.string.browserFrameFileErrorLabel :
2706 R.string.browserFrameNetworkErrorLabel,
2707 desc, err);
2708 mQueuedErrors.addLast(errDialog);
2709
2710 // Show the dialog now if the queue was empty.
2711 if (mQueuedErrors.size() == 1) {
2712 showError(errDialog);
2713 }
2714 }
2715
2716 private void showError(ErrorDialog errDialog) {
2717 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2718 .setTitle(errDialog.mTitle)
2719 .setMessage(errDialog.mDescription)
2720 .setPositiveButton(R.string.ok, null)
2721 .create();
2722 d.setOnDismissListener(mDialogListener);
2723 d.show();
2724 }
2725
The Android Open Source Project0c908882009-03-03 19:32:16 -08002726 /**
2727 * Show a dialog informing the user of the network error reported by
2728 * WebCore.
2729 */
2730 @Override
2731 public void onReceivedError(WebView view, int errorCode,
2732 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002733 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2734 errorCode != WebViewClient.ERROR_CONNECT &&
2735 errorCode != WebViewClient.ERROR_BAD_URL &&
2736 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2737 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002738 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002739 }
Patrick Scott37911c72009-03-24 18:02:58 -07002740 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2741 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002742
2743 // We need to reset the title after an error.
2744 resetTitleAndRevertLockIcon();
2745 }
2746
2747 /**
2748 * Check with the user if it is ok to resend POST data as the page they
2749 * are trying to navigate to is the result of a POST.
2750 */
2751 @Override
2752 public void onFormResubmission(WebView view, final Message dontResend,
2753 final Message resend) {
2754 new AlertDialog.Builder(BrowserActivity.this)
2755 .setTitle(R.string.browserFrameFormResubmitLabel)
2756 .setMessage(R.string.browserFrameFormResubmitMessage)
2757 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2758 public void onClick(DialogInterface dialog, int which) {
2759 resend.sendToTarget();
2760 }})
2761 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2762 public void onClick(DialogInterface dialog, int which) {
2763 dontResend.sendToTarget();
2764 }})
2765 .setOnCancelListener(new OnCancelListener() {
2766 public void onCancel(DialogInterface dialog) {
2767 dontResend.sendToTarget();
2768 }})
2769 .show();
2770 }
2771
2772 /**
2773 * Insert the url into the visited history database.
2774 * @param url The url to be inserted.
2775 * @param isReload True if this url is being reloaded.
2776 * FIXME: Not sure what to do when reloading the page.
2777 */
2778 @Override
2779 public void doUpdateVisitedHistory(WebView view, String url,
2780 boolean isReload) {
2781 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2782 return;
2783 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002784 // remove "client" before updating it to the history so that it wont
2785 // show up in the auto-complete list.
2786 int index = url.indexOf("client=ms-");
2787 if (index > 0 && url.contains(".google.")) {
2788 int end = url.indexOf('&', index);
2789 if (end > 0) {
2790 url = url.substring(0, index-1).concat(url.substring(end));
2791 } else {
2792 url = url.substring(0, index-1);
2793 }
2794 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002795 Browser.updateVisitedHistory(mResolver, url, true);
2796 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2797 }
2798
2799 /**
2800 * Displays SSL error(s) dialog to the user.
2801 */
2802 @Override
2803 public void onReceivedSslError(
2804 final WebView view, final SslErrorHandler handler, final SslError error) {
2805
2806 if (mSettings.showSecurityWarnings()) {
2807 final LayoutInflater factory =
2808 LayoutInflater.from(BrowserActivity.this);
2809 final View warningsView =
2810 factory.inflate(R.layout.ssl_warnings, null);
2811 final LinearLayout placeholder =
2812 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2813
2814 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2815 LinearLayout ll = (LinearLayout)factory
2816 .inflate(R.layout.ssl_warning, null);
2817 ((TextView)ll.findViewById(R.id.warning))
2818 .setText(R.string.ssl_untrusted);
2819 placeholder.addView(ll);
2820 }
2821
2822 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2823 LinearLayout ll = (LinearLayout)factory
2824 .inflate(R.layout.ssl_warning, null);
2825 ((TextView)ll.findViewById(R.id.warning))
2826 .setText(R.string.ssl_mismatch);
2827 placeholder.addView(ll);
2828 }
2829
2830 if (error.hasError(SslError.SSL_EXPIRED)) {
2831 LinearLayout ll = (LinearLayout)factory
2832 .inflate(R.layout.ssl_warning, null);
2833 ((TextView)ll.findViewById(R.id.warning))
2834 .setText(R.string.ssl_expired);
2835 placeholder.addView(ll);
2836 }
2837
2838 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2839 LinearLayout ll = (LinearLayout)factory
2840 .inflate(R.layout.ssl_warning, null);
2841 ((TextView)ll.findViewById(R.id.warning))
2842 .setText(R.string.ssl_not_yet_valid);
2843 placeholder.addView(ll);
2844 }
2845
2846 new AlertDialog.Builder(BrowserActivity.this)
2847 .setTitle(R.string.security_warning)
2848 .setIcon(android.R.drawable.ic_dialog_alert)
2849 .setView(warningsView)
2850 .setPositiveButton(R.string.ssl_continue,
2851 new DialogInterface.OnClickListener() {
2852 public void onClick(DialogInterface dialog, int whichButton) {
2853 handler.proceed();
2854 }
2855 })
2856 .setNeutralButton(R.string.view_certificate,
2857 new DialogInterface.OnClickListener() {
2858 public void onClick(DialogInterface dialog, int whichButton) {
2859 showSSLCertificateOnError(view, handler, error);
2860 }
2861 })
2862 .setNegativeButton(R.string.cancel,
2863 new DialogInterface.OnClickListener() {
2864 public void onClick(DialogInterface dialog, int whichButton) {
2865 handler.cancel();
2866 BrowserActivity.this.resetTitleAndRevertLockIcon();
2867 }
2868 })
2869 .setOnCancelListener(
2870 new DialogInterface.OnCancelListener() {
2871 public void onCancel(DialogInterface dialog) {
2872 handler.cancel();
2873 BrowserActivity.this.resetTitleAndRevertLockIcon();
2874 }
2875 })
2876 .show();
2877 } else {
2878 handler.proceed();
2879 }
2880 }
2881
2882 /**
2883 * Handles an HTTP authentication request.
2884 *
2885 * @param handler The authentication handler
2886 * @param host The host
2887 * @param realm The realm
2888 */
2889 @Override
2890 public void onReceivedHttpAuthRequest(WebView view,
2891 final HttpAuthHandler handler, final String host, final String realm) {
2892 String username = null;
2893 String password = null;
2894
2895 boolean reuseHttpAuthUsernamePassword =
2896 handler.useHttpAuthUsernamePassword();
2897
2898 if (reuseHttpAuthUsernamePassword &&
2899 (mTabControl.getCurrentWebView() != null)) {
2900 String[] credentials =
2901 mTabControl.getCurrentWebView()
2902 .getHttpAuthUsernamePassword(host, realm);
2903 if (credentials != null && credentials.length == 2) {
2904 username = credentials[0];
2905 password = credentials[1];
2906 }
2907 }
2908
2909 if (username != null && password != null) {
2910 handler.proceed(username, password);
2911 } else {
2912 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2913 }
2914 }
2915
2916 @Override
2917 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2918 if (mMenuIsDown) {
2919 // only check shortcut key when MENU is held
2920 return getWindow().isShortcutKey(event.getKeyCode(), event);
2921 } else {
2922 return false;
2923 }
2924 }
2925
2926 @Override
2927 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2928 if (view != mTabControl.getCurrentTopWebView()) {
2929 return;
2930 }
2931 if (event.isDown()) {
2932 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2933 } else {
2934 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2935 }
2936 }
2937 };
2938
2939 //--------------------------------------------------------------------------
2940 // WebChromeClient implementation
2941 //--------------------------------------------------------------------------
2942
2943 /* package */ WebChromeClient getWebChromeClient() {
2944 return mWebChromeClient;
2945 }
2946
2947 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2948 // Helper method to create a new tab or sub window.
2949 private void createWindow(final boolean dialog, final Message msg) {
2950 if (dialog) {
2951 mTabControl.createSubWindow();
2952 final TabControl.Tab t = mTabControl.getCurrentTab();
2953 attachSubWindow(t);
2954 WebView.WebViewTransport transport =
2955 (WebView.WebViewTransport) msg.obj;
2956 transport.setWebView(t.getSubWebView());
2957 msg.sendToTarget();
2958 } else {
2959 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04002960 final TabControl.Tab newTab
2961 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07002962 if (newTab != parent) {
2963 parent.addChildTab(newTab);
2964 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002965 WebView.WebViewTransport transport =
2966 (WebView.WebViewTransport) msg.obj;
2967 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04002968 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002969 }
2970 }
2971
2972 @Override
2973 public boolean onCreateWindow(WebView view, final boolean dialog,
2974 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002975 // Short-circuit if we can't create any more tabs or sub windows.
2976 if (dialog && mTabControl.getCurrentSubWindow() != null) {
2977 new AlertDialog.Builder(BrowserActivity.this)
2978 .setTitle(R.string.too_many_subwindows_dialog_title)
2979 .setIcon(android.R.drawable.ic_dialog_alert)
2980 .setMessage(R.string.too_many_subwindows_dialog_message)
2981 .setPositiveButton(R.string.ok, null)
2982 .show();
2983 return false;
2984 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
2985 new AlertDialog.Builder(BrowserActivity.this)
2986 .setTitle(R.string.too_many_windows_dialog_title)
2987 .setIcon(android.R.drawable.ic_dialog_alert)
2988 .setMessage(R.string.too_many_windows_dialog_message)
2989 .setPositiveButton(R.string.ok, null)
2990 .show();
2991 return false;
2992 }
2993
2994 // Short-circuit if this was a user gesture.
2995 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002996 createWindow(dialog, resultMsg);
2997 return true;
2998 }
2999
3000 // Allow the popup and create the appropriate window.
3001 final AlertDialog.OnClickListener allowListener =
3002 new AlertDialog.OnClickListener() {
3003 public void onClick(DialogInterface d,
3004 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003005 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003006 }
3007 };
3008
3009 // Block the popup by returning a null WebView.
3010 final AlertDialog.OnClickListener blockListener =
3011 new AlertDialog.OnClickListener() {
3012 public void onClick(DialogInterface d, int which) {
3013 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003014 }
3015 };
3016
3017 // Build a confirmation dialog to display to the user.
3018 final AlertDialog d =
3019 new AlertDialog.Builder(BrowserActivity.this)
3020 .setTitle(R.string.attention)
3021 .setIcon(android.R.drawable.ic_dialog_alert)
3022 .setMessage(R.string.popup_window_attempt)
3023 .setPositiveButton(R.string.allow, allowListener)
3024 .setNegativeButton(R.string.block, blockListener)
3025 .setCancelable(false)
3026 .create();
3027
3028 // Show the confirmation dialog.
3029 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003030 return true;
3031 }
3032
3033 @Override
3034 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003035 final TabControl.Tab current = mTabControl.getCurrentTab();
3036 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003037 if (parent != null) {
3038 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003039 switchToTab(mTabControl.getTabIndex(parent));
3040 // Now we need to close the window
3041 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003042 }
3043 }
3044
3045 @Override
3046 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003047 mTitleBar.setProgress(newProgress);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003048 if (mFakeTitleBar != null) {
3049 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003050 }
3051
3052 if (newProgress == 100) {
3053 // onProgressChanged() is called for sub-frame too while
3054 // onPageFinished() is only called for the main frame. sync
3055 // cookie and cache promptly here.
3056 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003057 if (mInLoad) {
3058 mInLoad = false;
3059 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003060 // If the options menu is open, leave the title bar
3061 if (!mOptionsMenuOpen || !mIconView) {
3062 hideFakeTitleBar();
3063 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003064 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003065 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003066 // onPageFinished may have already been called but a subframe
3067 // is still loading and updating the progress. Reset mInLoad
3068 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003069 mInLoad = true;
3070 updateInLoadMenuItems();
3071 WebView currentWebView = mTabControl.getCurrentWebView();
3072 if ((currentWebView == null || currentWebView.getScrollY() != 0)
3073 && (!mOptionsMenuOpen || mIconView)) {
3074 // This page has begun to load, so show the title bar
3075 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003076 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003077 }
3078 }
3079
3080 @Override
3081 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003082 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003083
3084 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003085 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003086
3087 if (url == null ||
3088 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3089 return;
3090 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003091 // See if we can find the current url in our history database and
3092 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003093 if (url.startsWith("http://www.")) {
3094 url = url.substring(11);
3095 } else if (url.startsWith("http://")) {
3096 url = url.substring(4);
3097 }
3098 try {
3099 url = "%" + url;
3100 String [] selArgs = new String[] { url };
3101
3102 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3103 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3104 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3105 Browser.HISTORY_PROJECTION, where, selArgs, null);
3106 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003107 // Current implementation of database only has one entry per
3108 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003109 ContentValues map = new ContentValues();
3110 map.put(Browser.BookmarkColumns.TITLE, title);
3111 mResolver.update(Browser.BOOKMARKS_URI, map,
3112 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003113 }
3114 c.close();
3115 } catch (IllegalStateException e) {
3116 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3117 } catch (SQLiteException ex) {
3118 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3119 }
3120 }
3121
3122 @Override
3123 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003124 updateIcon(view, icon);
3125 }
3126
3127 @Override
3128 public void onReceivedTouchIconUrl(WebView view, String url) {
3129 final ContentResolver cr = getContentResolver();
3130 final Cursor c =
3131 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003132 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003133 if (c != null) {
3134 if (c.getCount() > 0) {
3135 new DownloadTouchIcon(cr, c, view).execute(url);
3136 } else {
3137 c.close();
3138 }
3139 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003140 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003141
Andrei Popescuadc008d2009-06-26 14:11:30 +01003142 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003143 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003144 if (mCustomView != null)
3145 return;
3146
3147 // Add the custom view to its container.
3148 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3149 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003150 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003151 // Save the menu state and set it to empty while the custom
3152 // view is showing.
3153 mOldMenuState = mMenuState;
3154 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003155 // Hide the content view.
3156 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003157 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003158 mCustomViewContainer.setVisibility(View.VISIBLE);
3159 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003160 }
3161
3162 @Override
3163 public void onHideCustomView() {
3164 if (mCustomView == null)
3165 return;
3166
Andrei Popescuc9b55562009-07-07 10:51:15 +01003167 // Hide the custom view.
3168 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003169 // Remove the custom view from its container.
3170 mCustomViewContainer.removeView(mCustomView);
3171 mCustomView = null;
3172 // Reset the old menu state.
3173 mMenuState = mOldMenuState;
3174 mOldMenuState = EMPTY_MENU;
3175 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003176 mCustomViewCallback.onCustomViewHidden();
3177 // Show the content view.
3178 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003179 }
3180
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003181 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003182 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003183 * @param url the URL that exceeded the quota
3184 * @param databaseIdentifier the identifier of the database on
3185 * which the transaction that caused the quota overflow was run
3186 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003187 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003188 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003189 * @param quotaUpdater The callback to run when a decision to allow or
3190 * deny quota has been made. Don't forget to call this!
3191 */
3192 @Override
3193 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003194 String databaseIdentifier, long currentQuota, long estimatedSize,
3195 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003196 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003197 url, databaseIdentifier, currentQuota, estimatedSize,
3198 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003199 }
3200
3201 /**
3202 * The Application Cache has exceeded its max size.
3203 * @param spaceNeeded is the amount of disk space that would be needed
3204 * in order for the last appcache operation to succeed.
3205 * @param totalUsedQuota is the sum of all origins' quota.
3206 * @param quotaUpdater A callback to inform the WebCore thread that a new
3207 * app cache size is available. This callback must always be executed at
3208 * some point to ensure that the sleeping WebCore thread is woken up.
3209 */
3210 @Override
3211 public void onReachedMaxAppCacheSize(long spaceNeeded,
3212 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3213 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3214 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003215 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003216
Steve Block2bc69912009-07-30 14:45:13 +01003217 /**
3218 * Instructs the browser to show a prompt to ask the user to set the
3219 * Geolocation permission state for the specified origin.
3220 * @param origin The origin for which Geolocation permissions are
3221 * requested.
3222 * @param callback The callback to call once the user has set the
3223 * Geolocation permission state.
3224 */
3225 @Override
3226 public void onGeolocationPermissionsShowPrompt(String origin,
3227 GeolocationPermissions.Callback callback) {
3228 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3229 origin, callback);
3230 }
3231
3232 /**
3233 * Instructs the browser to hide the Geolocation permissions prompt.
3234 */
3235 @Override
3236 public void onGeolocationPermissionsHidePrompt() {
3237 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3238 }
3239
Ben Murdoch7db26342009-06-03 18:21:19 +01003240 /* Adds a JavaScript error message to the system log.
3241 * @param message The error message to report.
3242 * @param lineNumber The line number of the error.
3243 * @param sourceID The name of the source file that caused the error.
3244 */
3245 @Override
3246 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003247 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3248 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3249 if (mShouldShowErrorConsole &&
3250 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3251 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3252 }
3253 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003254 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003255 };
3256
3257 /**
3258 * Notify the host application a download should be done, or that
3259 * the data should be streamed if a streaming viewer is available.
3260 * @param url The full url to the content that should be downloaded
3261 * @param contentDisposition Content-disposition http header, if
3262 * present.
3263 * @param mimetype The mimetype of the content reported by the server
3264 * @param contentLength The file size reported by the server
3265 */
3266 public void onDownloadStart(String url, String userAgent,
3267 String contentDisposition, String mimetype, long contentLength) {
3268 // if we're dealing wih A/V content that's not explicitly marked
3269 // for download, check if it's streamable.
3270 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003271 || !contentDisposition.regionMatches(
3272 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003273 // query the package manager to see if there's a registered handler
3274 // that matches.
3275 Intent intent = new Intent(Intent.ACTION_VIEW);
3276 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003277 ResolveInfo info = getPackageManager().resolveActivity(intent,
3278 PackageManager.MATCH_DEFAULT_ONLY);
3279 if (info != null) {
3280 ComponentName myName = getComponentName();
3281 // If we resolved to ourselves, we don't want to attempt to
3282 // load the url only to try and download it again.
3283 if (!myName.getPackageName().equals(
3284 info.activityInfo.packageName)
3285 || !myName.getClassName().equals(
3286 info.activityInfo.name)) {
3287 // someone (other than us) knows how to handle this mime
3288 // type with this scheme, don't download.
3289 try {
3290 startActivity(intent);
3291 return;
3292 } catch (ActivityNotFoundException ex) {
3293 if (LOGD_ENABLED) {
3294 Log.d(LOGTAG, "activity not found for " + mimetype
3295 + " over " + Uri.parse(url).getScheme(),
3296 ex);
3297 }
3298 // Best behavior is to fall back to a download in this
3299 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003300 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003301 }
3302 }
3303 }
3304 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3305 }
3306
3307 /**
3308 * Notify the host application a download should be done, even if there
3309 * is a streaming viewer available for thise type.
3310 * @param url The full url to the content that should be downloaded
3311 * @param contentDisposition Content-disposition http header, if
3312 * present.
3313 * @param mimetype The mimetype of the content reported by the server
3314 * @param contentLength The file size reported by the server
3315 */
3316 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3317 String contentDisposition, String mimetype, long contentLength) {
3318
3319 String filename = URLUtil.guessFileName(url,
3320 contentDisposition, mimetype);
3321
3322 // Check to see if we have an SDCard
3323 String status = Environment.getExternalStorageState();
3324 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3325 int title;
3326 String msg;
3327
3328 // Check to see if the SDCard is busy, same as the music app
3329 if (status.equals(Environment.MEDIA_SHARED)) {
3330 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3331 title = R.string.download_sdcard_busy_dlg_title;
3332 } else {
3333 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3334 title = R.string.download_no_sdcard_dlg_title;
3335 }
3336
3337 new AlertDialog.Builder(this)
3338 .setTitle(title)
3339 .setIcon(android.R.drawable.ic_dialog_alert)
3340 .setMessage(msg)
3341 .setPositiveButton(R.string.ok, null)
3342 .show();
3343 return;
3344 }
3345
3346 // java.net.URI is a lot stricter than KURL so we have to undo
3347 // KURL's percent-encoding and redo the encoding using java.net.URI.
3348 URI uri = null;
3349 try {
3350 // Undo the percent-encoding that KURL may have done.
3351 String newUrl = new String(URLUtil.decode(url.getBytes()));
3352 // Parse the url into pieces
3353 WebAddress w = new WebAddress(newUrl);
3354 String frag = null;
3355 String query = null;
3356 String path = w.mPath;
3357 // Break the path into path, query, and fragment
3358 if (path.length() > 0) {
3359 // Strip the fragment
3360 int idx = path.lastIndexOf('#');
3361 if (idx != -1) {
3362 frag = path.substring(idx + 1);
3363 path = path.substring(0, idx);
3364 }
3365 idx = path.lastIndexOf('?');
3366 if (idx != -1) {
3367 query = path.substring(idx + 1);
3368 path = path.substring(0, idx);
3369 }
3370 }
3371 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3372 query, frag);
3373 } catch (Exception e) {
3374 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3375 return;
3376 }
3377
3378 // XXX: Have to use the old url since the cookies were stored using the
3379 // old percent-encoded url.
3380 String cookies = CookieManager.getInstance().getCookie(url);
3381
3382 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003383 values.put(Downloads.COLUMN_URI, uri.toString());
3384 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3385 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3386 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003387 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003388 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003389 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003390 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3391 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3392 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3393 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003394 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003395 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003396 }
3397 if (mimetype == null) {
3398 // We must have long pressed on a link or image to download it. We
3399 // are not sure of the mimetype in this case, so do a head request
3400 new FetchUrlMimeType(this).execute(values);
3401 } else {
3402 final Uri contentUri =
3403 getContentResolver().insert(Downloads.CONTENT_URI, values);
3404 viewDownloads(contentUri);
3405 }
3406
3407 }
3408
3409 /**
3410 * Resets the lock icon. This method is called when we start a new load and
3411 * know the url to be loaded.
3412 */
3413 private void resetLockIcon(String url) {
3414 // Save the lock-icon state (we revert to it if the load gets cancelled)
3415 saveLockIcon();
3416
3417 mLockIconType = LOCK_ICON_UNSECURE;
3418 if (URLUtil.isHttpsUrl(url)) {
3419 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003420 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003421 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3422 " reset lock icon to " + mLockIconType);
3423 }
3424 }
3425
3426 updateLockIconImage(LOCK_ICON_UNSECURE);
3427 }
3428
3429 /**
3430 * Resets the lock icon. This method is called when the icon needs to be
3431 * reset but we do not know whether we are loading a secure or not secure
3432 * page.
3433 */
3434 private void resetLockIcon() {
3435 // Save the lock-icon state (we revert to it if the load gets cancelled)
3436 saveLockIcon();
3437
3438 mLockIconType = LOCK_ICON_UNSECURE;
3439
Dave Bort31a6d1c2009-04-13 15:56:49 -07003440 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003441 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3442 " reset lock icon to " + mLockIconType);
3443 }
3444
3445 updateLockIconImage(LOCK_ICON_UNSECURE);
3446 }
3447
3448 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003449 * Update the lock icon to correspond to our latest state.
3450 */
3451 /* package */ void updateLockIconToLatest() {
3452 updateLockIconImage(mLockIconType);
3453 }
3454
3455 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003456 * Updates the lock-icon image in the title-bar.
3457 */
3458 private void updateLockIconImage(int lockIconType) {
3459 Drawable d = null;
3460 if (lockIconType == LOCK_ICON_SECURE) {
3461 d = mSecLockIcon;
3462 } else if (lockIconType == LOCK_ICON_MIXED) {
3463 d = mMixLockIcon;
3464 }
Leon Scroggins68579392009-09-15 15:31:54 -04003465 mTitleBar.setLock(d);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003466 if (mFakeTitleBar != null) {
3467 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003468 }
3469 }
3470
3471 /**
3472 * Displays a page-info dialog.
3473 * @param tab The tab to show info about
3474 * @param fromShowSSLCertificateOnError The flag that indicates whether
3475 * this dialog was opened from the SSL-certificate-on-error dialog or
3476 * not. This is important, since we need to know whether to return to
3477 * the parent dialog or simply dismiss.
3478 */
3479 private void showPageInfo(final TabControl.Tab tab,
3480 final boolean fromShowSSLCertificateOnError) {
3481 final LayoutInflater factory = LayoutInflater
3482 .from(this);
3483
3484 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3485
3486 final WebView view = tab.getWebView();
3487
3488 String url = null;
3489 String title = null;
3490
3491 if (view == null) {
3492 url = tab.getUrl();
3493 title = tab.getTitle();
3494 } else if (view == mTabControl.getCurrentWebView()) {
3495 // Use the cached title and url if this is the current WebView
3496 url = mUrl;
3497 title = mTitle;
3498 } else {
3499 url = view.getUrl();
3500 title = view.getTitle();
3501 }
3502
3503 if (url == null) {
3504 url = "";
3505 }
3506 if (title == null) {
3507 title = "";
3508 }
3509
3510 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3511 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3512
3513 mPageInfoView = tab;
3514 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3515
3516 AlertDialog.Builder alertDialogBuilder =
3517 new AlertDialog.Builder(this)
3518 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3519 .setView(pageInfoView)
3520 .setPositiveButton(
3521 R.string.ok,
3522 new DialogInterface.OnClickListener() {
3523 public void onClick(DialogInterface dialog,
3524 int whichButton) {
3525 mPageInfoDialog = null;
3526 mPageInfoView = null;
3527 mPageInfoFromShowSSLCertificateOnError = null;
3528
3529 // if we came here from the SSL error dialog
3530 if (fromShowSSLCertificateOnError) {
3531 // go back to the SSL error dialog
3532 showSSLCertificateOnError(
3533 mSSLCertificateOnErrorView,
3534 mSSLCertificateOnErrorHandler,
3535 mSSLCertificateOnErrorError);
3536 }
3537 }
3538 })
3539 .setOnCancelListener(
3540 new DialogInterface.OnCancelListener() {
3541 public void onCancel(DialogInterface dialog) {
3542 mPageInfoDialog = null;
3543 mPageInfoView = null;
3544 mPageInfoFromShowSSLCertificateOnError = null;
3545
3546 // if we came here from the SSL error dialog
3547 if (fromShowSSLCertificateOnError) {
3548 // go back to the SSL error dialog
3549 showSSLCertificateOnError(
3550 mSSLCertificateOnErrorView,
3551 mSSLCertificateOnErrorHandler,
3552 mSSLCertificateOnErrorError);
3553 }
3554 }
3555 });
3556
3557 // if we have a main top-level page SSL certificate set or a certificate
3558 // error
3559 if (fromShowSSLCertificateOnError ||
3560 (view != null && view.getCertificate() != null)) {
3561 // add a 'View Certificate' button
3562 alertDialogBuilder.setNeutralButton(
3563 R.string.view_certificate,
3564 new DialogInterface.OnClickListener() {
3565 public void onClick(DialogInterface dialog,
3566 int whichButton) {
3567 mPageInfoDialog = null;
3568 mPageInfoView = null;
3569 mPageInfoFromShowSSLCertificateOnError = null;
3570
3571 // if we came here from the SSL error dialog
3572 if (fromShowSSLCertificateOnError) {
3573 // go back to the SSL error dialog
3574 showSSLCertificateOnError(
3575 mSSLCertificateOnErrorView,
3576 mSSLCertificateOnErrorHandler,
3577 mSSLCertificateOnErrorError);
3578 } else {
3579 // otherwise, display the top-most certificate from
3580 // the chain
3581 if (view.getCertificate() != null) {
3582 showSSLCertificate(tab);
3583 }
3584 }
3585 }
3586 });
3587 }
3588
3589 mPageInfoDialog = alertDialogBuilder.show();
3590 }
3591
3592 /**
3593 * Displays the main top-level page SSL certificate dialog
3594 * (accessible from the Page-Info dialog).
3595 * @param tab The tab to show certificate for.
3596 */
3597 private void showSSLCertificate(final TabControl.Tab tab) {
3598 final View certificateView =
3599 inflateCertificateView(tab.getWebView().getCertificate());
3600 if (certificateView == null) {
3601 return;
3602 }
3603
3604 LayoutInflater factory = LayoutInflater.from(this);
3605
3606 final LinearLayout placeholder =
3607 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3608
3609 LinearLayout ll = (LinearLayout) factory.inflate(
3610 R.layout.ssl_success, placeholder);
3611 ((TextView)ll.findViewById(R.id.success))
3612 .setText(R.string.ssl_certificate_is_valid);
3613
3614 mSSLCertificateView = tab;
3615 mSSLCertificateDialog =
3616 new AlertDialog.Builder(this)
3617 .setTitle(R.string.ssl_certificate).setIcon(
3618 R.drawable.ic_dialog_browser_certificate_secure)
3619 .setView(certificateView)
3620 .setPositiveButton(R.string.ok,
3621 new DialogInterface.OnClickListener() {
3622 public void onClick(DialogInterface dialog,
3623 int whichButton) {
3624 mSSLCertificateDialog = null;
3625 mSSLCertificateView = null;
3626
3627 showPageInfo(tab, false);
3628 }
3629 })
3630 .setOnCancelListener(
3631 new DialogInterface.OnCancelListener() {
3632 public void onCancel(DialogInterface dialog) {
3633 mSSLCertificateDialog = null;
3634 mSSLCertificateView = null;
3635
3636 showPageInfo(tab, false);
3637 }
3638 })
3639 .show();
3640 }
3641
3642 /**
3643 * Displays the SSL error certificate dialog.
3644 * @param view The target web-view.
3645 * @param handler The SSL error handler responsible for cancelling the
3646 * connection that resulted in an SSL error or proceeding per user request.
3647 * @param error The SSL error object.
3648 */
3649 private void showSSLCertificateOnError(
3650 final WebView view, final SslErrorHandler handler, final SslError error) {
3651
3652 final View certificateView =
3653 inflateCertificateView(error.getCertificate());
3654 if (certificateView == null) {
3655 return;
3656 }
3657
3658 LayoutInflater factory = LayoutInflater.from(this);
3659
3660 final LinearLayout placeholder =
3661 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3662
3663 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3664 LinearLayout ll = (LinearLayout)factory
3665 .inflate(R.layout.ssl_warning, placeholder);
3666 ((TextView)ll.findViewById(R.id.warning))
3667 .setText(R.string.ssl_untrusted);
3668 }
3669
3670 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3671 LinearLayout ll = (LinearLayout)factory
3672 .inflate(R.layout.ssl_warning, placeholder);
3673 ((TextView)ll.findViewById(R.id.warning))
3674 .setText(R.string.ssl_mismatch);
3675 }
3676
3677 if (error.hasError(SslError.SSL_EXPIRED)) {
3678 LinearLayout ll = (LinearLayout)factory
3679 .inflate(R.layout.ssl_warning, placeholder);
3680 ((TextView)ll.findViewById(R.id.warning))
3681 .setText(R.string.ssl_expired);
3682 }
3683
3684 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3685 LinearLayout ll = (LinearLayout)factory
3686 .inflate(R.layout.ssl_warning, placeholder);
3687 ((TextView)ll.findViewById(R.id.warning))
3688 .setText(R.string.ssl_not_yet_valid);
3689 }
3690
3691 mSSLCertificateOnErrorHandler = handler;
3692 mSSLCertificateOnErrorView = view;
3693 mSSLCertificateOnErrorError = error;
3694 mSSLCertificateOnErrorDialog =
3695 new AlertDialog.Builder(this)
3696 .setTitle(R.string.ssl_certificate).setIcon(
3697 R.drawable.ic_dialog_browser_certificate_partially_secure)
3698 .setView(certificateView)
3699 .setPositiveButton(R.string.ok,
3700 new DialogInterface.OnClickListener() {
3701 public void onClick(DialogInterface dialog,
3702 int whichButton) {
3703 mSSLCertificateOnErrorDialog = null;
3704 mSSLCertificateOnErrorView = null;
3705 mSSLCertificateOnErrorHandler = null;
3706 mSSLCertificateOnErrorError = null;
3707
3708 mWebViewClient.onReceivedSslError(
3709 view, handler, error);
3710 }
3711 })
3712 .setNeutralButton(R.string.page_info_view,
3713 new DialogInterface.OnClickListener() {
3714 public void onClick(DialogInterface dialog,
3715 int whichButton) {
3716 mSSLCertificateOnErrorDialog = null;
3717
3718 // do not clear the dialog state: we will
3719 // need to show the dialog again once the
3720 // user is done exploring the page-info details
3721
3722 showPageInfo(mTabControl.getTabFromView(view),
3723 true);
3724 }
3725 })
3726 .setOnCancelListener(
3727 new DialogInterface.OnCancelListener() {
3728 public void onCancel(DialogInterface dialog) {
3729 mSSLCertificateOnErrorDialog = null;
3730 mSSLCertificateOnErrorView = null;
3731 mSSLCertificateOnErrorHandler = null;
3732 mSSLCertificateOnErrorError = null;
3733
3734 mWebViewClient.onReceivedSslError(
3735 view, handler, error);
3736 }
3737 })
3738 .show();
3739 }
3740
3741 /**
3742 * Inflates the SSL certificate view (helper method).
3743 * @param certificate The SSL certificate.
3744 * @return The resultant certificate view with issued-to, issued-by,
3745 * issued-on, expires-on, and possibly other fields set.
3746 * If the input certificate is null, returns null.
3747 */
3748 private View inflateCertificateView(SslCertificate certificate) {
3749 if (certificate == null) {
3750 return null;
3751 }
3752
3753 LayoutInflater factory = LayoutInflater.from(this);
3754
3755 View certificateView = factory.inflate(
3756 R.layout.ssl_certificate, null);
3757
3758 // issued to:
3759 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3760 if (issuedTo != null) {
3761 ((TextView) certificateView.findViewById(R.id.to_common))
3762 .setText(issuedTo.getCName());
3763 ((TextView) certificateView.findViewById(R.id.to_org))
3764 .setText(issuedTo.getOName());
3765 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3766 .setText(issuedTo.getUName());
3767 }
3768
3769 // issued by:
3770 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3771 if (issuedBy != null) {
3772 ((TextView) certificateView.findViewById(R.id.by_common))
3773 .setText(issuedBy.getCName());
3774 ((TextView) certificateView.findViewById(R.id.by_org))
3775 .setText(issuedBy.getOName());
3776 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3777 .setText(issuedBy.getUName());
3778 }
3779
3780 // issued on:
3781 String issuedOn = reformatCertificateDate(
3782 certificate.getValidNotBefore());
3783 ((TextView) certificateView.findViewById(R.id.issued_on))
3784 .setText(issuedOn);
3785
3786 // expires on:
3787 String expiresOn = reformatCertificateDate(
3788 certificate.getValidNotAfter());
3789 ((TextView) certificateView.findViewById(R.id.expires_on))
3790 .setText(expiresOn);
3791
3792 return certificateView;
3793 }
3794
3795 /**
3796 * Re-formats the certificate date (Date.toString()) string to
3797 * a properly localized date string.
3798 * @return Properly localized version of the certificate date string and
3799 * the original certificate date string if fails to localize.
3800 * If the original string is null, returns an empty string "".
3801 */
3802 private String reformatCertificateDate(String certificateDate) {
3803 String reformattedDate = null;
3804
3805 if (certificateDate != null) {
3806 Date date = null;
3807 try {
3808 date = java.text.DateFormat.getInstance().parse(certificateDate);
3809 } catch (ParseException e) {
3810 date = null;
3811 }
3812
3813 if (date != null) {
3814 reformattedDate =
3815 DateFormat.getDateFormat(this).format(date);
3816 }
3817 }
3818
3819 return reformattedDate != null ? reformattedDate :
3820 (certificateDate != null ? certificateDate : "");
3821 }
3822
3823 /**
3824 * Displays an http-authentication dialog.
3825 */
3826 private void showHttpAuthentication(final HttpAuthHandler handler,
3827 final String host, final String realm, final String title,
3828 final String name, final String password, int focusId) {
3829 LayoutInflater factory = LayoutInflater.from(this);
3830 final View v = factory
3831 .inflate(R.layout.http_authentication, null);
3832 if (name != null) {
3833 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3834 }
3835 if (password != null) {
3836 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3837 }
3838
3839 String titleText = title;
3840 if (titleText == null) {
3841 titleText = getText(R.string.sign_in_to).toString().replace(
3842 "%s1", host).replace("%s2", realm);
3843 }
3844
3845 mHttpAuthHandler = handler;
3846 AlertDialog dialog = new AlertDialog.Builder(this)
3847 .setTitle(titleText)
3848 .setIcon(android.R.drawable.ic_dialog_alert)
3849 .setView(v)
3850 .setPositiveButton(R.string.action,
3851 new DialogInterface.OnClickListener() {
3852 public void onClick(DialogInterface dialog,
3853 int whichButton) {
3854 String nm = ((EditText) v
3855 .findViewById(R.id.username_edit))
3856 .getText().toString();
3857 String pw = ((EditText) v
3858 .findViewById(R.id.password_edit))
3859 .getText().toString();
3860 BrowserActivity.this.setHttpAuthUsernamePassword
3861 (host, realm, nm, pw);
3862 handler.proceed(nm, pw);
3863 mHttpAuthenticationDialog = null;
3864 mHttpAuthHandler = null;
3865 }})
3866 .setNegativeButton(R.string.cancel,
3867 new DialogInterface.OnClickListener() {
3868 public void onClick(DialogInterface dialog,
3869 int whichButton) {
3870 handler.cancel();
3871 BrowserActivity.this.resetTitleAndRevertLockIcon();
3872 mHttpAuthenticationDialog = null;
3873 mHttpAuthHandler = null;
3874 }})
3875 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3876 public void onCancel(DialogInterface dialog) {
3877 handler.cancel();
3878 BrowserActivity.this.resetTitleAndRevertLockIcon();
3879 mHttpAuthenticationDialog = null;
3880 mHttpAuthHandler = null;
3881 }})
3882 .create();
3883 // Make the IME appear when the dialog is displayed if applicable.
3884 dialog.getWindow().setSoftInputMode(
3885 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3886 dialog.show();
3887 if (focusId != 0) {
3888 dialog.findViewById(focusId).requestFocus();
3889 } else {
3890 v.findViewById(R.id.username_edit).requestFocus();
3891 }
3892 mHttpAuthenticationDialog = dialog;
3893 }
3894
3895 public int getProgress() {
3896 WebView w = mTabControl.getCurrentWebView();
3897 if (w != null) {
3898 return w.getProgress();
3899 } else {
3900 return 100;
3901 }
3902 }
3903
3904 /**
3905 * Set HTTP authentication password.
3906 *
3907 * @param host The host for the password
3908 * @param realm The realm for the password
3909 * @param username The username for the password. If it is null, it means
3910 * password can't be saved.
3911 * @param password The password
3912 */
3913 public void setHttpAuthUsernamePassword(String host, String realm,
3914 String username,
3915 String password) {
3916 WebView w = mTabControl.getCurrentWebView();
3917 if (w != null) {
3918 w.setHttpAuthUsernamePassword(host, realm, username, password);
3919 }
3920 }
3921
3922 /**
3923 * connectivity manager says net has come or gone... inform the user
3924 * @param up true if net has come up, false if net has gone down
3925 */
3926 public void onNetworkToggle(boolean up) {
3927 if (up == mIsNetworkUp) {
3928 return;
3929 } else if (up) {
3930 mIsNetworkUp = true;
3931 if (mAlertDialog != null) {
3932 mAlertDialog.cancel();
3933 mAlertDialog = null;
3934 }
3935 } else {
3936 mIsNetworkUp = false;
3937 if (mInLoad && mAlertDialog == null) {
3938 mAlertDialog = new AlertDialog.Builder(this)
3939 .setTitle(R.string.loadSuspendedTitle)
3940 .setMessage(R.string.loadSuspended)
3941 .setPositiveButton(R.string.ok, null)
3942 .show();
3943 }
3944 }
3945 WebView w = mTabControl.getCurrentWebView();
3946 if (w != null) {
3947 w.setNetworkAvailable(up);
3948 }
3949 }
3950
3951 @Override
3952 protected void onActivityResult(int requestCode, int resultCode,
3953 Intent intent) {
3954 switch (requestCode) {
3955 case COMBO_PAGE:
3956 if (resultCode == RESULT_OK && intent != null) {
3957 String data = intent.getAction();
3958 Bundle extras = intent.getExtras();
3959 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003960 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003961 } else {
3962 final TabControl.Tab currentTab =
3963 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003964 dismissSubWindow(currentTab);
3965 if (data != null && data.length() != 0) {
3966 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003967 }
3968 }
3969 }
3970 break;
3971 default:
3972 break;
3973 }
Leon Scroggins30444232009-09-04 18:36:20 -04003974 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003975 }
3976
3977 /*
3978 * This method is called as a result of the user selecting the options
3979 * menu to see the download window, or when a download changes state. It
3980 * shows the download window ontop of the current window.
3981 */
3982 /* package */ void viewDownloads(Uri downloadRecord) {
3983 Intent intent = new Intent(this,
3984 BrowserDownloadPage.class);
3985 intent.setData(downloadRecord);
3986 startActivityForResult(intent, this.DOWNLOAD_PAGE);
3987
3988 }
3989
Leon Scroggins160a7e72009-08-14 18:28:01 -04003990 /**
3991 * Open the Go page.
3992 * @param startWithHistory If true, open starting on the history tab.
3993 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003994 */
Leon Scroggins30444232009-09-04 18:36:20 -04003995 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003996 WebView current = mTabControl.getCurrentWebView();
3997 if (current == null) {
3998 return;
3999 }
4000 Intent intent = new Intent(this,
4001 CombinedBookmarkHistoryActivity.class);
4002 String title = current.getTitle();
4003 String url = current.getUrl();
4004 // Just in case the user opens bookmarks before a page finishes loading
4005 // so the current history item, and therefore the page, is null.
4006 if (null == url) {
4007 url = mLastEnteredUrl;
4008 // This can happen.
4009 if (null == url) {
4010 url = mSettings.getHomePage();
4011 }
4012 }
4013 // In case the web page has not yet received its associated title.
4014 if (title == null) {
4015 title = url;
4016 }
4017 intent.putExtra("title", title);
4018 intent.putExtra("url", url);
Leon Scroggins30444232009-09-04 18:36:20 -04004019 // Disable opening in a new window if we have maxed out the windows
4020 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4021 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004022 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004023 if (startWithHistory) {
4024 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4025 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4026 }
4027 startActivityForResult(intent, COMBO_PAGE);
4028 }
4029
4030 // Called when loading from context menu or LOAD_URL message
4031 private void loadURL(WebView view, String url) {
4032 // In case the user enters nothing.
4033 if (url != null && url.length() != 0 && view != null) {
4034 url = smartUrlFilter(url);
4035 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4036 view.loadUrl(url);
4037 }
4038 }
4039 }
4040
The Android Open Source Project0c908882009-03-03 19:32:16 -08004041 private String smartUrlFilter(Uri inUri) {
4042 if (inUri != null) {
4043 return smartUrlFilter(inUri.toString());
4044 }
4045 return null;
4046 }
4047
4048
4049 // get window count
4050
4051 int getWindowCount(){
4052 if(mTabControl != null){
4053 return mTabControl.getTabCount();
4054 }
4055 return 0;
4056 }
4057
Feng Qianb34f87a2009-03-24 21:27:26 -07004058 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004059 "(?i)" + // switch on case insensitive matching
4060 "(" + // begin group for schema
4061 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004062 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004063 ")" +
4064 "(.*)" );
4065
4066 /**
4067 * Attempts to determine whether user input is a URL or search
4068 * terms. Anything with a space is passed to search.
4069 *
4070 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4071 * "Http://" converts to "http://"
4072 *
4073 * @return Original or modified URL
4074 *
4075 */
4076 String smartUrlFilter(String url) {
4077
4078 String inUrl = url.trim();
4079 boolean hasSpace = inUrl.indexOf(' ') != -1;
4080
4081 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4082 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004083 // force scheme to lowercase
4084 String scheme = matcher.group(1);
4085 String lcScheme = scheme.toLowerCase();
4086 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004087 inUrl = lcScheme + matcher.group(2);
4088 }
4089 if (hasSpace) {
4090 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004091 }
4092 return inUrl;
4093 }
4094 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004095 // FIXME: Is this the correct place to add to searches?
4096 // what if someone else calls this function?
4097 int shortcut = parseUrlShortcut(inUrl);
4098 if (shortcut != SHORTCUT_INVALID) {
4099 Browser.addSearchUrl(mResolver, inUrl);
4100 String query = inUrl.substring(2);
4101 switch (shortcut) {
4102 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004103 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004104 case SHORTCUT_WIKIPEDIA_SEARCH:
4105 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4106 case SHORTCUT_DICTIONARY_SEARCH:
4107 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4108 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004109 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004110 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004111 }
4112 }
4113 } else {
4114 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4115 return URLUtil.guessUrl(inUrl);
4116 }
4117 }
4118
4119 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004120 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004121 }
4122
Ben Murdochbff2d602009-07-01 20:19:05 +01004123 /* package */ void setShouldShowErrorConsole(boolean flag) {
4124 if (flag == mShouldShowErrorConsole) {
4125 // Nothing to do.
4126 return;
4127 }
4128
4129 mShouldShowErrorConsole = flag;
4130
4131 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4132
4133 if (flag) {
4134 // Setting the show state of the console will cause it's the layout to be inflated.
4135 if (errorConsole.numberOfErrors() > 0) {
4136 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4137 } else {
4138 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4139 }
4140
4141 // Now we can add it to the main view.
4142 mErrorConsoleContainer.addView(errorConsole,
4143 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4144 ViewGroup.LayoutParams.WRAP_CONTENT));
4145 } else {
4146 mErrorConsoleContainer.removeView(errorConsole);
4147 }
4148
4149 }
4150
The Android Open Source Project0c908882009-03-03 19:32:16 -08004151 private final static int LOCK_ICON_UNSECURE = 0;
4152 private final static int LOCK_ICON_SECURE = 1;
4153 private final static int LOCK_ICON_MIXED = 2;
4154
4155 private int mLockIconType = LOCK_ICON_UNSECURE;
4156 private int mPrevLockType = LOCK_ICON_UNSECURE;
4157
4158 private BrowserSettings mSettings;
4159 private TabControl mTabControl;
4160 private ContentResolver mResolver;
4161 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004162 private View mCustomView;
4163 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004164 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004165
4166 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4167 // view, we should rewrite this.
4168 private int mCurrentMenuState = 0;
4169 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004170 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004171 private static final int EMPTY_MENU = -1;
4172 private Menu mMenu;
4173
4174 private FindDialog mFindDialog;
4175 // Used to prevent chording to result in firing two shortcuts immediately
4176 // one after another. Fixes bug 1211714.
4177 boolean mCanChord;
4178
4179 private boolean mInLoad;
4180 private boolean mIsNetworkUp;
4181
4182 private boolean mPageStarted;
4183 private boolean mActivityInPause = true;
4184
4185 private boolean mMenuIsDown;
4186
4187 private final KeyTracker mKeyTracker = new KeyTracker(this);
4188
4189 // As trackball doesn't send repeat down, we have to track it ourselves
4190 private boolean mTrackTrackball;
4191
4192 private static boolean mInTrace;
4193
4194 // Performance probe
4195 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4196 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4197 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4198 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4199 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4200 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4201 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4202 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4203 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4204 };
4205
4206 private long mStart;
4207 private long mProcessStart;
4208 private long mUserStart;
4209 private long mSystemStart;
4210 private long mIdleStart;
4211 private long mIrqStart;
4212
4213 private long mUiStart;
4214
4215 private Drawable mMixLockIcon;
4216 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004217
4218 /* hold a ref so we can auto-cancel if necessary */
4219 private AlertDialog mAlertDialog;
4220
4221 // Wait for credentials before loading google.com
4222 private ProgressDialog mCredsDlg;
4223
4224 // The up-to-date URL and title (these can be different from those stored
4225 // in WebView, since it takes some time for the information in WebView to
4226 // get updated)
4227 private String mUrl;
4228 private String mTitle;
4229
4230 // As PageInfo has different style for landscape / portrait, we have
4231 // to re-open it when configuration changed
4232 private AlertDialog mPageInfoDialog;
4233 private TabControl.Tab mPageInfoView;
4234 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4235 // dialog, we should not just dismiss it, but should get back to the
4236 // SSL-certificate-on-error dialog. This flag is used to store this state
4237 private Boolean mPageInfoFromShowSSLCertificateOnError;
4238
4239 // as SSLCertificateOnError has different style for landscape / portrait,
4240 // we have to re-open it when configuration changed
4241 private AlertDialog mSSLCertificateOnErrorDialog;
4242 private WebView mSSLCertificateOnErrorView;
4243 private SslErrorHandler mSSLCertificateOnErrorHandler;
4244 private SslError mSSLCertificateOnErrorError;
4245
4246 // as SSLCertificate has different style for landscape / portrait, we
4247 // have to re-open it when configuration changed
4248 private AlertDialog mSSLCertificateDialog;
4249 private TabControl.Tab mSSLCertificateView;
4250
4251 // as HttpAuthentication has different style for landscape / portrait, we
4252 // have to re-open it when configuration changed
4253 private AlertDialog mHttpAuthenticationDialog;
4254 private HttpAuthHandler mHttpAuthHandler;
4255
4256 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4257 new FrameLayout.LayoutParams(
4258 ViewGroup.LayoutParams.FILL_PARENT,
4259 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004260 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4261 new FrameLayout.LayoutParams(
4262 ViewGroup.LayoutParams.FILL_PARENT,
4263 ViewGroup.LayoutParams.FILL_PARENT,
4264 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004265 // Google search
4266 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004267 // Wikipedia search
4268 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4269 // Dictionary search
4270 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4271 // Google Mobile Local search
4272 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4273
4274 final static String QUERY_PLACE_HOLDER = "%s";
4275
4276 // "source" parameter for Google search through search key
4277 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4278 // "source" parameter for Google search through goto menu
4279 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4280 // "source" parameter for Google search through simplily type
4281 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4282 // "source" parameter for Google search suggested by the browser
4283 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4284 // "source" parameter for Google search from unknown source
4285 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4286
4287 private final static String LOGTAG = "browser";
4288
The Android Open Source Project0c908882009-03-03 19:32:16 -08004289 private String mLastEnteredUrl;
4290
4291 private PowerManager.WakeLock mWakeLock;
4292 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4293
4294 private Toast mStopToast;
4295
Leon Scroggins68579392009-09-15 15:31:54 -04004296 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004297
Ben Murdochbff2d602009-07-01 20:19:05 +01004298 private LinearLayout mErrorConsoleContainer = null;
4299 private boolean mShouldShowErrorConsole = false;
4300
The Android Open Source Project0c908882009-03-03 19:32:16 -08004301 // As the ids are dynamically created, we can't guarantee that they will
4302 // be in sequence, so this static array maps ids to a window number.
4303 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4304 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4305 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4306 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4307
4308 // monitor platform changes
4309 private IntentFilter mNetworkStateChangedFilter;
4310 private BroadcastReceiver mNetworkStateIntentReceiver;
4311
Grace Klobab4da0ad2009-05-14 14:45:40 -07004312 private BroadcastReceiver mPackageInstallationReceiver;
4313
The Android Open Source Project0c908882009-03-03 19:32:16 -08004314 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004315 final static int COMBO_PAGE = 1;
4316 final static int DOWNLOAD_PAGE = 2;
4317 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004318
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004319 /**
4320 * A UrlData class to abstract how the content will be set to WebView.
4321 * This base class uses loadUrl to show the content.
4322 */
4323 private static class UrlData {
4324 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004325 byte[] mPostData;
4326
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004327 UrlData(String url) {
4328 this.mUrl = url;
4329 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004330
4331 void setPostData(byte[] postData) {
4332 mPostData = postData;
4333 }
4334
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004335 boolean isEmpty() {
4336 return mUrl == null || mUrl.length() == 0;
4337 }
4338
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004339 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004340 if (mPostData != null) {
4341 webView.postUrl(mUrl, mPostData);
4342 } else {
4343 webView.loadUrl(mUrl);
4344 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004345 }
4346 };
4347
4348 /**
4349 * A subclass of UrlData class that can display inlined content using
4350 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4351 */
4352 private static class InlinedUrlData extends UrlData {
4353 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4354 super(failUrl);
4355 mInlined = inlined;
4356 mMimeType = mimeType;
4357 mEncoding = encoding;
4358 }
4359 String mMimeType;
4360 String mInlined;
4361 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004362 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004363 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004364 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004365 }
4366
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004367 @Override
4368 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004369 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4370 }
4371 }
4372
Leon Scroggins1f005d32009-08-10 17:36:42 -04004373 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004374}