blob: 896660bdf116e840d41fbe56ea1519074e0426c7 [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 Scroggins4d7e4062009-09-15 15:49:45 -0400938 if (mFakeTitleBar == null && mActiveTabsPage == null
939 && !mActivityInPause) {
Leon Scrogginsf4bb18a2009-09-11 18:37:53 -0400940 final WebView webView = getTopWindow();
Leon Scroggins68579392009-09-15 15:31:54 -0400941 mFakeTitleBar = new TitleBar(this);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400942 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
943 mFakeTitleBar.setProgress(webView.getProgress());
944 mFakeTitleBar.setFavicon(webView.getFavicon());
945 updateLockIconToLatest();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400946
947 WindowManager manager
948 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
949
950 // Add the title bar to the window manager so it can receive touches
951 // while the menu is up
952 WindowManager.LayoutParams params
953 = new WindowManager.LayoutParams(
954 ViewGroup.LayoutParams.FILL_PARENT,
955 ViewGroup.LayoutParams.WRAP_CONTENT,
956 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
957 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
958 PixelFormat.OPAQUE);
959 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400960 WebView mainView = mTabControl.getCurrentWebView();
961 params.windowAnimations = mainView == null
962 || mainView.getScrollY() != 0
963 ? com.android.internal.R.style.Animation_DropDownDown : 0;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400964 // XXX : Without providing an offset, the fake title bar will be
965 // placed underneath the status bar. Use the global visible rect
966 // of mBrowserFrameLayout to determine the bottom of the status bar
967 Rect rectangle = new Rect();
968 mBrowserFrameLayout.getGlobalVisibleRect(rectangle);
969 params.y = rectangle.top;
970 manager.addView(mFakeTitleBar, params);
971 }
972 }
973
974 @Override
975 public void onOptionsMenuClosed(Menu menu) {
976 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400977 if (!mInLoad) {
978 hideFakeTitleBar();
979 } else if (!mIconView) {
980 // The page is currently loading, and we are in expanded mode, so
981 // we were not showing the menu. Show it once again. It will be
982 // removed when the page finishes.
983 showFakeTitleBar();
984 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400985 }
986 private void hideFakeTitleBar() {
987 if (mFakeTitleBar == null) return;
988 WindowManager manager
989 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
990 manager.removeView(mFakeTitleBar);
991 mFakeTitleBar = null;
992 }
993
The Android Open Source Project0c908882009-03-03 19:32:16 -0800994 /**
995 * onSaveInstanceState(Bundle map)
996 * onSaveInstanceState is called right before onStop(). The map contains
997 * the saved state.
998 */
999 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001000 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001001 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1002 }
1003 // the default implementation requires each view to have an id. As the
1004 // browser handles the state itself and it doesn't use id for the views,
1005 // don't call the default implementation. Otherwise it will trigger the
1006 // warning like this, "couldn't save which view has focus because the
1007 // focused view XXX has no id".
1008
1009 // Save all the tabs
1010 mTabControl.saveState(outState);
1011 }
1012
1013 @Override protected void onPause() {
1014 super.onPause();
1015
1016 if (mActivityInPause) {
1017 Log.e(LOGTAG, "BrowserActivity is already paused.");
1018 return;
1019 }
1020
Mike Reed7bfa63b2009-05-28 11:08:32 -04001021 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001022 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001023 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001024 mWakeLock.acquire();
1025 mHandler.sendMessageDelayed(mHandler
1026 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1027 }
1028
1029 // Clear the credentials toast if it is up
1030 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1031 mCredsDlg.dismiss();
1032 }
1033 mCredsDlg = null;
1034
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001035 // FIXME: This removes the active tabs page and resets the menu to
1036 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1037 // but then we would need to save it in onSaveInstanceState and restore
1038 // it in onCreate/onRestoreInstanceState
1039 if (mActiveTabsPage != null) {
1040 removeActiveTabPage(true);
1041 }
1042
The Android Open Source Project0c908882009-03-03 19:32:16 -08001043 cancelStopToast();
1044
1045 // unregister network state listener
1046 unregisterReceiver(mNetworkStateIntentReceiver);
1047 WebView.disablePlatformNotifications();
1048
1049 if (mSensorManager != null) {
1050 mSensorManager.unregisterListener(mSensorListener);
1051 }
1052 }
1053
1054 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001055 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001056 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1057 }
1058 super.onDestroy();
1059 // Remove the current tab and sub window
1060 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001061 if (t != null) {
1062 dismissSubWindow(t);
1063 removeTabFromContentView(t);
1064 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001065 // Destroy all the tabs
1066 mTabControl.destroy();
1067 WebIconDatabase.getInstance().close();
1068 if (mGlsConnection != null) {
1069 unbindService(mGlsConnection);
1070 mGlsConnection = null;
1071 }
1072
1073 //
1074 // stop MASF proxy service
1075 //
1076 //Intent proxyServiceIntent = new Intent();
1077 //proxyServiceIntent.setComponent
1078 // (new ComponentName(
1079 // "com.android.masfproxyservice",
1080 // "com.android.masfproxyservice.MasfProxyService"));
1081 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001082
1083 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001084 }
1085
1086 @Override
1087 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001088 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001089 super.onConfigurationChanged(newConfig);
1090
1091 if (mPageInfoDialog != null) {
1092 mPageInfoDialog.dismiss();
1093 showPageInfo(
1094 mPageInfoView,
1095 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1096 }
1097 if (mSSLCertificateDialog != null) {
1098 mSSLCertificateDialog.dismiss();
1099 showSSLCertificate(
1100 mSSLCertificateView);
1101 }
1102 if (mSSLCertificateOnErrorDialog != null) {
1103 mSSLCertificateOnErrorDialog.dismiss();
1104 showSSLCertificateOnError(
1105 mSSLCertificateOnErrorView,
1106 mSSLCertificateOnErrorHandler,
1107 mSSLCertificateOnErrorError);
1108 }
1109 if (mHttpAuthenticationDialog != null) {
1110 String title = ((TextView) mHttpAuthenticationDialog
1111 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1112 .toString();
1113 String name = ((TextView) mHttpAuthenticationDialog
1114 .findViewById(R.id.username_edit)).getText().toString();
1115 String password = ((TextView) mHttpAuthenticationDialog
1116 .findViewById(R.id.password_edit)).getText().toString();
1117 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1118 .getId();
1119 mHttpAuthenticationDialog.dismiss();
1120 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1121 name, password, focusId);
1122 }
1123 if (mFindDialog != null && mFindDialog.isShowing()) {
1124 mFindDialog.onConfigurationChanged(newConfig);
1125 }
1126 }
1127
1128 @Override public void onLowMemory() {
1129 super.onLowMemory();
1130 mTabControl.freeMemory();
1131 }
1132
Mike Reed7bfa63b2009-05-28 11:08:32 -04001133 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001134 if ((!mActivityInPause && !mPageStarted) ||
1135 (mActivityInPause && mPageStarted)) {
1136 CookieSyncManager.getInstance().startSync();
1137 WebView w = mTabControl.getCurrentWebView();
1138 if (w != null) {
1139 w.resumeTimers();
1140 }
1141 return true;
1142 } else {
1143 return false;
1144 }
1145 }
1146
Mike Reed7bfa63b2009-05-28 11:08:32 -04001147 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001148 if (mActivityInPause && !mPageStarted) {
1149 CookieSyncManager.getInstance().stopSync();
1150 WebView w = mTabControl.getCurrentWebView();
1151 if (w != null) {
1152 w.pauseTimers();
1153 }
1154 return true;
1155 } else {
1156 return false;
1157 }
1158 }
1159
Leon Scroggins1f005d32009-08-10 17:36:42 -04001160 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001161 /*
1162 * This function is called when we are launching for the first time. We
1163 * are waiting for the login credentials before loading Google home
1164 * pages. This way the user will be logged in straight away.
1165 */
1166 private void waitForCredentials() {
1167 // Show a toast
1168 mCredsDlg = new ProgressDialog(this);
1169 mCredsDlg.setIndeterminate(true);
1170 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1171 // If the user cancels the operation, then cancel the Google
1172 // Credentials request.
1173 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1174 mCredsDlg.show();
1175
1176 // We set a timeout for the retrieval of credentials in onResume()
1177 // as that is when we have freed up some CPU time to get
1178 // the login credentials.
1179 }
1180
1181 /*
1182 * If we have received the credentials or we have timed out and we are
1183 * showing the credentials dialog, then it is time to move on.
1184 */
1185 private void resumeAfterCredentials() {
1186 if (mCredsDlg == null) {
1187 return;
1188 }
1189
1190 // Clear the toast
1191 if (mCredsDlg.isShowing()) {
1192 mCredsDlg.dismiss();
1193 }
1194 mCredsDlg = null;
1195
1196 // Clear any pending timeout
1197 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1198
1199 // Load the page
1200 WebView w = mTabControl.getCurrentWebView();
1201 if (w != null) {
1202 w.loadUrl(mSettings.getHomePage());
1203 }
1204
1205 // Update the settings, need to do this last as it can take a moment
1206 // to persist the settings. In the mean time we could be loading
1207 // content.
1208 mSettings.setLoginInitialized(this);
1209 }
1210
1211 // Open the icon database and retain all the icons for visited sites.
1212 private void retainIconsOnStartup() {
1213 final WebIconDatabase db = WebIconDatabase.getInstance();
1214 db.open(getDir("icons", 0).getPath());
1215 try {
1216 Cursor c = Browser.getAllBookmarks(mResolver);
1217 if (!c.moveToFirst()) {
1218 c.deactivate();
1219 return;
1220 }
1221 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1222 do {
1223 String url = c.getString(urlIndex);
1224 db.retainIconForPageUrl(url);
1225 } while (c.moveToNext());
1226 c.deactivate();
1227 } catch (IllegalStateException e) {
1228 Log.e(LOGTAG, "retainIconsOnStartup", e);
1229 }
1230 }
1231
1232 // Helper method for getting the top window.
1233 WebView getTopWindow() {
1234 return mTabControl.getCurrentTopWebView();
1235 }
1236
1237 @Override
1238 public boolean onCreateOptionsMenu(Menu menu) {
1239 super.onCreateOptionsMenu(menu);
1240
1241 MenuInflater inflater = getMenuInflater();
1242 inflater.inflate(R.menu.browser, menu);
1243 mMenu = menu;
1244 updateInLoadMenuItems();
1245 return true;
1246 }
1247
1248 /**
1249 * As the menu can be open when loading state changes
1250 * we must manually update the state of the stop/reload menu
1251 * item
1252 */
1253 private void updateInLoadMenuItems() {
1254 if (mMenu == null) {
1255 return;
1256 }
1257 MenuItem src = mInLoad ?
1258 mMenu.findItem(R.id.stop_menu_id):
1259 mMenu.findItem(R.id.reload_menu_id);
1260 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1261 dest.setIcon(src.getIcon());
1262 dest.setTitle(src.getTitle());
1263 }
1264
1265 @Override
1266 public boolean onContextItemSelected(MenuItem item) {
1267 // chording is not an issue with context menus, but we use the same
1268 // options selector, so set mCanChord to true so we can access them.
1269 mCanChord = true;
1270 int id = item.getItemId();
1271 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001272 if (null == webView) {
1273 return false;
1274 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001275 final HashMap hrefMap = new HashMap();
1276 hrefMap.put("webview", webView);
1277 final Message msg = mHandler.obtainMessage(
1278 FOCUS_NODE_HREF, id, 0, hrefMap);
1279 switch (id) {
1280 // -- Browser context menu
1281 case R.id.open_context_menu_id:
1282 case R.id.open_newtab_context_menu_id:
1283 case R.id.bookmark_context_menu_id:
1284 case R.id.save_link_context_menu_id:
1285 case R.id.share_link_context_menu_id:
1286 case R.id.copy_link_context_menu_id:
1287 webView.requestFocusNodeHref(msg);
1288 break;
1289
1290 default:
1291 // For other context menus
1292 return onOptionsItemSelected(item);
1293 }
1294 mCanChord = false;
1295 return true;
1296 }
1297
1298 private Bundle createGoogleSearchSourceBundle(String source) {
1299 Bundle bundle = new Bundle();
1300 bundle.putString(SearchManager.SOURCE, source);
1301 return bundle;
1302 }
1303
1304 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001305 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001306 */
1307 @Override
1308 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001309 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001310 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001311 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001312 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001313 return true;
1314 }
1315
1316 @Override
1317 public void startSearch(String initialQuery, boolean selectInitialQuery,
1318 Bundle appSearchData, boolean globalSearch) {
1319 if (appSearchData == null) {
1320 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1321 }
1322 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1323 }
1324
Leon Scroggins1f005d32009-08-10 17:36:42 -04001325 /**
1326 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1327 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001328 * @param index Index of the tab to change to, as defined by
1329 * mTabControl.getTabIndex(Tab t).
1330 * @return boolean True if we successfully switched to a different tab. If
1331 * the indexth tab is null, or if that tab is the same as
1332 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001333 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001334 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001335 TabControl.Tab tab = mTabControl.getTab(index);
1336 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1337 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001338 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001339 }
1340 if (currentTab != null) {
1341 // currentTab may be null if it was just removed. In that case,
1342 // we do not need to remove it
1343 removeTabFromContentView(currentTab);
1344 }
1345 removeTabFromContentView(tab);
1346 mTabControl.setCurrentTab(tab);
1347 attachTabToContentView(tab);
Patrick Scottdb22ea72009-09-15 10:57:22 -04001348 resetTitle();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001349 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001350 }
1351
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001352 /* package */ TabControl.Tab openTabToHomePage() {
1353 return openTabAndShow(mSettings.getHomePage(), false, null);
1354 }
1355
Leon Scroggins1f005d32009-08-10 17:36:42 -04001356 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001357 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001358 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001359 // This is the last tab. Open a new one, with the home
1360 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001361 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001362 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001363 return;
1364 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001365 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001366 int indexToShow = -1;
1367 if (parent != null) {
1368 indexToShow = mTabControl.getTabIndex(parent);
1369 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001370 final int currentIndex = mTabControl.getCurrentIndex();
1371 // Try to move to the tab to the right
1372 indexToShow = currentIndex + 1;
1373 if (indexToShow > mTabControl.getTabCount() - 1) {
1374 // Try to move to the tab to the left
1375 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001376 }
1377 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001378 if (switchToTab(indexToShow)) {
1379 // Close window
1380 closeTab(current);
1381 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001382 }
1383
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001384 private ActiveTabsPage mActiveTabsPage;
1385
1386 /**
1387 * Remove the active tabs page.
1388 * @param needToAttach If true, the active tabs page did not attach a tab
1389 * to the content view, so we need to do that here.
1390 */
1391 /* package */ void removeActiveTabPage(boolean needToAttach) {
1392 mContentView.removeView(mActiveTabsPage);
1393 mActiveTabsPage = null;
1394 mMenuState = R.id.MAIN_MENU;
1395 if (needToAttach) {
1396 attachTabToContentView(mTabControl.getCurrentTab());
1397 }
1398 getTopWindow().requestFocus();
1399 }
1400
The Android Open Source Project0c908882009-03-03 19:32:16 -08001401 @Override
1402 public boolean onOptionsItemSelected(MenuItem item) {
1403 if (!mCanChord) {
1404 // The user has already fired a shortcut with this hold down of the
1405 // menu key.
1406 return false;
1407 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001408 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001409 return false;
1410 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001411 if (mMenuIsDown) {
1412 // The shortcut action consumes the MENU. Even if it is still down,
1413 // it won't trigger the next shortcut action. In the case of the
1414 // shortcut action triggering a new activity, like Bookmarks, we
1415 // won't get onKeyUp for MENU. So it is important to reset it here.
1416 mMenuIsDown = false;
1417 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001418 switch (item.getItemId()) {
1419 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001420 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001421 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001422 break;
1423
Leon Scroggins64b80f32009-08-07 12:03:34 -04001424 case R.id.goto_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001425 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001426 break;
1427
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001428 case R.id.active_tabs_menu_id:
1429 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1430 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001431 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001432 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1433 mActiveTabsPage.requestFocus();
1434 mMenuState = EMPTY_MENU;
1435 break;
1436
Leon Scroggins1f005d32009-08-10 17:36:42 -04001437 case R.id.add_bookmark_menu_id:
1438 Intent i = new Intent(BrowserActivity.this,
1439 AddBookmarkPage.class);
1440 WebView w = getTopWindow();
1441 i.putExtra("url", w.getUrl());
1442 i.putExtra("title", w.getTitle());
1443 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001444 break;
1445
1446 case R.id.stop_reload_menu_id:
1447 if (mInLoad) {
1448 stopLoading();
1449 } else {
1450 getTopWindow().reload();
1451 }
1452 break;
1453
1454 case R.id.back_menu_id:
1455 getTopWindow().goBack();
1456 break;
1457
1458 case R.id.forward_menu_id:
1459 getTopWindow().goForward();
1460 break;
1461
1462 case R.id.close_menu_id:
1463 // Close the subwindow if it exists.
1464 if (mTabControl.getCurrentSubWindow() != null) {
1465 dismissSubWindow(mTabControl.getCurrentTab());
1466 break;
1467 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001468 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001469 break;
1470
1471 case R.id.homepage_menu_id:
1472 TabControl.Tab current = mTabControl.getCurrentTab();
1473 if (current != null) {
1474 dismissSubWindow(current);
1475 current.getWebView().loadUrl(mSettings.getHomePage());
1476 }
1477 break;
1478
1479 case R.id.preferences_menu_id:
1480 Intent intent = new Intent(this,
1481 BrowserPreferencesPage.class);
1482 startActivityForResult(intent, PREFERENCES_PAGE);
1483 break;
1484
1485 case R.id.find_menu_id:
1486 if (null == mFindDialog) {
1487 mFindDialog = new FindDialog(this);
1488 }
1489 mFindDialog.setWebView(getTopWindow());
1490 mFindDialog.show();
1491 mMenuState = EMPTY_MENU;
1492 break;
1493
1494 case R.id.select_text_id:
1495 getTopWindow().emulateShiftHeld();
1496 break;
1497 case R.id.page_info_menu_id:
1498 showPageInfo(mTabControl.getCurrentTab(), false);
1499 break;
1500
1501 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001502 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001503 break;
1504
1505 case R.id.share_page_menu_id:
1506 Browser.sendString(this, getTopWindow().getUrl());
1507 break;
1508
1509 case R.id.dump_nav_menu_id:
1510 getTopWindow().debugDump();
1511 break;
1512
1513 case R.id.zoom_in_menu_id:
1514 getTopWindow().zoomIn();
1515 break;
1516
1517 case R.id.zoom_out_menu_id:
1518 getTopWindow().zoomOut();
1519 break;
1520
1521 case R.id.view_downloads_menu_id:
1522 viewDownloads(null);
1523 break;
1524
The Android Open Source Project0c908882009-03-03 19:32:16 -08001525 case R.id.window_one_menu_id:
1526 case R.id.window_two_menu_id:
1527 case R.id.window_three_menu_id:
1528 case R.id.window_four_menu_id:
1529 case R.id.window_five_menu_id:
1530 case R.id.window_six_menu_id:
1531 case R.id.window_seven_menu_id:
1532 case R.id.window_eight_menu_id:
1533 {
1534 int menuid = item.getItemId();
1535 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1536 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1537 TabControl.Tab desiredTab = mTabControl.getTab(id);
1538 if (desiredTab != null &&
1539 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001540 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001541 }
1542 break;
1543 }
1544 }
1545 }
1546 break;
1547
1548 default:
1549 if (!super.onOptionsItemSelected(item)) {
1550 return false;
1551 }
1552 // Otherwise fall through.
1553 }
1554 mCanChord = false;
1555 return true;
1556 }
1557
1558 public void closeFind() {
1559 mMenuState = R.id.MAIN_MENU;
1560 }
1561
1562 @Override public boolean onPrepareOptionsMenu(Menu menu)
1563 {
1564 // This happens when the user begins to hold down the menu key, so
1565 // allow them to chord to get a shortcut.
1566 mCanChord = true;
1567 // Note: setVisible will decide whether an item is visible; while
1568 // setEnabled() will decide whether an item is enabled, which also means
1569 // whether the matching shortcut key will function.
1570 super.onPrepareOptionsMenu(menu);
1571 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001572 case EMPTY_MENU:
1573 if (mCurrentMenuState != mMenuState) {
1574 menu.setGroupVisible(R.id.MAIN_MENU, false);
1575 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1576 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001577 }
1578 break;
1579 default:
1580 if (mCurrentMenuState != mMenuState) {
1581 menu.setGroupVisible(R.id.MAIN_MENU, true);
1582 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1583 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001584 }
1585 final WebView w = getTopWindow();
1586 boolean canGoBack = false;
1587 boolean canGoForward = false;
1588 boolean isHome = false;
1589 if (w != null) {
1590 canGoBack = w.canGoBack();
1591 canGoForward = w.canGoForward();
1592 isHome = mSettings.getHomePage().equals(w.getUrl());
1593 }
1594 final MenuItem back = menu.findItem(R.id.back_menu_id);
1595 back.setEnabled(canGoBack);
1596
1597 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1598 home.setEnabled(!isHome);
1599
1600 menu.findItem(R.id.forward_menu_id)
1601 .setEnabled(canGoForward);
1602
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001603 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1604 mTabControl.getTabCount() < TabControl.MAX_TABS);
1605
The Android Open Source Project0c908882009-03-03 19:32:16 -08001606 // decide whether to show the share link option
1607 PackageManager pm = getPackageManager();
1608 Intent send = new Intent(Intent.ACTION_SEND);
1609 send.setType("text/plain");
1610 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1611 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1612
The Android Open Source Project0c908882009-03-03 19:32:16 -08001613 boolean isNavDump = mSettings.isNavDump();
1614 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1615 nav.setVisible(isNavDump);
1616 nav.setEnabled(isNavDump);
1617 break;
1618 }
1619 mCurrentMenuState = mMenuState;
1620 return true;
1621 }
1622
1623 @Override
1624 public void onCreateContextMenu(ContextMenu menu, View v,
1625 ContextMenuInfo menuInfo) {
1626 WebView webview = (WebView) v;
1627 WebView.HitTestResult result = webview.getHitTestResult();
1628 if (result == null) {
1629 return;
1630 }
1631
1632 int type = result.getType();
1633 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1634 Log.w(LOGTAG,
1635 "We should not show context menu when nothing is touched");
1636 return;
1637 }
1638 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1639 // let TextView handles context menu
1640 return;
1641 }
1642
1643 // Note, http://b/issue?id=1106666 is requesting that
1644 // an inflated menu can be used again. This is not available
1645 // yet, so inflate each time (yuk!)
1646 MenuInflater inflater = getMenuInflater();
1647 inflater.inflate(R.menu.browsercontext, menu);
1648
1649 // Show the correct menu group
1650 String extra = result.getExtra();
1651 menu.setGroupVisible(R.id.PHONE_MENU,
1652 type == WebView.HitTestResult.PHONE_TYPE);
1653 menu.setGroupVisible(R.id.EMAIL_MENU,
1654 type == WebView.HitTestResult.EMAIL_TYPE);
1655 menu.setGroupVisible(R.id.GEO_MENU,
1656 type == WebView.HitTestResult.GEO_TYPE);
1657 menu.setGroupVisible(R.id.IMAGE_MENU,
1658 type == WebView.HitTestResult.IMAGE_TYPE
1659 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1660 menu.setGroupVisible(R.id.ANCHOR_MENU,
1661 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1662 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1663
1664 // Setup custom handling depending on the type
1665 switch (type) {
1666 case WebView.HitTestResult.PHONE_TYPE:
1667 menu.setHeaderTitle(Uri.decode(extra));
1668 menu.findItem(R.id.dial_context_menu_id).setIntent(
1669 new Intent(Intent.ACTION_VIEW, Uri
1670 .parse(WebView.SCHEME_TEL + extra)));
1671 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1672 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1673 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1674 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1675 addIntent);
1676 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1677 new Copy(extra));
1678 break;
1679
1680 case WebView.HitTestResult.EMAIL_TYPE:
1681 menu.setHeaderTitle(extra);
1682 menu.findItem(R.id.email_context_menu_id).setIntent(
1683 new Intent(Intent.ACTION_VIEW, Uri
1684 .parse(WebView.SCHEME_MAILTO + extra)));
1685 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1686 new Copy(extra));
1687 break;
1688
1689 case WebView.HitTestResult.GEO_TYPE:
1690 menu.setHeaderTitle(extra);
1691 menu.findItem(R.id.map_context_menu_id).setIntent(
1692 new Intent(Intent.ACTION_VIEW, Uri
1693 .parse(WebView.SCHEME_GEO
1694 + URLEncoder.encode(extra))));
1695 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1696 new Copy(extra));
1697 break;
1698
1699 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1700 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1701 TextView titleView = (TextView) LayoutInflater.from(this)
1702 .inflate(android.R.layout.browser_link_context_header,
1703 null);
1704 titleView.setText(extra);
1705 menu.setHeaderView(titleView);
1706 // decide whether to show the open link in new tab option
1707 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1708 mTabControl.getTabCount() < TabControl.MAX_TABS);
1709 PackageManager pm = getPackageManager();
1710 Intent send = new Intent(Intent.ACTION_SEND);
1711 send.setType("text/plain");
1712 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1713 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1714 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1715 break;
1716 }
1717 // otherwise fall through to handle image part
1718 case WebView.HitTestResult.IMAGE_TYPE:
1719 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1720 menu.setHeaderTitle(extra);
1721 }
1722 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1723 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1724 menu.findItem(R.id.download_context_menu_id).
1725 setOnMenuItemClickListener(new Download(extra));
1726 break;
1727
1728 default:
1729 Log.w(LOGTAG, "We should not get here.");
1730 break;
1731 }
1732 }
1733
The Android Open Source Project0c908882009-03-03 19:32:16 -08001734 // Attach the given tab to the content view.
1735 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001736 // Attach the container that contains the main WebView and any other UI
1737 // associated with the tab.
1738 mContentView.addView(t.getContainer(), COVER_SCREEN_PARAMS);
Ben Murdochbff2d602009-07-01 20:19:05 +01001739
1740 if (mShouldShowErrorConsole) {
1741 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1742 if (errorConsole.numberOfErrors() == 0) {
1743 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1744 } else {
1745 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1746 }
1747
1748 mErrorConsoleContainer.addView(errorConsole,
1749 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1750 ViewGroup.LayoutParams.WRAP_CONTENT));
1751 }
1752
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001753 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001754 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001755 // Attach the sub window if necessary
1756 attachSubWindow(t);
1757 // Request focus on the top window.
1758 t.getTopWindow().requestFocus();
1759 }
1760
1761 // Attach a sub window to the main WebView of the given tab.
1762 private void attachSubWindow(TabControl.Tab t) {
1763 // If a sub window exists, attach it to the content view.
1764 final WebView subView = t.getSubWebView();
1765 if (subView != null) {
1766 final View container = t.getSubWebViewContainer();
1767 mContentView.addView(container, COVER_SCREEN_PARAMS);
1768 subView.requestFocus();
1769 }
1770 }
1771
1772 // Remove the given tab from the content view.
1773 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001774 // Remove the container that contains the main WebView.
1775 mContentView.removeView(t.getContainer());
Ben Murdochbff2d602009-07-01 20:19:05 +01001776
1777 if (mTabControl.getCurrentErrorConsole(false) != null) {
1778 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1779 }
1780
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001781 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001782 if (view != null) {
1783 view.setEmbeddedTitleBar(null);
1784 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001785
The Android Open Source Project0c908882009-03-03 19:32:16 -08001786 // Remove the sub window if it exists.
1787 if (t.getSubWebView() != null) {
1788 mContentView.removeView(t.getSubWebViewContainer());
1789 }
1790 }
1791
1792 // Remove the sub window if it exists. Also called by TabControl when the
1793 // user clicks the 'X' to dismiss a sub window.
1794 /* package */ void dismissSubWindow(TabControl.Tab t) {
1795 final WebView mainView = t.getWebView();
1796 if (t.getSubWebView() != null) {
1797 // Remove the container view and request focus on the main WebView.
1798 mContentView.removeView(t.getSubWebViewContainer());
1799 mainView.requestFocus();
1800 // Tell the TabControl to dismiss the subwindow. This will destroy
1801 // the WebView.
1802 mTabControl.dismissSubWindow(t);
1803 }
1804 }
1805
Leon Scroggins1f005d32009-08-10 17:36:42 -04001806 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001807 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001808 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1809 String appId) {
1810 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001811 }
1812
1813 // This method does a ton of stuff. It will attempt to create a new tab
1814 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001815 // url isn't null, it will load the given url.
1816 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001817 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001818 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1819 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1820 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001821 final TabControl.Tab tab = mTabControl.createNewTab(
1822 closeOnExit, appId, urlData.mUrl);
1823 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001824 // If the last tab was removed from the active tabs page, currentTab
1825 // will be null.
1826 if (currentTab != null) {
1827 removeTabFromContentView(currentTab);
1828 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001829 attachTabToContentView(tab);
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001830 // We must set the new tab as the current tab to reflect the old
1831 // animation behavior.
1832 mTabControl.setCurrentTab(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001833 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001834 urlData.loadIn(webview);
1835 }
1836 return tab;
1837 } else {
1838 // Get rid of the subwindow if it exists
1839 dismissSubWindow(currentTab);
1840 if (!urlData.isEmpty()) {
1841 // Load the given url.
1842 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001843 }
1844 }
Grace Klobac9181842009-04-14 08:53:22 -07001845 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001846 }
1847
Grace Klobac9181842009-04-14 08:53:22 -07001848 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001849 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001850 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001851 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001852 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001853 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001854 }
Grace Klobac9181842009-04-14 08:53:22 -07001855 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001856 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001857 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001858 }
1859 }
1860
1861 private class Copy implements OnMenuItemClickListener {
1862 private CharSequence mText;
1863
1864 public boolean onMenuItemClick(MenuItem item) {
1865 copy(mText);
1866 return true;
1867 }
1868
1869 public Copy(CharSequence toCopy) {
1870 mText = toCopy;
1871 }
1872 }
1873
1874 private class Download implements OnMenuItemClickListener {
1875 private String mText;
1876
1877 public boolean onMenuItemClick(MenuItem item) {
1878 onDownloadStartNoStream(mText, null, null, null, -1);
1879 return true;
1880 }
1881
1882 public Download(String toDownload) {
1883 mText = toDownload;
1884 }
1885 }
1886
1887 private void copy(CharSequence text) {
1888 try {
1889 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1890 if (clip != null) {
1891 clip.setClipboardText(text);
1892 }
1893 } catch (android.os.RemoteException e) {
1894 Log.e(LOGTAG, "Copy failed", e);
1895 }
1896 }
1897
1898 /**
1899 * Resets the browser title-view to whatever it must be (for example, if we
1900 * load a page from history).
1901 */
1902 private void resetTitle() {
1903 resetLockIcon();
1904 resetTitleIconAndProgress();
1905 }
1906
1907 /**
1908 * Resets the browser title-view to whatever it must be
1909 * (for example, if we had a loading error)
1910 * When we have a new page, we call resetTitle, when we
1911 * have to reset the titlebar to whatever it used to be
1912 * (for example, if the user chose to stop loading), we
1913 * call resetTitleAndRevertLockIcon.
1914 */
1915 /* package */ void resetTitleAndRevertLockIcon() {
1916 revertLockIcon();
1917 resetTitleIconAndProgress();
1918 }
1919
1920 /**
1921 * Reset the title, favicon, and progress.
1922 */
1923 private void resetTitleIconAndProgress() {
1924 WebView current = mTabControl.getCurrentWebView();
1925 if (current == null) {
1926 return;
1927 }
1928 resetTitleAndIcon(current);
1929 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001930 mWebChromeClient.onProgressChanged(current, progress);
1931 }
1932
1933 // Reset the title and the icon based on the given item.
1934 private void resetTitleAndIcon(WebView view) {
1935 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1936 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001937 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001938 setFavicon(item.getFavicon());
1939 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001940 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001941 setFavicon(null);
1942 }
1943 }
1944
1945 /**
1946 * Sets a title composed of the URL and the title string.
1947 * @param url The URL of the site being loaded.
1948 * @param title The title of the site being loaded.
1949 */
Leon Scroggins68579392009-09-15 15:31:54 -04001950 private void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001951 mUrl = url;
1952 mTitle = title;
1953
Leon Scroggins68579392009-09-15 15:31:54 -04001954 mTitleBar.setTitleAndUrl(title, url);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001955 if (mFakeTitleBar != null) {
1956 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001957 }
1958 }
1959
1960 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001961 * @param url The URL to build a title version of the URL from.
1962 * @return The title version of the URL or null if fails.
1963 * The title version of the URL can be either the URL hostname,
1964 * or the hostname with an "https://" prefix (for secure URLs),
1965 * or an empty string if, for example, the URL in question is a
1966 * file:// URL with no hostname.
1967 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001968 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001969 String titleUrl = null;
1970
1971 if (url != null) {
1972 try {
1973 // parse the url string
1974 URL urlObj = new URL(url);
1975 if (urlObj != null) {
1976 titleUrl = "";
1977
1978 String protocol = urlObj.getProtocol();
1979 String host = urlObj.getHost();
1980
1981 if (host != null && 0 < host.length()) {
1982 titleUrl = host;
1983 if (protocol != null) {
1984 // if a secure site, add an "https://" prefix!
1985 if (protocol.equalsIgnoreCase("https")) {
1986 titleUrl = protocol + "://" + host;
1987 }
1988 }
1989 }
1990 }
1991 } catch (MalformedURLException e) {}
1992 }
1993
1994 return titleUrl;
1995 }
1996
1997 // Set the favicon in the title bar.
1998 private void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04001999 mTitleBar.setFavicon(icon);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002000 if (mFakeTitleBar != null) {
2001 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002002 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002003 }
2004
2005 /**
2006 * Saves the current lock-icon state before resetting
2007 * the lock icon. If we have an error, we may need to
2008 * roll back to the previous state.
2009 */
2010 private void saveLockIcon() {
2011 mPrevLockType = mLockIconType;
2012 }
2013
2014 /**
2015 * Reverts the lock-icon state to the last saved state,
2016 * for example, if we had an error, and need to cancel
2017 * the load.
2018 */
2019 private void revertLockIcon() {
2020 mLockIconType = mPrevLockType;
2021
Dave Bort31a6d1c2009-04-13 15:56:49 -07002022 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002023 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2024 " revert lock icon to " + mLockIconType);
2025 }
2026
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002027 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002028 }
2029
Leon Scroggins1f005d32009-08-10 17:36:42 -04002030 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002031 * Close the tab, remove its associated title bar, and adjust mTabControl's
2032 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002033 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002034 /* package */ void closeTab(TabControl.Tab t) {
2035 int currentIndex = mTabControl.getCurrentIndex();
2036 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002037 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002038 if (currentIndex >= removeIndex && currentIndex != 0) {
2039 currentIndex--;
2040 }
2041 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
The Android Open Source Project0c908882009-03-03 19:32:16 -08002042 }
2043
2044 private void goBackOnePageOrQuit() {
2045 TabControl.Tab current = mTabControl.getCurrentTab();
2046 if (current == null) {
2047 /*
2048 * Instead of finishing the activity, simply push this to the back
2049 * of the stack and let ActivityManager to choose the foreground
2050 * activity. As BrowserActivity is singleTask, it will be always the
2051 * root of the task. So we can use either true or false for
2052 * moveTaskToBack().
2053 */
2054 moveTaskToBack(true);
2055 }
2056 WebView w = current.getWebView();
2057 if (w.canGoBack()) {
2058 w.goBack();
2059 } else {
2060 // Check to see if we are closing a window that was created by
2061 // another window. If so, we switch back to that window.
2062 TabControl.Tab parent = current.getParentTab();
2063 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002064 switchToTab(mTabControl.getTabIndex(parent));
2065 // Now we close the other tab
2066 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002067 } else {
2068 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002069 // force mPageStarted to be false as we are going to either
2070 // finish the activity or remove the tab. This will ensure
2071 // pauseWebView() taking action.
2072 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002073 if (mTabControl.getTabCount() == 1) {
2074 finish();
2075 return;
2076 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002077 // call pauseWebViewTimers() now, we won't be able to call
2078 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002079 // Temporarily change mActivityInPause to be true as
2080 // pauseWebViewTimers() will do nothing if mActivityInPause
2081 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002082 boolean savedState = mActivityInPause;
2083 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002084 Log.e(LOGTAG, "BrowserActivity is already paused "
2085 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002086 }
2087 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002088 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002089 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002090 removeTabFromContentView(current);
2091 mTabControl.removeTab(current);
2092 }
2093 /*
2094 * Instead of finishing the activity, simply push this to the back
2095 * of the stack and let ActivityManager to choose the foreground
2096 * activity. As BrowserActivity is singleTask, it will be always the
2097 * root of the task. So we can use either true or false for
2098 * moveTaskToBack().
2099 */
2100 moveTaskToBack(true);
2101 }
2102 }
2103 }
2104
2105 public KeyTracker.State onKeyTracker(int keyCode,
2106 KeyEvent event,
2107 KeyTracker.Stage stage,
2108 int duration) {
2109 // if onKeyTracker() is called after activity onStop()
2110 // because of accumulated key events,
2111 // we should ignore it as browser is not active any more.
2112 WebView topWindow = getTopWindow();
Andrei Popescuadc008d2009-06-26 14:11:30 +01002113 if (topWindow == null && mCustomView == null)
The Android Open Source Project0c908882009-03-03 19:32:16 -08002114 return KeyTracker.State.NOT_TRACKING;
2115
2116 if (keyCode == KeyEvent.KEYCODE_BACK) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01002117 // Check if a custom view is currently showing and, if it is, hide it.
2118 if (mCustomView != null) {
2119 mWebChromeClient.onHideCustomView();
2120 return KeyTracker.State.DONE_TRACKING;
2121 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002122 if (stage == KeyTracker.Stage.LONG_REPEAT) {
Leon Scroggins30444232009-09-04 18:36:20 -04002123 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002124 return KeyTracker.State.DONE_TRACKING;
2125 } else if (stage == KeyTracker.Stage.UP) {
2126 // FIXME: Currently, we do not have a notion of the
2127 // history picker for the subwindow, but maybe we
2128 // should?
2129 WebView subwindow = mTabControl.getCurrentSubWindow();
2130 if (subwindow != null) {
2131 if (subwindow.canGoBack()) {
2132 subwindow.goBack();
2133 } else {
2134 dismissSubWindow(mTabControl.getCurrentTab());
2135 }
2136 } else {
2137 goBackOnePageOrQuit();
2138 }
2139 return KeyTracker.State.DONE_TRACKING;
2140 }
2141 return KeyTracker.State.KEEP_TRACKING;
2142 }
2143 return KeyTracker.State.NOT_TRACKING;
2144 }
2145
2146 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2147 if (keyCode == KeyEvent.KEYCODE_MENU) {
2148 mMenuIsDown = true;
Grace Kloba6ee9c492009-07-13 10:04:34 -07002149 } else if (mMenuIsDown) {
2150 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2151 // still down, we don't want to trigger the search. Pretend to
2152 // consume the key and do nothing.
2153 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002154 }
2155 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2156 if (!handled) {
2157 switch (keyCode) {
2158 case KeyEvent.KEYCODE_SPACE:
2159 if (event.isShiftPressed()) {
2160 getTopWindow().pageUp(false);
2161 } else {
2162 getTopWindow().pageDown(false);
2163 }
2164 handled = true;
2165 break;
2166
2167 default:
2168 break;
2169 }
2170 }
2171 return handled || super.onKeyDown(keyCode, event);
2172 }
2173
2174 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2175 if (keyCode == KeyEvent.KEYCODE_MENU) {
2176 mMenuIsDown = false;
2177 }
2178 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2179 }
2180
Leon Scroggins68579392009-09-15 15:31:54 -04002181 /* package */ void stopLoading() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002182 resetTitleAndRevertLockIcon();
2183 WebView w = getTopWindow();
2184 w.stopLoading();
2185 mWebViewClient.onPageFinished(w, w.getUrl());
2186
2187 cancelStopToast();
2188 mStopToast = Toast
2189 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2190 mStopToast.show();
2191 }
2192
2193 private void cancelStopToast() {
2194 if (mStopToast != null) {
2195 mStopToast.cancel();
2196 mStopToast = null;
2197 }
2198 }
2199
2200 // called by a non-UI thread to post the message
2201 public void postMessage(int what, int arg1, int arg2, Object obj) {
2202 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2203 }
2204
2205 // public message ids
2206 public final static int LOAD_URL = 1001;
2207 public final static int STOP_LOAD = 1002;
2208
2209 // Message Ids
2210 private static final int FOCUS_NODE_HREF = 102;
2211 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002212 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002213
2214 // Private handler for handling javascript and saving passwords
2215 private Handler mHandler = new Handler() {
2216
2217 public void handleMessage(Message msg) {
2218 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002219 case FOCUS_NODE_HREF:
2220 String url = (String) msg.getData().get("url");
2221 if (url == null || url.length() == 0) {
2222 break;
2223 }
2224 HashMap focusNodeMap = (HashMap) msg.obj;
2225 WebView view = (WebView) focusNodeMap.get("webview");
2226 // Only apply the action if the top window did not change.
2227 if (getTopWindow() != view) {
2228 break;
2229 }
2230 switch (msg.arg1) {
2231 case R.id.open_context_menu_id:
2232 case R.id.view_image_context_menu_id:
2233 loadURL(getTopWindow(), url);
2234 break;
2235 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002236 final TabControl.Tab parent = mTabControl
2237 .getCurrentTab();
2238 final TabControl.Tab newTab = openTab(url);
2239 if (newTab != parent) {
2240 parent.addChildTab(newTab);
2241 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002242 break;
2243 case R.id.bookmark_context_menu_id:
2244 Intent intent = new Intent(BrowserActivity.this,
2245 AddBookmarkPage.class);
2246 intent.putExtra("url", url);
2247 startActivity(intent);
2248 break;
2249 case R.id.share_link_context_menu_id:
2250 Browser.sendString(BrowserActivity.this, url);
2251 break;
2252 case R.id.copy_link_context_menu_id:
2253 copy(url);
2254 break;
2255 case R.id.save_link_context_menu_id:
2256 case R.id.download_context_menu_id:
2257 onDownloadStartNoStream(url, null, null, null, -1);
2258 break;
2259 }
2260 break;
2261
2262 case LOAD_URL:
2263 loadURL(getTopWindow(), (String) msg.obj);
2264 break;
2265
2266 case STOP_LOAD:
2267 stopLoading();
2268 break;
2269
2270 case CANCEL_CREDS_REQUEST:
2271 resumeAfterCredentials();
2272 break;
2273
The Android Open Source Project0c908882009-03-03 19:32:16 -08002274 case RELEASE_WAKELOCK:
2275 if (mWakeLock.isHeld()) {
2276 mWakeLock.release();
2277 }
2278 break;
2279 }
2280 }
2281 };
2282
Leon Scroggins89c6d362009-07-15 16:54:37 -04002283 private void updateScreenshot(WebView view) {
2284 // If this is a bookmarked site, add a screenshot to the database.
2285 // FIXME: When should we update? Every time?
2286 // FIXME: Would like to make sure there is actually something to
2287 // draw, but the API for that (WebViewCore.pictureReady()) is not
2288 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002289 ContentResolver cr = getContentResolver();
2290 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002291 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002292 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002293 boolean succeed = c.moveToFirst();
2294 ContentValues values = null;
2295 while (succeed) {
2296 if (values == null) {
2297 final ByteArrayOutputStream os
2298 = new ByteArrayOutputStream();
2299 Picture thumbnail = view.capturePicture();
2300 // Keep width and height in sync with BrowserBookmarksPage
2301 // and bookmark_thumb
2302 Bitmap bm = Bitmap.createBitmap(100, 80,
2303 Bitmap.Config.ARGB_4444);
2304 Canvas canvas = new Canvas(bm);
2305 // May need to tweak these values to determine what is the
2306 // best scale factor
2307 canvas.scale(.5f, .5f);
2308 thumbnail.draw(canvas);
2309 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2310 values = new ContentValues();
2311 values.put(Browser.BookmarkColumns.THUMBNAIL,
2312 os.toByteArray());
2313 }
2314 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2315 c.getInt(0)), values, null, null);
2316 succeed = c.moveToNext();
2317 }
2318 c.close();
2319 }
2320 }
2321
The Android Open Source Project0c908882009-03-03 19:32:16 -08002322 // -------------------------------------------------------------------------
2323 // WebViewClient implementation.
2324 //-------------------------------------------------------------------------
2325
2326 // Use in overrideUrlLoading
2327 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2328 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2329 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2330 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2331
2332 /* package */ WebViewClient getWebViewClient() {
2333 return mWebViewClient;
2334 }
2335
Patrick Scott3918d442009-08-04 13:22:29 -04002336 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002337 if (icon != null) {
2338 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott3918d442009-08-04 13:22:29 -04002339 view, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002340 }
2341 setFavicon(icon);
2342 }
2343
2344 private final WebViewClient mWebViewClient = new WebViewClient() {
2345 @Override
2346 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2347 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002348 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002349
2350 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2351 if (errorConsole != null) {
2352 errorConsole.clearErrorMessages();
2353 if (mShouldShowErrorConsole) {
2354 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2355 }
2356 }
2357
The Android Open Source Project0c908882009-03-03 19:32:16 -08002358 // Call updateIcon instead of setFavicon so the bookmark
2359 // database can be updated.
Patrick Scott3918d442009-08-04 13:22:29 -04002360 updateIcon(view, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002361
Grace Kloba4d7880f2009-08-12 09:35:42 -07002362 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002363 String host;
2364 try {
2365 WebAddress uri = new WebAddress(url);
2366 host = uri.mHost;
2367 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002368 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002369 }
2370 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002371 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002372 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002373 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002374 }
2375
2376 // Performance probe
2377 if (false) {
2378 mStart = SystemClock.uptimeMillis();
2379 mProcessStart = Process.getElapsedCpuTime();
2380 long[] sysCpu = new long[7];
2381 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2382 sysCpu, null)) {
2383 mUserStart = sysCpu[0] + sysCpu[1];
2384 mSystemStart = sysCpu[2];
2385 mIdleStart = sysCpu[3];
2386 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2387 }
2388 mUiStart = SystemClock.currentThreadTimeMillis();
2389 }
2390
2391 if (!mPageStarted) {
2392 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002393 // if onResume() has been called, resumeWebViewTimers() does
2394 // nothing.
2395 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002396 }
2397
2398 // reset sync timer to avoid sync starts during loading a page
2399 CookieSyncManager.getInstance().resetSync();
2400
2401 mInLoad = true;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002402 WebView currentWebView = mTabControl.getCurrentWebView();
2403 if (currentWebView == null || currentWebView.getScrollY() != 0) {
2404 // This page has begun to load, so show the title bar
2405 showFakeTitleBar();
2406 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002407 updateInLoadMenuItems();
2408 if (!mIsNetworkUp) {
2409 if ( mAlertDialog == null) {
2410 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2411 .setTitle(R.string.loadSuspendedTitle)
2412 .setMessage(R.string.loadSuspended)
2413 .setPositiveButton(R.string.ok, null)
2414 .show();
2415 }
2416 if (view != null) {
2417 view.setNetworkAvailable(false);
2418 }
2419 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002420 }
2421
2422 @Override
2423 public void onPageFinished(WebView view, String url) {
2424 // Reset the title and icon in case we stopped a provisional
2425 // load.
2426 resetTitleAndIcon(view);
2427
2428 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002429 updateLockIconToLatest();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002430 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002431
The Android Open Source Project0c908882009-03-03 19:32:16 -08002432 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002433 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002434 long[] sysCpu = new long[7];
2435 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2436 sysCpu, null)) {
2437 String uiInfo = "UI thread used "
2438 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2439 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002440 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002441 Log.d(LOGTAG, uiInfo);
2442 }
2443 //The string that gets written to the log
2444 String performanceString = "It took total "
2445 + (SystemClock.uptimeMillis() - mStart)
2446 + " ms clock time to load the page."
2447 + "\nbrowser process used "
2448 + (Process.getElapsedCpuTime() - mProcessStart)
2449 + " ms, user processes used "
2450 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2451 + " ms, kernel used "
2452 + (sysCpu[2] - mSystemStart) * 10
2453 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2454 + " ms and irq took "
2455 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2456 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002457 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002458 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2459 }
2460 if (url != null) {
2461 // strip the url to maintain consistency
2462 String newUrl = new String(url);
2463 if (newUrl.startsWith("http://www.")) {
2464 newUrl = newUrl.substring(11);
2465 } else if (newUrl.startsWith("http://")) {
2466 newUrl = newUrl.substring(7);
2467 } else if (newUrl.startsWith("https://www.")) {
2468 newUrl = newUrl.substring(12);
2469 } else if (newUrl.startsWith("https://")) {
2470 newUrl = newUrl.substring(8);
2471 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002472 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002473 Log.d(LOGTAG, newUrl + " loaded");
2474 }
2475 /*
2476 if (sWhiteList.contains(newUrl)) {
2477 // The string that gets pushed to the statistcs
2478 // service
2479 performanceString = performanceString
2480 + "\nWebpage: "
2481 + newUrl
2482 + "\nCarrier: "
2483 + android.os.SystemProperties
2484 .get("gsm.sim.operator.alpha");
2485 if (mWebView != null
2486 && mWebView.getContext() != null
2487 && mWebView.getContext().getSystemService(
2488 Context.CONNECTIVITY_SERVICE) != null) {
2489 ConnectivityManager cManager =
2490 (ConnectivityManager) mWebView
2491 .getContext().getSystemService(
2492 Context.CONNECTIVITY_SERVICE);
2493 NetworkInfo nInfo = cManager
2494 .getActiveNetworkInfo();
2495 if (nInfo != null) {
2496 performanceString = performanceString
2497 + "\nNetwork Type: "
2498 + nInfo.getType().toString();
2499 }
2500 }
2501 Checkin.logEvent(mResolver,
2502 Checkin.Events.Tag.WEBPAGE_LOAD,
2503 performanceString);
2504 Log.w(LOGTAG, "pushed to the statistics service");
2505 }
2506 */
2507 }
2508 }
2509 }
2510
2511 if (mInTrace) {
2512 mInTrace = false;
2513 Debug.stopMethodTracing();
2514 }
2515
2516 if (mPageStarted) {
2517 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002518 // pauseWebViewTimers() will do nothing and return false if
2519 // onPause() is not called yet.
2520 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002521 if (mWakeLock.isHeld()) {
2522 mHandler.removeMessages(RELEASE_WAKELOCK);
2523 mWakeLock.release();
2524 }
2525 }
2526 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002527 }
2528
2529 // return true if want to hijack the url to let another app to handle it
2530 @Override
2531 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2532 if (url.startsWith(SCHEME_WTAI)) {
2533 // wtai://wp/mc;number
2534 // number=string(phone-number)
2535 if (url.startsWith(SCHEME_WTAI_MC)) {
2536 Intent intent = new Intent(Intent.ACTION_VIEW,
2537 Uri.parse(WebView.SCHEME_TEL +
2538 url.substring(SCHEME_WTAI_MC.length())));
2539 startActivity(intent);
2540 return true;
2541 }
2542 // wtai://wp/sd;dtmf
2543 // dtmf=string(dialstring)
2544 if (url.startsWith(SCHEME_WTAI_SD)) {
2545 // TODO
2546 // only send when there is active voice connection
2547 return false;
2548 }
2549 // wtai://wp/ap;number;name
2550 // number=string(phone-number)
2551 // name=string
2552 if (url.startsWith(SCHEME_WTAI_AP)) {
2553 // TODO
2554 return false;
2555 }
2556 }
2557
Dianne Hackborn99189432009-06-17 18:06:18 -07002558 // The "about:" schemes are internal to the browser; don't
2559 // want these to be dispatched to other apps.
2560 if (url.startsWith("about:")) {
2561 return false;
2562 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002563
Dianne Hackborn99189432009-06-17 18:06:18 -07002564 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002565
Dianne Hackborn99189432009-06-17 18:06:18 -07002566 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002567 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002568 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2569 } catch (URISyntaxException ex) {
2570 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002571 return false;
2572 }
2573
Grace Kloba5b078b52009-06-24 20:23:41 -07002574 // check whether the intent can be resolved. If not, we will see
2575 // whether we can download it from the Market.
2576 if (getPackageManager().resolveActivity(intent, 0) == null) {
2577 String packagename = intent.getPackage();
2578 if (packagename != null) {
2579 intent = new Intent(Intent.ACTION_VIEW, Uri
2580 .parse("market://search?q=pname:" + packagename));
2581 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2582 startActivity(intent);
2583 return true;
2584 } else {
2585 return false;
2586 }
2587 }
2588
Dianne Hackborn99189432009-06-17 18:06:18 -07002589 // sanitize the Intent, ensuring web pages can not bypass browser
2590 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002591 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002592 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002593 try {
2594 if (startActivityIfNeeded(intent, -1)) {
2595 return true;
2596 }
2597 } catch (ActivityNotFoundException ex) {
2598 // ignore the error. If no application can handle the URL,
2599 // eg about:blank, assume the browser can handle it.
2600 }
2601
2602 if (mMenuIsDown) {
2603 openTab(url);
2604 closeOptionsMenu();
2605 return true;
2606 }
2607
2608 return false;
2609 }
2610
2611 /**
2612 * Updates the lock icon. This method is called when we discover another
2613 * resource to be loaded for this page (for example, javascript). While
2614 * we update the icon type, we do not update the lock icon itself until
2615 * we are done loading, it is slightly more secure this way.
2616 */
2617 @Override
2618 public void onLoadResource(WebView view, String url) {
2619 if (url != null && url.length() > 0) {
2620 // It is only if the page claims to be secure
2621 // that we may have to update the lock:
2622 if (mLockIconType == LOCK_ICON_SECURE) {
2623 // If NOT a 'safe' url, change the lock to mixed content!
2624 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2625 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002626 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002627 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2628 " updated lock icon to " + mLockIconType + " due to " + url);
2629 }
2630 }
2631 }
2632 }
2633 }
2634
2635 /**
2636 * Show the dialog, asking the user if they would like to continue after
2637 * an excessive number of HTTP redirects.
2638 */
2639 @Override
2640 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2641 final Message continueMsg) {
2642 new AlertDialog.Builder(BrowserActivity.this)
2643 .setTitle(R.string.browserFrameRedirect)
2644 .setMessage(R.string.browserFrame307Post)
2645 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2646 public void onClick(DialogInterface dialog, int which) {
2647 continueMsg.sendToTarget();
2648 }})
2649 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2650 public void onClick(DialogInterface dialog, int which) {
2651 cancelMsg.sendToTarget();
2652 }})
2653 .setOnCancelListener(new OnCancelListener() {
2654 public void onCancel(DialogInterface dialog) {
2655 cancelMsg.sendToTarget();
2656 }})
2657 .show();
2658 }
2659
Patrick Scott37911c72009-03-24 18:02:58 -07002660 // Container class for the next error dialog that needs to be
2661 // displayed.
2662 class ErrorDialog {
2663 public final int mTitle;
2664 public final String mDescription;
2665 public final int mError;
2666 ErrorDialog(int title, String desc, int error) {
2667 mTitle = title;
2668 mDescription = desc;
2669 mError = error;
2670 }
2671 };
2672
2673 private void processNextError() {
2674 if (mQueuedErrors == null) {
2675 return;
2676 }
2677 // The first one is currently displayed so just remove it.
2678 mQueuedErrors.removeFirst();
2679 if (mQueuedErrors.size() == 0) {
2680 mQueuedErrors = null;
2681 return;
2682 }
2683 showError(mQueuedErrors.getFirst());
2684 }
2685
2686 private DialogInterface.OnDismissListener mDialogListener =
2687 new DialogInterface.OnDismissListener() {
2688 public void onDismiss(DialogInterface d) {
2689 processNextError();
2690 }
2691 };
2692 private LinkedList<ErrorDialog> mQueuedErrors;
2693
2694 private void queueError(int err, String desc) {
2695 if (mQueuedErrors == null) {
2696 mQueuedErrors = new LinkedList<ErrorDialog>();
2697 }
2698 for (ErrorDialog d : mQueuedErrors) {
2699 if (d.mError == err) {
2700 // Already saw a similar error, ignore the new one.
2701 return;
2702 }
2703 }
2704 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002705 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002706 R.string.browserFrameFileErrorLabel :
2707 R.string.browserFrameNetworkErrorLabel,
2708 desc, err);
2709 mQueuedErrors.addLast(errDialog);
2710
2711 // Show the dialog now if the queue was empty.
2712 if (mQueuedErrors.size() == 1) {
2713 showError(errDialog);
2714 }
2715 }
2716
2717 private void showError(ErrorDialog errDialog) {
2718 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2719 .setTitle(errDialog.mTitle)
2720 .setMessage(errDialog.mDescription)
2721 .setPositiveButton(R.string.ok, null)
2722 .create();
2723 d.setOnDismissListener(mDialogListener);
2724 d.show();
2725 }
2726
The Android Open Source Project0c908882009-03-03 19:32:16 -08002727 /**
2728 * Show a dialog informing the user of the network error reported by
2729 * WebCore.
2730 */
2731 @Override
2732 public void onReceivedError(WebView view, int errorCode,
2733 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002734 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2735 errorCode != WebViewClient.ERROR_CONNECT &&
2736 errorCode != WebViewClient.ERROR_BAD_URL &&
2737 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2738 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002739 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002740 }
Patrick Scott37911c72009-03-24 18:02:58 -07002741 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2742 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002743
2744 // We need to reset the title after an error.
2745 resetTitleAndRevertLockIcon();
2746 }
2747
2748 /**
2749 * Check with the user if it is ok to resend POST data as the page they
2750 * are trying to navigate to is the result of a POST.
2751 */
2752 @Override
2753 public void onFormResubmission(WebView view, final Message dontResend,
2754 final Message resend) {
2755 new AlertDialog.Builder(BrowserActivity.this)
2756 .setTitle(R.string.browserFrameFormResubmitLabel)
2757 .setMessage(R.string.browserFrameFormResubmitMessage)
2758 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2759 public void onClick(DialogInterface dialog, int which) {
2760 resend.sendToTarget();
2761 }})
2762 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2763 public void onClick(DialogInterface dialog, int which) {
2764 dontResend.sendToTarget();
2765 }})
2766 .setOnCancelListener(new OnCancelListener() {
2767 public void onCancel(DialogInterface dialog) {
2768 dontResend.sendToTarget();
2769 }})
2770 .show();
2771 }
2772
2773 /**
2774 * Insert the url into the visited history database.
2775 * @param url The url to be inserted.
2776 * @param isReload True if this url is being reloaded.
2777 * FIXME: Not sure what to do when reloading the page.
2778 */
2779 @Override
2780 public void doUpdateVisitedHistory(WebView view, String url,
2781 boolean isReload) {
2782 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2783 return;
2784 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002785 // remove "client" before updating it to the history so that it wont
2786 // show up in the auto-complete list.
2787 int index = url.indexOf("client=ms-");
2788 if (index > 0 && url.contains(".google.")) {
2789 int end = url.indexOf('&', index);
2790 if (end > 0) {
2791 url = url.substring(0, index-1).concat(url.substring(end));
2792 } else {
2793 url = url.substring(0, index-1);
2794 }
2795 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002796 Browser.updateVisitedHistory(mResolver, url, true);
2797 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2798 }
2799
2800 /**
2801 * Displays SSL error(s) dialog to the user.
2802 */
2803 @Override
2804 public void onReceivedSslError(
2805 final WebView view, final SslErrorHandler handler, final SslError error) {
2806
2807 if (mSettings.showSecurityWarnings()) {
2808 final LayoutInflater factory =
2809 LayoutInflater.from(BrowserActivity.this);
2810 final View warningsView =
2811 factory.inflate(R.layout.ssl_warnings, null);
2812 final LinearLayout placeholder =
2813 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2814
2815 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2816 LinearLayout ll = (LinearLayout)factory
2817 .inflate(R.layout.ssl_warning, null);
2818 ((TextView)ll.findViewById(R.id.warning))
2819 .setText(R.string.ssl_untrusted);
2820 placeholder.addView(ll);
2821 }
2822
2823 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2824 LinearLayout ll = (LinearLayout)factory
2825 .inflate(R.layout.ssl_warning, null);
2826 ((TextView)ll.findViewById(R.id.warning))
2827 .setText(R.string.ssl_mismatch);
2828 placeholder.addView(ll);
2829 }
2830
2831 if (error.hasError(SslError.SSL_EXPIRED)) {
2832 LinearLayout ll = (LinearLayout)factory
2833 .inflate(R.layout.ssl_warning, null);
2834 ((TextView)ll.findViewById(R.id.warning))
2835 .setText(R.string.ssl_expired);
2836 placeholder.addView(ll);
2837 }
2838
2839 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2840 LinearLayout ll = (LinearLayout)factory
2841 .inflate(R.layout.ssl_warning, null);
2842 ((TextView)ll.findViewById(R.id.warning))
2843 .setText(R.string.ssl_not_yet_valid);
2844 placeholder.addView(ll);
2845 }
2846
2847 new AlertDialog.Builder(BrowserActivity.this)
2848 .setTitle(R.string.security_warning)
2849 .setIcon(android.R.drawable.ic_dialog_alert)
2850 .setView(warningsView)
2851 .setPositiveButton(R.string.ssl_continue,
2852 new DialogInterface.OnClickListener() {
2853 public void onClick(DialogInterface dialog, int whichButton) {
2854 handler.proceed();
2855 }
2856 })
2857 .setNeutralButton(R.string.view_certificate,
2858 new DialogInterface.OnClickListener() {
2859 public void onClick(DialogInterface dialog, int whichButton) {
2860 showSSLCertificateOnError(view, handler, error);
2861 }
2862 })
2863 .setNegativeButton(R.string.cancel,
2864 new DialogInterface.OnClickListener() {
2865 public void onClick(DialogInterface dialog, int whichButton) {
2866 handler.cancel();
2867 BrowserActivity.this.resetTitleAndRevertLockIcon();
2868 }
2869 })
2870 .setOnCancelListener(
2871 new DialogInterface.OnCancelListener() {
2872 public void onCancel(DialogInterface dialog) {
2873 handler.cancel();
2874 BrowserActivity.this.resetTitleAndRevertLockIcon();
2875 }
2876 })
2877 .show();
2878 } else {
2879 handler.proceed();
2880 }
2881 }
2882
2883 /**
2884 * Handles an HTTP authentication request.
2885 *
2886 * @param handler The authentication handler
2887 * @param host The host
2888 * @param realm The realm
2889 */
2890 @Override
2891 public void onReceivedHttpAuthRequest(WebView view,
2892 final HttpAuthHandler handler, final String host, final String realm) {
2893 String username = null;
2894 String password = null;
2895
2896 boolean reuseHttpAuthUsernamePassword =
2897 handler.useHttpAuthUsernamePassword();
2898
2899 if (reuseHttpAuthUsernamePassword &&
2900 (mTabControl.getCurrentWebView() != null)) {
2901 String[] credentials =
2902 mTabControl.getCurrentWebView()
2903 .getHttpAuthUsernamePassword(host, realm);
2904 if (credentials != null && credentials.length == 2) {
2905 username = credentials[0];
2906 password = credentials[1];
2907 }
2908 }
2909
2910 if (username != null && password != null) {
2911 handler.proceed(username, password);
2912 } else {
2913 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2914 }
2915 }
2916
2917 @Override
2918 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2919 if (mMenuIsDown) {
2920 // only check shortcut key when MENU is held
2921 return getWindow().isShortcutKey(event.getKeyCode(), event);
2922 } else {
2923 return false;
2924 }
2925 }
2926
2927 @Override
2928 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2929 if (view != mTabControl.getCurrentTopWebView()) {
2930 return;
2931 }
2932 if (event.isDown()) {
2933 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2934 } else {
2935 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2936 }
2937 }
2938 };
2939
2940 //--------------------------------------------------------------------------
2941 // WebChromeClient implementation
2942 //--------------------------------------------------------------------------
2943
2944 /* package */ WebChromeClient getWebChromeClient() {
2945 return mWebChromeClient;
2946 }
2947
2948 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2949 // Helper method to create a new tab or sub window.
2950 private void createWindow(final boolean dialog, final Message msg) {
2951 if (dialog) {
2952 mTabControl.createSubWindow();
2953 final TabControl.Tab t = mTabControl.getCurrentTab();
2954 attachSubWindow(t);
2955 WebView.WebViewTransport transport =
2956 (WebView.WebViewTransport) msg.obj;
2957 transport.setWebView(t.getSubWebView());
2958 msg.sendToTarget();
2959 } else {
2960 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04002961 final TabControl.Tab newTab
2962 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07002963 if (newTab != parent) {
2964 parent.addChildTab(newTab);
2965 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002966 WebView.WebViewTransport transport =
2967 (WebView.WebViewTransport) msg.obj;
2968 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04002969 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002970 }
2971 }
2972
2973 @Override
2974 public boolean onCreateWindow(WebView view, final boolean dialog,
2975 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002976 // Short-circuit if we can't create any more tabs or sub windows.
2977 if (dialog && mTabControl.getCurrentSubWindow() != null) {
2978 new AlertDialog.Builder(BrowserActivity.this)
2979 .setTitle(R.string.too_many_subwindows_dialog_title)
2980 .setIcon(android.R.drawable.ic_dialog_alert)
2981 .setMessage(R.string.too_many_subwindows_dialog_message)
2982 .setPositiveButton(R.string.ok, null)
2983 .show();
2984 return false;
2985 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
2986 new AlertDialog.Builder(BrowserActivity.this)
2987 .setTitle(R.string.too_many_windows_dialog_title)
2988 .setIcon(android.R.drawable.ic_dialog_alert)
2989 .setMessage(R.string.too_many_windows_dialog_message)
2990 .setPositiveButton(R.string.ok, null)
2991 .show();
2992 return false;
2993 }
2994
2995 // Short-circuit if this was a user gesture.
2996 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002997 createWindow(dialog, resultMsg);
2998 return true;
2999 }
3000
3001 // Allow the popup and create the appropriate window.
3002 final AlertDialog.OnClickListener allowListener =
3003 new AlertDialog.OnClickListener() {
3004 public void onClick(DialogInterface d,
3005 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003006 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003007 }
3008 };
3009
3010 // Block the popup by returning a null WebView.
3011 final AlertDialog.OnClickListener blockListener =
3012 new AlertDialog.OnClickListener() {
3013 public void onClick(DialogInterface d, int which) {
3014 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003015 }
3016 };
3017
3018 // Build a confirmation dialog to display to the user.
3019 final AlertDialog d =
3020 new AlertDialog.Builder(BrowserActivity.this)
3021 .setTitle(R.string.attention)
3022 .setIcon(android.R.drawable.ic_dialog_alert)
3023 .setMessage(R.string.popup_window_attempt)
3024 .setPositiveButton(R.string.allow, allowListener)
3025 .setNegativeButton(R.string.block, blockListener)
3026 .setCancelable(false)
3027 .create();
3028
3029 // Show the confirmation dialog.
3030 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003031 return true;
3032 }
3033
3034 @Override
3035 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003036 final TabControl.Tab current = mTabControl.getCurrentTab();
3037 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003038 if (parent != null) {
3039 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003040 switchToTab(mTabControl.getTabIndex(parent));
3041 // Now we need to close the window
3042 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003043 }
3044 }
3045
3046 @Override
3047 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003048 mTitleBar.setProgress(newProgress);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003049 if (mFakeTitleBar != null) {
3050 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003051 }
3052
3053 if (newProgress == 100) {
3054 // onProgressChanged() is called for sub-frame too while
3055 // onPageFinished() is only called for the main frame. sync
3056 // cookie and cache promptly here.
3057 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003058 if (mInLoad) {
3059 mInLoad = false;
3060 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003061 // If the options menu is open, leave the title bar
3062 if (!mOptionsMenuOpen || !mIconView) {
3063 hideFakeTitleBar();
3064 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003065 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003066 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003067 // onPageFinished may have already been called but a subframe
3068 // is still loading and updating the progress. Reset mInLoad
3069 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003070 mInLoad = true;
3071 updateInLoadMenuItems();
3072 WebView currentWebView = mTabControl.getCurrentWebView();
3073 if ((currentWebView == null || currentWebView.getScrollY() != 0)
3074 && (!mOptionsMenuOpen || mIconView)) {
3075 // This page has begun to load, so show the title bar
3076 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003077 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003078 }
3079 }
3080
3081 @Override
3082 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003083 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003084
3085 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003086 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003087
3088 if (url == null ||
3089 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3090 return;
3091 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003092 // See if we can find the current url in our history database and
3093 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003094 if (url.startsWith("http://www.")) {
3095 url = url.substring(11);
3096 } else if (url.startsWith("http://")) {
3097 url = url.substring(4);
3098 }
3099 try {
3100 url = "%" + url;
3101 String [] selArgs = new String[] { url };
3102
3103 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3104 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3105 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3106 Browser.HISTORY_PROJECTION, where, selArgs, null);
3107 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003108 // Current implementation of database only has one entry per
3109 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003110 ContentValues map = new ContentValues();
3111 map.put(Browser.BookmarkColumns.TITLE, title);
3112 mResolver.update(Browser.BOOKMARKS_URI, map,
3113 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003114 }
3115 c.close();
3116 } catch (IllegalStateException e) {
3117 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3118 } catch (SQLiteException ex) {
3119 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3120 }
3121 }
3122
3123 @Override
3124 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003125 updateIcon(view, icon);
3126 }
3127
3128 @Override
3129 public void onReceivedTouchIconUrl(WebView view, String url) {
3130 final ContentResolver cr = getContentResolver();
3131 final Cursor c =
3132 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003133 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003134 if (c != null) {
3135 if (c.getCount() > 0) {
3136 new DownloadTouchIcon(cr, c, view).execute(url);
3137 } else {
3138 c.close();
3139 }
3140 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003141 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003142
Andrei Popescuadc008d2009-06-26 14:11:30 +01003143 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003144 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003145 if (mCustomView != null)
3146 return;
3147
3148 // Add the custom view to its container.
3149 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3150 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003151 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003152 // Save the menu state and set it to empty while the custom
3153 // view is showing.
3154 mOldMenuState = mMenuState;
3155 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003156 // Hide the content view.
3157 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003158 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003159 mCustomViewContainer.setVisibility(View.VISIBLE);
3160 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003161 }
3162
3163 @Override
3164 public void onHideCustomView() {
3165 if (mCustomView == null)
3166 return;
3167
Andrei Popescuc9b55562009-07-07 10:51:15 +01003168 // Hide the custom view.
3169 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003170 // Remove the custom view from its container.
3171 mCustomViewContainer.removeView(mCustomView);
3172 mCustomView = null;
3173 // Reset the old menu state.
3174 mMenuState = mOldMenuState;
3175 mOldMenuState = EMPTY_MENU;
3176 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003177 mCustomViewCallback.onCustomViewHidden();
3178 // Show the content view.
3179 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003180 }
3181
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003182 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003183 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003184 * @param url the URL that exceeded the quota
3185 * @param databaseIdentifier the identifier of the database on
3186 * which the transaction that caused the quota overflow was run
3187 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003188 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003189 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003190 * @param quotaUpdater The callback to run when a decision to allow or
3191 * deny quota has been made. Don't forget to call this!
3192 */
3193 @Override
3194 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003195 String databaseIdentifier, long currentQuota, long estimatedSize,
3196 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003197 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003198 url, databaseIdentifier, currentQuota, estimatedSize,
3199 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003200 }
3201
3202 /**
3203 * The Application Cache has exceeded its max size.
3204 * @param spaceNeeded is the amount of disk space that would be needed
3205 * in order for the last appcache operation to succeed.
3206 * @param totalUsedQuota is the sum of all origins' quota.
3207 * @param quotaUpdater A callback to inform the WebCore thread that a new
3208 * app cache size is available. This callback must always be executed at
3209 * some point to ensure that the sleeping WebCore thread is woken up.
3210 */
3211 @Override
3212 public void onReachedMaxAppCacheSize(long spaceNeeded,
3213 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3214 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3215 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003216 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003217
Steve Block2bc69912009-07-30 14:45:13 +01003218 /**
3219 * Instructs the browser to show a prompt to ask the user to set the
3220 * Geolocation permission state for the specified origin.
3221 * @param origin The origin for which Geolocation permissions are
3222 * requested.
3223 * @param callback The callback to call once the user has set the
3224 * Geolocation permission state.
3225 */
3226 @Override
3227 public void onGeolocationPermissionsShowPrompt(String origin,
3228 GeolocationPermissions.Callback callback) {
3229 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3230 origin, callback);
3231 }
3232
3233 /**
3234 * Instructs the browser to hide the Geolocation permissions prompt.
3235 */
3236 @Override
3237 public void onGeolocationPermissionsHidePrompt() {
3238 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3239 }
3240
Ben Murdoch7db26342009-06-03 18:21:19 +01003241 /* Adds a JavaScript error message to the system log.
3242 * @param message The error message to report.
3243 * @param lineNumber The line number of the error.
3244 * @param sourceID The name of the source file that caused the error.
3245 */
3246 @Override
3247 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003248 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3249 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3250 if (mShouldShowErrorConsole &&
3251 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3252 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3253 }
3254 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003255 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003256 };
3257
3258 /**
3259 * Notify the host application a download should be done, or that
3260 * the data should be streamed if a streaming viewer is available.
3261 * @param url The full url to the content that should be downloaded
3262 * @param contentDisposition Content-disposition http header, if
3263 * present.
3264 * @param mimetype The mimetype of the content reported by the server
3265 * @param contentLength The file size reported by the server
3266 */
3267 public void onDownloadStart(String url, String userAgent,
3268 String contentDisposition, String mimetype, long contentLength) {
3269 // if we're dealing wih A/V content that's not explicitly marked
3270 // for download, check if it's streamable.
3271 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003272 || !contentDisposition.regionMatches(
3273 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003274 // query the package manager to see if there's a registered handler
3275 // that matches.
3276 Intent intent = new Intent(Intent.ACTION_VIEW);
3277 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003278 ResolveInfo info = getPackageManager().resolveActivity(intent,
3279 PackageManager.MATCH_DEFAULT_ONLY);
3280 if (info != null) {
3281 ComponentName myName = getComponentName();
3282 // If we resolved to ourselves, we don't want to attempt to
3283 // load the url only to try and download it again.
3284 if (!myName.getPackageName().equals(
3285 info.activityInfo.packageName)
3286 || !myName.getClassName().equals(
3287 info.activityInfo.name)) {
3288 // someone (other than us) knows how to handle this mime
3289 // type with this scheme, don't download.
3290 try {
3291 startActivity(intent);
3292 return;
3293 } catch (ActivityNotFoundException ex) {
3294 if (LOGD_ENABLED) {
3295 Log.d(LOGTAG, "activity not found for " + mimetype
3296 + " over " + Uri.parse(url).getScheme(),
3297 ex);
3298 }
3299 // Best behavior is to fall back to a download in this
3300 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003301 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003302 }
3303 }
3304 }
3305 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3306 }
3307
3308 /**
3309 * Notify the host application a download should be done, even if there
3310 * is a streaming viewer available for thise type.
3311 * @param url The full url to the content that should be downloaded
3312 * @param contentDisposition Content-disposition http header, if
3313 * present.
3314 * @param mimetype The mimetype of the content reported by the server
3315 * @param contentLength The file size reported by the server
3316 */
3317 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3318 String contentDisposition, String mimetype, long contentLength) {
3319
3320 String filename = URLUtil.guessFileName(url,
3321 contentDisposition, mimetype);
3322
3323 // Check to see if we have an SDCard
3324 String status = Environment.getExternalStorageState();
3325 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3326 int title;
3327 String msg;
3328
3329 // Check to see if the SDCard is busy, same as the music app
3330 if (status.equals(Environment.MEDIA_SHARED)) {
3331 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3332 title = R.string.download_sdcard_busy_dlg_title;
3333 } else {
3334 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3335 title = R.string.download_no_sdcard_dlg_title;
3336 }
3337
3338 new AlertDialog.Builder(this)
3339 .setTitle(title)
3340 .setIcon(android.R.drawable.ic_dialog_alert)
3341 .setMessage(msg)
3342 .setPositiveButton(R.string.ok, null)
3343 .show();
3344 return;
3345 }
3346
3347 // java.net.URI is a lot stricter than KURL so we have to undo
3348 // KURL's percent-encoding and redo the encoding using java.net.URI.
3349 URI uri = null;
3350 try {
3351 // Undo the percent-encoding that KURL may have done.
3352 String newUrl = new String(URLUtil.decode(url.getBytes()));
3353 // Parse the url into pieces
3354 WebAddress w = new WebAddress(newUrl);
3355 String frag = null;
3356 String query = null;
3357 String path = w.mPath;
3358 // Break the path into path, query, and fragment
3359 if (path.length() > 0) {
3360 // Strip the fragment
3361 int idx = path.lastIndexOf('#');
3362 if (idx != -1) {
3363 frag = path.substring(idx + 1);
3364 path = path.substring(0, idx);
3365 }
3366 idx = path.lastIndexOf('?');
3367 if (idx != -1) {
3368 query = path.substring(idx + 1);
3369 path = path.substring(0, idx);
3370 }
3371 }
3372 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3373 query, frag);
3374 } catch (Exception e) {
3375 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3376 return;
3377 }
3378
3379 // XXX: Have to use the old url since the cookies were stored using the
3380 // old percent-encoded url.
3381 String cookies = CookieManager.getInstance().getCookie(url);
3382
3383 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003384 values.put(Downloads.COLUMN_URI, uri.toString());
3385 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3386 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3387 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003388 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003389 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003390 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003391 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3392 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3393 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3394 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003395 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003396 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003397 }
3398 if (mimetype == null) {
3399 // We must have long pressed on a link or image to download it. We
3400 // are not sure of the mimetype in this case, so do a head request
3401 new FetchUrlMimeType(this).execute(values);
3402 } else {
3403 final Uri contentUri =
3404 getContentResolver().insert(Downloads.CONTENT_URI, values);
3405 viewDownloads(contentUri);
3406 }
3407
3408 }
3409
3410 /**
3411 * Resets the lock icon. This method is called when we start a new load and
3412 * know the url to be loaded.
3413 */
3414 private void resetLockIcon(String url) {
3415 // Save the lock-icon state (we revert to it if the load gets cancelled)
3416 saveLockIcon();
3417
3418 mLockIconType = LOCK_ICON_UNSECURE;
3419 if (URLUtil.isHttpsUrl(url)) {
3420 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003421 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003422 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3423 " reset lock icon to " + mLockIconType);
3424 }
3425 }
3426
3427 updateLockIconImage(LOCK_ICON_UNSECURE);
3428 }
3429
3430 /**
3431 * Resets the lock icon. This method is called when the icon needs to be
3432 * reset but we do not know whether we are loading a secure or not secure
3433 * page.
3434 */
3435 private void resetLockIcon() {
3436 // Save the lock-icon state (we revert to it if the load gets cancelled)
3437 saveLockIcon();
3438
3439 mLockIconType = LOCK_ICON_UNSECURE;
3440
Dave Bort31a6d1c2009-04-13 15:56:49 -07003441 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003442 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3443 " reset lock icon to " + mLockIconType);
3444 }
3445
3446 updateLockIconImage(LOCK_ICON_UNSECURE);
3447 }
3448
3449 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003450 * Update the lock icon to correspond to our latest state.
3451 */
3452 /* package */ void updateLockIconToLatest() {
3453 updateLockIconImage(mLockIconType);
3454 }
3455
3456 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003457 * Updates the lock-icon image in the title-bar.
3458 */
3459 private void updateLockIconImage(int lockIconType) {
3460 Drawable d = null;
3461 if (lockIconType == LOCK_ICON_SECURE) {
3462 d = mSecLockIcon;
3463 } else if (lockIconType == LOCK_ICON_MIXED) {
3464 d = mMixLockIcon;
3465 }
Leon Scroggins68579392009-09-15 15:31:54 -04003466 mTitleBar.setLock(d);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003467 if (mFakeTitleBar != null) {
3468 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003469 }
3470 }
3471
3472 /**
3473 * Displays a page-info dialog.
3474 * @param tab The tab to show info about
3475 * @param fromShowSSLCertificateOnError The flag that indicates whether
3476 * this dialog was opened from the SSL-certificate-on-error dialog or
3477 * not. This is important, since we need to know whether to return to
3478 * the parent dialog or simply dismiss.
3479 */
3480 private void showPageInfo(final TabControl.Tab tab,
3481 final boolean fromShowSSLCertificateOnError) {
3482 final LayoutInflater factory = LayoutInflater
3483 .from(this);
3484
3485 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3486
3487 final WebView view = tab.getWebView();
3488
3489 String url = null;
3490 String title = null;
3491
3492 if (view == null) {
3493 url = tab.getUrl();
3494 title = tab.getTitle();
3495 } else if (view == mTabControl.getCurrentWebView()) {
3496 // Use the cached title and url if this is the current WebView
3497 url = mUrl;
3498 title = mTitle;
3499 } else {
3500 url = view.getUrl();
3501 title = view.getTitle();
3502 }
3503
3504 if (url == null) {
3505 url = "";
3506 }
3507 if (title == null) {
3508 title = "";
3509 }
3510
3511 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3512 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3513
3514 mPageInfoView = tab;
3515 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3516
3517 AlertDialog.Builder alertDialogBuilder =
3518 new AlertDialog.Builder(this)
3519 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3520 .setView(pageInfoView)
3521 .setPositiveButton(
3522 R.string.ok,
3523 new DialogInterface.OnClickListener() {
3524 public void onClick(DialogInterface dialog,
3525 int whichButton) {
3526 mPageInfoDialog = null;
3527 mPageInfoView = null;
3528 mPageInfoFromShowSSLCertificateOnError = null;
3529
3530 // if we came here from the SSL error dialog
3531 if (fromShowSSLCertificateOnError) {
3532 // go back to the SSL error dialog
3533 showSSLCertificateOnError(
3534 mSSLCertificateOnErrorView,
3535 mSSLCertificateOnErrorHandler,
3536 mSSLCertificateOnErrorError);
3537 }
3538 }
3539 })
3540 .setOnCancelListener(
3541 new DialogInterface.OnCancelListener() {
3542 public void onCancel(DialogInterface dialog) {
3543 mPageInfoDialog = null;
3544 mPageInfoView = null;
3545 mPageInfoFromShowSSLCertificateOnError = null;
3546
3547 // if we came here from the SSL error dialog
3548 if (fromShowSSLCertificateOnError) {
3549 // go back to the SSL error dialog
3550 showSSLCertificateOnError(
3551 mSSLCertificateOnErrorView,
3552 mSSLCertificateOnErrorHandler,
3553 mSSLCertificateOnErrorError);
3554 }
3555 }
3556 });
3557
3558 // if we have a main top-level page SSL certificate set or a certificate
3559 // error
3560 if (fromShowSSLCertificateOnError ||
3561 (view != null && view.getCertificate() != null)) {
3562 // add a 'View Certificate' button
3563 alertDialogBuilder.setNeutralButton(
3564 R.string.view_certificate,
3565 new DialogInterface.OnClickListener() {
3566 public void onClick(DialogInterface dialog,
3567 int whichButton) {
3568 mPageInfoDialog = null;
3569 mPageInfoView = null;
3570 mPageInfoFromShowSSLCertificateOnError = null;
3571
3572 // if we came here from the SSL error dialog
3573 if (fromShowSSLCertificateOnError) {
3574 // go back to the SSL error dialog
3575 showSSLCertificateOnError(
3576 mSSLCertificateOnErrorView,
3577 mSSLCertificateOnErrorHandler,
3578 mSSLCertificateOnErrorError);
3579 } else {
3580 // otherwise, display the top-most certificate from
3581 // the chain
3582 if (view.getCertificate() != null) {
3583 showSSLCertificate(tab);
3584 }
3585 }
3586 }
3587 });
3588 }
3589
3590 mPageInfoDialog = alertDialogBuilder.show();
3591 }
3592
3593 /**
3594 * Displays the main top-level page SSL certificate dialog
3595 * (accessible from the Page-Info dialog).
3596 * @param tab The tab to show certificate for.
3597 */
3598 private void showSSLCertificate(final TabControl.Tab tab) {
3599 final View certificateView =
3600 inflateCertificateView(tab.getWebView().getCertificate());
3601 if (certificateView == null) {
3602 return;
3603 }
3604
3605 LayoutInflater factory = LayoutInflater.from(this);
3606
3607 final LinearLayout placeholder =
3608 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3609
3610 LinearLayout ll = (LinearLayout) factory.inflate(
3611 R.layout.ssl_success, placeholder);
3612 ((TextView)ll.findViewById(R.id.success))
3613 .setText(R.string.ssl_certificate_is_valid);
3614
3615 mSSLCertificateView = tab;
3616 mSSLCertificateDialog =
3617 new AlertDialog.Builder(this)
3618 .setTitle(R.string.ssl_certificate).setIcon(
3619 R.drawable.ic_dialog_browser_certificate_secure)
3620 .setView(certificateView)
3621 .setPositiveButton(R.string.ok,
3622 new DialogInterface.OnClickListener() {
3623 public void onClick(DialogInterface dialog,
3624 int whichButton) {
3625 mSSLCertificateDialog = null;
3626 mSSLCertificateView = null;
3627
3628 showPageInfo(tab, false);
3629 }
3630 })
3631 .setOnCancelListener(
3632 new DialogInterface.OnCancelListener() {
3633 public void onCancel(DialogInterface dialog) {
3634 mSSLCertificateDialog = null;
3635 mSSLCertificateView = null;
3636
3637 showPageInfo(tab, false);
3638 }
3639 })
3640 .show();
3641 }
3642
3643 /**
3644 * Displays the SSL error certificate dialog.
3645 * @param view The target web-view.
3646 * @param handler The SSL error handler responsible for cancelling the
3647 * connection that resulted in an SSL error or proceeding per user request.
3648 * @param error The SSL error object.
3649 */
3650 private void showSSLCertificateOnError(
3651 final WebView view, final SslErrorHandler handler, final SslError error) {
3652
3653 final View certificateView =
3654 inflateCertificateView(error.getCertificate());
3655 if (certificateView == null) {
3656 return;
3657 }
3658
3659 LayoutInflater factory = LayoutInflater.from(this);
3660
3661 final LinearLayout placeholder =
3662 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3663
3664 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3665 LinearLayout ll = (LinearLayout)factory
3666 .inflate(R.layout.ssl_warning, placeholder);
3667 ((TextView)ll.findViewById(R.id.warning))
3668 .setText(R.string.ssl_untrusted);
3669 }
3670
3671 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3672 LinearLayout ll = (LinearLayout)factory
3673 .inflate(R.layout.ssl_warning, placeholder);
3674 ((TextView)ll.findViewById(R.id.warning))
3675 .setText(R.string.ssl_mismatch);
3676 }
3677
3678 if (error.hasError(SslError.SSL_EXPIRED)) {
3679 LinearLayout ll = (LinearLayout)factory
3680 .inflate(R.layout.ssl_warning, placeholder);
3681 ((TextView)ll.findViewById(R.id.warning))
3682 .setText(R.string.ssl_expired);
3683 }
3684
3685 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3686 LinearLayout ll = (LinearLayout)factory
3687 .inflate(R.layout.ssl_warning, placeholder);
3688 ((TextView)ll.findViewById(R.id.warning))
3689 .setText(R.string.ssl_not_yet_valid);
3690 }
3691
3692 mSSLCertificateOnErrorHandler = handler;
3693 mSSLCertificateOnErrorView = view;
3694 mSSLCertificateOnErrorError = error;
3695 mSSLCertificateOnErrorDialog =
3696 new AlertDialog.Builder(this)
3697 .setTitle(R.string.ssl_certificate).setIcon(
3698 R.drawable.ic_dialog_browser_certificate_partially_secure)
3699 .setView(certificateView)
3700 .setPositiveButton(R.string.ok,
3701 new DialogInterface.OnClickListener() {
3702 public void onClick(DialogInterface dialog,
3703 int whichButton) {
3704 mSSLCertificateOnErrorDialog = null;
3705 mSSLCertificateOnErrorView = null;
3706 mSSLCertificateOnErrorHandler = null;
3707 mSSLCertificateOnErrorError = null;
3708
3709 mWebViewClient.onReceivedSslError(
3710 view, handler, error);
3711 }
3712 })
3713 .setNeutralButton(R.string.page_info_view,
3714 new DialogInterface.OnClickListener() {
3715 public void onClick(DialogInterface dialog,
3716 int whichButton) {
3717 mSSLCertificateOnErrorDialog = null;
3718
3719 // do not clear the dialog state: we will
3720 // need to show the dialog again once the
3721 // user is done exploring the page-info details
3722
3723 showPageInfo(mTabControl.getTabFromView(view),
3724 true);
3725 }
3726 })
3727 .setOnCancelListener(
3728 new DialogInterface.OnCancelListener() {
3729 public void onCancel(DialogInterface dialog) {
3730 mSSLCertificateOnErrorDialog = null;
3731 mSSLCertificateOnErrorView = null;
3732 mSSLCertificateOnErrorHandler = null;
3733 mSSLCertificateOnErrorError = null;
3734
3735 mWebViewClient.onReceivedSslError(
3736 view, handler, error);
3737 }
3738 })
3739 .show();
3740 }
3741
3742 /**
3743 * Inflates the SSL certificate view (helper method).
3744 * @param certificate The SSL certificate.
3745 * @return The resultant certificate view with issued-to, issued-by,
3746 * issued-on, expires-on, and possibly other fields set.
3747 * If the input certificate is null, returns null.
3748 */
3749 private View inflateCertificateView(SslCertificate certificate) {
3750 if (certificate == null) {
3751 return null;
3752 }
3753
3754 LayoutInflater factory = LayoutInflater.from(this);
3755
3756 View certificateView = factory.inflate(
3757 R.layout.ssl_certificate, null);
3758
3759 // issued to:
3760 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3761 if (issuedTo != null) {
3762 ((TextView) certificateView.findViewById(R.id.to_common))
3763 .setText(issuedTo.getCName());
3764 ((TextView) certificateView.findViewById(R.id.to_org))
3765 .setText(issuedTo.getOName());
3766 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3767 .setText(issuedTo.getUName());
3768 }
3769
3770 // issued by:
3771 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3772 if (issuedBy != null) {
3773 ((TextView) certificateView.findViewById(R.id.by_common))
3774 .setText(issuedBy.getCName());
3775 ((TextView) certificateView.findViewById(R.id.by_org))
3776 .setText(issuedBy.getOName());
3777 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3778 .setText(issuedBy.getUName());
3779 }
3780
3781 // issued on:
3782 String issuedOn = reformatCertificateDate(
3783 certificate.getValidNotBefore());
3784 ((TextView) certificateView.findViewById(R.id.issued_on))
3785 .setText(issuedOn);
3786
3787 // expires on:
3788 String expiresOn = reformatCertificateDate(
3789 certificate.getValidNotAfter());
3790 ((TextView) certificateView.findViewById(R.id.expires_on))
3791 .setText(expiresOn);
3792
3793 return certificateView;
3794 }
3795
3796 /**
3797 * Re-formats the certificate date (Date.toString()) string to
3798 * a properly localized date string.
3799 * @return Properly localized version of the certificate date string and
3800 * the original certificate date string if fails to localize.
3801 * If the original string is null, returns an empty string "".
3802 */
3803 private String reformatCertificateDate(String certificateDate) {
3804 String reformattedDate = null;
3805
3806 if (certificateDate != null) {
3807 Date date = null;
3808 try {
3809 date = java.text.DateFormat.getInstance().parse(certificateDate);
3810 } catch (ParseException e) {
3811 date = null;
3812 }
3813
3814 if (date != null) {
3815 reformattedDate =
3816 DateFormat.getDateFormat(this).format(date);
3817 }
3818 }
3819
3820 return reformattedDate != null ? reformattedDate :
3821 (certificateDate != null ? certificateDate : "");
3822 }
3823
3824 /**
3825 * Displays an http-authentication dialog.
3826 */
3827 private void showHttpAuthentication(final HttpAuthHandler handler,
3828 final String host, final String realm, final String title,
3829 final String name, final String password, int focusId) {
3830 LayoutInflater factory = LayoutInflater.from(this);
3831 final View v = factory
3832 .inflate(R.layout.http_authentication, null);
3833 if (name != null) {
3834 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3835 }
3836 if (password != null) {
3837 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3838 }
3839
3840 String titleText = title;
3841 if (titleText == null) {
3842 titleText = getText(R.string.sign_in_to).toString().replace(
3843 "%s1", host).replace("%s2", realm);
3844 }
3845
3846 mHttpAuthHandler = handler;
3847 AlertDialog dialog = new AlertDialog.Builder(this)
3848 .setTitle(titleText)
3849 .setIcon(android.R.drawable.ic_dialog_alert)
3850 .setView(v)
3851 .setPositiveButton(R.string.action,
3852 new DialogInterface.OnClickListener() {
3853 public void onClick(DialogInterface dialog,
3854 int whichButton) {
3855 String nm = ((EditText) v
3856 .findViewById(R.id.username_edit))
3857 .getText().toString();
3858 String pw = ((EditText) v
3859 .findViewById(R.id.password_edit))
3860 .getText().toString();
3861 BrowserActivity.this.setHttpAuthUsernamePassword
3862 (host, realm, nm, pw);
3863 handler.proceed(nm, pw);
3864 mHttpAuthenticationDialog = null;
3865 mHttpAuthHandler = null;
3866 }})
3867 .setNegativeButton(R.string.cancel,
3868 new DialogInterface.OnClickListener() {
3869 public void onClick(DialogInterface dialog,
3870 int whichButton) {
3871 handler.cancel();
3872 BrowserActivity.this.resetTitleAndRevertLockIcon();
3873 mHttpAuthenticationDialog = null;
3874 mHttpAuthHandler = null;
3875 }})
3876 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3877 public void onCancel(DialogInterface dialog) {
3878 handler.cancel();
3879 BrowserActivity.this.resetTitleAndRevertLockIcon();
3880 mHttpAuthenticationDialog = null;
3881 mHttpAuthHandler = null;
3882 }})
3883 .create();
3884 // Make the IME appear when the dialog is displayed if applicable.
3885 dialog.getWindow().setSoftInputMode(
3886 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3887 dialog.show();
3888 if (focusId != 0) {
3889 dialog.findViewById(focusId).requestFocus();
3890 } else {
3891 v.findViewById(R.id.username_edit).requestFocus();
3892 }
3893 mHttpAuthenticationDialog = dialog;
3894 }
3895
3896 public int getProgress() {
3897 WebView w = mTabControl.getCurrentWebView();
3898 if (w != null) {
3899 return w.getProgress();
3900 } else {
3901 return 100;
3902 }
3903 }
3904
3905 /**
3906 * Set HTTP authentication password.
3907 *
3908 * @param host The host for the password
3909 * @param realm The realm for the password
3910 * @param username The username for the password. If it is null, it means
3911 * password can't be saved.
3912 * @param password The password
3913 */
3914 public void setHttpAuthUsernamePassword(String host, String realm,
3915 String username,
3916 String password) {
3917 WebView w = mTabControl.getCurrentWebView();
3918 if (w != null) {
3919 w.setHttpAuthUsernamePassword(host, realm, username, password);
3920 }
3921 }
3922
3923 /**
3924 * connectivity manager says net has come or gone... inform the user
3925 * @param up true if net has come up, false if net has gone down
3926 */
3927 public void onNetworkToggle(boolean up) {
3928 if (up == mIsNetworkUp) {
3929 return;
3930 } else if (up) {
3931 mIsNetworkUp = true;
3932 if (mAlertDialog != null) {
3933 mAlertDialog.cancel();
3934 mAlertDialog = null;
3935 }
3936 } else {
3937 mIsNetworkUp = false;
3938 if (mInLoad && mAlertDialog == null) {
3939 mAlertDialog = new AlertDialog.Builder(this)
3940 .setTitle(R.string.loadSuspendedTitle)
3941 .setMessage(R.string.loadSuspended)
3942 .setPositiveButton(R.string.ok, null)
3943 .show();
3944 }
3945 }
3946 WebView w = mTabControl.getCurrentWebView();
3947 if (w != null) {
3948 w.setNetworkAvailable(up);
3949 }
3950 }
3951
3952 @Override
3953 protected void onActivityResult(int requestCode, int resultCode,
3954 Intent intent) {
3955 switch (requestCode) {
3956 case COMBO_PAGE:
3957 if (resultCode == RESULT_OK && intent != null) {
3958 String data = intent.getAction();
3959 Bundle extras = intent.getExtras();
3960 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003961 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003962 } else {
3963 final TabControl.Tab currentTab =
3964 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003965 dismissSubWindow(currentTab);
3966 if (data != null && data.length() != 0) {
3967 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003968 }
3969 }
3970 }
3971 break;
3972 default:
3973 break;
3974 }
Leon Scroggins30444232009-09-04 18:36:20 -04003975 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003976 }
3977
3978 /*
3979 * This method is called as a result of the user selecting the options
3980 * menu to see the download window, or when a download changes state. It
3981 * shows the download window ontop of the current window.
3982 */
3983 /* package */ void viewDownloads(Uri downloadRecord) {
3984 Intent intent = new Intent(this,
3985 BrowserDownloadPage.class);
3986 intent.setData(downloadRecord);
3987 startActivityForResult(intent, this.DOWNLOAD_PAGE);
3988
3989 }
3990
Leon Scroggins160a7e72009-08-14 18:28:01 -04003991 /**
3992 * Open the Go page.
3993 * @param startWithHistory If true, open starting on the history tab.
3994 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003995 */
Leon Scroggins30444232009-09-04 18:36:20 -04003996 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003997 WebView current = mTabControl.getCurrentWebView();
3998 if (current == null) {
3999 return;
4000 }
4001 Intent intent = new Intent(this,
4002 CombinedBookmarkHistoryActivity.class);
4003 String title = current.getTitle();
4004 String url = current.getUrl();
4005 // Just in case the user opens bookmarks before a page finishes loading
4006 // so the current history item, and therefore the page, is null.
4007 if (null == url) {
4008 url = mLastEnteredUrl;
4009 // This can happen.
4010 if (null == url) {
4011 url = mSettings.getHomePage();
4012 }
4013 }
4014 // In case the web page has not yet received its associated title.
4015 if (title == null) {
4016 title = url;
4017 }
4018 intent.putExtra("title", title);
4019 intent.putExtra("url", url);
Leon Scroggins30444232009-09-04 18:36:20 -04004020 // Disable opening in a new window if we have maxed out the windows
4021 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4022 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004023 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004024 if (startWithHistory) {
4025 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4026 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4027 }
4028 startActivityForResult(intent, COMBO_PAGE);
4029 }
4030
4031 // Called when loading from context menu or LOAD_URL message
4032 private void loadURL(WebView view, String url) {
4033 // In case the user enters nothing.
4034 if (url != null && url.length() != 0 && view != null) {
4035 url = smartUrlFilter(url);
4036 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4037 view.loadUrl(url);
4038 }
4039 }
4040 }
4041
The Android Open Source Project0c908882009-03-03 19:32:16 -08004042 private String smartUrlFilter(Uri inUri) {
4043 if (inUri != null) {
4044 return smartUrlFilter(inUri.toString());
4045 }
4046 return null;
4047 }
4048
4049
4050 // get window count
4051
4052 int getWindowCount(){
4053 if(mTabControl != null){
4054 return mTabControl.getTabCount();
4055 }
4056 return 0;
4057 }
4058
Feng Qianb34f87a2009-03-24 21:27:26 -07004059 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004060 "(?i)" + // switch on case insensitive matching
4061 "(" + // begin group for schema
4062 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004063 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004064 ")" +
4065 "(.*)" );
4066
4067 /**
4068 * Attempts to determine whether user input is a URL or search
4069 * terms. Anything with a space is passed to search.
4070 *
4071 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4072 * "Http://" converts to "http://"
4073 *
4074 * @return Original or modified URL
4075 *
4076 */
4077 String smartUrlFilter(String url) {
4078
4079 String inUrl = url.trim();
4080 boolean hasSpace = inUrl.indexOf(' ') != -1;
4081
4082 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4083 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004084 // force scheme to lowercase
4085 String scheme = matcher.group(1);
4086 String lcScheme = scheme.toLowerCase();
4087 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004088 inUrl = lcScheme + matcher.group(2);
4089 }
4090 if (hasSpace) {
4091 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004092 }
4093 return inUrl;
4094 }
4095 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004096 // FIXME: Is this the correct place to add to searches?
4097 // what if someone else calls this function?
4098 int shortcut = parseUrlShortcut(inUrl);
4099 if (shortcut != SHORTCUT_INVALID) {
4100 Browser.addSearchUrl(mResolver, inUrl);
4101 String query = inUrl.substring(2);
4102 switch (shortcut) {
4103 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004104 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004105 case SHORTCUT_WIKIPEDIA_SEARCH:
4106 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4107 case SHORTCUT_DICTIONARY_SEARCH:
4108 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4109 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004110 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004111 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004112 }
4113 }
4114 } else {
4115 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4116 return URLUtil.guessUrl(inUrl);
4117 }
4118 }
4119
4120 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004121 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004122 }
4123
Ben Murdochbff2d602009-07-01 20:19:05 +01004124 /* package */ void setShouldShowErrorConsole(boolean flag) {
4125 if (flag == mShouldShowErrorConsole) {
4126 // Nothing to do.
4127 return;
4128 }
4129
4130 mShouldShowErrorConsole = flag;
4131
4132 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4133
4134 if (flag) {
4135 // Setting the show state of the console will cause it's the layout to be inflated.
4136 if (errorConsole.numberOfErrors() > 0) {
4137 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4138 } else {
4139 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4140 }
4141
4142 // Now we can add it to the main view.
4143 mErrorConsoleContainer.addView(errorConsole,
4144 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4145 ViewGroup.LayoutParams.WRAP_CONTENT));
4146 } else {
4147 mErrorConsoleContainer.removeView(errorConsole);
4148 }
4149
4150 }
4151
The Android Open Source Project0c908882009-03-03 19:32:16 -08004152 private final static int LOCK_ICON_UNSECURE = 0;
4153 private final static int LOCK_ICON_SECURE = 1;
4154 private final static int LOCK_ICON_MIXED = 2;
4155
4156 private int mLockIconType = LOCK_ICON_UNSECURE;
4157 private int mPrevLockType = LOCK_ICON_UNSECURE;
4158
4159 private BrowserSettings mSettings;
4160 private TabControl mTabControl;
4161 private ContentResolver mResolver;
4162 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004163 private View mCustomView;
4164 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004165 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004166
4167 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4168 // view, we should rewrite this.
4169 private int mCurrentMenuState = 0;
4170 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004171 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004172 private static final int EMPTY_MENU = -1;
4173 private Menu mMenu;
4174
4175 private FindDialog mFindDialog;
4176 // Used to prevent chording to result in firing two shortcuts immediately
4177 // one after another. Fixes bug 1211714.
4178 boolean mCanChord;
4179
4180 private boolean mInLoad;
4181 private boolean mIsNetworkUp;
4182
4183 private boolean mPageStarted;
4184 private boolean mActivityInPause = true;
4185
4186 private boolean mMenuIsDown;
4187
4188 private final KeyTracker mKeyTracker = new KeyTracker(this);
4189
4190 // As trackball doesn't send repeat down, we have to track it ourselves
4191 private boolean mTrackTrackball;
4192
4193 private static boolean mInTrace;
4194
4195 // Performance probe
4196 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4197 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4198 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4199 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4200 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4201 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4202 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4203 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4204 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4205 };
4206
4207 private long mStart;
4208 private long mProcessStart;
4209 private long mUserStart;
4210 private long mSystemStart;
4211 private long mIdleStart;
4212 private long mIrqStart;
4213
4214 private long mUiStart;
4215
4216 private Drawable mMixLockIcon;
4217 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004218
4219 /* hold a ref so we can auto-cancel if necessary */
4220 private AlertDialog mAlertDialog;
4221
4222 // Wait for credentials before loading google.com
4223 private ProgressDialog mCredsDlg;
4224
4225 // The up-to-date URL and title (these can be different from those stored
4226 // in WebView, since it takes some time for the information in WebView to
4227 // get updated)
4228 private String mUrl;
4229 private String mTitle;
4230
4231 // As PageInfo has different style for landscape / portrait, we have
4232 // to re-open it when configuration changed
4233 private AlertDialog mPageInfoDialog;
4234 private TabControl.Tab mPageInfoView;
4235 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4236 // dialog, we should not just dismiss it, but should get back to the
4237 // SSL-certificate-on-error dialog. This flag is used to store this state
4238 private Boolean mPageInfoFromShowSSLCertificateOnError;
4239
4240 // as SSLCertificateOnError has different style for landscape / portrait,
4241 // we have to re-open it when configuration changed
4242 private AlertDialog mSSLCertificateOnErrorDialog;
4243 private WebView mSSLCertificateOnErrorView;
4244 private SslErrorHandler mSSLCertificateOnErrorHandler;
4245 private SslError mSSLCertificateOnErrorError;
4246
4247 // as SSLCertificate has different style for landscape / portrait, we
4248 // have to re-open it when configuration changed
4249 private AlertDialog mSSLCertificateDialog;
4250 private TabControl.Tab mSSLCertificateView;
4251
4252 // as HttpAuthentication has different style for landscape / portrait, we
4253 // have to re-open it when configuration changed
4254 private AlertDialog mHttpAuthenticationDialog;
4255 private HttpAuthHandler mHttpAuthHandler;
4256
4257 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4258 new FrameLayout.LayoutParams(
4259 ViewGroup.LayoutParams.FILL_PARENT,
4260 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004261 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4262 new FrameLayout.LayoutParams(
4263 ViewGroup.LayoutParams.FILL_PARENT,
4264 ViewGroup.LayoutParams.FILL_PARENT,
4265 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004266 // Google search
4267 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004268 // Wikipedia search
4269 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4270 // Dictionary search
4271 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4272 // Google Mobile Local search
4273 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4274
4275 final static String QUERY_PLACE_HOLDER = "%s";
4276
4277 // "source" parameter for Google search through search key
4278 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4279 // "source" parameter for Google search through goto menu
4280 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4281 // "source" parameter for Google search through simplily type
4282 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4283 // "source" parameter for Google search suggested by the browser
4284 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4285 // "source" parameter for Google search from unknown source
4286 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4287
4288 private final static String LOGTAG = "browser";
4289
The Android Open Source Project0c908882009-03-03 19:32:16 -08004290 private String mLastEnteredUrl;
4291
4292 private PowerManager.WakeLock mWakeLock;
4293 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4294
4295 private Toast mStopToast;
4296
Leon Scroggins68579392009-09-15 15:31:54 -04004297 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004298
Ben Murdochbff2d602009-07-01 20:19:05 +01004299 private LinearLayout mErrorConsoleContainer = null;
4300 private boolean mShouldShowErrorConsole = false;
4301
The Android Open Source Project0c908882009-03-03 19:32:16 -08004302 // As the ids are dynamically created, we can't guarantee that they will
4303 // be in sequence, so this static array maps ids to a window number.
4304 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4305 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4306 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4307 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4308
4309 // monitor platform changes
4310 private IntentFilter mNetworkStateChangedFilter;
4311 private BroadcastReceiver mNetworkStateIntentReceiver;
4312
Grace Klobab4da0ad2009-05-14 14:45:40 -07004313 private BroadcastReceiver mPackageInstallationReceiver;
4314
The Android Open Source Project0c908882009-03-03 19:32:16 -08004315 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004316 final static int COMBO_PAGE = 1;
4317 final static int DOWNLOAD_PAGE = 2;
4318 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004319
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004320 /**
4321 * A UrlData class to abstract how the content will be set to WebView.
4322 * This base class uses loadUrl to show the content.
4323 */
4324 private static class UrlData {
4325 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004326 byte[] mPostData;
4327
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004328 UrlData(String url) {
4329 this.mUrl = url;
4330 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004331
4332 void setPostData(byte[] postData) {
4333 mPostData = postData;
4334 }
4335
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004336 boolean isEmpty() {
4337 return mUrl == null || mUrl.length() == 0;
4338 }
4339
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004340 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004341 if (mPostData != null) {
4342 webView.postUrl(mUrl, mPostData);
4343 } else {
4344 webView.loadUrl(mUrl);
4345 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004346 }
4347 };
4348
4349 /**
4350 * A subclass of UrlData class that can display inlined content using
4351 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4352 */
4353 private static class InlinedUrlData extends UrlData {
4354 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4355 super(failUrl);
4356 mInlined = inlined;
4357 mMimeType = mimeType;
4358 mEncoding = encoding;
4359 }
4360 String mMimeType;
4361 String mInlined;
4362 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004363 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004364 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004365 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004366 }
4367
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004368 @Override
4369 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004370 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4371 }
4372 }
4373
Leon Scroggins1f005d32009-08-10 17:36:42 -04004374 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004375}