blob: d4cd7eb1fe642e3d36986f68f4057550192cbb9f [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());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001443 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Leon Scroggins1f005d32009-08-10 17:36:42 -04001444 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001445 break;
1446
1447 case R.id.stop_reload_menu_id:
1448 if (mInLoad) {
1449 stopLoading();
1450 } else {
1451 getTopWindow().reload();
1452 }
1453 break;
1454
1455 case R.id.back_menu_id:
1456 getTopWindow().goBack();
1457 break;
1458
1459 case R.id.forward_menu_id:
1460 getTopWindow().goForward();
1461 break;
1462
1463 case R.id.close_menu_id:
1464 // Close the subwindow if it exists.
1465 if (mTabControl.getCurrentSubWindow() != null) {
1466 dismissSubWindow(mTabControl.getCurrentTab());
1467 break;
1468 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001469 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001470 break;
1471
1472 case R.id.homepage_menu_id:
1473 TabControl.Tab current = mTabControl.getCurrentTab();
1474 if (current != null) {
1475 dismissSubWindow(current);
1476 current.getWebView().loadUrl(mSettings.getHomePage());
1477 }
1478 break;
1479
1480 case R.id.preferences_menu_id:
1481 Intent intent = new Intent(this,
1482 BrowserPreferencesPage.class);
1483 startActivityForResult(intent, PREFERENCES_PAGE);
1484 break;
1485
1486 case R.id.find_menu_id:
1487 if (null == mFindDialog) {
1488 mFindDialog = new FindDialog(this);
1489 }
1490 mFindDialog.setWebView(getTopWindow());
1491 mFindDialog.show();
1492 mMenuState = EMPTY_MENU;
1493 break;
1494
1495 case R.id.select_text_id:
1496 getTopWindow().emulateShiftHeld();
1497 break;
1498 case R.id.page_info_menu_id:
1499 showPageInfo(mTabControl.getCurrentTab(), false);
1500 break;
1501
1502 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001503 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001504 break;
1505
1506 case R.id.share_page_menu_id:
1507 Browser.sendString(this, getTopWindow().getUrl());
1508 break;
1509
1510 case R.id.dump_nav_menu_id:
1511 getTopWindow().debugDump();
1512 break;
1513
1514 case R.id.zoom_in_menu_id:
1515 getTopWindow().zoomIn();
1516 break;
1517
1518 case R.id.zoom_out_menu_id:
1519 getTopWindow().zoomOut();
1520 break;
1521
1522 case R.id.view_downloads_menu_id:
1523 viewDownloads(null);
1524 break;
1525
The Android Open Source Project0c908882009-03-03 19:32:16 -08001526 case R.id.window_one_menu_id:
1527 case R.id.window_two_menu_id:
1528 case R.id.window_three_menu_id:
1529 case R.id.window_four_menu_id:
1530 case R.id.window_five_menu_id:
1531 case R.id.window_six_menu_id:
1532 case R.id.window_seven_menu_id:
1533 case R.id.window_eight_menu_id:
1534 {
1535 int menuid = item.getItemId();
1536 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1537 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1538 TabControl.Tab desiredTab = mTabControl.getTab(id);
1539 if (desiredTab != null &&
1540 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001541 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001542 }
1543 break;
1544 }
1545 }
1546 }
1547 break;
1548
1549 default:
1550 if (!super.onOptionsItemSelected(item)) {
1551 return false;
1552 }
1553 // Otherwise fall through.
1554 }
1555 mCanChord = false;
1556 return true;
1557 }
1558
1559 public void closeFind() {
1560 mMenuState = R.id.MAIN_MENU;
1561 }
1562
1563 @Override public boolean onPrepareOptionsMenu(Menu menu)
1564 {
1565 // This happens when the user begins to hold down the menu key, so
1566 // allow them to chord to get a shortcut.
1567 mCanChord = true;
1568 // Note: setVisible will decide whether an item is visible; while
1569 // setEnabled() will decide whether an item is enabled, which also means
1570 // whether the matching shortcut key will function.
1571 super.onPrepareOptionsMenu(menu);
1572 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001573 case EMPTY_MENU:
1574 if (mCurrentMenuState != mMenuState) {
1575 menu.setGroupVisible(R.id.MAIN_MENU, false);
1576 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1577 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001578 }
1579 break;
1580 default:
1581 if (mCurrentMenuState != mMenuState) {
1582 menu.setGroupVisible(R.id.MAIN_MENU, true);
1583 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1584 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001585 }
1586 final WebView w = getTopWindow();
1587 boolean canGoBack = false;
1588 boolean canGoForward = false;
1589 boolean isHome = false;
1590 if (w != null) {
1591 canGoBack = w.canGoBack();
1592 canGoForward = w.canGoForward();
1593 isHome = mSettings.getHomePage().equals(w.getUrl());
1594 }
1595 final MenuItem back = menu.findItem(R.id.back_menu_id);
1596 back.setEnabled(canGoBack);
1597
1598 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1599 home.setEnabled(!isHome);
1600
1601 menu.findItem(R.id.forward_menu_id)
1602 .setEnabled(canGoForward);
1603
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001604 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1605 mTabControl.getTabCount() < TabControl.MAX_TABS);
1606
The Android Open Source Project0c908882009-03-03 19:32:16 -08001607 // decide whether to show the share link option
1608 PackageManager pm = getPackageManager();
1609 Intent send = new Intent(Intent.ACTION_SEND);
1610 send.setType("text/plain");
1611 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1612 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1613
The Android Open Source Project0c908882009-03-03 19:32:16 -08001614 boolean isNavDump = mSettings.isNavDump();
1615 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1616 nav.setVisible(isNavDump);
1617 nav.setEnabled(isNavDump);
1618 break;
1619 }
1620 mCurrentMenuState = mMenuState;
1621 return true;
1622 }
1623
1624 @Override
1625 public void onCreateContextMenu(ContextMenu menu, View v,
1626 ContextMenuInfo menuInfo) {
1627 WebView webview = (WebView) v;
1628 WebView.HitTestResult result = webview.getHitTestResult();
1629 if (result == null) {
1630 return;
1631 }
1632
1633 int type = result.getType();
1634 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1635 Log.w(LOGTAG,
1636 "We should not show context menu when nothing is touched");
1637 return;
1638 }
1639 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1640 // let TextView handles context menu
1641 return;
1642 }
1643
1644 // Note, http://b/issue?id=1106666 is requesting that
1645 // an inflated menu can be used again. This is not available
1646 // yet, so inflate each time (yuk!)
1647 MenuInflater inflater = getMenuInflater();
1648 inflater.inflate(R.menu.browsercontext, menu);
1649
1650 // Show the correct menu group
1651 String extra = result.getExtra();
1652 menu.setGroupVisible(R.id.PHONE_MENU,
1653 type == WebView.HitTestResult.PHONE_TYPE);
1654 menu.setGroupVisible(R.id.EMAIL_MENU,
1655 type == WebView.HitTestResult.EMAIL_TYPE);
1656 menu.setGroupVisible(R.id.GEO_MENU,
1657 type == WebView.HitTestResult.GEO_TYPE);
1658 menu.setGroupVisible(R.id.IMAGE_MENU,
1659 type == WebView.HitTestResult.IMAGE_TYPE
1660 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1661 menu.setGroupVisible(R.id.ANCHOR_MENU,
1662 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1663 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1664
1665 // Setup custom handling depending on the type
1666 switch (type) {
1667 case WebView.HitTestResult.PHONE_TYPE:
1668 menu.setHeaderTitle(Uri.decode(extra));
1669 menu.findItem(R.id.dial_context_menu_id).setIntent(
1670 new Intent(Intent.ACTION_VIEW, Uri
1671 .parse(WebView.SCHEME_TEL + extra)));
1672 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1673 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1674 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1675 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1676 addIntent);
1677 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1678 new Copy(extra));
1679 break;
1680
1681 case WebView.HitTestResult.EMAIL_TYPE:
1682 menu.setHeaderTitle(extra);
1683 menu.findItem(R.id.email_context_menu_id).setIntent(
1684 new Intent(Intent.ACTION_VIEW, Uri
1685 .parse(WebView.SCHEME_MAILTO + extra)));
1686 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1687 new Copy(extra));
1688 break;
1689
1690 case WebView.HitTestResult.GEO_TYPE:
1691 menu.setHeaderTitle(extra);
1692 menu.findItem(R.id.map_context_menu_id).setIntent(
1693 new Intent(Intent.ACTION_VIEW, Uri
1694 .parse(WebView.SCHEME_GEO
1695 + URLEncoder.encode(extra))));
1696 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1697 new Copy(extra));
1698 break;
1699
1700 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1701 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1702 TextView titleView = (TextView) LayoutInflater.from(this)
1703 .inflate(android.R.layout.browser_link_context_header,
1704 null);
1705 titleView.setText(extra);
1706 menu.setHeaderView(titleView);
1707 // decide whether to show the open link in new tab option
1708 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1709 mTabControl.getTabCount() < TabControl.MAX_TABS);
1710 PackageManager pm = getPackageManager();
1711 Intent send = new Intent(Intent.ACTION_SEND);
1712 send.setType("text/plain");
1713 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1714 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1715 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1716 break;
1717 }
1718 // otherwise fall through to handle image part
1719 case WebView.HitTestResult.IMAGE_TYPE:
1720 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1721 menu.setHeaderTitle(extra);
1722 }
1723 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1724 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1725 menu.findItem(R.id.download_context_menu_id).
1726 setOnMenuItemClickListener(new Download(extra));
1727 break;
1728
1729 default:
1730 Log.w(LOGTAG, "We should not get here.");
1731 break;
1732 }
1733 }
1734
The Android Open Source Project0c908882009-03-03 19:32:16 -08001735 // Attach the given tab to the content view.
1736 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001737 // Attach the container that contains the main WebView and any other UI
1738 // associated with the tab.
1739 mContentView.addView(t.getContainer(), COVER_SCREEN_PARAMS);
Ben Murdochbff2d602009-07-01 20:19:05 +01001740
1741 if (mShouldShowErrorConsole) {
1742 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1743 if (errorConsole.numberOfErrors() == 0) {
1744 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1745 } else {
1746 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1747 }
1748
1749 mErrorConsoleContainer.addView(errorConsole,
1750 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1751 ViewGroup.LayoutParams.WRAP_CONTENT));
1752 }
1753
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001754 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001755 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001756 // Attach the sub window if necessary
1757 attachSubWindow(t);
1758 // Request focus on the top window.
1759 t.getTopWindow().requestFocus();
1760 }
1761
1762 // Attach a sub window to the main WebView of the given tab.
1763 private void attachSubWindow(TabControl.Tab t) {
1764 // If a sub window exists, attach it to the content view.
1765 final WebView subView = t.getSubWebView();
1766 if (subView != null) {
1767 final View container = t.getSubWebViewContainer();
1768 mContentView.addView(container, COVER_SCREEN_PARAMS);
1769 subView.requestFocus();
1770 }
1771 }
1772
1773 // Remove the given tab from the content view.
1774 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001775 // Remove the container that contains the main WebView.
1776 mContentView.removeView(t.getContainer());
Ben Murdochbff2d602009-07-01 20:19:05 +01001777
1778 if (mTabControl.getCurrentErrorConsole(false) != null) {
1779 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1780 }
1781
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001782 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001783 if (view != null) {
1784 view.setEmbeddedTitleBar(null);
1785 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001786
The Android Open Source Project0c908882009-03-03 19:32:16 -08001787 // Remove the sub window if it exists.
1788 if (t.getSubWebView() != null) {
1789 mContentView.removeView(t.getSubWebViewContainer());
1790 }
1791 }
1792
1793 // Remove the sub window if it exists. Also called by TabControl when the
1794 // user clicks the 'X' to dismiss a sub window.
1795 /* package */ void dismissSubWindow(TabControl.Tab t) {
1796 final WebView mainView = t.getWebView();
1797 if (t.getSubWebView() != null) {
1798 // Remove the container view and request focus on the main WebView.
1799 mContentView.removeView(t.getSubWebViewContainer());
1800 mainView.requestFocus();
1801 // Tell the TabControl to dismiss the subwindow. This will destroy
1802 // the WebView.
1803 mTabControl.dismissSubWindow(t);
1804 }
1805 }
1806
Leon Scroggins1f005d32009-08-10 17:36:42 -04001807 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001808 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001809 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1810 String appId) {
1811 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001812 }
1813
1814 // This method does a ton of stuff. It will attempt to create a new tab
1815 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001816 // url isn't null, it will load the given url.
1817 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001818 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001819 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1820 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1821 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001822 final TabControl.Tab tab = mTabControl.createNewTab(
1823 closeOnExit, appId, urlData.mUrl);
1824 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001825 // If the last tab was removed from the active tabs page, currentTab
1826 // will be null.
1827 if (currentTab != null) {
1828 removeTabFromContentView(currentTab);
1829 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001830 attachTabToContentView(tab);
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001831 // We must set the new tab as the current tab to reflect the old
1832 // animation behavior.
1833 mTabControl.setCurrentTab(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001834 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001835 urlData.loadIn(webview);
1836 }
1837 return tab;
1838 } else {
1839 // Get rid of the subwindow if it exists
1840 dismissSubWindow(currentTab);
1841 if (!urlData.isEmpty()) {
1842 // Load the given url.
1843 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001844 }
1845 }
Grace Klobac9181842009-04-14 08:53:22 -07001846 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001847 }
1848
Grace Klobac9181842009-04-14 08:53:22 -07001849 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001850 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001851 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001852 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001853 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001854 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001855 }
Grace Klobac9181842009-04-14 08:53:22 -07001856 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001857 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001858 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001859 }
1860 }
1861
1862 private class Copy implements OnMenuItemClickListener {
1863 private CharSequence mText;
1864
1865 public boolean onMenuItemClick(MenuItem item) {
1866 copy(mText);
1867 return true;
1868 }
1869
1870 public Copy(CharSequence toCopy) {
1871 mText = toCopy;
1872 }
1873 }
1874
1875 private class Download implements OnMenuItemClickListener {
1876 private String mText;
1877
1878 public boolean onMenuItemClick(MenuItem item) {
1879 onDownloadStartNoStream(mText, null, null, null, -1);
1880 return true;
1881 }
1882
1883 public Download(String toDownload) {
1884 mText = toDownload;
1885 }
1886 }
1887
1888 private void copy(CharSequence text) {
1889 try {
1890 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1891 if (clip != null) {
1892 clip.setClipboardText(text);
1893 }
1894 } catch (android.os.RemoteException e) {
1895 Log.e(LOGTAG, "Copy failed", e);
1896 }
1897 }
1898
1899 /**
1900 * Resets the browser title-view to whatever it must be (for example, if we
1901 * load a page from history).
1902 */
1903 private void resetTitle() {
1904 resetLockIcon();
1905 resetTitleIconAndProgress();
1906 }
1907
1908 /**
1909 * Resets the browser title-view to whatever it must be
1910 * (for example, if we had a loading error)
1911 * When we have a new page, we call resetTitle, when we
1912 * have to reset the titlebar to whatever it used to be
1913 * (for example, if the user chose to stop loading), we
1914 * call resetTitleAndRevertLockIcon.
1915 */
1916 /* package */ void resetTitleAndRevertLockIcon() {
1917 revertLockIcon();
1918 resetTitleIconAndProgress();
1919 }
1920
1921 /**
1922 * Reset the title, favicon, and progress.
1923 */
1924 private void resetTitleIconAndProgress() {
1925 WebView current = mTabControl.getCurrentWebView();
1926 if (current == null) {
1927 return;
1928 }
1929 resetTitleAndIcon(current);
1930 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001931 mWebChromeClient.onProgressChanged(current, progress);
1932 }
1933
1934 // Reset the title and the icon based on the given item.
1935 private void resetTitleAndIcon(WebView view) {
1936 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1937 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001938 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001939 setFavicon(item.getFavicon());
1940 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001941 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001942 setFavicon(null);
1943 }
1944 }
1945
1946 /**
1947 * Sets a title composed of the URL and the title string.
1948 * @param url The URL of the site being loaded.
1949 * @param title The title of the site being loaded.
1950 */
Leon Scroggins68579392009-09-15 15:31:54 -04001951 private void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001952 mUrl = url;
1953 mTitle = title;
1954
Leon Scroggins68579392009-09-15 15:31:54 -04001955 mTitleBar.setTitleAndUrl(title, url);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001956 if (mFakeTitleBar != null) {
1957 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001958 }
1959 }
1960
1961 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001962 * @param url The URL to build a title version of the URL from.
1963 * @return The title version of the URL or null if fails.
1964 * The title version of the URL can be either the URL hostname,
1965 * or the hostname with an "https://" prefix (for secure URLs),
1966 * or an empty string if, for example, the URL in question is a
1967 * file:// URL with no hostname.
1968 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001969 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001970 String titleUrl = null;
1971
1972 if (url != null) {
1973 try {
1974 // parse the url string
1975 URL urlObj = new URL(url);
1976 if (urlObj != null) {
1977 titleUrl = "";
1978
1979 String protocol = urlObj.getProtocol();
1980 String host = urlObj.getHost();
1981
1982 if (host != null && 0 < host.length()) {
1983 titleUrl = host;
1984 if (protocol != null) {
1985 // if a secure site, add an "https://" prefix!
1986 if (protocol.equalsIgnoreCase("https")) {
1987 titleUrl = protocol + "://" + host;
1988 }
1989 }
1990 }
1991 }
1992 } catch (MalformedURLException e) {}
1993 }
1994
1995 return titleUrl;
1996 }
1997
1998 // Set the favicon in the title bar.
1999 private void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002000 mTitleBar.setFavicon(icon);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002001 if (mFakeTitleBar != null) {
2002 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002003 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002004 }
2005
2006 /**
2007 * Saves the current lock-icon state before resetting
2008 * the lock icon. If we have an error, we may need to
2009 * roll back to the previous state.
2010 */
2011 private void saveLockIcon() {
2012 mPrevLockType = mLockIconType;
2013 }
2014
2015 /**
2016 * Reverts the lock-icon state to the last saved state,
2017 * for example, if we had an error, and need to cancel
2018 * the load.
2019 */
2020 private void revertLockIcon() {
2021 mLockIconType = mPrevLockType;
2022
Dave Bort31a6d1c2009-04-13 15:56:49 -07002023 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002024 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2025 " revert lock icon to " + mLockIconType);
2026 }
2027
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002028 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002029 }
2030
Leon Scroggins1f005d32009-08-10 17:36:42 -04002031 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002032 * Close the tab, remove its associated title bar, and adjust mTabControl's
2033 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002034 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002035 /* package */ void closeTab(TabControl.Tab t) {
2036 int currentIndex = mTabControl.getCurrentIndex();
2037 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002038 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002039 if (currentIndex >= removeIndex && currentIndex != 0) {
2040 currentIndex--;
2041 }
2042 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
The Android Open Source Project0c908882009-03-03 19:32:16 -08002043 }
2044
2045 private void goBackOnePageOrQuit() {
2046 TabControl.Tab current = mTabControl.getCurrentTab();
2047 if (current == null) {
2048 /*
2049 * Instead of finishing the activity, simply push this to the back
2050 * of the stack and let ActivityManager to choose the foreground
2051 * activity. As BrowserActivity is singleTask, it will be always the
2052 * root of the task. So we can use either true or false for
2053 * moveTaskToBack().
2054 */
2055 moveTaskToBack(true);
2056 }
2057 WebView w = current.getWebView();
2058 if (w.canGoBack()) {
2059 w.goBack();
2060 } else {
2061 // Check to see if we are closing a window that was created by
2062 // another window. If so, we switch back to that window.
2063 TabControl.Tab parent = current.getParentTab();
2064 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002065 switchToTab(mTabControl.getTabIndex(parent));
2066 // Now we close the other tab
2067 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002068 } else {
2069 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002070 // force mPageStarted to be false as we are going to either
2071 // finish the activity or remove the tab. This will ensure
2072 // pauseWebView() taking action.
2073 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002074 if (mTabControl.getTabCount() == 1) {
2075 finish();
2076 return;
2077 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002078 // call pauseWebViewTimers() now, we won't be able to call
2079 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002080 // Temporarily change mActivityInPause to be true as
2081 // pauseWebViewTimers() will do nothing if mActivityInPause
2082 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002083 boolean savedState = mActivityInPause;
2084 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002085 Log.e(LOGTAG, "BrowserActivity is already paused "
2086 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002087 }
2088 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002089 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002090 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002091 removeTabFromContentView(current);
2092 mTabControl.removeTab(current);
2093 }
2094 /*
2095 * Instead of finishing the activity, simply push this to the back
2096 * of the stack and let ActivityManager to choose the foreground
2097 * activity. As BrowserActivity is singleTask, it will be always the
2098 * root of the task. So we can use either true or false for
2099 * moveTaskToBack().
2100 */
2101 moveTaskToBack(true);
2102 }
2103 }
2104 }
2105
2106 public KeyTracker.State onKeyTracker(int keyCode,
2107 KeyEvent event,
2108 KeyTracker.Stage stage,
2109 int duration) {
2110 // if onKeyTracker() is called after activity onStop()
2111 // because of accumulated key events,
2112 // we should ignore it as browser is not active any more.
2113 WebView topWindow = getTopWindow();
Andrei Popescuadc008d2009-06-26 14:11:30 +01002114 if (topWindow == null && mCustomView == null)
The Android Open Source Project0c908882009-03-03 19:32:16 -08002115 return KeyTracker.State.NOT_TRACKING;
2116
2117 if (keyCode == KeyEvent.KEYCODE_BACK) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01002118 // Check if a custom view is currently showing and, if it is, hide it.
2119 if (mCustomView != null) {
2120 mWebChromeClient.onHideCustomView();
2121 return KeyTracker.State.DONE_TRACKING;
2122 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002123 if (stage == KeyTracker.Stage.LONG_REPEAT) {
Leon Scroggins30444232009-09-04 18:36:20 -04002124 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002125 return KeyTracker.State.DONE_TRACKING;
2126 } else if (stage == KeyTracker.Stage.UP) {
2127 // FIXME: Currently, we do not have a notion of the
2128 // history picker for the subwindow, but maybe we
2129 // should?
2130 WebView subwindow = mTabControl.getCurrentSubWindow();
2131 if (subwindow != null) {
2132 if (subwindow.canGoBack()) {
2133 subwindow.goBack();
2134 } else {
2135 dismissSubWindow(mTabControl.getCurrentTab());
2136 }
2137 } else {
2138 goBackOnePageOrQuit();
2139 }
2140 return KeyTracker.State.DONE_TRACKING;
2141 }
2142 return KeyTracker.State.KEEP_TRACKING;
2143 }
2144 return KeyTracker.State.NOT_TRACKING;
2145 }
2146
2147 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2148 if (keyCode == KeyEvent.KEYCODE_MENU) {
2149 mMenuIsDown = true;
Grace Kloba6ee9c492009-07-13 10:04:34 -07002150 } else if (mMenuIsDown) {
2151 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2152 // still down, we don't want to trigger the search. Pretend to
2153 // consume the key and do nothing.
2154 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002155 }
2156 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2157 if (!handled) {
2158 switch (keyCode) {
2159 case KeyEvent.KEYCODE_SPACE:
2160 if (event.isShiftPressed()) {
2161 getTopWindow().pageUp(false);
2162 } else {
2163 getTopWindow().pageDown(false);
2164 }
2165 handled = true;
2166 break;
2167
2168 default:
2169 break;
2170 }
2171 }
2172 return handled || super.onKeyDown(keyCode, event);
2173 }
2174
2175 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2176 if (keyCode == KeyEvent.KEYCODE_MENU) {
2177 mMenuIsDown = false;
2178 }
2179 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2180 }
2181
Leon Scroggins68579392009-09-15 15:31:54 -04002182 /* package */ void stopLoading() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002183 resetTitleAndRevertLockIcon();
2184 WebView w = getTopWindow();
2185 w.stopLoading();
2186 mWebViewClient.onPageFinished(w, w.getUrl());
2187
2188 cancelStopToast();
2189 mStopToast = Toast
2190 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2191 mStopToast.show();
2192 }
2193
2194 private void cancelStopToast() {
2195 if (mStopToast != null) {
2196 mStopToast.cancel();
2197 mStopToast = null;
2198 }
2199 }
2200
2201 // called by a non-UI thread to post the message
2202 public void postMessage(int what, int arg1, int arg2, Object obj) {
2203 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2204 }
2205
2206 // public message ids
2207 public final static int LOAD_URL = 1001;
2208 public final static int STOP_LOAD = 1002;
2209
2210 // Message Ids
2211 private static final int FOCUS_NODE_HREF = 102;
2212 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002213 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002214
2215 // Private handler for handling javascript and saving passwords
2216 private Handler mHandler = new Handler() {
2217
2218 public void handleMessage(Message msg) {
2219 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002220 case FOCUS_NODE_HREF:
2221 String url = (String) msg.getData().get("url");
2222 if (url == null || url.length() == 0) {
2223 break;
2224 }
2225 HashMap focusNodeMap = (HashMap) msg.obj;
2226 WebView view = (WebView) focusNodeMap.get("webview");
2227 // Only apply the action if the top window did not change.
2228 if (getTopWindow() != view) {
2229 break;
2230 }
2231 switch (msg.arg1) {
2232 case R.id.open_context_menu_id:
2233 case R.id.view_image_context_menu_id:
2234 loadURL(getTopWindow(), url);
2235 break;
2236 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002237 final TabControl.Tab parent = mTabControl
2238 .getCurrentTab();
2239 final TabControl.Tab newTab = openTab(url);
2240 if (newTab != parent) {
2241 parent.addChildTab(newTab);
2242 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002243 break;
2244 case R.id.bookmark_context_menu_id:
2245 Intent intent = new Intent(BrowserActivity.this,
2246 AddBookmarkPage.class);
2247 intent.putExtra("url", url);
2248 startActivity(intent);
2249 break;
2250 case R.id.share_link_context_menu_id:
2251 Browser.sendString(BrowserActivity.this, url);
2252 break;
2253 case R.id.copy_link_context_menu_id:
2254 copy(url);
2255 break;
2256 case R.id.save_link_context_menu_id:
2257 case R.id.download_context_menu_id:
2258 onDownloadStartNoStream(url, null, null, null, -1);
2259 break;
2260 }
2261 break;
2262
2263 case LOAD_URL:
2264 loadURL(getTopWindow(), (String) msg.obj);
2265 break;
2266
2267 case STOP_LOAD:
2268 stopLoading();
2269 break;
2270
2271 case CANCEL_CREDS_REQUEST:
2272 resumeAfterCredentials();
2273 break;
2274
The Android Open Source Project0c908882009-03-03 19:32:16 -08002275 case RELEASE_WAKELOCK:
2276 if (mWakeLock.isHeld()) {
2277 mWakeLock.release();
2278 }
2279 break;
2280 }
2281 }
2282 };
2283
Leon Scroggins89c6d362009-07-15 16:54:37 -04002284 private void updateScreenshot(WebView view) {
2285 // If this is a bookmarked site, add a screenshot to the database.
2286 // FIXME: When should we update? Every time?
2287 // FIXME: Would like to make sure there is actually something to
2288 // draw, but the API for that (WebViewCore.pictureReady()) is not
2289 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002290 ContentResolver cr = getContentResolver();
2291 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002292 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002293 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002294 boolean succeed = c.moveToFirst();
2295 ContentValues values = null;
2296 while (succeed) {
2297 if (values == null) {
2298 final ByteArrayOutputStream os
2299 = new ByteArrayOutputStream();
2300 Picture thumbnail = view.capturePicture();
2301 // Keep width and height in sync with BrowserBookmarksPage
2302 // and bookmark_thumb
2303 Bitmap bm = Bitmap.createBitmap(100, 80,
2304 Bitmap.Config.ARGB_4444);
2305 Canvas canvas = new Canvas(bm);
2306 // May need to tweak these values to determine what is the
2307 // best scale factor
2308 canvas.scale(.5f, .5f);
2309 thumbnail.draw(canvas);
2310 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2311 values = new ContentValues();
2312 values.put(Browser.BookmarkColumns.THUMBNAIL,
2313 os.toByteArray());
2314 }
2315 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2316 c.getInt(0)), values, null, null);
2317 succeed = c.moveToNext();
2318 }
2319 c.close();
2320 }
2321 }
2322
The Android Open Source Project0c908882009-03-03 19:32:16 -08002323 // -------------------------------------------------------------------------
2324 // WebViewClient implementation.
2325 //-------------------------------------------------------------------------
2326
2327 // Use in overrideUrlLoading
2328 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2329 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2330 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2331 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2332
2333 /* package */ WebViewClient getWebViewClient() {
2334 return mWebViewClient;
2335 }
2336
Patrick Scott3918d442009-08-04 13:22:29 -04002337 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002338 if (icon != null) {
2339 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott3918d442009-08-04 13:22:29 -04002340 view, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002341 }
2342 setFavicon(icon);
2343 }
2344
2345 private final WebViewClient mWebViewClient = new WebViewClient() {
2346 @Override
2347 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2348 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002349 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002350
2351 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2352 if (errorConsole != null) {
2353 errorConsole.clearErrorMessages();
2354 if (mShouldShowErrorConsole) {
2355 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2356 }
2357 }
2358
The Android Open Source Project0c908882009-03-03 19:32:16 -08002359 // Call updateIcon instead of setFavicon so the bookmark
2360 // database can be updated.
Patrick Scott3918d442009-08-04 13:22:29 -04002361 updateIcon(view, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002362
Grace Kloba4d7880f2009-08-12 09:35:42 -07002363 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002364 String host;
2365 try {
2366 WebAddress uri = new WebAddress(url);
2367 host = uri.mHost;
2368 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002369 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002370 }
2371 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002372 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002373 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002374 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002375 }
2376
2377 // Performance probe
2378 if (false) {
2379 mStart = SystemClock.uptimeMillis();
2380 mProcessStart = Process.getElapsedCpuTime();
2381 long[] sysCpu = new long[7];
2382 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2383 sysCpu, null)) {
2384 mUserStart = sysCpu[0] + sysCpu[1];
2385 mSystemStart = sysCpu[2];
2386 mIdleStart = sysCpu[3];
2387 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2388 }
2389 mUiStart = SystemClock.currentThreadTimeMillis();
2390 }
2391
2392 if (!mPageStarted) {
2393 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002394 // if onResume() has been called, resumeWebViewTimers() does
2395 // nothing.
2396 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002397 }
2398
2399 // reset sync timer to avoid sync starts during loading a page
2400 CookieSyncManager.getInstance().resetSync();
2401
2402 mInLoad = true;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002403 WebView currentWebView = mTabControl.getCurrentWebView();
2404 if (currentWebView == null || currentWebView.getScrollY() != 0) {
2405 // This page has begun to load, so show the title bar
2406 showFakeTitleBar();
2407 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002408 updateInLoadMenuItems();
2409 if (!mIsNetworkUp) {
2410 if ( mAlertDialog == null) {
2411 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2412 .setTitle(R.string.loadSuspendedTitle)
2413 .setMessage(R.string.loadSuspended)
2414 .setPositiveButton(R.string.ok, null)
2415 .show();
2416 }
2417 if (view != null) {
2418 view.setNetworkAvailable(false);
2419 }
2420 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002421 }
2422
2423 @Override
2424 public void onPageFinished(WebView view, String url) {
2425 // Reset the title and icon in case we stopped a provisional
2426 // load.
2427 resetTitleAndIcon(view);
2428
2429 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002430 updateLockIconToLatest();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002431 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002432
The Android Open Source Project0c908882009-03-03 19:32:16 -08002433 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002434 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002435 long[] sysCpu = new long[7];
2436 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2437 sysCpu, null)) {
2438 String uiInfo = "UI thread used "
2439 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2440 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002441 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002442 Log.d(LOGTAG, uiInfo);
2443 }
2444 //The string that gets written to the log
2445 String performanceString = "It took total "
2446 + (SystemClock.uptimeMillis() - mStart)
2447 + " ms clock time to load the page."
2448 + "\nbrowser process used "
2449 + (Process.getElapsedCpuTime() - mProcessStart)
2450 + " ms, user processes used "
2451 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2452 + " ms, kernel used "
2453 + (sysCpu[2] - mSystemStart) * 10
2454 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2455 + " ms and irq took "
2456 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2457 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002458 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002459 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2460 }
2461 if (url != null) {
2462 // strip the url to maintain consistency
2463 String newUrl = new String(url);
2464 if (newUrl.startsWith("http://www.")) {
2465 newUrl = newUrl.substring(11);
2466 } else if (newUrl.startsWith("http://")) {
2467 newUrl = newUrl.substring(7);
2468 } else if (newUrl.startsWith("https://www.")) {
2469 newUrl = newUrl.substring(12);
2470 } else if (newUrl.startsWith("https://")) {
2471 newUrl = newUrl.substring(8);
2472 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002473 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002474 Log.d(LOGTAG, newUrl + " loaded");
2475 }
2476 /*
2477 if (sWhiteList.contains(newUrl)) {
2478 // The string that gets pushed to the statistcs
2479 // service
2480 performanceString = performanceString
2481 + "\nWebpage: "
2482 + newUrl
2483 + "\nCarrier: "
2484 + android.os.SystemProperties
2485 .get("gsm.sim.operator.alpha");
2486 if (mWebView != null
2487 && mWebView.getContext() != null
2488 && mWebView.getContext().getSystemService(
2489 Context.CONNECTIVITY_SERVICE) != null) {
2490 ConnectivityManager cManager =
2491 (ConnectivityManager) mWebView
2492 .getContext().getSystemService(
2493 Context.CONNECTIVITY_SERVICE);
2494 NetworkInfo nInfo = cManager
2495 .getActiveNetworkInfo();
2496 if (nInfo != null) {
2497 performanceString = performanceString
2498 + "\nNetwork Type: "
2499 + nInfo.getType().toString();
2500 }
2501 }
2502 Checkin.logEvent(mResolver,
2503 Checkin.Events.Tag.WEBPAGE_LOAD,
2504 performanceString);
2505 Log.w(LOGTAG, "pushed to the statistics service");
2506 }
2507 */
2508 }
2509 }
2510 }
2511
2512 if (mInTrace) {
2513 mInTrace = false;
2514 Debug.stopMethodTracing();
2515 }
2516
2517 if (mPageStarted) {
2518 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002519 // pauseWebViewTimers() will do nothing and return false if
2520 // onPause() is not called yet.
2521 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002522 if (mWakeLock.isHeld()) {
2523 mHandler.removeMessages(RELEASE_WAKELOCK);
2524 mWakeLock.release();
2525 }
2526 }
2527 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002528 }
2529
2530 // return true if want to hijack the url to let another app to handle it
2531 @Override
2532 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2533 if (url.startsWith(SCHEME_WTAI)) {
2534 // wtai://wp/mc;number
2535 // number=string(phone-number)
2536 if (url.startsWith(SCHEME_WTAI_MC)) {
2537 Intent intent = new Intent(Intent.ACTION_VIEW,
2538 Uri.parse(WebView.SCHEME_TEL +
2539 url.substring(SCHEME_WTAI_MC.length())));
2540 startActivity(intent);
2541 return true;
2542 }
2543 // wtai://wp/sd;dtmf
2544 // dtmf=string(dialstring)
2545 if (url.startsWith(SCHEME_WTAI_SD)) {
2546 // TODO
2547 // only send when there is active voice connection
2548 return false;
2549 }
2550 // wtai://wp/ap;number;name
2551 // number=string(phone-number)
2552 // name=string
2553 if (url.startsWith(SCHEME_WTAI_AP)) {
2554 // TODO
2555 return false;
2556 }
2557 }
2558
Dianne Hackborn99189432009-06-17 18:06:18 -07002559 // The "about:" schemes are internal to the browser; don't
2560 // want these to be dispatched to other apps.
2561 if (url.startsWith("about:")) {
2562 return false;
2563 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002564
Dianne Hackborn99189432009-06-17 18:06:18 -07002565 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002566
Dianne Hackborn99189432009-06-17 18:06:18 -07002567 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002568 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002569 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2570 } catch (URISyntaxException ex) {
2571 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002572 return false;
2573 }
2574
Grace Kloba5b078b52009-06-24 20:23:41 -07002575 // check whether the intent can be resolved. If not, we will see
2576 // whether we can download it from the Market.
2577 if (getPackageManager().resolveActivity(intent, 0) == null) {
2578 String packagename = intent.getPackage();
2579 if (packagename != null) {
2580 intent = new Intent(Intent.ACTION_VIEW, Uri
2581 .parse("market://search?q=pname:" + packagename));
2582 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2583 startActivity(intent);
2584 return true;
2585 } else {
2586 return false;
2587 }
2588 }
2589
Dianne Hackborn99189432009-06-17 18:06:18 -07002590 // sanitize the Intent, ensuring web pages can not bypass browser
2591 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002592 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002593 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002594 try {
2595 if (startActivityIfNeeded(intent, -1)) {
2596 return true;
2597 }
2598 } catch (ActivityNotFoundException ex) {
2599 // ignore the error. If no application can handle the URL,
2600 // eg about:blank, assume the browser can handle it.
2601 }
2602
2603 if (mMenuIsDown) {
2604 openTab(url);
2605 closeOptionsMenu();
2606 return true;
2607 }
2608
2609 return false;
2610 }
2611
2612 /**
2613 * Updates the lock icon. This method is called when we discover another
2614 * resource to be loaded for this page (for example, javascript). While
2615 * we update the icon type, we do not update the lock icon itself until
2616 * we are done loading, it is slightly more secure this way.
2617 */
2618 @Override
2619 public void onLoadResource(WebView view, String url) {
2620 if (url != null && url.length() > 0) {
2621 // It is only if the page claims to be secure
2622 // that we may have to update the lock:
2623 if (mLockIconType == LOCK_ICON_SECURE) {
2624 // If NOT a 'safe' url, change the lock to mixed content!
2625 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2626 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002627 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002628 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2629 " updated lock icon to " + mLockIconType + " due to " + url);
2630 }
2631 }
2632 }
2633 }
2634 }
2635
2636 /**
2637 * Show the dialog, asking the user if they would like to continue after
2638 * an excessive number of HTTP redirects.
2639 */
2640 @Override
2641 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2642 final Message continueMsg) {
2643 new AlertDialog.Builder(BrowserActivity.this)
2644 .setTitle(R.string.browserFrameRedirect)
2645 .setMessage(R.string.browserFrame307Post)
2646 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2647 public void onClick(DialogInterface dialog, int which) {
2648 continueMsg.sendToTarget();
2649 }})
2650 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2651 public void onClick(DialogInterface dialog, int which) {
2652 cancelMsg.sendToTarget();
2653 }})
2654 .setOnCancelListener(new OnCancelListener() {
2655 public void onCancel(DialogInterface dialog) {
2656 cancelMsg.sendToTarget();
2657 }})
2658 .show();
2659 }
2660
Patrick Scott37911c72009-03-24 18:02:58 -07002661 // Container class for the next error dialog that needs to be
2662 // displayed.
2663 class ErrorDialog {
2664 public final int mTitle;
2665 public final String mDescription;
2666 public final int mError;
2667 ErrorDialog(int title, String desc, int error) {
2668 mTitle = title;
2669 mDescription = desc;
2670 mError = error;
2671 }
2672 };
2673
2674 private void processNextError() {
2675 if (mQueuedErrors == null) {
2676 return;
2677 }
2678 // The first one is currently displayed so just remove it.
2679 mQueuedErrors.removeFirst();
2680 if (mQueuedErrors.size() == 0) {
2681 mQueuedErrors = null;
2682 return;
2683 }
2684 showError(mQueuedErrors.getFirst());
2685 }
2686
2687 private DialogInterface.OnDismissListener mDialogListener =
2688 new DialogInterface.OnDismissListener() {
2689 public void onDismiss(DialogInterface d) {
2690 processNextError();
2691 }
2692 };
2693 private LinkedList<ErrorDialog> mQueuedErrors;
2694
2695 private void queueError(int err, String desc) {
2696 if (mQueuedErrors == null) {
2697 mQueuedErrors = new LinkedList<ErrorDialog>();
2698 }
2699 for (ErrorDialog d : mQueuedErrors) {
2700 if (d.mError == err) {
2701 // Already saw a similar error, ignore the new one.
2702 return;
2703 }
2704 }
2705 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002706 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002707 R.string.browserFrameFileErrorLabel :
2708 R.string.browserFrameNetworkErrorLabel,
2709 desc, err);
2710 mQueuedErrors.addLast(errDialog);
2711
2712 // Show the dialog now if the queue was empty.
2713 if (mQueuedErrors.size() == 1) {
2714 showError(errDialog);
2715 }
2716 }
2717
2718 private void showError(ErrorDialog errDialog) {
2719 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2720 .setTitle(errDialog.mTitle)
2721 .setMessage(errDialog.mDescription)
2722 .setPositiveButton(R.string.ok, null)
2723 .create();
2724 d.setOnDismissListener(mDialogListener);
2725 d.show();
2726 }
2727
The Android Open Source Project0c908882009-03-03 19:32:16 -08002728 /**
2729 * Show a dialog informing the user of the network error reported by
2730 * WebCore.
2731 */
2732 @Override
2733 public void onReceivedError(WebView view, int errorCode,
2734 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002735 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2736 errorCode != WebViewClient.ERROR_CONNECT &&
2737 errorCode != WebViewClient.ERROR_BAD_URL &&
2738 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2739 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002740 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002741 }
Patrick Scott37911c72009-03-24 18:02:58 -07002742 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2743 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002744
2745 // We need to reset the title after an error.
2746 resetTitleAndRevertLockIcon();
2747 }
2748
2749 /**
2750 * Check with the user if it is ok to resend POST data as the page they
2751 * are trying to navigate to is the result of a POST.
2752 */
2753 @Override
2754 public void onFormResubmission(WebView view, final Message dontResend,
2755 final Message resend) {
2756 new AlertDialog.Builder(BrowserActivity.this)
2757 .setTitle(R.string.browserFrameFormResubmitLabel)
2758 .setMessage(R.string.browserFrameFormResubmitMessage)
2759 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2760 public void onClick(DialogInterface dialog, int which) {
2761 resend.sendToTarget();
2762 }})
2763 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2764 public void onClick(DialogInterface dialog, int which) {
2765 dontResend.sendToTarget();
2766 }})
2767 .setOnCancelListener(new OnCancelListener() {
2768 public void onCancel(DialogInterface dialog) {
2769 dontResend.sendToTarget();
2770 }})
2771 .show();
2772 }
2773
2774 /**
2775 * Insert the url into the visited history database.
2776 * @param url The url to be inserted.
2777 * @param isReload True if this url is being reloaded.
2778 * FIXME: Not sure what to do when reloading the page.
2779 */
2780 @Override
2781 public void doUpdateVisitedHistory(WebView view, String url,
2782 boolean isReload) {
2783 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2784 return;
2785 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002786 // remove "client" before updating it to the history so that it wont
2787 // show up in the auto-complete list.
2788 int index = url.indexOf("client=ms-");
2789 if (index > 0 && url.contains(".google.")) {
2790 int end = url.indexOf('&', index);
2791 if (end > 0) {
2792 url = url.substring(0, index-1).concat(url.substring(end));
2793 } else {
2794 url = url.substring(0, index-1);
2795 }
2796 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002797 Browser.updateVisitedHistory(mResolver, url, true);
2798 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2799 }
2800
2801 /**
2802 * Displays SSL error(s) dialog to the user.
2803 */
2804 @Override
2805 public void onReceivedSslError(
2806 final WebView view, final SslErrorHandler handler, final SslError error) {
2807
2808 if (mSettings.showSecurityWarnings()) {
2809 final LayoutInflater factory =
2810 LayoutInflater.from(BrowserActivity.this);
2811 final View warningsView =
2812 factory.inflate(R.layout.ssl_warnings, null);
2813 final LinearLayout placeholder =
2814 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2815
2816 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2817 LinearLayout ll = (LinearLayout)factory
2818 .inflate(R.layout.ssl_warning, null);
2819 ((TextView)ll.findViewById(R.id.warning))
2820 .setText(R.string.ssl_untrusted);
2821 placeholder.addView(ll);
2822 }
2823
2824 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2825 LinearLayout ll = (LinearLayout)factory
2826 .inflate(R.layout.ssl_warning, null);
2827 ((TextView)ll.findViewById(R.id.warning))
2828 .setText(R.string.ssl_mismatch);
2829 placeholder.addView(ll);
2830 }
2831
2832 if (error.hasError(SslError.SSL_EXPIRED)) {
2833 LinearLayout ll = (LinearLayout)factory
2834 .inflate(R.layout.ssl_warning, null);
2835 ((TextView)ll.findViewById(R.id.warning))
2836 .setText(R.string.ssl_expired);
2837 placeholder.addView(ll);
2838 }
2839
2840 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2841 LinearLayout ll = (LinearLayout)factory
2842 .inflate(R.layout.ssl_warning, null);
2843 ((TextView)ll.findViewById(R.id.warning))
2844 .setText(R.string.ssl_not_yet_valid);
2845 placeholder.addView(ll);
2846 }
2847
2848 new AlertDialog.Builder(BrowserActivity.this)
2849 .setTitle(R.string.security_warning)
2850 .setIcon(android.R.drawable.ic_dialog_alert)
2851 .setView(warningsView)
2852 .setPositiveButton(R.string.ssl_continue,
2853 new DialogInterface.OnClickListener() {
2854 public void onClick(DialogInterface dialog, int whichButton) {
2855 handler.proceed();
2856 }
2857 })
2858 .setNeutralButton(R.string.view_certificate,
2859 new DialogInterface.OnClickListener() {
2860 public void onClick(DialogInterface dialog, int whichButton) {
2861 showSSLCertificateOnError(view, handler, error);
2862 }
2863 })
2864 .setNegativeButton(R.string.cancel,
2865 new DialogInterface.OnClickListener() {
2866 public void onClick(DialogInterface dialog, int whichButton) {
2867 handler.cancel();
2868 BrowserActivity.this.resetTitleAndRevertLockIcon();
2869 }
2870 })
2871 .setOnCancelListener(
2872 new DialogInterface.OnCancelListener() {
2873 public void onCancel(DialogInterface dialog) {
2874 handler.cancel();
2875 BrowserActivity.this.resetTitleAndRevertLockIcon();
2876 }
2877 })
2878 .show();
2879 } else {
2880 handler.proceed();
2881 }
2882 }
2883
2884 /**
2885 * Handles an HTTP authentication request.
2886 *
2887 * @param handler The authentication handler
2888 * @param host The host
2889 * @param realm The realm
2890 */
2891 @Override
2892 public void onReceivedHttpAuthRequest(WebView view,
2893 final HttpAuthHandler handler, final String host, final String realm) {
2894 String username = null;
2895 String password = null;
2896
2897 boolean reuseHttpAuthUsernamePassword =
2898 handler.useHttpAuthUsernamePassword();
2899
2900 if (reuseHttpAuthUsernamePassword &&
2901 (mTabControl.getCurrentWebView() != null)) {
2902 String[] credentials =
2903 mTabControl.getCurrentWebView()
2904 .getHttpAuthUsernamePassword(host, realm);
2905 if (credentials != null && credentials.length == 2) {
2906 username = credentials[0];
2907 password = credentials[1];
2908 }
2909 }
2910
2911 if (username != null && password != null) {
2912 handler.proceed(username, password);
2913 } else {
2914 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2915 }
2916 }
2917
2918 @Override
2919 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2920 if (mMenuIsDown) {
2921 // only check shortcut key when MENU is held
2922 return getWindow().isShortcutKey(event.getKeyCode(), event);
2923 } else {
2924 return false;
2925 }
2926 }
2927
2928 @Override
2929 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2930 if (view != mTabControl.getCurrentTopWebView()) {
2931 return;
2932 }
2933 if (event.isDown()) {
2934 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2935 } else {
2936 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2937 }
2938 }
2939 };
2940
2941 //--------------------------------------------------------------------------
2942 // WebChromeClient implementation
2943 //--------------------------------------------------------------------------
2944
2945 /* package */ WebChromeClient getWebChromeClient() {
2946 return mWebChromeClient;
2947 }
2948
2949 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2950 // Helper method to create a new tab or sub window.
2951 private void createWindow(final boolean dialog, final Message msg) {
2952 if (dialog) {
2953 mTabControl.createSubWindow();
2954 final TabControl.Tab t = mTabControl.getCurrentTab();
2955 attachSubWindow(t);
2956 WebView.WebViewTransport transport =
2957 (WebView.WebViewTransport) msg.obj;
2958 transport.setWebView(t.getSubWebView());
2959 msg.sendToTarget();
2960 } else {
2961 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04002962 final TabControl.Tab newTab
2963 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07002964 if (newTab != parent) {
2965 parent.addChildTab(newTab);
2966 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002967 WebView.WebViewTransport transport =
2968 (WebView.WebViewTransport) msg.obj;
2969 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04002970 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002971 }
2972 }
2973
2974 @Override
2975 public boolean onCreateWindow(WebView view, final boolean dialog,
2976 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002977 // Short-circuit if we can't create any more tabs or sub windows.
2978 if (dialog && mTabControl.getCurrentSubWindow() != null) {
2979 new AlertDialog.Builder(BrowserActivity.this)
2980 .setTitle(R.string.too_many_subwindows_dialog_title)
2981 .setIcon(android.R.drawable.ic_dialog_alert)
2982 .setMessage(R.string.too_many_subwindows_dialog_message)
2983 .setPositiveButton(R.string.ok, null)
2984 .show();
2985 return false;
2986 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
2987 new AlertDialog.Builder(BrowserActivity.this)
2988 .setTitle(R.string.too_many_windows_dialog_title)
2989 .setIcon(android.R.drawable.ic_dialog_alert)
2990 .setMessage(R.string.too_many_windows_dialog_message)
2991 .setPositiveButton(R.string.ok, null)
2992 .show();
2993 return false;
2994 }
2995
2996 // Short-circuit if this was a user gesture.
2997 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002998 createWindow(dialog, resultMsg);
2999 return true;
3000 }
3001
3002 // Allow the popup and create the appropriate window.
3003 final AlertDialog.OnClickListener allowListener =
3004 new AlertDialog.OnClickListener() {
3005 public void onClick(DialogInterface d,
3006 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003007 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003008 }
3009 };
3010
3011 // Block the popup by returning a null WebView.
3012 final AlertDialog.OnClickListener blockListener =
3013 new AlertDialog.OnClickListener() {
3014 public void onClick(DialogInterface d, int which) {
3015 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003016 }
3017 };
3018
3019 // Build a confirmation dialog to display to the user.
3020 final AlertDialog d =
3021 new AlertDialog.Builder(BrowserActivity.this)
3022 .setTitle(R.string.attention)
3023 .setIcon(android.R.drawable.ic_dialog_alert)
3024 .setMessage(R.string.popup_window_attempt)
3025 .setPositiveButton(R.string.allow, allowListener)
3026 .setNegativeButton(R.string.block, blockListener)
3027 .setCancelable(false)
3028 .create();
3029
3030 // Show the confirmation dialog.
3031 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003032 return true;
3033 }
3034
3035 @Override
3036 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003037 final TabControl.Tab current = mTabControl.getCurrentTab();
3038 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003039 if (parent != null) {
3040 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003041 switchToTab(mTabControl.getTabIndex(parent));
3042 // Now we need to close the window
3043 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003044 }
3045 }
3046
3047 @Override
3048 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003049 mTitleBar.setProgress(newProgress);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003050 if (mFakeTitleBar != null) {
3051 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003052 }
3053
3054 if (newProgress == 100) {
3055 // onProgressChanged() is called for sub-frame too while
3056 // onPageFinished() is only called for the main frame. sync
3057 // cookie and cache promptly here.
3058 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003059 if (mInLoad) {
3060 mInLoad = false;
3061 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003062 // If the options menu is open, leave the title bar
3063 if (!mOptionsMenuOpen || !mIconView) {
3064 hideFakeTitleBar();
3065 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003066 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003067 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003068 // onPageFinished may have already been called but a subframe
3069 // is still loading and updating the progress. Reset mInLoad
3070 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003071 mInLoad = true;
3072 updateInLoadMenuItems();
3073 WebView currentWebView = mTabControl.getCurrentWebView();
3074 if ((currentWebView == null || currentWebView.getScrollY() != 0)
3075 && (!mOptionsMenuOpen || mIconView)) {
3076 // This page has begun to load, so show the title bar
3077 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003078 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003079 }
3080 }
3081
3082 @Override
3083 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003084 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003085
3086 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003087 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003088
3089 if (url == null ||
3090 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3091 return;
3092 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003093 // See if we can find the current url in our history database and
3094 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003095 if (url.startsWith("http://www.")) {
3096 url = url.substring(11);
3097 } else if (url.startsWith("http://")) {
3098 url = url.substring(4);
3099 }
3100 try {
3101 url = "%" + url;
3102 String [] selArgs = new String[] { url };
3103
3104 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3105 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3106 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3107 Browser.HISTORY_PROJECTION, where, selArgs, null);
3108 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003109 // Current implementation of database only has one entry per
3110 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003111 ContentValues map = new ContentValues();
3112 map.put(Browser.BookmarkColumns.TITLE, title);
3113 mResolver.update(Browser.BOOKMARKS_URI, map,
3114 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003115 }
3116 c.close();
3117 } catch (IllegalStateException e) {
3118 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3119 } catch (SQLiteException ex) {
3120 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3121 }
3122 }
3123
3124 @Override
3125 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003126 updateIcon(view, icon);
3127 }
3128
3129 @Override
3130 public void onReceivedTouchIconUrl(WebView view, String url) {
3131 final ContentResolver cr = getContentResolver();
3132 final Cursor c =
3133 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003134 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003135 if (c != null) {
3136 if (c.getCount() > 0) {
3137 new DownloadTouchIcon(cr, c, view).execute(url);
3138 } else {
3139 c.close();
3140 }
3141 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003142 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003143
Andrei Popescuadc008d2009-06-26 14:11:30 +01003144 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003145 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003146 if (mCustomView != null)
3147 return;
3148
3149 // Add the custom view to its container.
3150 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3151 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003152 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003153 // Save the menu state and set it to empty while the custom
3154 // view is showing.
3155 mOldMenuState = mMenuState;
3156 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003157 // Hide the content view.
3158 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003159 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003160 mCustomViewContainer.setVisibility(View.VISIBLE);
3161 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003162 }
3163
3164 @Override
3165 public void onHideCustomView() {
3166 if (mCustomView == null)
3167 return;
3168
Andrei Popescuc9b55562009-07-07 10:51:15 +01003169 // Hide the custom view.
3170 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003171 // Remove the custom view from its container.
3172 mCustomViewContainer.removeView(mCustomView);
3173 mCustomView = null;
3174 // Reset the old menu state.
3175 mMenuState = mOldMenuState;
3176 mOldMenuState = EMPTY_MENU;
3177 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003178 mCustomViewCallback.onCustomViewHidden();
3179 // Show the content view.
3180 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003181 }
3182
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003183 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003184 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003185 * @param url the URL that exceeded the quota
3186 * @param databaseIdentifier the identifier of the database on
3187 * which the transaction that caused the quota overflow was run
3188 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003189 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003190 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003191 * @param quotaUpdater The callback to run when a decision to allow or
3192 * deny quota has been made. Don't forget to call this!
3193 */
3194 @Override
3195 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003196 String databaseIdentifier, long currentQuota, long estimatedSize,
3197 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003198 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003199 url, databaseIdentifier, currentQuota, estimatedSize,
3200 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003201 }
3202
3203 /**
3204 * The Application Cache has exceeded its max size.
3205 * @param spaceNeeded is the amount of disk space that would be needed
3206 * in order for the last appcache operation to succeed.
3207 * @param totalUsedQuota is the sum of all origins' quota.
3208 * @param quotaUpdater A callback to inform the WebCore thread that a new
3209 * app cache size is available. This callback must always be executed at
3210 * some point to ensure that the sleeping WebCore thread is woken up.
3211 */
3212 @Override
3213 public void onReachedMaxAppCacheSize(long spaceNeeded,
3214 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3215 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3216 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003217 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003218
Steve Block2bc69912009-07-30 14:45:13 +01003219 /**
3220 * Instructs the browser to show a prompt to ask the user to set the
3221 * Geolocation permission state for the specified origin.
3222 * @param origin The origin for which Geolocation permissions are
3223 * requested.
3224 * @param callback The callback to call once the user has set the
3225 * Geolocation permission state.
3226 */
3227 @Override
3228 public void onGeolocationPermissionsShowPrompt(String origin,
3229 GeolocationPermissions.Callback callback) {
3230 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3231 origin, callback);
3232 }
3233
3234 /**
3235 * Instructs the browser to hide the Geolocation permissions prompt.
3236 */
3237 @Override
3238 public void onGeolocationPermissionsHidePrompt() {
3239 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3240 }
3241
Ben Murdoch7db26342009-06-03 18:21:19 +01003242 /* Adds a JavaScript error message to the system log.
3243 * @param message The error message to report.
3244 * @param lineNumber The line number of the error.
3245 * @param sourceID The name of the source file that caused the error.
3246 */
3247 @Override
3248 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003249 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3250 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3251 if (mShouldShowErrorConsole &&
3252 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3253 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3254 }
3255 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003256 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003257 };
3258
3259 /**
3260 * Notify the host application a download should be done, or that
3261 * the data should be streamed if a streaming viewer is available.
3262 * @param url The full url to the content that should be downloaded
3263 * @param contentDisposition Content-disposition http header, if
3264 * present.
3265 * @param mimetype The mimetype of the content reported by the server
3266 * @param contentLength The file size reported by the server
3267 */
3268 public void onDownloadStart(String url, String userAgent,
3269 String contentDisposition, String mimetype, long contentLength) {
3270 // if we're dealing wih A/V content that's not explicitly marked
3271 // for download, check if it's streamable.
3272 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003273 || !contentDisposition.regionMatches(
3274 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003275 // query the package manager to see if there's a registered handler
3276 // that matches.
3277 Intent intent = new Intent(Intent.ACTION_VIEW);
3278 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003279 ResolveInfo info = getPackageManager().resolveActivity(intent,
3280 PackageManager.MATCH_DEFAULT_ONLY);
3281 if (info != null) {
3282 ComponentName myName = getComponentName();
3283 // If we resolved to ourselves, we don't want to attempt to
3284 // load the url only to try and download it again.
3285 if (!myName.getPackageName().equals(
3286 info.activityInfo.packageName)
3287 || !myName.getClassName().equals(
3288 info.activityInfo.name)) {
3289 // someone (other than us) knows how to handle this mime
3290 // type with this scheme, don't download.
3291 try {
3292 startActivity(intent);
3293 return;
3294 } catch (ActivityNotFoundException ex) {
3295 if (LOGD_ENABLED) {
3296 Log.d(LOGTAG, "activity not found for " + mimetype
3297 + " over " + Uri.parse(url).getScheme(),
3298 ex);
3299 }
3300 // Best behavior is to fall back to a download in this
3301 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003302 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003303 }
3304 }
3305 }
3306 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3307 }
3308
3309 /**
3310 * Notify the host application a download should be done, even if there
3311 * is a streaming viewer available for thise type.
3312 * @param url The full url to the content that should be downloaded
3313 * @param contentDisposition Content-disposition http header, if
3314 * present.
3315 * @param mimetype The mimetype of the content reported by the server
3316 * @param contentLength The file size reported by the server
3317 */
3318 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3319 String contentDisposition, String mimetype, long contentLength) {
3320
3321 String filename = URLUtil.guessFileName(url,
3322 contentDisposition, mimetype);
3323
3324 // Check to see if we have an SDCard
3325 String status = Environment.getExternalStorageState();
3326 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3327 int title;
3328 String msg;
3329
3330 // Check to see if the SDCard is busy, same as the music app
3331 if (status.equals(Environment.MEDIA_SHARED)) {
3332 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3333 title = R.string.download_sdcard_busy_dlg_title;
3334 } else {
3335 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3336 title = R.string.download_no_sdcard_dlg_title;
3337 }
3338
3339 new AlertDialog.Builder(this)
3340 .setTitle(title)
3341 .setIcon(android.R.drawable.ic_dialog_alert)
3342 .setMessage(msg)
3343 .setPositiveButton(R.string.ok, null)
3344 .show();
3345 return;
3346 }
3347
3348 // java.net.URI is a lot stricter than KURL so we have to undo
3349 // KURL's percent-encoding and redo the encoding using java.net.URI.
3350 URI uri = null;
3351 try {
3352 // Undo the percent-encoding that KURL may have done.
3353 String newUrl = new String(URLUtil.decode(url.getBytes()));
3354 // Parse the url into pieces
3355 WebAddress w = new WebAddress(newUrl);
3356 String frag = null;
3357 String query = null;
3358 String path = w.mPath;
3359 // Break the path into path, query, and fragment
3360 if (path.length() > 0) {
3361 // Strip the fragment
3362 int idx = path.lastIndexOf('#');
3363 if (idx != -1) {
3364 frag = path.substring(idx + 1);
3365 path = path.substring(0, idx);
3366 }
3367 idx = path.lastIndexOf('?');
3368 if (idx != -1) {
3369 query = path.substring(idx + 1);
3370 path = path.substring(0, idx);
3371 }
3372 }
3373 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3374 query, frag);
3375 } catch (Exception e) {
3376 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3377 return;
3378 }
3379
3380 // XXX: Have to use the old url since the cookies were stored using the
3381 // old percent-encoded url.
3382 String cookies = CookieManager.getInstance().getCookie(url);
3383
3384 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003385 values.put(Downloads.COLUMN_URI, uri.toString());
3386 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3387 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3388 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003389 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003390 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003391 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003392 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3393 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3394 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3395 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003396 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003397 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003398 }
3399 if (mimetype == null) {
3400 // We must have long pressed on a link or image to download it. We
3401 // are not sure of the mimetype in this case, so do a head request
3402 new FetchUrlMimeType(this).execute(values);
3403 } else {
3404 final Uri contentUri =
3405 getContentResolver().insert(Downloads.CONTENT_URI, values);
3406 viewDownloads(contentUri);
3407 }
3408
3409 }
3410
3411 /**
3412 * Resets the lock icon. This method is called when we start a new load and
3413 * know the url to be loaded.
3414 */
3415 private void resetLockIcon(String url) {
3416 // Save the lock-icon state (we revert to it if the load gets cancelled)
3417 saveLockIcon();
3418
3419 mLockIconType = LOCK_ICON_UNSECURE;
3420 if (URLUtil.isHttpsUrl(url)) {
3421 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003422 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003423 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3424 " reset lock icon to " + mLockIconType);
3425 }
3426 }
3427
3428 updateLockIconImage(LOCK_ICON_UNSECURE);
3429 }
3430
3431 /**
3432 * Resets the lock icon. This method is called when the icon needs to be
3433 * reset but we do not know whether we are loading a secure or not secure
3434 * page.
3435 */
3436 private void resetLockIcon() {
3437 // Save the lock-icon state (we revert to it if the load gets cancelled)
3438 saveLockIcon();
3439
3440 mLockIconType = LOCK_ICON_UNSECURE;
3441
Dave Bort31a6d1c2009-04-13 15:56:49 -07003442 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003443 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3444 " reset lock icon to " + mLockIconType);
3445 }
3446
3447 updateLockIconImage(LOCK_ICON_UNSECURE);
3448 }
3449
3450 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003451 * Update the lock icon to correspond to our latest state.
3452 */
3453 /* package */ void updateLockIconToLatest() {
3454 updateLockIconImage(mLockIconType);
3455 }
3456
3457 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003458 * Updates the lock-icon image in the title-bar.
3459 */
3460 private void updateLockIconImage(int lockIconType) {
3461 Drawable d = null;
3462 if (lockIconType == LOCK_ICON_SECURE) {
3463 d = mSecLockIcon;
3464 } else if (lockIconType == LOCK_ICON_MIXED) {
3465 d = mMixLockIcon;
3466 }
Leon Scroggins68579392009-09-15 15:31:54 -04003467 mTitleBar.setLock(d);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003468 if (mFakeTitleBar != null) {
3469 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003470 }
3471 }
3472
3473 /**
3474 * Displays a page-info dialog.
3475 * @param tab The tab to show info about
3476 * @param fromShowSSLCertificateOnError The flag that indicates whether
3477 * this dialog was opened from the SSL-certificate-on-error dialog or
3478 * not. This is important, since we need to know whether to return to
3479 * the parent dialog or simply dismiss.
3480 */
3481 private void showPageInfo(final TabControl.Tab tab,
3482 final boolean fromShowSSLCertificateOnError) {
3483 final LayoutInflater factory = LayoutInflater
3484 .from(this);
3485
3486 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3487
3488 final WebView view = tab.getWebView();
3489
3490 String url = null;
3491 String title = null;
3492
3493 if (view == null) {
3494 url = tab.getUrl();
3495 title = tab.getTitle();
3496 } else if (view == mTabControl.getCurrentWebView()) {
3497 // Use the cached title and url if this is the current WebView
3498 url = mUrl;
3499 title = mTitle;
3500 } else {
3501 url = view.getUrl();
3502 title = view.getTitle();
3503 }
3504
3505 if (url == null) {
3506 url = "";
3507 }
3508 if (title == null) {
3509 title = "";
3510 }
3511
3512 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3513 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3514
3515 mPageInfoView = tab;
3516 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3517
3518 AlertDialog.Builder alertDialogBuilder =
3519 new AlertDialog.Builder(this)
3520 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3521 .setView(pageInfoView)
3522 .setPositiveButton(
3523 R.string.ok,
3524 new DialogInterface.OnClickListener() {
3525 public void onClick(DialogInterface dialog,
3526 int whichButton) {
3527 mPageInfoDialog = null;
3528 mPageInfoView = null;
3529 mPageInfoFromShowSSLCertificateOnError = null;
3530
3531 // if we came here from the SSL error dialog
3532 if (fromShowSSLCertificateOnError) {
3533 // go back to the SSL error dialog
3534 showSSLCertificateOnError(
3535 mSSLCertificateOnErrorView,
3536 mSSLCertificateOnErrorHandler,
3537 mSSLCertificateOnErrorError);
3538 }
3539 }
3540 })
3541 .setOnCancelListener(
3542 new DialogInterface.OnCancelListener() {
3543 public void onCancel(DialogInterface dialog) {
3544 mPageInfoDialog = null;
3545 mPageInfoView = null;
3546 mPageInfoFromShowSSLCertificateOnError = null;
3547
3548 // if we came here from the SSL error dialog
3549 if (fromShowSSLCertificateOnError) {
3550 // go back to the SSL error dialog
3551 showSSLCertificateOnError(
3552 mSSLCertificateOnErrorView,
3553 mSSLCertificateOnErrorHandler,
3554 mSSLCertificateOnErrorError);
3555 }
3556 }
3557 });
3558
3559 // if we have a main top-level page SSL certificate set or a certificate
3560 // error
3561 if (fromShowSSLCertificateOnError ||
3562 (view != null && view.getCertificate() != null)) {
3563 // add a 'View Certificate' button
3564 alertDialogBuilder.setNeutralButton(
3565 R.string.view_certificate,
3566 new DialogInterface.OnClickListener() {
3567 public void onClick(DialogInterface dialog,
3568 int whichButton) {
3569 mPageInfoDialog = null;
3570 mPageInfoView = null;
3571 mPageInfoFromShowSSLCertificateOnError = null;
3572
3573 // if we came here from the SSL error dialog
3574 if (fromShowSSLCertificateOnError) {
3575 // go back to the SSL error dialog
3576 showSSLCertificateOnError(
3577 mSSLCertificateOnErrorView,
3578 mSSLCertificateOnErrorHandler,
3579 mSSLCertificateOnErrorError);
3580 } else {
3581 // otherwise, display the top-most certificate from
3582 // the chain
3583 if (view.getCertificate() != null) {
3584 showSSLCertificate(tab);
3585 }
3586 }
3587 }
3588 });
3589 }
3590
3591 mPageInfoDialog = alertDialogBuilder.show();
3592 }
3593
3594 /**
3595 * Displays the main top-level page SSL certificate dialog
3596 * (accessible from the Page-Info dialog).
3597 * @param tab The tab to show certificate for.
3598 */
3599 private void showSSLCertificate(final TabControl.Tab tab) {
3600 final View certificateView =
3601 inflateCertificateView(tab.getWebView().getCertificate());
3602 if (certificateView == null) {
3603 return;
3604 }
3605
3606 LayoutInflater factory = LayoutInflater.from(this);
3607
3608 final LinearLayout placeholder =
3609 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3610
3611 LinearLayout ll = (LinearLayout) factory.inflate(
3612 R.layout.ssl_success, placeholder);
3613 ((TextView)ll.findViewById(R.id.success))
3614 .setText(R.string.ssl_certificate_is_valid);
3615
3616 mSSLCertificateView = tab;
3617 mSSLCertificateDialog =
3618 new AlertDialog.Builder(this)
3619 .setTitle(R.string.ssl_certificate).setIcon(
3620 R.drawable.ic_dialog_browser_certificate_secure)
3621 .setView(certificateView)
3622 .setPositiveButton(R.string.ok,
3623 new DialogInterface.OnClickListener() {
3624 public void onClick(DialogInterface dialog,
3625 int whichButton) {
3626 mSSLCertificateDialog = null;
3627 mSSLCertificateView = null;
3628
3629 showPageInfo(tab, false);
3630 }
3631 })
3632 .setOnCancelListener(
3633 new DialogInterface.OnCancelListener() {
3634 public void onCancel(DialogInterface dialog) {
3635 mSSLCertificateDialog = null;
3636 mSSLCertificateView = null;
3637
3638 showPageInfo(tab, false);
3639 }
3640 })
3641 .show();
3642 }
3643
3644 /**
3645 * Displays the SSL error certificate dialog.
3646 * @param view The target web-view.
3647 * @param handler The SSL error handler responsible for cancelling the
3648 * connection that resulted in an SSL error or proceeding per user request.
3649 * @param error The SSL error object.
3650 */
3651 private void showSSLCertificateOnError(
3652 final WebView view, final SslErrorHandler handler, final SslError error) {
3653
3654 final View certificateView =
3655 inflateCertificateView(error.getCertificate());
3656 if (certificateView == null) {
3657 return;
3658 }
3659
3660 LayoutInflater factory = LayoutInflater.from(this);
3661
3662 final LinearLayout placeholder =
3663 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3664
3665 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3666 LinearLayout ll = (LinearLayout)factory
3667 .inflate(R.layout.ssl_warning, placeholder);
3668 ((TextView)ll.findViewById(R.id.warning))
3669 .setText(R.string.ssl_untrusted);
3670 }
3671
3672 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3673 LinearLayout ll = (LinearLayout)factory
3674 .inflate(R.layout.ssl_warning, placeholder);
3675 ((TextView)ll.findViewById(R.id.warning))
3676 .setText(R.string.ssl_mismatch);
3677 }
3678
3679 if (error.hasError(SslError.SSL_EXPIRED)) {
3680 LinearLayout ll = (LinearLayout)factory
3681 .inflate(R.layout.ssl_warning, placeholder);
3682 ((TextView)ll.findViewById(R.id.warning))
3683 .setText(R.string.ssl_expired);
3684 }
3685
3686 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3687 LinearLayout ll = (LinearLayout)factory
3688 .inflate(R.layout.ssl_warning, placeholder);
3689 ((TextView)ll.findViewById(R.id.warning))
3690 .setText(R.string.ssl_not_yet_valid);
3691 }
3692
3693 mSSLCertificateOnErrorHandler = handler;
3694 mSSLCertificateOnErrorView = view;
3695 mSSLCertificateOnErrorError = error;
3696 mSSLCertificateOnErrorDialog =
3697 new AlertDialog.Builder(this)
3698 .setTitle(R.string.ssl_certificate).setIcon(
3699 R.drawable.ic_dialog_browser_certificate_partially_secure)
3700 .setView(certificateView)
3701 .setPositiveButton(R.string.ok,
3702 new DialogInterface.OnClickListener() {
3703 public void onClick(DialogInterface dialog,
3704 int whichButton) {
3705 mSSLCertificateOnErrorDialog = null;
3706 mSSLCertificateOnErrorView = null;
3707 mSSLCertificateOnErrorHandler = null;
3708 mSSLCertificateOnErrorError = null;
3709
3710 mWebViewClient.onReceivedSslError(
3711 view, handler, error);
3712 }
3713 })
3714 .setNeutralButton(R.string.page_info_view,
3715 new DialogInterface.OnClickListener() {
3716 public void onClick(DialogInterface dialog,
3717 int whichButton) {
3718 mSSLCertificateOnErrorDialog = null;
3719
3720 // do not clear the dialog state: we will
3721 // need to show the dialog again once the
3722 // user is done exploring the page-info details
3723
3724 showPageInfo(mTabControl.getTabFromView(view),
3725 true);
3726 }
3727 })
3728 .setOnCancelListener(
3729 new DialogInterface.OnCancelListener() {
3730 public void onCancel(DialogInterface dialog) {
3731 mSSLCertificateOnErrorDialog = null;
3732 mSSLCertificateOnErrorView = null;
3733 mSSLCertificateOnErrorHandler = null;
3734 mSSLCertificateOnErrorError = null;
3735
3736 mWebViewClient.onReceivedSslError(
3737 view, handler, error);
3738 }
3739 })
3740 .show();
3741 }
3742
3743 /**
3744 * Inflates the SSL certificate view (helper method).
3745 * @param certificate The SSL certificate.
3746 * @return The resultant certificate view with issued-to, issued-by,
3747 * issued-on, expires-on, and possibly other fields set.
3748 * If the input certificate is null, returns null.
3749 */
3750 private View inflateCertificateView(SslCertificate certificate) {
3751 if (certificate == null) {
3752 return null;
3753 }
3754
3755 LayoutInflater factory = LayoutInflater.from(this);
3756
3757 View certificateView = factory.inflate(
3758 R.layout.ssl_certificate, null);
3759
3760 // issued to:
3761 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3762 if (issuedTo != null) {
3763 ((TextView) certificateView.findViewById(R.id.to_common))
3764 .setText(issuedTo.getCName());
3765 ((TextView) certificateView.findViewById(R.id.to_org))
3766 .setText(issuedTo.getOName());
3767 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3768 .setText(issuedTo.getUName());
3769 }
3770
3771 // issued by:
3772 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3773 if (issuedBy != null) {
3774 ((TextView) certificateView.findViewById(R.id.by_common))
3775 .setText(issuedBy.getCName());
3776 ((TextView) certificateView.findViewById(R.id.by_org))
3777 .setText(issuedBy.getOName());
3778 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3779 .setText(issuedBy.getUName());
3780 }
3781
3782 // issued on:
3783 String issuedOn = reformatCertificateDate(
3784 certificate.getValidNotBefore());
3785 ((TextView) certificateView.findViewById(R.id.issued_on))
3786 .setText(issuedOn);
3787
3788 // expires on:
3789 String expiresOn = reformatCertificateDate(
3790 certificate.getValidNotAfter());
3791 ((TextView) certificateView.findViewById(R.id.expires_on))
3792 .setText(expiresOn);
3793
3794 return certificateView;
3795 }
3796
3797 /**
3798 * Re-formats the certificate date (Date.toString()) string to
3799 * a properly localized date string.
3800 * @return Properly localized version of the certificate date string and
3801 * the original certificate date string if fails to localize.
3802 * If the original string is null, returns an empty string "".
3803 */
3804 private String reformatCertificateDate(String certificateDate) {
3805 String reformattedDate = null;
3806
3807 if (certificateDate != null) {
3808 Date date = null;
3809 try {
3810 date = java.text.DateFormat.getInstance().parse(certificateDate);
3811 } catch (ParseException e) {
3812 date = null;
3813 }
3814
3815 if (date != null) {
3816 reformattedDate =
3817 DateFormat.getDateFormat(this).format(date);
3818 }
3819 }
3820
3821 return reformattedDate != null ? reformattedDate :
3822 (certificateDate != null ? certificateDate : "");
3823 }
3824
3825 /**
3826 * Displays an http-authentication dialog.
3827 */
3828 private void showHttpAuthentication(final HttpAuthHandler handler,
3829 final String host, final String realm, final String title,
3830 final String name, final String password, int focusId) {
3831 LayoutInflater factory = LayoutInflater.from(this);
3832 final View v = factory
3833 .inflate(R.layout.http_authentication, null);
3834 if (name != null) {
3835 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3836 }
3837 if (password != null) {
3838 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3839 }
3840
3841 String titleText = title;
3842 if (titleText == null) {
3843 titleText = getText(R.string.sign_in_to).toString().replace(
3844 "%s1", host).replace("%s2", realm);
3845 }
3846
3847 mHttpAuthHandler = handler;
3848 AlertDialog dialog = new AlertDialog.Builder(this)
3849 .setTitle(titleText)
3850 .setIcon(android.R.drawable.ic_dialog_alert)
3851 .setView(v)
3852 .setPositiveButton(R.string.action,
3853 new DialogInterface.OnClickListener() {
3854 public void onClick(DialogInterface dialog,
3855 int whichButton) {
3856 String nm = ((EditText) v
3857 .findViewById(R.id.username_edit))
3858 .getText().toString();
3859 String pw = ((EditText) v
3860 .findViewById(R.id.password_edit))
3861 .getText().toString();
3862 BrowserActivity.this.setHttpAuthUsernamePassword
3863 (host, realm, nm, pw);
3864 handler.proceed(nm, pw);
3865 mHttpAuthenticationDialog = null;
3866 mHttpAuthHandler = null;
3867 }})
3868 .setNegativeButton(R.string.cancel,
3869 new DialogInterface.OnClickListener() {
3870 public void onClick(DialogInterface dialog,
3871 int whichButton) {
3872 handler.cancel();
3873 BrowserActivity.this.resetTitleAndRevertLockIcon();
3874 mHttpAuthenticationDialog = null;
3875 mHttpAuthHandler = null;
3876 }})
3877 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3878 public void onCancel(DialogInterface dialog) {
3879 handler.cancel();
3880 BrowserActivity.this.resetTitleAndRevertLockIcon();
3881 mHttpAuthenticationDialog = null;
3882 mHttpAuthHandler = null;
3883 }})
3884 .create();
3885 // Make the IME appear when the dialog is displayed if applicable.
3886 dialog.getWindow().setSoftInputMode(
3887 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3888 dialog.show();
3889 if (focusId != 0) {
3890 dialog.findViewById(focusId).requestFocus();
3891 } else {
3892 v.findViewById(R.id.username_edit).requestFocus();
3893 }
3894 mHttpAuthenticationDialog = dialog;
3895 }
3896
3897 public int getProgress() {
3898 WebView w = mTabControl.getCurrentWebView();
3899 if (w != null) {
3900 return w.getProgress();
3901 } else {
3902 return 100;
3903 }
3904 }
3905
3906 /**
3907 * Set HTTP authentication password.
3908 *
3909 * @param host The host for the password
3910 * @param realm The realm for the password
3911 * @param username The username for the password. If it is null, it means
3912 * password can't be saved.
3913 * @param password The password
3914 */
3915 public void setHttpAuthUsernamePassword(String host, String realm,
3916 String username,
3917 String password) {
3918 WebView w = mTabControl.getCurrentWebView();
3919 if (w != null) {
3920 w.setHttpAuthUsernamePassword(host, realm, username, password);
3921 }
3922 }
3923
3924 /**
3925 * connectivity manager says net has come or gone... inform the user
3926 * @param up true if net has come up, false if net has gone down
3927 */
3928 public void onNetworkToggle(boolean up) {
3929 if (up == mIsNetworkUp) {
3930 return;
3931 } else if (up) {
3932 mIsNetworkUp = true;
3933 if (mAlertDialog != null) {
3934 mAlertDialog.cancel();
3935 mAlertDialog = null;
3936 }
3937 } else {
3938 mIsNetworkUp = false;
3939 if (mInLoad && mAlertDialog == null) {
3940 mAlertDialog = new AlertDialog.Builder(this)
3941 .setTitle(R.string.loadSuspendedTitle)
3942 .setMessage(R.string.loadSuspended)
3943 .setPositiveButton(R.string.ok, null)
3944 .show();
3945 }
3946 }
3947 WebView w = mTabControl.getCurrentWebView();
3948 if (w != null) {
3949 w.setNetworkAvailable(up);
3950 }
3951 }
3952
3953 @Override
3954 protected void onActivityResult(int requestCode, int resultCode,
3955 Intent intent) {
3956 switch (requestCode) {
3957 case COMBO_PAGE:
3958 if (resultCode == RESULT_OK && intent != null) {
3959 String data = intent.getAction();
3960 Bundle extras = intent.getExtras();
3961 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003962 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003963 } else {
3964 final TabControl.Tab currentTab =
3965 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003966 dismissSubWindow(currentTab);
3967 if (data != null && data.length() != 0) {
3968 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003969 }
3970 }
3971 }
3972 break;
3973 default:
3974 break;
3975 }
Leon Scroggins30444232009-09-04 18:36:20 -04003976 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003977 }
3978
3979 /*
3980 * This method is called as a result of the user selecting the options
3981 * menu to see the download window, or when a download changes state. It
3982 * shows the download window ontop of the current window.
3983 */
3984 /* package */ void viewDownloads(Uri downloadRecord) {
3985 Intent intent = new Intent(this,
3986 BrowserDownloadPage.class);
3987 intent.setData(downloadRecord);
3988 startActivityForResult(intent, this.DOWNLOAD_PAGE);
3989
3990 }
3991
Leon Scroggins160a7e72009-08-14 18:28:01 -04003992 /**
3993 * Open the Go page.
3994 * @param startWithHistory If true, open starting on the history tab.
3995 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003996 */
Leon Scroggins30444232009-09-04 18:36:20 -04003997 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003998 WebView current = mTabControl.getCurrentWebView();
3999 if (current == null) {
4000 return;
4001 }
4002 Intent intent = new Intent(this,
4003 CombinedBookmarkHistoryActivity.class);
4004 String title = current.getTitle();
4005 String url = current.getUrl();
4006 // Just in case the user opens bookmarks before a page finishes loading
4007 // so the current history item, and therefore the page, is null.
4008 if (null == url) {
4009 url = mLastEnteredUrl;
4010 // This can happen.
4011 if (null == url) {
4012 url = mSettings.getHomePage();
4013 }
4014 }
4015 // In case the web page has not yet received its associated title.
4016 if (title == null) {
4017 title = url;
4018 }
4019 intent.putExtra("title", title);
4020 intent.putExtra("url", url);
Leon Scroggins30444232009-09-04 18:36:20 -04004021 // Disable opening in a new window if we have maxed out the windows
4022 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4023 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004024 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004025 if (startWithHistory) {
4026 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4027 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4028 }
4029 startActivityForResult(intent, COMBO_PAGE);
4030 }
4031
4032 // Called when loading from context menu or LOAD_URL message
4033 private void loadURL(WebView view, String url) {
4034 // In case the user enters nothing.
4035 if (url != null && url.length() != 0 && view != null) {
4036 url = smartUrlFilter(url);
4037 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4038 view.loadUrl(url);
4039 }
4040 }
4041 }
4042
The Android Open Source Project0c908882009-03-03 19:32:16 -08004043 private String smartUrlFilter(Uri inUri) {
4044 if (inUri != null) {
4045 return smartUrlFilter(inUri.toString());
4046 }
4047 return null;
4048 }
4049
4050
4051 // get window count
4052
4053 int getWindowCount(){
4054 if(mTabControl != null){
4055 return mTabControl.getTabCount();
4056 }
4057 return 0;
4058 }
4059
Feng Qianb34f87a2009-03-24 21:27:26 -07004060 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004061 "(?i)" + // switch on case insensitive matching
4062 "(" + // begin group for schema
4063 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004064 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004065 ")" +
4066 "(.*)" );
4067
4068 /**
4069 * Attempts to determine whether user input is a URL or search
4070 * terms. Anything with a space is passed to search.
4071 *
4072 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4073 * "Http://" converts to "http://"
4074 *
4075 * @return Original or modified URL
4076 *
4077 */
4078 String smartUrlFilter(String url) {
4079
4080 String inUrl = url.trim();
4081 boolean hasSpace = inUrl.indexOf(' ') != -1;
4082
4083 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4084 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004085 // force scheme to lowercase
4086 String scheme = matcher.group(1);
4087 String lcScheme = scheme.toLowerCase();
4088 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004089 inUrl = lcScheme + matcher.group(2);
4090 }
4091 if (hasSpace) {
4092 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004093 }
4094 return inUrl;
4095 }
4096 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004097 // FIXME: Is this the correct place to add to searches?
4098 // what if someone else calls this function?
4099 int shortcut = parseUrlShortcut(inUrl);
4100 if (shortcut != SHORTCUT_INVALID) {
4101 Browser.addSearchUrl(mResolver, inUrl);
4102 String query = inUrl.substring(2);
4103 switch (shortcut) {
4104 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004105 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004106 case SHORTCUT_WIKIPEDIA_SEARCH:
4107 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4108 case SHORTCUT_DICTIONARY_SEARCH:
4109 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4110 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004111 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004112 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004113 }
4114 }
4115 } else {
4116 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4117 return URLUtil.guessUrl(inUrl);
4118 }
4119 }
4120
4121 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004122 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004123 }
4124
Ben Murdochbff2d602009-07-01 20:19:05 +01004125 /* package */ void setShouldShowErrorConsole(boolean flag) {
4126 if (flag == mShouldShowErrorConsole) {
4127 // Nothing to do.
4128 return;
4129 }
4130
4131 mShouldShowErrorConsole = flag;
4132
4133 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4134
4135 if (flag) {
4136 // Setting the show state of the console will cause it's the layout to be inflated.
4137 if (errorConsole.numberOfErrors() > 0) {
4138 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4139 } else {
4140 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4141 }
4142
4143 // Now we can add it to the main view.
4144 mErrorConsoleContainer.addView(errorConsole,
4145 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4146 ViewGroup.LayoutParams.WRAP_CONTENT));
4147 } else {
4148 mErrorConsoleContainer.removeView(errorConsole);
4149 }
4150
4151 }
4152
The Android Open Source Project0c908882009-03-03 19:32:16 -08004153 private final static int LOCK_ICON_UNSECURE = 0;
4154 private final static int LOCK_ICON_SECURE = 1;
4155 private final static int LOCK_ICON_MIXED = 2;
4156
4157 private int mLockIconType = LOCK_ICON_UNSECURE;
4158 private int mPrevLockType = LOCK_ICON_UNSECURE;
4159
4160 private BrowserSettings mSettings;
4161 private TabControl mTabControl;
4162 private ContentResolver mResolver;
4163 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004164 private View mCustomView;
4165 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004166 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004167
4168 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4169 // view, we should rewrite this.
4170 private int mCurrentMenuState = 0;
4171 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004172 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004173 private static final int EMPTY_MENU = -1;
4174 private Menu mMenu;
4175
4176 private FindDialog mFindDialog;
4177 // Used to prevent chording to result in firing two shortcuts immediately
4178 // one after another. Fixes bug 1211714.
4179 boolean mCanChord;
4180
4181 private boolean mInLoad;
4182 private boolean mIsNetworkUp;
4183
4184 private boolean mPageStarted;
4185 private boolean mActivityInPause = true;
4186
4187 private boolean mMenuIsDown;
4188
4189 private final KeyTracker mKeyTracker = new KeyTracker(this);
4190
4191 // As trackball doesn't send repeat down, we have to track it ourselves
4192 private boolean mTrackTrackball;
4193
4194 private static boolean mInTrace;
4195
4196 // Performance probe
4197 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4198 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4199 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4200 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4201 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4202 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4203 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4204 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4205 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4206 };
4207
4208 private long mStart;
4209 private long mProcessStart;
4210 private long mUserStart;
4211 private long mSystemStart;
4212 private long mIdleStart;
4213 private long mIrqStart;
4214
4215 private long mUiStart;
4216
4217 private Drawable mMixLockIcon;
4218 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004219
4220 /* hold a ref so we can auto-cancel if necessary */
4221 private AlertDialog mAlertDialog;
4222
4223 // Wait for credentials before loading google.com
4224 private ProgressDialog mCredsDlg;
4225
4226 // The up-to-date URL and title (these can be different from those stored
4227 // in WebView, since it takes some time for the information in WebView to
4228 // get updated)
4229 private String mUrl;
4230 private String mTitle;
4231
4232 // As PageInfo has different style for landscape / portrait, we have
4233 // to re-open it when configuration changed
4234 private AlertDialog mPageInfoDialog;
4235 private TabControl.Tab mPageInfoView;
4236 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4237 // dialog, we should not just dismiss it, but should get back to the
4238 // SSL-certificate-on-error dialog. This flag is used to store this state
4239 private Boolean mPageInfoFromShowSSLCertificateOnError;
4240
4241 // as SSLCertificateOnError has different style for landscape / portrait,
4242 // we have to re-open it when configuration changed
4243 private AlertDialog mSSLCertificateOnErrorDialog;
4244 private WebView mSSLCertificateOnErrorView;
4245 private SslErrorHandler mSSLCertificateOnErrorHandler;
4246 private SslError mSSLCertificateOnErrorError;
4247
4248 // as SSLCertificate has different style for landscape / portrait, we
4249 // have to re-open it when configuration changed
4250 private AlertDialog mSSLCertificateDialog;
4251 private TabControl.Tab mSSLCertificateView;
4252
4253 // as HttpAuthentication has different style for landscape / portrait, we
4254 // have to re-open it when configuration changed
4255 private AlertDialog mHttpAuthenticationDialog;
4256 private HttpAuthHandler mHttpAuthHandler;
4257
4258 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4259 new FrameLayout.LayoutParams(
4260 ViewGroup.LayoutParams.FILL_PARENT,
4261 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004262 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4263 new FrameLayout.LayoutParams(
4264 ViewGroup.LayoutParams.FILL_PARENT,
4265 ViewGroup.LayoutParams.FILL_PARENT,
4266 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004267 // Google search
4268 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004269 // Wikipedia search
4270 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4271 // Dictionary search
4272 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4273 // Google Mobile Local search
4274 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4275
4276 final static String QUERY_PLACE_HOLDER = "%s";
4277
4278 // "source" parameter for Google search through search key
4279 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4280 // "source" parameter for Google search through goto menu
4281 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4282 // "source" parameter for Google search through simplily type
4283 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4284 // "source" parameter for Google search suggested by the browser
4285 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4286 // "source" parameter for Google search from unknown source
4287 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4288
4289 private final static String LOGTAG = "browser";
4290
The Android Open Source Project0c908882009-03-03 19:32:16 -08004291 private String mLastEnteredUrl;
4292
4293 private PowerManager.WakeLock mWakeLock;
4294 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4295
4296 private Toast mStopToast;
4297
Leon Scroggins68579392009-09-15 15:31:54 -04004298 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004299
Ben Murdochbff2d602009-07-01 20:19:05 +01004300 private LinearLayout mErrorConsoleContainer = null;
4301 private boolean mShouldShowErrorConsole = false;
4302
The Android Open Source Project0c908882009-03-03 19:32:16 -08004303 // As the ids are dynamically created, we can't guarantee that they will
4304 // be in sequence, so this static array maps ids to a window number.
4305 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4306 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4307 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4308 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4309
4310 // monitor platform changes
4311 private IntentFilter mNetworkStateChangedFilter;
4312 private BroadcastReceiver mNetworkStateIntentReceiver;
4313
Grace Klobab4da0ad2009-05-14 14:45:40 -07004314 private BroadcastReceiver mPackageInstallationReceiver;
4315
The Android Open Source Project0c908882009-03-03 19:32:16 -08004316 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004317 final static int COMBO_PAGE = 1;
4318 final static int DOWNLOAD_PAGE = 2;
4319 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004320
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004321 /**
4322 * A UrlData class to abstract how the content will be set to WebView.
4323 * This base class uses loadUrl to show the content.
4324 */
4325 private static class UrlData {
4326 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004327 byte[] mPostData;
4328
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004329 UrlData(String url) {
4330 this.mUrl = url;
4331 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004332
4333 void setPostData(byte[] postData) {
4334 mPostData = postData;
4335 }
4336
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004337 boolean isEmpty() {
4338 return mUrl == null || mUrl.length() == 0;
4339 }
4340
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004341 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004342 if (mPostData != null) {
4343 webView.postUrl(mUrl, mPostData);
4344 } else {
4345 webView.loadUrl(mUrl);
4346 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004347 }
4348 };
4349
4350 /**
4351 * A subclass of UrlData class that can display inlined content using
4352 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4353 */
4354 private static class InlinedUrlData extends UrlData {
4355 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4356 super(failUrl);
4357 mInlined = inlined;
4358 mMimeType = mimeType;
4359 mEncoding = encoding;
4360 }
4361 String mMimeType;
4362 String mInlined;
4363 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004364 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004365 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004366 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004367 }
4368
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004369 @Override
4370 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004371 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4372 }
4373 }
4374
Leon Scroggins1f005d32009-08-10 17:36:42 -04004375 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004376}