blob: 68fd8b8b4d32f24cbd3cbe696bd0c63f95e31ced [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;
The Android Open Source Project0c908882009-03-03 19:32:16 -080041import android.content.res.Configuration;
42import android.content.res.Resources;
43import android.database.Cursor;
44import android.database.sqlite.SQLiteDatabase;
45import android.database.sqlite.SQLiteException;
46import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010047import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040050import android.graphics.PixelFormat;
51import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080052import android.graphics.drawable.Drawable;
Christian Mehlmauerfdf5c2d2010-05-25 19:52:28 +020053import android.hardware.Sensor;
54import android.hardware.SensorEvent;
55import android.hardware.SensorEventListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080056import android.hardware.SensorManager;
57import android.net.ConnectivityManager;
58import android.net.Uri;
59import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080060import android.net.http.SslCertificate;
61import android.net.http.SslError;
62import android.os.AsyncTask;
63import android.os.Bundle;
64import android.os.Debug;
65import android.os.Environment;
66import android.os.Handler;
67import android.os.IBinder;
68import android.os.Message;
69import android.os.PowerManager;
70import android.os.Process;
71import android.os.RemoteException;
72import android.os.ServiceManager;
73import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080074import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040075import android.provider.ContactsContract;
76import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080077import android.provider.Downloads;
78import android.provider.MediaStore;
The Android Open Source Project0c908882009-03-03 19:32:16 -080079import android.text.IClipboard;
80import android.text.TextUtils;
81import android.text.format.DateFormat;
82import android.text.util.Regex;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040083import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080084import android.util.Log;
85import android.view.ContextMenu;
86import android.view.Gravity;
87import android.view.KeyEvent;
88import android.view.LayoutInflater;
89import android.view.Menu;
90import android.view.MenuInflater;
91import android.view.MenuItem;
92import android.view.View;
93import android.view.ViewGroup;
94import android.view.Window;
95import android.view.WindowManager;
96import android.view.ContextMenu.ContextMenuInfo;
97import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080098import android.webkit.CookieManager;
99import android.webkit.CookieSyncManager;
100import android.webkit.DownloadListener;
Steve Block2bc69912009-07-30 14:45:13 +0100101import android.webkit.GeolocationPermissions;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800102import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -0700103import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800104import android.webkit.SslErrorHandler;
105import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +0100106import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800107import android.webkit.WebChromeClient;
108import android.webkit.WebHistoryItem;
109import android.webkit.WebIconDatabase;
Ben Murdoch092dd5d2009-04-22 12:34:12 +0100110import android.webkit.WebStorage;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800111import android.webkit.WebView;
112import android.webkit.WebViewClient;
113import android.widget.EditText;
114import android.widget.FrameLayout;
115import android.widget.LinearLayout;
116import android.widget.TextView;
117import android.widget.Toast;
118
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400119import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.io.File;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.net.MalformedURLException;
122import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700123import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800124import java.net.URL;
125import java.net.URLEncoder;
126import java.text.ParseException;
127import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128import java.util.HashMap;
Patrick Scott37911c72009-03-24 18:02:58 -0700129import java.util.LinkedList;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130import java.util.regex.Matcher;
131import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800132
133public class BrowserActivity extends Activity
Grace Kloba5942df02009-09-18 11:48:29 -0700134 implements View.OnCreateContextMenuListener,
The Android Open Source Project0c908882009-03-03 19:32:16 -0800135 DownloadListener {
136
Dave Bort31a6d1c2009-04-13 15:56:49 -0700137 /* Define some aliases to make these debugging flags easier to refer to.
138 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
139 */
140 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
141 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
142 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
143
The Android Open Source Project0c908882009-03-03 19:32:16 -0800144 private IGoogleLoginService mGls = null;
145 private ServiceConnection mGlsConnection = null;
146
147 private SensorManager mSensorManager = null;
148
Satish Sampath565505b2009-05-29 15:37:27 +0100149 // These are single-character shortcuts for searching popular sources.
150 private static final int SHORTCUT_INVALID = 0;
151 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
152 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
153 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
154 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
155
The Android Open Source Project0c908882009-03-03 19:32:16 -0800156 /* Whitelisted webpages
157 private static HashSet<String> sWhiteList;
158
159 static {
160 sWhiteList = new HashSet<String>();
161 sWhiteList.add("cnn.com/");
162 sWhiteList.add("espn.go.com/");
163 sWhiteList.add("nytimes.com/");
164 sWhiteList.add("engadget.com/");
165 sWhiteList.add("yahoo.com/");
166 sWhiteList.add("msn.com/");
167 sWhiteList.add("amazon.com/");
168 sWhiteList.add("consumerist.com/");
169 sWhiteList.add("google.com/m/news");
170 }
171 */
172
173 private void setupHomePage() {
174 final Runnable getAccount = new Runnable() {
175 public void run() {
176 // Lower priority
177 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
178 // get the default home page
179 String homepage = mSettings.getHomePage();
180
181 try {
182 if (mGls == null) return;
183
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700184 if (!homepage.startsWith("http://www.google.")) return;
185 if (homepage.indexOf('?') == -1) return;
186
The Android Open Source Project0c908882009-03-03 19:32:16 -0800187 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
188 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
189
190 // three cases:
191 //
192 // hostedUser == googleUser
193 // The device has only a google account
194 //
195 // hostedUser != googleUser
196 // The device has a hosted account and a google account
197 //
198 // hostedUser != null, googleUser == null
199 // The device has only a hosted account (so far)
200
201 // developers might have no accounts at all
202 if (hostedUser == null) return;
203
204 if (googleUser == null || !hostedUser.equals(googleUser)) {
205 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700206 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800207 }
208 } catch (RemoteException ignore) {
209 // Login service died; carry on
210 } catch (RuntimeException ignore) {
211 // Login service died; carry on
212 } finally {
213 finish(homepage);
214 }
215 }
216
217 private void finish(final String homepage) {
218 mHandler.post(new Runnable() {
219 public void run() {
220 mSettings.setHomePage(BrowserActivity.this, homepage);
221 resumeAfterCredentials();
222
223 // as this is running in a separate thread,
224 // BrowserActivity's onDestroy() may have been called,
225 // which also calls unbindService().
226 if (mGlsConnection != null) {
227 // we no longer need to keep GLS open
228 unbindService(mGlsConnection);
229 mGlsConnection = null;
230 }
231 } });
232 } };
233
234 final boolean[] done = { false };
235
236 // Open a connection to the Google Login Service. The first
237 // time the connection is established, set up the homepage depending on
238 // the account in a background thread.
239 mGlsConnection = new ServiceConnection() {
240 public void onServiceConnected(ComponentName className, IBinder service) {
241 mGls = IGoogleLoginService.Stub.asInterface(service);
242 if (done[0] == false) {
243 done[0] = true;
244 Thread account = new Thread(getAccount);
245 account.setName("GLSAccount");
246 account.start();
247 }
248 }
249 public void onServiceDisconnected(ComponentName className) {
250 mGls = null;
251 }
252 };
253
254 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
255 mGlsConnection, Context.BIND_AUTO_CREATE);
256 }
257
Cary Clarka9771242009-08-11 16:42:26 -0400258 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800259 @Override
260 public Void doInBackground(File... files) {
261 if (files != null) {
262 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400263 if (!f.delete()) {
264 Log.e(LOGTAG, f.getPath() + " was not deleted");
265 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800266 }
267 }
268 return null;
269 }
270 }
271
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400272 /**
273 * This layout holds everything you see below the status bar, including the
274 * error console, the custom view container, and the webviews.
275 */
276 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400277
The Android Open Source Project0c908882009-03-03 19:32:16 -0800278 @Override public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700279 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800280 Log.v(LOGTAG, this + " onStart");
281 }
282 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800283 // test the browser in OpenGL
284 // requestWindowFeature(Window.FEATURE_OPENGL);
285
286 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
287
288 mResolver = getContentResolver();
289
Grace Kloba0923d692009-09-23 21:37:25 -0700290 // If this was a web search request, pass it on to the default web
291 // search provider and finish this activity.
292 if (handleWebSearchIntent(getIntent())) {
293 finish();
294 return;
295 }
296
The Android Open Source Project0c908882009-03-03 19:32:16 -0800297 //
298 // start MASF proxy service
299 //
300 //Intent proxyServiceIntent = new Intent();
301 //proxyServiceIntent.setComponent
302 // (new ComponentName(
303 // "com.android.masfproxyservice",
304 // "com.android.masfproxyservice.MasfProxyService"));
305 //startService(proxyServiceIntent, null);
306
307 mSecLockIcon = Resources.getSystem().getDrawable(
308 android.R.drawable.ic_secure);
309 mMixLockIcon = Resources.getSystem().getDrawable(
310 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800311
Leon Scroggins81db3662009-06-04 17:45:11 -0400312 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
313 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400314 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
315 .inflate(R.layout.custom_screen, null);
316 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
317 R.id.main_content);
318 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
319 .findViewById(R.id.error_console);
320 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
321 .findViewById(R.id.fullscreen_custom_content);
322 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400323 mTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800324
325 // Create the tab control and our initial tab
326 mTabControl = new TabControl(this);
327
328 // Open the icon database and retain all the bookmark urls for favicons
329 retainIconsOnStartup();
330
331 // Keep a settings instance handy.
332 mSettings = BrowserSettings.getInstance();
333 mSettings.setTabControl(mTabControl);
334 mSettings.loadFromDb(this);
335
336 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
337 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
338
Grace Klobaa34f6862009-07-31 16:28:17 -0700339 /* enables registration for changes in network status from
340 http stack */
341 mNetworkStateChangedFilter = new IntentFilter();
342 mNetworkStateChangedFilter.addAction(
343 ConnectivityManager.CONNECTIVITY_ACTION);
344 mNetworkStateIntentReceiver = new BroadcastReceiver() {
345 @Override
346 public void onReceive(Context context, Intent intent) {
347 if (intent.getAction().equals(
348 ConnectivityManager.CONNECTIVITY_ACTION)) {
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700349 boolean noConnectivity = intent.getBooleanExtra(
350 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
351 onNetworkToggle(!noConnectivity);
Grace Klobaa34f6862009-07-31 16:28:17 -0700352 }
353 }
354 };
355
Grace Kloba615c6c92009-08-03 10:22:44 -0700356 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
357 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
358 filter.addDataScheme("package");
359 mPackageInstallationReceiver = new BroadcastReceiver() {
360 @Override
361 public void onReceive(Context context, Intent intent) {
362 final String action = intent.getAction();
363 final String packageName = intent.getData()
364 .getSchemeSpecificPart();
365 final boolean replacing = intent.getBooleanExtra(
366 Intent.EXTRA_REPLACING, false);
367 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
368 // if it is replacing, refreshPlugins() when adding
369 return;
370 }
371 PackageManager pm = BrowserActivity.this.getPackageManager();
372 PackageInfo pkgInfo = null;
373 try {
374 pkgInfo = pm.getPackageInfo(packageName,
375 PackageManager.GET_PERMISSIONS);
376 } catch (PackageManager.NameNotFoundException e) {
377 return;
378 }
379 if (pkgInfo != null) {
380 String permissions[] = pkgInfo.requestedPermissions;
381 if (permissions == null) {
382 return;
383 }
384 boolean permissionOk = false;
385 for (String permit : permissions) {
386 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
387 permissionOk = true;
388 break;
389 }
390 }
391 if (permissionOk) {
392 PluginManager.getInstance(BrowserActivity.this)
393 .refreshPlugins(
394 Intent.ACTION_PACKAGE_ADDED
395 .equals(action));
396 }
397 }
398 }
399 };
400 registerReceiver(mPackageInstallationReceiver, filter);
401
The Android Open Source Project0c908882009-03-03 19:32:16 -0800402 if (!mTabControl.restoreState(icicle)) {
403 // clear up the thumbnail directory if we can't restore the state as
404 // none of the files in the directory are referenced any more.
405 new ClearThumbnails().execute(
406 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700407 // there is no quit on Android. But if we can't restore the state,
408 // we can treat it as a new Browser, remove the old session cookies.
409 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800410 final Intent intent = getIntent();
411 final Bundle extra = intent.getExtras();
412 // Create an initial tab.
413 // If the intent is ACTION_VIEW and data is not null, the Browser is
414 // invoked to view the content by another application. In this case,
415 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700416 UrlData urlData = getUrlDataFromIntent(intent);
417
The Android Open Source Project0c908882009-03-03 19:32:16 -0800418 final TabControl.Tab t = mTabControl.createNewTab(
419 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700420 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700421 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800422 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800423 attachTabToContentView(t);
424 WebView webView = t.getWebView();
425 if (extra != null) {
426 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
427 if (scale > 0 && scale <= 1000) {
428 webView.setInitialScale(scale);
429 }
430 }
431 // If we are not restoring from an icicle, then there is a high
432 // likely hood this is the first run. So, check to see if the
433 // homepage needs to be configured and copy any plugins from our
434 // asset directory to the data partition.
435 if ((extra == null || !extra.getBoolean("testing"))
436 && !mSettings.isLoginInitialized()) {
437 setupHomePage();
438 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800439
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700440 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400441 if (mSettings.isLoginInitialized()) {
442 webView.loadUrl(mSettings.getHomePage());
443 } else {
444 waitForCredentials();
445 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800446 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700447 if (extra != null) {
448 urlData.setPostData(extra
449 .getByteArray(Browser.EXTRA_POST_DATA));
450 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700451 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800452 }
453 } else {
454 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400455 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800456 attachTabToContentView(mTabControl.getCurrentTab());
457 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700458
Feng Qianb3c02da2009-06-29 15:58:08 -0700459 // Read JavaScript flags if it exists.
460 String jsFlags = mSettings.getJsFlags();
461 if (jsFlags.trim().length() != 0) {
462 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
463 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800464 }
465
466 @Override
467 protected void onNewIntent(Intent intent) {
468 TabControl.Tab current = mTabControl.getCurrentTab();
469 // When a tab is closed on exit, the current tab index is set to -1.
470 // Reset before proceed as Browser requires the current tab to be set.
471 if (current == null) {
472 // Try to reset the tab in case the index was incorrect.
473 current = mTabControl.getTab(0);
474 if (current == null) {
475 // No tabs at all so just ignore this intent.
476 return;
477 }
478 mTabControl.setCurrentTab(current);
479 attachTabToContentView(current);
480 resetTitleAndIcon(current.getWebView());
481 }
482 final String action = intent.getAction();
483 final int flags = intent.getFlags();
484 if (Intent.ACTION_MAIN.equals(action) ||
485 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
486 // just resume the browser
487 return;
488 }
489 if (Intent.ACTION_VIEW.equals(action)
490 || Intent.ACTION_SEARCH.equals(action)
491 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
492 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100493 // If this was a search request (e.g. search query directly typed into the address bar),
494 // pass it on to the default web search provider.
495 if (handleWebSearchIntent(intent)) {
496 return;
497 }
498
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700499 UrlData urlData = getUrlDataFromIntent(intent);
500 if (urlData.isEmpty()) {
501 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800502 }
Grace Kloba81678d92009-06-30 07:09:56 -0700503 urlData.setPostData(intent
504 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700505
Grace Klobacc634032009-07-28 15:58:19 -0700506 final String appId = intent
507 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
508 if (Intent.ACTION_VIEW.equals(action)
509 && !getPackageName().equals(appId)
510 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Patrick Scottcd115892009-07-16 09:42:58 -0400511 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700512 if (appTab != null) {
513 Log.i(LOGTAG, "Reusing tab for " + appId);
514 // Dismiss the subwindow if applicable.
515 dismissSubWindow(appTab);
516 // Since we might kill the WebView, remove it from the
517 // content view first.
518 removeTabFromContentView(appTab);
519 // Recreate the main WebView after destroying the old one.
520 // If the WebView has the same original url and is on that
521 // page, it can be reused.
522 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700523 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100524
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700525 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400526 switchToTab(mTabControl.getTabIndex(appTab));
527 if (needsLoad) {
528 urlData.loadIn(appTab.getWebView());
529 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700530 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400531 // If the tab was the current tab, we have to attach
532 // it to the view system again.
533 attachTabToContentView(appTab);
534 if (needsLoad) {
535 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700536 }
537 }
538 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400539 } else {
540 // No matching application tab, try to find a regular tab
541 // with a matching url.
542 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400543 if (appTab != null) {
544 if (current != appTab) {
545 switchToTab(mTabControl.getTabIndex(appTab));
546 }
547 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400548 } else {
549 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
550 // will be opened in a new tab unless we have reached
551 // MAX_TABS. Then the url will be opened in the current
552 // tab. If a new tab is created, it will have "true" for
553 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400554 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400555 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700556 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800557 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700558 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800559 mSettings.toggleDebugSettings();
560 return;
561 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400562 // Get rid of the subwindow if it exists
563 dismissSubWindow(current);
564 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800565 }
566 }
567 }
568
Satish Sampath565505b2009-05-29 15:37:27 +0100569 private int parseUrlShortcut(String url) {
570 if (url == null) return SHORTCUT_INVALID;
571
572 // FIXME: quick search, need to be customized by setting
573 if (url.length() > 2 && url.charAt(1) == ' ') {
574 switch (url.charAt(0)) {
575 case 'g': return SHORTCUT_GOOGLE_SEARCH;
576 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
577 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
578 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
579 }
580 }
581 return SHORTCUT_INVALID;
582 }
583
584 /**
585 * Launches the default web search activity with the query parameters if the given intent's data
586 * are identified as plain search terms and not URLs/shortcuts.
587 * @return true if the intent was handled and web search activity was launched, false if not.
588 */
589 private boolean handleWebSearchIntent(Intent intent) {
590 if (intent == null) return false;
591
592 String url = null;
593 final String action = intent.getAction();
594 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700595 Uri data = intent.getData();
596 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100597 } else if (Intent.ACTION_SEARCH.equals(action)
598 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
599 || Intent.ACTION_WEB_SEARCH.equals(action)) {
600 url = intent.getStringExtra(SearchManager.QUERY);
601 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100602 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
603 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100604 }
605
606 /**
607 * Launches the default web search activity with the query parameters if the given url string
608 * was identified as plain search terms and not URL/shortcut.
609 * @return true if the request was handled and web search activity was launched, false if not.
610 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100611 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100612 if (inUrl == null) return false;
613
614 // In general, we shouldn't modify URL from Intent.
615 // But currently, we get the user-typed URL from search box as well.
616 String url = fixUrl(inUrl).trim();
617
618 // URLs and site specific search shortcuts are handled by the regular flow of control, so
619 // return early.
620 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100621 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100622 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
623 return false;
624 }
625
626 Browser.updateVisitedHistory(mResolver, url, false);
627 Browser.addSearchUrl(mResolver, url);
628
629 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
630 intent.addCategory(Intent.CATEGORY_DEFAULT);
631 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100632 if (appData != null) {
633 intent.putExtra(SearchManager.APP_DATA, appData);
634 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100635 if (extraData != null) {
636 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
637 }
Grace Klobacc634032009-07-28 15:58:19 -0700638 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100639 startActivity(intent);
640
641 return true;
642 }
643
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700644 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800645 String url = null;
646 if (intent != null) {
647 final String action = intent.getAction();
648 if (Intent.ACTION_VIEW.equals(action)) {
649 url = smartUrlFilter(intent.getData());
650 if (url != null && url.startsWith("content:")) {
651 /* Append mimetype so webview knows how to display */
652 String mimeType = intent.resolveType(getContentResolver());
653 if (mimeType != null) {
654 url += "?" + mimeType;
655 }
656 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700657 if ("inline:".equals(url)) {
658 return new InlinedUrlData(
659 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
660 intent.getType(),
661 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
662 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
663 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800664 } else if (Intent.ACTION_SEARCH.equals(action)
665 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
666 || Intent.ACTION_WEB_SEARCH.equals(action)) {
667 url = intent.getStringExtra(SearchManager.QUERY);
668 if (url != null) {
669 mLastEnteredUrl = url;
670 // Don't add Urls, just search terms.
671 // Urls will get added when the page is loaded.
672 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
673 Browser.updateVisitedHistory(mResolver, url, false);
674 }
675 // In general, we shouldn't modify URL from Intent.
676 // But currently, we get the user-typed URL from search box as well.
677 url = fixUrl(url);
678 url = smartUrlFilter(url);
679 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
680 if (url.contains(searchSource)) {
681 String source = null;
682 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
683 if (appData != null) {
684 source = appData.getString(SearchManager.SOURCE);
685 }
686 if (TextUtils.isEmpty(source)) {
687 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
688 }
689 url = url.replace(searchSource, "&source=android-"+source+"&");
690 }
691 }
692 }
693 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700694 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800695 }
696
697 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400698 // FIXME: Converting the url to lower case
699 // duplicates functionality in smartUrlFilter().
700 // However, changing all current callers of fixUrl to
701 // call smartUrlFilter in addition may have unwanted
702 // consequences, and is deferred for now.
703 int colon = inUrl.indexOf(':');
704 boolean allLower = true;
705 for (int index = 0; index < colon; index++) {
706 char ch = inUrl.charAt(index);
707 if (!Character.isLetter(ch)) {
708 break;
709 }
710 allLower &= Character.isLowerCase(ch);
711 if (index == colon - 1 && !allLower) {
712 inUrl = inUrl.substring(0, colon).toLowerCase()
713 + inUrl.substring(colon);
714 }
715 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800716 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
717 return inUrl;
718 if (inUrl.startsWith("http:") ||
719 inUrl.startsWith("https:")) {
720 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
721 inUrl = inUrl.replaceFirst("/", "//");
722 } else inUrl = inUrl.replaceFirst(":", "://");
723 }
724 return inUrl;
725 }
726
727 /**
728 * Looking for the pattern like this
729 *
730 * *
731 * * *
732 * *** * *******
733 * * *
734 * * *
735 * *
736 */
Christian Mehlmauerfdf5c2d2010-05-25 19:52:28 +0200737 private final SensorEventListener mSensorEventListener = new SensorEventListener() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800738 private long mLastGestureTime;
739 private float[] mPrev = new float[3];
740 private float[] mPrevDiff = new float[3];
741 private float[] mDiff = new float[3];
742 private float[] mRevertDiff = new float[3];
743
Christian Mehlmauerfdf5c2d2010-05-25 19:52:28 +0200744 public void onSensorChanged(SensorEvent event) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800745 boolean show = false;
746 float[] diff = new float[3];
747
748 for (int i = 0; i < 3; i++) {
Christian Mehlmauerfdf5c2d2010-05-25 19:52:28 +0200749 diff[i] = event.values[i] - mPrev[i];
The Android Open Source Project0c908882009-03-03 19:32:16 -0800750 if (Math.abs(diff[i]) > 1) {
751 show = true;
752 }
753 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
754 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
755 // start track when there is a big move, or revert
756 mRevertDiff[i] = mDiff[i];
757 mDiff[i] = 0;
758 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
759 // reset when it is flat
760 mDiff[i] = mRevertDiff[i] = 0;
761 }
762 mDiff[i] += diff[i];
763 mPrevDiff[i] = diff[i];
Christian Mehlmauerfdf5c2d2010-05-25 19:52:28 +0200764 mPrev[i] = event.values[i];
The Android Open Source Project0c908882009-03-03 19:32:16 -0800765 }
766
767 if (false) {
768 // only shows if we think the delta is big enough, in an attempt
769 // to detect "serious" moves left/right or up/down
Christian Mehlmauerfdf5c2d2010-05-25 19:52:28 +0200770 Log.d("BrowserSensorHack", "sensorChanged " + event.sensor.getName() + " ("
771 + event.values[0] + ", " + event.values[1] + ", " + event.values[2] + ")"
The Android Open Source Project0c908882009-03-03 19:32:16 -0800772 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
773 + ")");
774 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
775 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
776 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
777 + mRevertDiff[2] + ")");
778 }
779
780 long now = android.os.SystemClock.uptimeMillis();
781 if (now - mLastGestureTime > 1000) {
782 mLastGestureTime = 0;
783
784 float y = mDiff[1];
785 float z = mDiff[2];
786 float ay = Math.abs(y);
787 float az = Math.abs(z);
788 float ry = mRevertDiff[1];
789 float rz = mRevertDiff[2];
790 float ary = Math.abs(ry);
791 float arz = Math.abs(rz);
792 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
793 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
794
795 if ((gestY || gestZ) && !(gestY && gestZ)) {
796 WebView view = mTabControl.getCurrentWebView();
797
798 if (view != null) {
799 if (gestZ) {
800 if (z < 0) {
801 view.zoomOut();
802 } else {
803 view.zoomIn();
804 }
805 } else {
806 view.flingScroll(0, Math.round(y * 100));
807 }
808 }
809 mLastGestureTime = now;
810 }
811 }
812 }
813
Christian Mehlmauerfdf5c2d2010-05-25 19:52:28 +0200814 public void onAccuracyChanged(Sensor sensor, int accuracy) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800815 // TODO Auto-generated method stub
816
817 }
818 };
819
820 @Override protected void onResume() {
821 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700822 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800823 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
824 }
825
826 if (!mActivityInPause) {
827 Log.e(LOGTAG, "BrowserActivity is already resumed.");
828 return;
829 }
830
Mike Reed7bfa63b2009-05-28 11:08:32 -0400831 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800832 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400833 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800834
835 if (mWakeLock.isHeld()) {
836 mHandler.removeMessages(RELEASE_WAKELOCK);
837 mWakeLock.release();
838 }
839
840 if (mCredsDlg != null) {
841 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
842 // In case credential request never comes back
843 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
844 }
845 }
846
847 registerReceiver(mNetworkStateIntentReceiver,
848 mNetworkStateChangedFilter);
849 WebView.enablePlatformNotifications();
850
851 if (mSettings.doFlick()) {
852 if (mSensorManager == null) {
853 mSensorManager = (SensorManager) getSystemService(
854 Context.SENSOR_SERVICE);
855 }
Christian Mehlmauerfdf5c2d2010-05-25 19:52:28 +0200856 mSensorManager.registerListener(mSensorEventListener,
857 mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
The Android Open Source Project0c908882009-03-03 19:32:16 -0800858 SensorManager.SENSOR_DELAY_FASTEST);
859 } else {
860 mSensorManager = null;
861 }
862 }
863
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400864 /**
865 * Since the actual title bar is embedded in the WebView, and removing it
866 * would change its appearance, create a temporary title bar to go at
867 * the top of the screen while the menu is open.
868 */
869 private TitleBar mFakeTitleBar;
870
871 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400872 * Holder for the fake title bar. It will have a foreground shadow, as well
873 * as a white background, so the fake title bar looks like the real one.
874 */
875 private ViewGroup mFakeTitleBarHolder;
876
877 /**
878 * Layout parameters for the fake title bar within mFakeTitleBarHolder
879 */
880 private FrameLayout.LayoutParams mFakeTitleBarParams
881 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400882 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400883 ViewGroup.LayoutParams.WRAP_CONTENT);
884 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400885 * Keeps track of whether the options menu is open. This is important in
886 * determining whether to show or hide the title bar overlay.
887 */
888 private boolean mOptionsMenuOpen;
889
890 /**
891 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
892 * of whether the configuration has changed. The first onMenuOpened call
893 * after a configuration change is simply a reopening of the same menu
894 * (i.e. mIconView did not change).
895 */
896 private boolean mConfigChanged;
897
898 /**
899 * Whether or not the options menu is in its smaller, icon menu form. When
900 * true, we want the title bar overlay to be up. When false, we do not.
901 * Only meaningful if mOptionsMenuOpen is true.
902 */
903 private boolean mIconView;
904
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400905 @Override
906 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400907 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
908 if (mOptionsMenuOpen) {
909 if (mConfigChanged) {
910 // We do not need to make any changes to the state of the
911 // title bar, since the only thing that happened was a
912 // change in orientation
913 mConfigChanged = false;
914 } else {
915 if (mIconView) {
916 // Switching the menu to expanded view, so hide the
917 // title bar.
918 hideFakeTitleBar();
919 mIconView = false;
920 } else {
921 // Switching the menu back to icon view, so show the
922 // title bar once again.
923 showFakeTitleBar();
924 mIconView = true;
925 }
926 }
927 } else {
928 // The options menu is closed, so open it, and show the title
929 showFakeTitleBar();
930 mOptionsMenuOpen = true;
931 mConfigChanged = false;
932 mIconView = true;
933 }
934 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400935 return true;
936 }
937
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400938 /**
939 * Special class used exclusively for the shadow drawn underneath the fake
940 * title bar. The shadow does not need to be drawn if the WebView
941 * underneath is scrolled to the top, because it will draw directly on top
942 * of the embedded shadow.
943 */
944 private static class Shadow extends View {
945 private WebView mWebView;
946
947 public Shadow(Context context, AttributeSet attrs) {
948 super(context, attrs);
949 }
950
951 public void setWebView(WebView view) {
952 mWebView = view;
953 }
954
955 @Override
956 public void draw(Canvas canvas) {
957 // In general onDraw is the method to override, but we care about
958 // whether or not the background gets drawn, which happens in draw()
959 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
960 super.draw(canvas);
961 }
962 // Need to invalidate so that if the scroll position changes, we
963 // still draw as appropriate.
964 invalidate();
965 }
966 }
967
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400968 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400969 final View decor = getWindow().peekDecorView();
Leon Scroggins4d7e4062009-09-15 15:49:45 -0400970 if (mFakeTitleBar == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400971 && !mActivityInPause && decor != null
972 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400973 Rect visRect = new Rect();
974 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
975 if (LOGD_ENABLED) {
976 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
977 }
978 return;
979 }
Leon Scrogginsf4bb18a2009-09-11 18:37:53 -0400980 final WebView webView = getTopWindow();
Leon Scroggins68579392009-09-15 15:31:54 -0400981 mFakeTitleBar = new TitleBar(this);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400982 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
983 mFakeTitleBar.setProgress(webView.getProgress());
984 mFakeTitleBar.setFavicon(webView.getFavicon());
985 updateLockIconToLatest();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400986
987 WindowManager manager
988 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
989
990 // Add the title bar to the window manager so it can receive touches
991 // while the menu is up
992 WindowManager.LayoutParams params
993 = new WindowManager.LayoutParams(
994 ViewGroup.LayoutParams.FILL_PARENT,
995 ViewGroup.LayoutParams.WRAP_CONTENT,
996 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
997 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400998 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400999 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04001000 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -04001001 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -04001002 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001003 // XXX : Without providing an offset, the fake title bar will be
1004 // placed underneath the status bar. Use the global visible rect
1005 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -04001006 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -04001007 // Add a holder for the title bar. It also holds a shadow to show
1008 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001009 if (mFakeTitleBarHolder == null) {
1010 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
1011 .inflate(R.layout.title_bar_bg, null);
1012 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -04001013 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
1014 R.id.shadow);
1015 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -04001016 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001017 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001018 }
1019 }
1020
1021 @Override
1022 public void onOptionsMenuClosed(Menu menu) {
1023 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04001024 if (!mInLoad) {
1025 hideFakeTitleBar();
1026 } else if (!mIconView) {
1027 // The page is currently loading, and we are in expanded mode, so
1028 // we were not showing the menu. Show it once again. It will be
1029 // removed when the page finishes.
1030 showFakeTitleBar();
1031 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001032 }
1033 private void hideFakeTitleBar() {
1034 if (mFakeTitleBar == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -04001035 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
1036 mFakeTitleBarHolder.getLayoutParams();
1037 WebView mainView = mTabControl.getCurrentWebView();
1038 // Although we decided whether or not to animate based on the current
1039 // scroll position, the scroll position may have changed since the
1040 // fake title bar was displayed. Make sure it has the appropriate
1041 // animation/lack thereof before removing.
1042 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -04001043 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001044 WindowManager manager
1045 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -04001046 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001047 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1048 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001049 mFakeTitleBar = null;
1050 }
1051
The Android Open Source Project0c908882009-03-03 19:32:16 -08001052 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001053 * Special method for the fake title bar to call when displaying its context
1054 * menu, since it is in its own Window, and its parent does not show a
1055 * context menu.
1056 */
1057 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -04001058 if (null == mTitleBar.getParent()) {
1059 return;
1060 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001061 openContextMenu(mTitleBar);
1062 }
1063
1064 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001065 * onSaveInstanceState(Bundle map)
1066 * onSaveInstanceState is called right before onStop(). The map contains
1067 * the saved state.
1068 */
1069 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001070 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001071 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1072 }
1073 // the default implementation requires each view to have an id. As the
1074 // browser handles the state itself and it doesn't use id for the views,
1075 // don't call the default implementation. Otherwise it will trigger the
1076 // warning like this, "couldn't save which view has focus because the
1077 // focused view XXX has no id".
1078
1079 // Save all the tabs
1080 mTabControl.saveState(outState);
1081 }
1082
1083 @Override protected void onPause() {
1084 super.onPause();
1085
1086 if (mActivityInPause) {
1087 Log.e(LOGTAG, "BrowserActivity is already paused.");
1088 return;
1089 }
1090
Mike Reed7bfa63b2009-05-28 11:08:32 -04001091 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001092 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001093 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001094 mWakeLock.acquire();
1095 mHandler.sendMessageDelayed(mHandler
1096 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1097 }
1098
1099 // Clear the credentials toast if it is up
1100 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1101 mCredsDlg.dismiss();
1102 }
1103 mCredsDlg = null;
1104
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001105 // FIXME: This removes the active tabs page and resets the menu to
1106 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1107 // but then we would need to save it in onSaveInstanceState and restore
1108 // it in onCreate/onRestoreInstanceState
1109 if (mActiveTabsPage != null) {
1110 removeActiveTabPage(true);
1111 }
1112
The Android Open Source Project0c908882009-03-03 19:32:16 -08001113 cancelStopToast();
1114
1115 // unregister network state listener
1116 unregisterReceiver(mNetworkStateIntentReceiver);
1117 WebView.disablePlatformNotifications();
1118
1119 if (mSensorManager != null) {
Christian Mehlmauerfdf5c2d2010-05-25 19:52:28 +02001120 mSensorManager.unregisterListener(mSensorEventListener);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001121 }
1122 }
1123
1124 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001125 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001126 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1127 }
1128 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001129
1130 if (mTabControl == null) return;
1131
The Android Open Source Project0c908882009-03-03 19:32:16 -08001132 // Remove the current tab and sub window
1133 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001134 if (t != null) {
1135 dismissSubWindow(t);
1136 removeTabFromContentView(t);
1137 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001138 // Destroy all the tabs
1139 mTabControl.destroy();
1140 WebIconDatabase.getInstance().close();
1141 if (mGlsConnection != null) {
1142 unbindService(mGlsConnection);
1143 mGlsConnection = null;
1144 }
1145
1146 //
1147 // stop MASF proxy service
1148 //
1149 //Intent proxyServiceIntent = new Intent();
1150 //proxyServiceIntent.setComponent
1151 // (new ComponentName(
1152 // "com.android.masfproxyservice",
1153 // "com.android.masfproxyservice.MasfProxyService"));
1154 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001155
1156 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001157 }
1158
1159 @Override
1160 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001161 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001162 super.onConfigurationChanged(newConfig);
1163
1164 if (mPageInfoDialog != null) {
1165 mPageInfoDialog.dismiss();
1166 showPageInfo(
1167 mPageInfoView,
1168 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1169 }
1170 if (mSSLCertificateDialog != null) {
1171 mSSLCertificateDialog.dismiss();
1172 showSSLCertificate(
1173 mSSLCertificateView);
1174 }
1175 if (mSSLCertificateOnErrorDialog != null) {
1176 mSSLCertificateOnErrorDialog.dismiss();
1177 showSSLCertificateOnError(
1178 mSSLCertificateOnErrorView,
1179 mSSLCertificateOnErrorHandler,
1180 mSSLCertificateOnErrorError);
1181 }
1182 if (mHttpAuthenticationDialog != null) {
1183 String title = ((TextView) mHttpAuthenticationDialog
1184 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1185 .toString();
1186 String name = ((TextView) mHttpAuthenticationDialog
1187 .findViewById(R.id.username_edit)).getText().toString();
1188 String password = ((TextView) mHttpAuthenticationDialog
1189 .findViewById(R.id.password_edit)).getText().toString();
1190 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1191 .getId();
1192 mHttpAuthenticationDialog.dismiss();
1193 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1194 name, password, focusId);
1195 }
1196 if (mFindDialog != null && mFindDialog.isShowing()) {
1197 mFindDialog.onConfigurationChanged(newConfig);
1198 }
1199 }
1200
1201 @Override public void onLowMemory() {
1202 super.onLowMemory();
1203 mTabControl.freeMemory();
1204 }
1205
Mike Reed7bfa63b2009-05-28 11:08:32 -04001206 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001207 if ((!mActivityInPause && !mPageStarted) ||
1208 (mActivityInPause && mPageStarted)) {
1209 CookieSyncManager.getInstance().startSync();
1210 WebView w = mTabControl.getCurrentWebView();
1211 if (w != null) {
1212 w.resumeTimers();
1213 }
1214 return true;
1215 } else {
1216 return false;
1217 }
1218 }
1219
Mike Reed7bfa63b2009-05-28 11:08:32 -04001220 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001221 if (mActivityInPause && !mPageStarted) {
1222 CookieSyncManager.getInstance().stopSync();
1223 WebView w = mTabControl.getCurrentWebView();
1224 if (w != null) {
1225 w.pauseTimers();
1226 }
1227 return true;
1228 } else {
1229 return false;
1230 }
1231 }
1232
Leon Scroggins1f005d32009-08-10 17:36:42 -04001233 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001234 /*
1235 * This function is called when we are launching for the first time. We
1236 * are waiting for the login credentials before loading Google home
1237 * pages. This way the user will be logged in straight away.
1238 */
1239 private void waitForCredentials() {
1240 // Show a toast
1241 mCredsDlg = new ProgressDialog(this);
1242 mCredsDlg.setIndeterminate(true);
1243 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1244 // If the user cancels the operation, then cancel the Google
1245 // Credentials request.
1246 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1247 mCredsDlg.show();
1248
1249 // We set a timeout for the retrieval of credentials in onResume()
1250 // as that is when we have freed up some CPU time to get
1251 // the login credentials.
1252 }
1253
1254 /*
1255 * If we have received the credentials or we have timed out and we are
1256 * showing the credentials dialog, then it is time to move on.
1257 */
1258 private void resumeAfterCredentials() {
1259 if (mCredsDlg == null) {
1260 return;
1261 }
1262
1263 // Clear the toast
1264 if (mCredsDlg.isShowing()) {
1265 mCredsDlg.dismiss();
1266 }
1267 mCredsDlg = null;
1268
1269 // Clear any pending timeout
1270 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1271
1272 // Load the page
1273 WebView w = mTabControl.getCurrentWebView();
1274 if (w != null) {
1275 w.loadUrl(mSettings.getHomePage());
1276 }
1277
1278 // Update the settings, need to do this last as it can take a moment
1279 // to persist the settings. In the mean time we could be loading
1280 // content.
1281 mSettings.setLoginInitialized(this);
1282 }
1283
1284 // Open the icon database and retain all the icons for visited sites.
1285 private void retainIconsOnStartup() {
1286 final WebIconDatabase db = WebIconDatabase.getInstance();
1287 db.open(getDir("icons", 0).getPath());
1288 try {
1289 Cursor c = Browser.getAllBookmarks(mResolver);
1290 if (!c.moveToFirst()) {
1291 c.deactivate();
1292 return;
1293 }
1294 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1295 do {
1296 String url = c.getString(urlIndex);
1297 db.retainIconForPageUrl(url);
1298 } while (c.moveToNext());
1299 c.deactivate();
1300 } catch (IllegalStateException e) {
1301 Log.e(LOGTAG, "retainIconsOnStartup", e);
1302 }
1303 }
1304
1305 // Helper method for getting the top window.
1306 WebView getTopWindow() {
1307 return mTabControl.getCurrentTopWebView();
1308 }
1309
1310 @Override
1311 public boolean onCreateOptionsMenu(Menu menu) {
1312 super.onCreateOptionsMenu(menu);
1313
1314 MenuInflater inflater = getMenuInflater();
1315 inflater.inflate(R.menu.browser, menu);
1316 mMenu = menu;
1317 updateInLoadMenuItems();
1318 return true;
1319 }
1320
1321 /**
1322 * As the menu can be open when loading state changes
1323 * we must manually update the state of the stop/reload menu
1324 * item
1325 */
1326 private void updateInLoadMenuItems() {
1327 if (mMenu == null) {
1328 return;
1329 }
1330 MenuItem src = mInLoad ?
1331 mMenu.findItem(R.id.stop_menu_id):
1332 mMenu.findItem(R.id.reload_menu_id);
1333 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1334 dest.setIcon(src.getIcon());
1335 dest.setTitle(src.getTitle());
1336 }
1337
1338 @Override
1339 public boolean onContextItemSelected(MenuItem item) {
1340 // chording is not an issue with context menus, but we use the same
1341 // options selector, so set mCanChord to true so we can access them.
1342 mCanChord = true;
1343 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001344 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001345 // For the context menu from the title bar
1346 case R.id.title_bar_share_page_url:
1347 case R.id.title_bar_copy_page_url:
1348 WebView mainView = mTabControl.getCurrentWebView();
1349 if (null == mainView) {
1350 return false;
1351 }
1352 if (id == R.id.title_bar_share_page_url) {
1353 Browser.sendString(this, mainView.getUrl());
1354 } else {
1355 copy(mainView.getUrl());
1356 }
1357 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001358 // -- Browser context menu
1359 case R.id.open_context_menu_id:
1360 case R.id.open_newtab_context_menu_id:
1361 case R.id.bookmark_context_menu_id:
1362 case R.id.save_link_context_menu_id:
1363 case R.id.share_link_context_menu_id:
1364 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001365 final WebView webView = getTopWindow();
1366 if (null == webView) {
1367 return false;
1368 }
1369 final HashMap hrefMap = new HashMap();
1370 hrefMap.put("webview", webView);
1371 final Message msg = mHandler.obtainMessage(
1372 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001373 webView.requestFocusNodeHref(msg);
1374 break;
1375
1376 default:
1377 // For other context menus
1378 return onOptionsItemSelected(item);
1379 }
1380 mCanChord = false;
1381 return true;
1382 }
1383
1384 private Bundle createGoogleSearchSourceBundle(String source) {
1385 Bundle bundle = new Bundle();
1386 bundle.putString(SearchManager.SOURCE, source);
1387 return bundle;
1388 }
1389
1390 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001391 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001392 */
1393 @Override
1394 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001395 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001396 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001397 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001398 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001399 return true;
1400 }
1401
1402 @Override
1403 public void startSearch(String initialQuery, boolean selectInitialQuery,
1404 Bundle appSearchData, boolean globalSearch) {
1405 if (appSearchData == null) {
1406 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1407 }
1408 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1409 }
1410
Leon Scroggins1f005d32009-08-10 17:36:42 -04001411 /**
1412 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1413 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001414 * @param index Index of the tab to change to, as defined by
1415 * mTabControl.getTabIndex(Tab t).
1416 * @return boolean True if we successfully switched to a different tab. If
1417 * the indexth tab is null, or if that tab is the same as
1418 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001419 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001420 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001421 TabControl.Tab tab = mTabControl.getTab(index);
1422 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1423 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001424 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001425 }
1426 if (currentTab != null) {
1427 // currentTab may be null if it was just removed. In that case,
1428 // we do not need to remove it
1429 removeTabFromContentView(currentTab);
1430 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001431 mTabControl.setCurrentTab(tab);
1432 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001433 resetTitleIconAndProgress();
1434 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001435 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001436 }
1437
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001438 /* package */ TabControl.Tab openTabToHomePage() {
1439 return openTabAndShow(mSettings.getHomePage(), false, null);
1440 }
1441
Leon Scroggins1f005d32009-08-10 17:36:42 -04001442 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001443 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001444 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001445 // This is the last tab. Open a new one, with the home
1446 // page and close the current one.
Henrik Baard4e0b6182010-04-21 12:31:47 +02001447 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001448 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001449 return;
1450 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001451 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001452 int indexToShow = -1;
1453 if (parent != null) {
1454 indexToShow = mTabControl.getTabIndex(parent);
1455 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001456 final int currentIndex = mTabControl.getCurrentIndex();
1457 // Try to move to the tab to the right
1458 indexToShow = currentIndex + 1;
1459 if (indexToShow > mTabControl.getTabCount() - 1) {
1460 // Try to move to the tab to the left
1461 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001462 }
1463 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001464 if (switchToTab(indexToShow)) {
1465 // Close window
1466 closeTab(current);
1467 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001468 }
1469
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001470 private ActiveTabsPage mActiveTabsPage;
1471
1472 /**
1473 * Remove the active tabs page.
1474 * @param needToAttach If true, the active tabs page did not attach a tab
1475 * to the content view, so we need to do that here.
1476 */
1477 /* package */ void removeActiveTabPage(boolean needToAttach) {
1478 mContentView.removeView(mActiveTabsPage);
1479 mActiveTabsPage = null;
1480 mMenuState = R.id.MAIN_MENU;
1481 if (needToAttach) {
1482 attachTabToContentView(mTabControl.getCurrentTab());
1483 }
1484 getTopWindow().requestFocus();
1485 }
1486
The Android Open Source Project0c908882009-03-03 19:32:16 -08001487 @Override
1488 public boolean onOptionsItemSelected(MenuItem item) {
1489 if (!mCanChord) {
1490 // The user has already fired a shortcut with this hold down of the
1491 // menu key.
1492 return false;
1493 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001494 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001495 return false;
1496 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001497 if (mMenuIsDown) {
1498 // The shortcut action consumes the MENU. Even if it is still down,
1499 // it won't trigger the next shortcut action. In the case of the
1500 // shortcut action triggering a new activity, like Bookmarks, we
1501 // won't get onKeyUp for MENU. So it is important to reset it here.
1502 mMenuIsDown = false;
1503 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001504 switch (item.getItemId()) {
1505 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001506 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001507 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001508 break;
1509
Leon Scroggins64b80f32009-08-07 12:03:34 -04001510 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001511 onSearchRequested();
1512 break;
1513
1514 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001515 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001516 break;
1517
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001518 case R.id.active_tabs_menu_id:
1519 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1520 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001521 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001522 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1523 mActiveTabsPage.requestFocus();
1524 mMenuState = EMPTY_MENU;
1525 break;
1526
Leon Scroggins1f005d32009-08-10 17:36:42 -04001527 case R.id.add_bookmark_menu_id:
1528 Intent i = new Intent(BrowserActivity.this,
1529 AddBookmarkPage.class);
1530 WebView w = getTopWindow();
1531 i.putExtra("url", w.getUrl());
1532 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001533 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001534 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001535 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001536 break;
1537
1538 case R.id.stop_reload_menu_id:
1539 if (mInLoad) {
1540 stopLoading();
1541 } else {
1542 getTopWindow().reload();
1543 }
1544 break;
1545
1546 case R.id.back_menu_id:
1547 getTopWindow().goBack();
1548 break;
1549
1550 case R.id.forward_menu_id:
1551 getTopWindow().goForward();
1552 break;
1553
1554 case R.id.close_menu_id:
1555 // Close the subwindow if it exists.
1556 if (mTabControl.getCurrentSubWindow() != null) {
1557 dismissSubWindow(mTabControl.getCurrentTab());
1558 break;
1559 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001560 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001561 break;
1562
1563 case R.id.homepage_menu_id:
1564 TabControl.Tab current = mTabControl.getCurrentTab();
1565 if (current != null) {
1566 dismissSubWindow(current);
1567 current.getWebView().loadUrl(mSettings.getHomePage());
1568 }
1569 break;
1570
1571 case R.id.preferences_menu_id:
1572 Intent intent = new Intent(this,
1573 BrowserPreferencesPage.class);
1574 startActivityForResult(intent, PREFERENCES_PAGE);
1575 break;
1576
1577 case R.id.find_menu_id:
1578 if (null == mFindDialog) {
1579 mFindDialog = new FindDialog(this);
1580 }
1581 mFindDialog.setWebView(getTopWindow());
1582 mFindDialog.show();
1583 mMenuState = EMPTY_MENU;
1584 break;
1585
1586 case R.id.select_text_id:
1587 getTopWindow().emulateShiftHeld();
1588 break;
1589 case R.id.page_info_menu_id:
1590 showPageInfo(mTabControl.getCurrentTab(), false);
1591 break;
1592
1593 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001594 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001595 break;
1596
1597 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001598 Browser.sendString(this, getTopWindow().getUrl(),
1599 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001600 break;
1601
1602 case R.id.dump_nav_menu_id:
1603 getTopWindow().debugDump();
1604 break;
1605
1606 case R.id.zoom_in_menu_id:
1607 getTopWindow().zoomIn();
1608 break;
1609
1610 case R.id.zoom_out_menu_id:
1611 getTopWindow().zoomOut();
1612 break;
1613
1614 case R.id.view_downloads_menu_id:
1615 viewDownloads(null);
1616 break;
1617
The Android Open Source Project0c908882009-03-03 19:32:16 -08001618 case R.id.window_one_menu_id:
1619 case R.id.window_two_menu_id:
1620 case R.id.window_three_menu_id:
1621 case R.id.window_four_menu_id:
1622 case R.id.window_five_menu_id:
1623 case R.id.window_six_menu_id:
1624 case R.id.window_seven_menu_id:
1625 case R.id.window_eight_menu_id:
1626 {
1627 int menuid = item.getItemId();
1628 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1629 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1630 TabControl.Tab desiredTab = mTabControl.getTab(id);
1631 if (desiredTab != null &&
1632 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001633 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001634 }
1635 break;
1636 }
1637 }
1638 }
1639 break;
1640
1641 default:
1642 if (!super.onOptionsItemSelected(item)) {
1643 return false;
1644 }
1645 // Otherwise fall through.
1646 }
1647 mCanChord = false;
1648 return true;
1649 }
1650
1651 public void closeFind() {
1652 mMenuState = R.id.MAIN_MENU;
1653 }
1654
1655 @Override public boolean onPrepareOptionsMenu(Menu menu)
1656 {
1657 // This happens when the user begins to hold down the menu key, so
1658 // allow them to chord to get a shortcut.
1659 mCanChord = true;
1660 // Note: setVisible will decide whether an item is visible; while
1661 // setEnabled() will decide whether an item is enabled, which also means
1662 // whether the matching shortcut key will function.
1663 super.onPrepareOptionsMenu(menu);
1664 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001665 case EMPTY_MENU:
1666 if (mCurrentMenuState != mMenuState) {
1667 menu.setGroupVisible(R.id.MAIN_MENU, false);
1668 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1669 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001670 }
1671 break;
1672 default:
1673 if (mCurrentMenuState != mMenuState) {
1674 menu.setGroupVisible(R.id.MAIN_MENU, true);
1675 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1676 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001677 }
1678 final WebView w = getTopWindow();
1679 boolean canGoBack = false;
1680 boolean canGoForward = false;
1681 boolean isHome = false;
1682 if (w != null) {
1683 canGoBack = w.canGoBack();
1684 canGoForward = w.canGoForward();
1685 isHome = mSettings.getHomePage().equals(w.getUrl());
1686 }
1687 final MenuItem back = menu.findItem(R.id.back_menu_id);
1688 back.setEnabled(canGoBack);
1689
1690 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1691 home.setEnabled(!isHome);
1692
1693 menu.findItem(R.id.forward_menu_id)
1694 .setEnabled(canGoForward);
1695
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001696 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1697 mTabControl.getTabCount() < TabControl.MAX_TABS);
1698
The Android Open Source Project0c908882009-03-03 19:32:16 -08001699 // decide whether to show the share link option
1700 PackageManager pm = getPackageManager();
1701 Intent send = new Intent(Intent.ACTION_SEND);
1702 send.setType("text/plain");
1703 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1704 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1705
The Android Open Source Project0c908882009-03-03 19:32:16 -08001706 boolean isNavDump = mSettings.isNavDump();
1707 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1708 nav.setVisible(isNavDump);
1709 nav.setEnabled(isNavDump);
1710 break;
1711 }
1712 mCurrentMenuState = mMenuState;
1713 return true;
1714 }
1715
1716 @Override
1717 public void onCreateContextMenu(ContextMenu menu, View v,
1718 ContextMenuInfo menuInfo) {
1719 WebView webview = (WebView) v;
1720 WebView.HitTestResult result = webview.getHitTestResult();
1721 if (result == null) {
1722 return;
1723 }
1724
1725 int type = result.getType();
1726 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1727 Log.w(LOGTAG,
1728 "We should not show context menu when nothing is touched");
1729 return;
1730 }
1731 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1732 // let TextView handles context menu
1733 return;
1734 }
1735
1736 // Note, http://b/issue?id=1106666 is requesting that
1737 // an inflated menu can be used again. This is not available
1738 // yet, so inflate each time (yuk!)
1739 MenuInflater inflater = getMenuInflater();
1740 inflater.inflate(R.menu.browsercontext, menu);
1741
1742 // Show the correct menu group
1743 String extra = result.getExtra();
1744 menu.setGroupVisible(R.id.PHONE_MENU,
1745 type == WebView.HitTestResult.PHONE_TYPE);
1746 menu.setGroupVisible(R.id.EMAIL_MENU,
1747 type == WebView.HitTestResult.EMAIL_TYPE);
1748 menu.setGroupVisible(R.id.GEO_MENU,
1749 type == WebView.HitTestResult.GEO_TYPE);
1750 menu.setGroupVisible(R.id.IMAGE_MENU,
1751 type == WebView.HitTestResult.IMAGE_TYPE
1752 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1753 menu.setGroupVisible(R.id.ANCHOR_MENU,
1754 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1755 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1756
1757 // Setup custom handling depending on the type
1758 switch (type) {
1759 case WebView.HitTestResult.PHONE_TYPE:
1760 menu.setHeaderTitle(Uri.decode(extra));
1761 menu.findItem(R.id.dial_context_menu_id).setIntent(
1762 new Intent(Intent.ACTION_VIEW, Uri
1763 .parse(WebView.SCHEME_TEL + extra)));
1764 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1765 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001766 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001767 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1768 addIntent);
1769 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1770 new Copy(extra));
1771 break;
1772
1773 case WebView.HitTestResult.EMAIL_TYPE:
1774 menu.setHeaderTitle(extra);
1775 menu.findItem(R.id.email_context_menu_id).setIntent(
1776 new Intent(Intent.ACTION_VIEW, Uri
1777 .parse(WebView.SCHEME_MAILTO + extra)));
1778 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1779 new Copy(extra));
1780 break;
1781
1782 case WebView.HitTestResult.GEO_TYPE:
1783 menu.setHeaderTitle(extra);
1784 menu.findItem(R.id.map_context_menu_id).setIntent(
1785 new Intent(Intent.ACTION_VIEW, Uri
1786 .parse(WebView.SCHEME_GEO
1787 + URLEncoder.encode(extra))));
1788 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1789 new Copy(extra));
1790 break;
1791
1792 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1793 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1794 TextView titleView = (TextView) LayoutInflater.from(this)
1795 .inflate(android.R.layout.browser_link_context_header,
1796 null);
1797 titleView.setText(extra);
1798 menu.setHeaderView(titleView);
1799 // decide whether to show the open link in new tab option
1800 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1801 mTabControl.getTabCount() < TabControl.MAX_TABS);
1802 PackageManager pm = getPackageManager();
1803 Intent send = new Intent(Intent.ACTION_SEND);
1804 send.setType("text/plain");
1805 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1806 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1807 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1808 break;
1809 }
1810 // otherwise fall through to handle image part
1811 case WebView.HitTestResult.IMAGE_TYPE:
1812 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1813 menu.setHeaderTitle(extra);
1814 }
1815 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1816 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1817 menu.findItem(R.id.download_context_menu_id).
1818 setOnMenuItemClickListener(new Download(extra));
1819 break;
1820
1821 default:
1822 Log.w(LOGTAG, "We should not get here.");
1823 break;
1824 }
1825 }
1826
The Android Open Source Project0c908882009-03-03 19:32:16 -08001827 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001828 // this should only be called for the current tab.
The Android Open Source Project0c908882009-03-03 19:32:16 -08001829 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001830 // Attach the container that contains the main WebView and any other UI
1831 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001832 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001833
1834 if (mShouldShowErrorConsole) {
1835 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1836 if (errorConsole.numberOfErrors() == 0) {
1837 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1838 } else {
1839 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1840 }
1841
1842 mErrorConsoleContainer.addView(errorConsole,
1843 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1844 ViewGroup.LayoutParams.WRAP_CONTENT));
1845 }
1846
Grace Klobac928c302009-09-17 11:51:21 -07001847 setLockIconType(t.getLockIconType());
1848 setPrevLockType(t.getPrevLockIconType());
1849
1850 // this is to match the code in removeTabFromContentView()
1851 if (!mPageStarted && t.getTopWindow().getProgress() < 100) {
1852 mPageStarted = true;
Grace Klobaeb6eef42009-09-15 17:56:32 -07001853 }
1854
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001855 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001856 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001857 // Request focus on the top window.
1858 t.getTopWindow().requestFocus();
1859 }
1860
1861 // Attach a sub window to the main WebView of the given tab.
1862 private void attachSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001863 t.attachSubWindow(mContentView);
1864 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001865 }
1866
1867 // Remove the given tab from the content view.
1868 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001869 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001870 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001871
1872 if (mTabControl.getCurrentErrorConsole(false) != null) {
1873 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1874 }
1875
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001876 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001877 if (view != null) {
1878 view.setEmbeddedTitleBar(null);
1879 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001880
Grace Klobac928c302009-09-17 11:51:21 -07001881 // unlike attachTabToContentView(), removeTabFromContentView() can be
1882 // called for the non-current tab. Need to add the check.
Grace Klobaeb6eef42009-09-15 17:56:32 -07001883 if (t == mTabControl.getCurrentTab()) {
1884 t.setLockIconType(getLockIconType());
1885 t.setPrevLockIconType(getPrevLockType());
Grace Klobac928c302009-09-17 11:51:21 -07001886
1887 // this is not a perfect solution. But currently there is one
1888 // WebViewClient for all the WebView. if user switches from an
1889 // in-load window to an already loaded window, mPageStarted will not
1890 // be set to false. If user leaves the Browser, pauseWebViewTimers()
1891 // won't do anything and leaves the timer running even Browser is in
1892 // the background.
1893 if (mPageStarted) {
1894 mPageStarted = false;
1895 }
Grace Klobaeb6eef42009-09-15 17:56:32 -07001896 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001897 }
1898
1899 // Remove the sub window if it exists. Also called by TabControl when the
1900 // user clicks the 'X' to dismiss a sub window.
1901 /* package */ void dismissSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001902 t.removeSubWindow(mContentView);
1903 // Tell the TabControl to dismiss the subwindow. This will destroy
1904 // the WebView.
1905 mTabControl.dismissSubWindow(t);
1906 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001907 }
1908
Leon Scroggins1f005d32009-08-10 17:36:42 -04001909 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001910 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001911 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1912 String appId) {
1913 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001914 }
1915
1916 // This method does a ton of stuff. It will attempt to create a new tab
1917 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001918 // url isn't null, it will load the given url.
1919 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001920 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001921 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1922 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1923 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001924 final TabControl.Tab tab = mTabControl.createNewTab(
1925 closeOnExit, appId, urlData.mUrl);
1926 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001927 // If the last tab was removed from the active tabs page, currentTab
1928 // will be null.
1929 if (currentTab != null) {
1930 removeTabFromContentView(currentTab);
1931 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001932 // We must set the new tab as the current tab to reflect the old
1933 // animation behavior.
1934 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001935 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001936 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001937 urlData.loadIn(webview);
1938 }
1939 return tab;
1940 } else {
1941 // Get rid of the subwindow if it exists
1942 dismissSubWindow(currentTab);
1943 if (!urlData.isEmpty()) {
1944 // Load the given url.
1945 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001946 }
1947 }
Grace Klobac9181842009-04-14 08:53:22 -07001948 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001949 }
1950
Grace Klobac9181842009-04-14 08:53:22 -07001951 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001952 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001953 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001954 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001955 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001956 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001957 }
Grace Klobac9181842009-04-14 08:53:22 -07001958 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001959 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001960 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001961 }
1962 }
1963
1964 private class Copy implements OnMenuItemClickListener {
1965 private CharSequence mText;
1966
1967 public boolean onMenuItemClick(MenuItem item) {
1968 copy(mText);
1969 return true;
1970 }
1971
1972 public Copy(CharSequence toCopy) {
1973 mText = toCopy;
1974 }
1975 }
1976
1977 private class Download implements OnMenuItemClickListener {
1978 private String mText;
1979
1980 public boolean onMenuItemClick(MenuItem item) {
1981 onDownloadStartNoStream(mText, null, null, null, -1);
1982 return true;
1983 }
1984
1985 public Download(String toDownload) {
1986 mText = toDownload;
1987 }
1988 }
1989
1990 private void copy(CharSequence text) {
1991 try {
1992 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1993 if (clip != null) {
1994 clip.setClipboardText(text);
1995 }
1996 } catch (android.os.RemoteException e) {
1997 Log.e(LOGTAG, "Copy failed", e);
1998 }
1999 }
2000
2001 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002002 * Resets the browser title-view to whatever it must be
2003 * (for example, if we had a loading error)
2004 * When we have a new page, we call resetTitle, when we
2005 * have to reset the titlebar to whatever it used to be
2006 * (for example, if the user chose to stop loading), we
2007 * call resetTitleAndRevertLockIcon.
2008 */
2009 /* package */ void resetTitleAndRevertLockIcon() {
2010 revertLockIcon();
2011 resetTitleIconAndProgress();
2012 }
2013
2014 /**
2015 * Reset the title, favicon, and progress.
2016 */
2017 private void resetTitleIconAndProgress() {
2018 WebView current = mTabControl.getCurrentWebView();
2019 if (current == null) {
2020 return;
2021 }
2022 resetTitleAndIcon(current);
2023 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002024 mWebChromeClient.onProgressChanged(current, progress);
2025 }
2026
2027 // Reset the title and the icon based on the given item.
2028 private void resetTitleAndIcon(WebView view) {
2029 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2030 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002031 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002032 setFavicon(item.getFavicon());
2033 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002034 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002035 setFavicon(null);
2036 }
2037 }
2038
2039 /**
2040 * Sets a title composed of the URL and the title string.
2041 * @param url The URL of the site being loaded.
2042 * @param title The title of the site being loaded.
2043 */
Leon Scroggins68579392009-09-15 15:31:54 -04002044 private void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002045 mUrl = url;
2046 mTitle = title;
2047
Leon Scroggins68579392009-09-15 15:31:54 -04002048 mTitleBar.setTitleAndUrl(title, url);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002049 if (mFakeTitleBar != null) {
2050 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002051 }
2052 }
2053
2054 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002055 * @param url The URL to build a title version of the URL from.
2056 * @return The title version of the URL or null if fails.
2057 * The title version of the URL can be either the URL hostname,
2058 * or the hostname with an "https://" prefix (for secure URLs),
2059 * or an empty string if, for example, the URL in question is a
2060 * file:// URL with no hostname.
2061 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002062 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002063 String titleUrl = null;
2064
2065 if (url != null) {
2066 try {
2067 // parse the url string
2068 URL urlObj = new URL(url);
2069 if (urlObj != null) {
2070 titleUrl = "";
2071
2072 String protocol = urlObj.getProtocol();
2073 String host = urlObj.getHost();
2074
2075 if (host != null && 0 < host.length()) {
2076 titleUrl = host;
2077 if (protocol != null) {
2078 // if a secure site, add an "https://" prefix!
2079 if (protocol.equalsIgnoreCase("https")) {
2080 titleUrl = protocol + "://" + host;
2081 }
2082 }
2083 }
2084 }
2085 } catch (MalformedURLException e) {}
2086 }
2087
2088 return titleUrl;
2089 }
2090
2091 // Set the favicon in the title bar.
2092 private void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002093 mTitleBar.setFavicon(icon);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002094 if (mFakeTitleBar != null) {
2095 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002096 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002097 }
2098
2099 /**
2100 * Saves the current lock-icon state before resetting
2101 * the lock icon. If we have an error, we may need to
2102 * roll back to the previous state.
2103 */
2104 private void saveLockIcon() {
2105 mPrevLockType = mLockIconType;
2106 }
2107
2108 /**
2109 * Reverts the lock-icon state to the last saved state,
2110 * for example, if we had an error, and need to cancel
2111 * the load.
2112 */
2113 private void revertLockIcon() {
2114 mLockIconType = mPrevLockType;
2115
Dave Bort31a6d1c2009-04-13 15:56:49 -07002116 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002117 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2118 " revert lock icon to " + mLockIconType);
2119 }
2120
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002121 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002122 }
2123
Leon Scroggins1f005d32009-08-10 17:36:42 -04002124 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002125 * Close the tab, remove its associated title bar, and adjust mTabControl's
2126 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002127 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002128 /* package */ void closeTab(TabControl.Tab t) {
2129 int currentIndex = mTabControl.getCurrentIndex();
2130 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002131 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002132 if (currentIndex >= removeIndex && currentIndex != 0) {
2133 currentIndex--;
2134 }
2135 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002136 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002137 }
2138
2139 private void goBackOnePageOrQuit() {
2140 TabControl.Tab current = mTabControl.getCurrentTab();
2141 if (current == null) {
2142 /*
2143 * Instead of finishing the activity, simply push this to the back
2144 * of the stack and let ActivityManager to choose the foreground
2145 * activity. As BrowserActivity is singleTask, it will be always the
2146 * root of the task. So we can use either true or false for
2147 * moveTaskToBack().
2148 */
2149 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002150 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002151 }
2152 WebView w = current.getWebView();
2153 if (w.canGoBack()) {
2154 w.goBack();
2155 } else {
2156 // Check to see if we are closing a window that was created by
2157 // another window. If so, we switch back to that window.
2158 TabControl.Tab parent = current.getParentTab();
2159 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002160 switchToTab(mTabControl.getTabIndex(parent));
2161 // Now we close the other tab
2162 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002163 } else {
2164 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002165 // force mPageStarted to be false as we are going to either
2166 // finish the activity or remove the tab. This will ensure
2167 // pauseWebView() taking action.
2168 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002169 if (mTabControl.getTabCount() == 1) {
2170 finish();
2171 return;
2172 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002173 // call pauseWebViewTimers() now, we won't be able to call
2174 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002175 // Temporarily change mActivityInPause to be true as
2176 // pauseWebViewTimers() will do nothing if mActivityInPause
2177 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002178 boolean savedState = mActivityInPause;
2179 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002180 Log.e(LOGTAG, "BrowserActivity is already paused "
2181 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002182 }
2183 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002184 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002185 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002186 removeTabFromContentView(current);
2187 mTabControl.removeTab(current);
2188 }
2189 /*
2190 * Instead of finishing the activity, simply push this to the back
2191 * of the stack and let ActivityManager to choose the foreground
2192 * activity. As BrowserActivity is singleTask, it will be always the
2193 * root of the task. So we can use either true or false for
2194 * moveTaskToBack().
2195 */
2196 moveTaskToBack(true);
2197 }
2198 }
2199 }
2200
Grace Kloba5942df02009-09-18 11:48:29 -07002201 @Override
2202 public boolean onKeyDown(int keyCode, KeyEvent event) {
2203 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2204 // still down, we don't want to trigger the search. Pretend to consume
2205 // the key and do nothing.
2206 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002207
Grace Kloba5942df02009-09-18 11:48:29 -07002208 switch(keyCode) {
2209 case KeyEvent.KEYCODE_MENU:
2210 mMenuIsDown = true;
2211 break;
2212 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002213 // WebView/WebTextView handle the keys in the KeyDown. As
2214 // the Activity's shortcut keys are only handled when WebView
2215 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2216 if (event.isShiftPressed()) {
2217 getTopWindow().pageUp(false);
2218 } else {
2219 getTopWindow().pageDown(false);
2220 }
Grace Kloba5942df02009-09-18 11:48:29 -07002221 return true;
2222 case KeyEvent.KEYCODE_BACK:
2223 if (event.getRepeatCount() == 0) {
2224 event.startTracking();
2225 return true;
2226 } else if (mCustomView == null && mActiveTabsPage == null
2227 && event.isLongPress()) {
2228 bookmarksOrHistoryPicker(true);
2229 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002230 }
Grace Kloba5942df02009-09-18 11:48:29 -07002231 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002232 }
Grace Kloba5942df02009-09-18 11:48:29 -07002233 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002234 }
2235
Grace Kloba5942df02009-09-18 11:48:29 -07002236 @Override
2237 public boolean onKeyUp(int keyCode, KeyEvent event) {
2238 switch(keyCode) {
2239 case KeyEvent.KEYCODE_MENU:
2240 mMenuIsDown = false;
2241 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002242 case KeyEvent.KEYCODE_BACK:
2243 if (event.isTracking() && !event.isCanceled()) {
2244 if (mCustomView != null) {
2245 // if a custom view is showing, hide it
2246 mWebChromeClient.onHideCustomView();
2247 } else if (mActiveTabsPage != null) {
2248 // if tab page is showing, hide it
2249 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002250 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002251 WebView subwindow = mTabControl.getCurrentSubWindow();
2252 if (subwindow != null) {
2253 if (subwindow.canGoBack()) {
2254 subwindow.goBack();
2255 } else {
2256 dismissSubWindow(mTabControl.getCurrentTab());
2257 }
2258 } else {
2259 goBackOnePageOrQuit();
2260 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002261 }
Grace Kloba5942df02009-09-18 11:48:29 -07002262 return true;
2263 }
2264 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002265 }
Grace Kloba5942df02009-09-18 11:48:29 -07002266 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002267 }
2268
Leon Scroggins68579392009-09-15 15:31:54 -04002269 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002270 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002271 resetTitleAndRevertLockIcon();
2272 WebView w = getTopWindow();
2273 w.stopLoading();
2274 mWebViewClient.onPageFinished(w, w.getUrl());
2275
2276 cancelStopToast();
2277 mStopToast = Toast
2278 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2279 mStopToast.show();
2280 }
2281
2282 private void cancelStopToast() {
2283 if (mStopToast != null) {
2284 mStopToast.cancel();
2285 mStopToast = null;
2286 }
2287 }
2288
2289 // called by a non-UI thread to post the message
2290 public void postMessage(int what, int arg1, int arg2, Object obj) {
2291 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2292 }
2293
2294 // public message ids
2295 public final static int LOAD_URL = 1001;
2296 public final static int STOP_LOAD = 1002;
2297
2298 // Message Ids
2299 private static final int FOCUS_NODE_HREF = 102;
2300 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002301 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002302
Ben Murdoch2694e232009-09-29 09:41:11 +01002303 private static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
2304
The Android Open Source Project0c908882009-03-03 19:32:16 -08002305 // Private handler for handling javascript and saving passwords
2306 private Handler mHandler = new Handler() {
2307
2308 public void handleMessage(Message msg) {
2309 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002310 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002311 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002312 String url = (String) msg.getData().get("url");
2313 if (url == null || url.length() == 0) {
2314 break;
2315 }
2316 HashMap focusNodeMap = (HashMap) msg.obj;
2317 WebView view = (WebView) focusNodeMap.get("webview");
2318 // Only apply the action if the top window did not change.
2319 if (getTopWindow() != view) {
2320 break;
2321 }
2322 switch (msg.arg1) {
2323 case R.id.open_context_menu_id:
2324 case R.id.view_image_context_menu_id:
2325 loadURL(getTopWindow(), url);
2326 break;
2327 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002328 final TabControl.Tab parent = mTabControl
2329 .getCurrentTab();
2330 final TabControl.Tab newTab = openTab(url);
2331 if (newTab != parent) {
2332 parent.addChildTab(newTab);
2333 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002334 break;
2335 case R.id.bookmark_context_menu_id:
2336 Intent intent = new Intent(BrowserActivity.this,
2337 AddBookmarkPage.class);
2338 intent.putExtra("url", url);
2339 startActivity(intent);
2340 break;
2341 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002342 Browser.sendString(BrowserActivity.this, url,
2343 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002344 break;
2345 case R.id.copy_link_context_menu_id:
2346 copy(url);
2347 break;
2348 case R.id.save_link_context_menu_id:
2349 case R.id.download_context_menu_id:
2350 onDownloadStartNoStream(url, null, null, null, -1);
2351 break;
2352 }
2353 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002354 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002355
2356 case LOAD_URL:
2357 loadURL(getTopWindow(), (String) msg.obj);
2358 break;
2359
2360 case STOP_LOAD:
2361 stopLoading();
2362 break;
2363
2364 case CANCEL_CREDS_REQUEST:
2365 resumeAfterCredentials();
2366 break;
2367
The Android Open Source Project0c908882009-03-03 19:32:16 -08002368 case RELEASE_WAKELOCK:
2369 if (mWakeLock.isHeld()) {
2370 mWakeLock.release();
2371 }
2372 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002373
2374 case UPDATE_BOOKMARK_THUMBNAIL:
2375 WebView view = (WebView) msg.obj;
2376 if (view != null) {
2377 updateScreenshot(view);
2378 }
2379 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002380 }
2381 }
2382 };
2383
Leon Scroggins89c6d362009-07-15 16:54:37 -04002384 private void updateScreenshot(WebView view) {
2385 // If this is a bookmarked site, add a screenshot to the database.
2386 // FIXME: When should we update? Every time?
2387 // FIXME: Would like to make sure there is actually something to
2388 // draw, but the API for that (WebViewCore.pictureReady()) is not
2389 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002390
Patrick Scott3918d442009-08-04 13:22:29 -04002391 ContentResolver cr = getContentResolver();
2392 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002393 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002394 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002395 boolean succeed = c.moveToFirst();
2396 ContentValues values = null;
2397 while (succeed) {
2398 if (values == null) {
2399 final ByteArrayOutputStream os
2400 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002401 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002402 if (bm == null) {
2403 c.close();
2404 return;
2405 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002406 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2407 values = new ContentValues();
2408 values.put(Browser.BookmarkColumns.THUMBNAIL,
2409 os.toByteArray());
2410 }
2411 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2412 c.getInt(0)), values, null, null);
2413 succeed = c.moveToNext();
2414 }
2415 c.close();
2416 }
2417 }
2418
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002419 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002420 * Values for the size of the thumbnail created when taking a screenshot.
2421 * Lazily initialized. Instead of using these directly, use
2422 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002423 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002424 private static int THUMBNAIL_WIDTH = 0;
2425 private static int THUMBNAIL_HEIGHT = 0;
2426
2427 /**
2428 * Return the desired width for thumbnail screenshots, which are stored in
2429 * the database, and used on the bookmarks screen.
2430 * @param context Context for finding out the density of the screen.
2431 * @return int desired width for thumbnail screenshot.
2432 */
2433 /* package */ static int getDesiredThumbnailWidth(Context context) {
2434 if (THUMBNAIL_WIDTH == 0) {
2435 float density = context.getResources().getDisplayMetrics().density;
2436 THUMBNAIL_WIDTH = (int) (90 * density);
2437 THUMBNAIL_HEIGHT = (int) (80 * density);
2438 }
2439 return THUMBNAIL_WIDTH;
2440 }
2441
2442 /**
2443 * Return the desired height for thumbnail screenshots, which are stored in
2444 * the database, and used on the bookmarks screen.
2445 * @param context Context for finding out the density of the screen.
2446 * @return int desired height for thumbnail screenshot.
2447 */
2448 /* package */ static int getDesiredThumbnailHeight(Context context) {
2449 // To ensure that they are both initialized.
2450 getDesiredThumbnailWidth(context);
2451 return THUMBNAIL_HEIGHT;
2452 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002453
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002454 private Bitmap createScreenshot(WebView view) {
2455 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002456 if (thumbnail == null) {
2457 return null;
2458 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002459 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2460 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002461 Canvas canvas = new Canvas(bm);
2462 // May need to tweak these values to determine what is the
2463 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002464 int thumbnailWidth = thumbnail.getWidth();
2465 if (thumbnailWidth > 0) {
2466 float scaleFactor = (float) getDesiredThumbnailWidth(this) /
2467 (float)thumbnailWidth;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002468 canvas.scale(scaleFactor, scaleFactor);
2469 }
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002470 thumbnail.draw(canvas);
2471 return bm;
2472 }
2473
The Android Open Source Project0c908882009-03-03 19:32:16 -08002474 // -------------------------------------------------------------------------
2475 // WebViewClient implementation.
2476 //-------------------------------------------------------------------------
2477
2478 // Use in overrideUrlLoading
2479 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2480 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2481 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2482 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2483
2484 /* package */ WebViewClient getWebViewClient() {
2485 return mWebViewClient;
2486 }
2487
Patrick Scott3918d442009-08-04 13:22:29 -04002488 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002489 if (icon != null) {
2490 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott15525d42009-09-21 13:39:37 -04002491 view.getOriginalUrl(), view.getUrl(), icon);
2492 }
2493 setFavicon(icon);
2494 }
2495
2496 private void updateIcon(String url, Bitmap icon) {
2497 if (icon != null) {
2498 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2499 null, url, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002500 }
2501 setFavicon(icon);
2502 }
2503
2504 private final WebViewClient mWebViewClient = new WebViewClient() {
2505 @Override
2506 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2507 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002508 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002509
Ben Murdoch2694e232009-09-29 09:41:11 +01002510 // We've started to load a new page. If there was a pending message
2511 // to save a screenshot then we will now take the new page and
2512 // save an incorrect screenshot. Therefore, remove any pending
2513 // thumbnail messages from the queue.
2514 mHandler.removeMessages(UPDATE_BOOKMARK_THUMBNAIL);
2515
Patrick Scott59ce8302009-09-18 16:29:38 -04002516 // If we start a touch icon load and then load a new page, we don't
2517 // want to cancel the current touch icon loader. But, we do want to
2518 // create a new one when the touch icon url is known.
2519 if (mTouchIconLoader != null) {
2520 mTouchIconLoader.mActivity = null;
2521 mTouchIconLoader = null;
2522 }
2523
Ben Murdochbff2d602009-07-01 20:19:05 +01002524 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2525 if (errorConsole != null) {
2526 errorConsole.clearErrorMessages();
2527 if (mShouldShowErrorConsole) {
2528 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2529 }
2530 }
2531
The Android Open Source Project0c908882009-03-03 19:32:16 -08002532 // Call updateIcon instead of setFavicon so the bookmark
2533 // database can be updated.
Patrick Scott15525d42009-09-21 13:39:37 -04002534 updateIcon(url, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002535
Grace Kloba4d7880f2009-08-12 09:35:42 -07002536 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002537 String host;
2538 try {
2539 WebAddress uri = new WebAddress(url);
2540 host = uri.mHost;
2541 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002542 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002543 }
2544 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002545 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002546 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002547 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002548 }
2549
2550 // Performance probe
2551 if (false) {
2552 mStart = SystemClock.uptimeMillis();
2553 mProcessStart = Process.getElapsedCpuTime();
2554 long[] sysCpu = new long[7];
2555 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2556 sysCpu, null)) {
2557 mUserStart = sysCpu[0] + sysCpu[1];
2558 mSystemStart = sysCpu[2];
2559 mIdleStart = sysCpu[3];
2560 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2561 }
2562 mUiStart = SystemClock.currentThreadTimeMillis();
2563 }
2564
2565 if (!mPageStarted) {
2566 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002567 // if onResume() has been called, resumeWebViewTimers() does
2568 // nothing.
2569 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002570 }
2571
2572 // reset sync timer to avoid sync starts during loading a page
2573 CookieSyncManager.getInstance().resetSync();
2574
2575 mInLoad = true;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002576 mDidStopLoad = false;
Leon Scroggins184f5e32009-09-21 10:38:24 -04002577 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002578 updateInLoadMenuItems();
2579 if (!mIsNetworkUp) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04002580 createAndShowNetworkDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002581 if (view != null) {
2582 view.setNetworkAvailable(false);
2583 }
2584 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002585 }
2586
2587 @Override
2588 public void onPageFinished(WebView view, String url) {
2589 // Reset the title and icon in case we stopped a provisional
2590 // load.
2591 resetTitleAndIcon(view);
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002592
2593 if (!mDidStopLoad) {
2594 // Only update the bookmark screenshot if the user did not
2595 // cancel the load early.
Ben Murdoch2694e232009-09-29 09:41:11 +01002596 Message updateScreenshot = Message.obtain(mHandler, UPDATE_BOOKMARK_THUMBNAIL, view);
2597 mHandler.sendMessageDelayed(updateScreenshot, 500);
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002598 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002599
2600 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002601 updateLockIconToLatest();
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002602
The Android Open Source Project0c908882009-03-03 19:32:16 -08002603 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002604 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002605 long[] sysCpu = new long[7];
2606 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2607 sysCpu, null)) {
2608 String uiInfo = "UI thread used "
2609 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2610 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002611 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002612 Log.d(LOGTAG, uiInfo);
2613 }
2614 //The string that gets written to the log
2615 String performanceString = "It took total "
2616 + (SystemClock.uptimeMillis() - mStart)
2617 + " ms clock time to load the page."
2618 + "\nbrowser process used "
2619 + (Process.getElapsedCpuTime() - mProcessStart)
2620 + " ms, user processes used "
2621 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2622 + " ms, kernel used "
2623 + (sysCpu[2] - mSystemStart) * 10
2624 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2625 + " ms and irq took "
2626 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2627 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002628 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002629 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2630 }
2631 if (url != null) {
2632 // strip the url to maintain consistency
2633 String newUrl = new String(url);
2634 if (newUrl.startsWith("http://www.")) {
2635 newUrl = newUrl.substring(11);
2636 } else if (newUrl.startsWith("http://")) {
2637 newUrl = newUrl.substring(7);
2638 } else if (newUrl.startsWith("https://www.")) {
2639 newUrl = newUrl.substring(12);
2640 } else if (newUrl.startsWith("https://")) {
2641 newUrl = newUrl.substring(8);
2642 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002643 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002644 Log.d(LOGTAG, newUrl + " loaded");
2645 }
2646 /*
2647 if (sWhiteList.contains(newUrl)) {
2648 // The string that gets pushed to the statistcs
2649 // service
2650 performanceString = performanceString
2651 + "\nWebpage: "
2652 + newUrl
2653 + "\nCarrier: "
2654 + android.os.SystemProperties
2655 .get("gsm.sim.operator.alpha");
2656 if (mWebView != null
2657 && mWebView.getContext() != null
2658 && mWebView.getContext().getSystemService(
2659 Context.CONNECTIVITY_SERVICE) != null) {
2660 ConnectivityManager cManager =
2661 (ConnectivityManager) mWebView
2662 .getContext().getSystemService(
2663 Context.CONNECTIVITY_SERVICE);
2664 NetworkInfo nInfo = cManager
2665 .getActiveNetworkInfo();
2666 if (nInfo != null) {
2667 performanceString = performanceString
2668 + "\nNetwork Type: "
2669 + nInfo.getType().toString();
2670 }
2671 }
2672 Checkin.logEvent(mResolver,
2673 Checkin.Events.Tag.WEBPAGE_LOAD,
2674 performanceString);
2675 Log.w(LOGTAG, "pushed to the statistics service");
2676 }
2677 */
2678 }
2679 }
2680 }
2681
2682 if (mInTrace) {
2683 mInTrace = false;
2684 Debug.stopMethodTracing();
2685 }
2686
2687 if (mPageStarted) {
2688 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002689 // pauseWebViewTimers() will do nothing and return false if
2690 // onPause() is not called yet.
2691 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002692 if (mWakeLock.isHeld()) {
2693 mHandler.removeMessages(RELEASE_WAKELOCK);
2694 mWakeLock.release();
2695 }
2696 }
2697 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002698 }
2699
2700 // return true if want to hijack the url to let another app to handle it
2701 @Override
2702 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2703 if (url.startsWith(SCHEME_WTAI)) {
2704 // wtai://wp/mc;number
2705 // number=string(phone-number)
2706 if (url.startsWith(SCHEME_WTAI_MC)) {
2707 Intent intent = new Intent(Intent.ACTION_VIEW,
2708 Uri.parse(WebView.SCHEME_TEL +
2709 url.substring(SCHEME_WTAI_MC.length())));
2710 startActivity(intent);
2711 return true;
2712 }
2713 // wtai://wp/sd;dtmf
2714 // dtmf=string(dialstring)
2715 if (url.startsWith(SCHEME_WTAI_SD)) {
2716 // TODO
2717 // only send when there is active voice connection
2718 return false;
2719 }
2720 // wtai://wp/ap;number;name
2721 // number=string(phone-number)
2722 // name=string
2723 if (url.startsWith(SCHEME_WTAI_AP)) {
2724 // TODO
2725 return false;
2726 }
2727 }
2728
Dianne Hackborn99189432009-06-17 18:06:18 -07002729 // The "about:" schemes are internal to the browser; don't
2730 // want these to be dispatched to other apps.
2731 if (url.startsWith("about:")) {
2732 return false;
2733 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002734
Dianne Hackborn99189432009-06-17 18:06:18 -07002735 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002736
Dianne Hackborn99189432009-06-17 18:06:18 -07002737 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002738 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002739 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2740 } catch (URISyntaxException ex) {
2741 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002742 return false;
2743 }
2744
Grace Kloba5b078b52009-06-24 20:23:41 -07002745 // check whether the intent can be resolved. If not, we will see
2746 // whether we can download it from the Market.
2747 if (getPackageManager().resolveActivity(intent, 0) == null) {
2748 String packagename = intent.getPackage();
2749 if (packagename != null) {
2750 intent = new Intent(Intent.ACTION_VIEW, Uri
2751 .parse("market://search?q=pname:" + packagename));
2752 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2753 startActivity(intent);
2754 return true;
2755 } else {
2756 return false;
2757 }
2758 }
2759
Dianne Hackborn99189432009-06-17 18:06:18 -07002760 // sanitize the Intent, ensuring web pages can not bypass browser
2761 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002762 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002763 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002764 try {
2765 if (startActivityIfNeeded(intent, -1)) {
2766 return true;
2767 }
2768 } catch (ActivityNotFoundException ex) {
2769 // ignore the error. If no application can handle the URL,
2770 // eg about:blank, assume the browser can handle it.
2771 }
2772
2773 if (mMenuIsDown) {
2774 openTab(url);
2775 closeOptionsMenu();
2776 return true;
2777 }
2778
2779 return false;
2780 }
2781
2782 /**
2783 * Updates the lock icon. This method is called when we discover another
2784 * resource to be loaded for this page (for example, javascript). While
2785 * we update the icon type, we do not update the lock icon itself until
2786 * we are done loading, it is slightly more secure this way.
2787 */
2788 @Override
2789 public void onLoadResource(WebView view, String url) {
2790 if (url != null && url.length() > 0) {
2791 // It is only if the page claims to be secure
2792 // that we may have to update the lock:
2793 if (mLockIconType == LOCK_ICON_SECURE) {
2794 // If NOT a 'safe' url, change the lock to mixed content!
2795 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2796 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002797 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002798 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2799 " updated lock icon to " + mLockIconType + " due to " + url);
2800 }
2801 }
2802 }
2803 }
2804 }
2805
2806 /**
2807 * Show the dialog, asking the user if they would like to continue after
2808 * an excessive number of HTTP redirects.
2809 */
2810 @Override
2811 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2812 final Message continueMsg) {
2813 new AlertDialog.Builder(BrowserActivity.this)
2814 .setTitle(R.string.browserFrameRedirect)
2815 .setMessage(R.string.browserFrame307Post)
2816 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2817 public void onClick(DialogInterface dialog, int which) {
2818 continueMsg.sendToTarget();
2819 }})
2820 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2821 public void onClick(DialogInterface dialog, int which) {
2822 cancelMsg.sendToTarget();
2823 }})
2824 .setOnCancelListener(new OnCancelListener() {
2825 public void onCancel(DialogInterface dialog) {
2826 cancelMsg.sendToTarget();
2827 }})
2828 .show();
2829 }
2830
Patrick Scott37911c72009-03-24 18:02:58 -07002831 // Container class for the next error dialog that needs to be
2832 // displayed.
2833 class ErrorDialog {
2834 public final int mTitle;
2835 public final String mDescription;
2836 public final int mError;
2837 ErrorDialog(int title, String desc, int error) {
2838 mTitle = title;
2839 mDescription = desc;
2840 mError = error;
2841 }
2842 };
2843
2844 private void processNextError() {
2845 if (mQueuedErrors == null) {
2846 return;
2847 }
2848 // The first one is currently displayed so just remove it.
2849 mQueuedErrors.removeFirst();
2850 if (mQueuedErrors.size() == 0) {
2851 mQueuedErrors = null;
2852 return;
2853 }
2854 showError(mQueuedErrors.getFirst());
2855 }
2856
2857 private DialogInterface.OnDismissListener mDialogListener =
2858 new DialogInterface.OnDismissListener() {
2859 public void onDismiss(DialogInterface d) {
2860 processNextError();
2861 }
2862 };
2863 private LinkedList<ErrorDialog> mQueuedErrors;
2864
2865 private void queueError(int err, String desc) {
2866 if (mQueuedErrors == null) {
2867 mQueuedErrors = new LinkedList<ErrorDialog>();
2868 }
2869 for (ErrorDialog d : mQueuedErrors) {
2870 if (d.mError == err) {
2871 // Already saw a similar error, ignore the new one.
2872 return;
2873 }
2874 }
2875 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002876 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002877 R.string.browserFrameFileErrorLabel :
2878 R.string.browserFrameNetworkErrorLabel,
2879 desc, err);
2880 mQueuedErrors.addLast(errDialog);
2881
2882 // Show the dialog now if the queue was empty.
2883 if (mQueuedErrors.size() == 1) {
2884 showError(errDialog);
2885 }
2886 }
2887
2888 private void showError(ErrorDialog errDialog) {
2889 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2890 .setTitle(errDialog.mTitle)
2891 .setMessage(errDialog.mDescription)
2892 .setPositiveButton(R.string.ok, null)
2893 .create();
2894 d.setOnDismissListener(mDialogListener);
2895 d.show();
2896 }
2897
The Android Open Source Project0c908882009-03-03 19:32:16 -08002898 /**
2899 * Show a dialog informing the user of the network error reported by
2900 * WebCore.
2901 */
2902 @Override
2903 public void onReceivedError(WebView view, int errorCode,
2904 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002905 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2906 errorCode != WebViewClient.ERROR_CONNECT &&
2907 errorCode != WebViewClient.ERROR_BAD_URL &&
2908 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2909 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002910 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002911 }
Patrick Scott37911c72009-03-24 18:02:58 -07002912 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2913 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002914
2915 // We need to reset the title after an error.
2916 resetTitleAndRevertLockIcon();
2917 }
2918
2919 /**
2920 * Check with the user if it is ok to resend POST data as the page they
2921 * are trying to navigate to is the result of a POST.
2922 */
2923 @Override
2924 public void onFormResubmission(WebView view, final Message dontResend,
2925 final Message resend) {
2926 new AlertDialog.Builder(BrowserActivity.this)
2927 .setTitle(R.string.browserFrameFormResubmitLabel)
2928 .setMessage(R.string.browserFrameFormResubmitMessage)
2929 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2930 public void onClick(DialogInterface dialog, int which) {
2931 resend.sendToTarget();
2932 }})
2933 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2934 public void onClick(DialogInterface dialog, int which) {
2935 dontResend.sendToTarget();
2936 }})
2937 .setOnCancelListener(new OnCancelListener() {
2938 public void onCancel(DialogInterface dialog) {
2939 dontResend.sendToTarget();
2940 }})
2941 .show();
2942 }
2943
2944 /**
2945 * Insert the url into the visited history database.
2946 * @param url The url to be inserted.
2947 * @param isReload True if this url is being reloaded.
2948 * FIXME: Not sure what to do when reloading the page.
2949 */
2950 @Override
2951 public void doUpdateVisitedHistory(WebView view, String url,
2952 boolean isReload) {
2953 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2954 return;
2955 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002956 // remove "client" before updating it to the history so that it wont
2957 // show up in the auto-complete list.
2958 int index = url.indexOf("client=ms-");
2959 if (index > 0 && url.contains(".google.")) {
2960 int end = url.indexOf('&', index);
2961 if (end > 0) {
Grace Klobaef292152009-10-07 19:15:59 -07002962 url = url.substring(0, index)
2963 .concat(url.substring(end + 1));
Grace Kloba6b52a552009-09-03 16:29:56 -07002964 } else {
Grace Klobaef292152009-10-07 19:15:59 -07002965 // the url.charAt(index-1) should be either '?' or '&'
Grace Kloba6b52a552009-09-03 16:29:56 -07002966 url = url.substring(0, index-1);
2967 }
2968 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002969 Browser.updateVisitedHistory(mResolver, url, true);
2970 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2971 }
2972
2973 /**
2974 * Displays SSL error(s) dialog to the user.
2975 */
2976 @Override
2977 public void onReceivedSslError(
2978 final WebView view, final SslErrorHandler handler, final SslError error) {
2979
2980 if (mSettings.showSecurityWarnings()) {
2981 final LayoutInflater factory =
2982 LayoutInflater.from(BrowserActivity.this);
2983 final View warningsView =
2984 factory.inflate(R.layout.ssl_warnings, null);
2985 final LinearLayout placeholder =
2986 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2987
2988 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2989 LinearLayout ll = (LinearLayout)factory
2990 .inflate(R.layout.ssl_warning, null);
2991 ((TextView)ll.findViewById(R.id.warning))
2992 .setText(R.string.ssl_untrusted);
2993 placeholder.addView(ll);
2994 }
2995
2996 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2997 LinearLayout ll = (LinearLayout)factory
2998 .inflate(R.layout.ssl_warning, null);
2999 ((TextView)ll.findViewById(R.id.warning))
3000 .setText(R.string.ssl_mismatch);
3001 placeholder.addView(ll);
3002 }
3003
3004 if (error.hasError(SslError.SSL_EXPIRED)) {
3005 LinearLayout ll = (LinearLayout)factory
3006 .inflate(R.layout.ssl_warning, null);
3007 ((TextView)ll.findViewById(R.id.warning))
3008 .setText(R.string.ssl_expired);
3009 placeholder.addView(ll);
3010 }
3011
3012 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3013 LinearLayout ll = (LinearLayout)factory
3014 .inflate(R.layout.ssl_warning, null);
3015 ((TextView)ll.findViewById(R.id.warning))
3016 .setText(R.string.ssl_not_yet_valid);
3017 placeholder.addView(ll);
3018 }
3019
3020 new AlertDialog.Builder(BrowserActivity.this)
3021 .setTitle(R.string.security_warning)
3022 .setIcon(android.R.drawable.ic_dialog_alert)
3023 .setView(warningsView)
3024 .setPositiveButton(R.string.ssl_continue,
3025 new DialogInterface.OnClickListener() {
3026 public void onClick(DialogInterface dialog, int whichButton) {
3027 handler.proceed();
3028 }
3029 })
3030 .setNeutralButton(R.string.view_certificate,
3031 new DialogInterface.OnClickListener() {
3032 public void onClick(DialogInterface dialog, int whichButton) {
3033 showSSLCertificateOnError(view, handler, error);
3034 }
3035 })
3036 .setNegativeButton(R.string.cancel,
3037 new DialogInterface.OnClickListener() {
3038 public void onClick(DialogInterface dialog, int whichButton) {
3039 handler.cancel();
3040 BrowserActivity.this.resetTitleAndRevertLockIcon();
3041 }
3042 })
3043 .setOnCancelListener(
3044 new DialogInterface.OnCancelListener() {
3045 public void onCancel(DialogInterface dialog) {
3046 handler.cancel();
3047 BrowserActivity.this.resetTitleAndRevertLockIcon();
3048 }
3049 })
3050 .show();
3051 } else {
3052 handler.proceed();
3053 }
3054 }
3055
3056 /**
3057 * Handles an HTTP authentication request.
3058 *
3059 * @param handler The authentication handler
3060 * @param host The host
3061 * @param realm The realm
3062 */
3063 @Override
3064 public void onReceivedHttpAuthRequest(WebView view,
3065 final HttpAuthHandler handler, final String host, final String realm) {
3066 String username = null;
3067 String password = null;
3068
3069 boolean reuseHttpAuthUsernamePassword =
3070 handler.useHttpAuthUsernamePassword();
3071
3072 if (reuseHttpAuthUsernamePassword &&
3073 (mTabControl.getCurrentWebView() != null)) {
3074 String[] credentials =
3075 mTabControl.getCurrentWebView()
3076 .getHttpAuthUsernamePassword(host, realm);
3077 if (credentials != null && credentials.length == 2) {
3078 username = credentials[0];
3079 password = credentials[1];
3080 }
3081 }
3082
3083 if (username != null && password != null) {
3084 handler.proceed(username, password);
3085 } else {
3086 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3087 }
3088 }
3089
3090 @Override
3091 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3092 if (mMenuIsDown) {
3093 // only check shortcut key when MENU is held
3094 return getWindow().isShortcutKey(event.getKeyCode(), event);
3095 } else {
3096 return false;
3097 }
3098 }
3099
3100 @Override
3101 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3102 if (view != mTabControl.getCurrentTopWebView()) {
3103 return;
3104 }
3105 if (event.isDown()) {
3106 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3107 } else {
3108 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3109 }
3110 }
3111 };
3112
3113 //--------------------------------------------------------------------------
3114 // WebChromeClient implementation
3115 //--------------------------------------------------------------------------
3116
3117 /* package */ WebChromeClient getWebChromeClient() {
3118 return mWebChromeClient;
3119 }
3120
3121 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3122 // Helper method to create a new tab or sub window.
3123 private void createWindow(final boolean dialog, final Message msg) {
3124 if (dialog) {
3125 mTabControl.createSubWindow();
3126 final TabControl.Tab t = mTabControl.getCurrentTab();
3127 attachSubWindow(t);
3128 WebView.WebViewTransport transport =
3129 (WebView.WebViewTransport) msg.obj;
3130 transport.setWebView(t.getSubWebView());
3131 msg.sendToTarget();
3132 } else {
3133 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003134 final TabControl.Tab newTab
3135 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07003136 if (newTab != parent) {
3137 parent.addChildTab(newTab);
3138 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003139 WebView.WebViewTransport transport =
3140 (WebView.WebViewTransport) msg.obj;
3141 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04003142 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003143 }
3144 }
3145
3146 @Override
3147 public boolean onCreateWindow(WebView view, final boolean dialog,
3148 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003149 // Short-circuit if we can't create any more tabs or sub windows.
3150 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3151 new AlertDialog.Builder(BrowserActivity.this)
3152 .setTitle(R.string.too_many_subwindows_dialog_title)
3153 .setIcon(android.R.drawable.ic_dialog_alert)
3154 .setMessage(R.string.too_many_subwindows_dialog_message)
3155 .setPositiveButton(R.string.ok, null)
3156 .show();
3157 return false;
3158 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3159 new AlertDialog.Builder(BrowserActivity.this)
3160 .setTitle(R.string.too_many_windows_dialog_title)
3161 .setIcon(android.R.drawable.ic_dialog_alert)
3162 .setMessage(R.string.too_many_windows_dialog_message)
3163 .setPositiveButton(R.string.ok, null)
3164 .show();
3165 return false;
3166 }
3167
3168 // Short-circuit if this was a user gesture.
3169 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003170 createWindow(dialog, resultMsg);
3171 return true;
3172 }
3173
3174 // Allow the popup and create the appropriate window.
3175 final AlertDialog.OnClickListener allowListener =
3176 new AlertDialog.OnClickListener() {
3177 public void onClick(DialogInterface d,
3178 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003179 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003180 }
3181 };
3182
3183 // Block the popup by returning a null WebView.
3184 final AlertDialog.OnClickListener blockListener =
3185 new AlertDialog.OnClickListener() {
3186 public void onClick(DialogInterface d, int which) {
3187 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003188 }
3189 };
3190
3191 // Build a confirmation dialog to display to the user.
3192 final AlertDialog d =
3193 new AlertDialog.Builder(BrowserActivity.this)
3194 .setTitle(R.string.attention)
3195 .setIcon(android.R.drawable.ic_dialog_alert)
3196 .setMessage(R.string.popup_window_attempt)
3197 .setPositiveButton(R.string.allow, allowListener)
3198 .setNegativeButton(R.string.block, blockListener)
3199 .setCancelable(false)
3200 .create();
3201
3202 // Show the confirmation dialog.
3203 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003204 return true;
3205 }
3206
3207 @Override
3208 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003209 final TabControl.Tab current = mTabControl.getCurrentTab();
3210 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003211 if (parent != null) {
3212 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003213 switchToTab(mTabControl.getTabIndex(parent));
3214 // Now we need to close the window
3215 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003216 }
3217 }
3218
3219 @Override
3220 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003221 mTitleBar.setProgress(newProgress);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003222 if (mFakeTitleBar != null) {
3223 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003224 }
3225
3226 if (newProgress == 100) {
Ben Murdochaac7aa62009-09-17 16:57:40 +01003227 // onProgressChanged() may continue to be called after the main
3228 // frame has finished loading, as any remaining sub frames
3229 // continue to load. We'll only get called once though with
3230 // newProgress as 100 when everything is loaded.
3231 // (onPageFinished is called once when the main frame completes
3232 // loading regardless of the state of any sub frames so calls
3233 // to onProgressChanges may continue after onPageFinished has
3234 // executed)
3235
3236 // sync cookies and cache promptly here.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003237 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003238 if (mInLoad) {
3239 mInLoad = false;
3240 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003241 // If the options menu is open, leave the title bar
3242 if (!mOptionsMenuOpen || !mIconView) {
3243 hideFakeTitleBar();
3244 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003245 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003246 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003247 // onPageFinished may have already been called but a subframe
3248 // is still loading and updating the progress. Reset mInLoad
3249 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003250 mInLoad = true;
3251 updateInLoadMenuItems();
Leon Scroggins184f5e32009-09-21 10:38:24 -04003252 if (!mOptionsMenuOpen || mIconView) {
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003253 // This page has begun to load, so show the title bar
3254 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003255 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003256 }
3257 }
3258
3259 @Override
3260 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003261 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003262
3263 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003264 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003265
3266 if (url == null ||
3267 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3268 return;
3269 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003270 // See if we can find the current url in our history database and
3271 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003272 if (url.startsWith("http://www.")) {
3273 url = url.substring(11);
3274 } else if (url.startsWith("http://")) {
3275 url = url.substring(4);
3276 }
Mats Mattsson73d30332010-02-12 15:28:23 +01003277 // Escape wildcards for LIKE operator.
3278 url = url.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003279 try {
3280 url = "%" + url;
3281 String [] selArgs = new String[] { url };
3282
Mats Mattsson73d30332010-02-12 15:28:23 +01003283 String where = Browser.BookmarkColumns.URL + " LIKE ? ESCAPE '\\' AND "
The Android Open Source Project0c908882009-03-03 19:32:16 -08003284 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3285 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3286 Browser.HISTORY_PROJECTION, where, selArgs, null);
3287 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003288 // Current implementation of database only has one entry per
3289 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003290 ContentValues map = new ContentValues();
3291 map.put(Browser.BookmarkColumns.TITLE, title);
3292 mResolver.update(Browser.BOOKMARKS_URI, map,
3293 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003294 }
3295 c.close();
3296 } catch (IllegalStateException e) {
3297 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3298 } catch (SQLiteException ex) {
3299 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3300 }
3301 }
3302
3303 @Override
3304 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003305 updateIcon(view, icon);
3306 }
3307
3308 @Override
Patrick Scott59ce8302009-09-18 16:29:38 -04003309 public void onReceivedTouchIconUrl(WebView view, String url,
3310 boolean precomposed) {
Patrick Scott3918d442009-08-04 13:22:29 -04003311 final ContentResolver cr = getContentResolver();
3312 final Cursor c =
3313 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003314 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003315 if (c != null) {
3316 if (c.getCount() > 0) {
Patrick Scott59ce8302009-09-18 16:29:38 -04003317 // Let precomposed icons take precedence over non-composed
3318 // icons.
3319 if (precomposed && mTouchIconLoader != null) {
3320 mTouchIconLoader.cancel(false);
3321 mTouchIconLoader = null;
3322 }
3323 // Have only one async task at a time.
3324 if (mTouchIconLoader == null) {
3325 mTouchIconLoader = new DownloadTouchIcon(
3326 BrowserActivity.this, cr, c, view);
3327 mTouchIconLoader.execute(url);
3328 }
Patrick Scott3918d442009-08-04 13:22:29 -04003329 } else {
3330 c.close();
3331 }
3332 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003333 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003334
Andrei Popescuadc008d2009-06-26 14:11:30 +01003335 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003336 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003337 if (mCustomView != null)
3338 return;
3339
3340 // Add the custom view to its container.
3341 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3342 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003343 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003344 // Save the menu state and set it to empty while the custom
3345 // view is showing.
3346 mOldMenuState = mMenuState;
3347 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003348 // Hide the content view.
3349 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003350 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003351 mCustomViewContainer.setVisibility(View.VISIBLE);
3352 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003353 }
3354
3355 @Override
3356 public void onHideCustomView() {
3357 if (mCustomView == null)
3358 return;
3359
Andrei Popescuc9b55562009-07-07 10:51:15 +01003360 // Hide the custom view.
3361 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003362 // Remove the custom view from its container.
3363 mCustomViewContainer.removeView(mCustomView);
3364 mCustomView = null;
3365 // Reset the old menu state.
3366 mMenuState = mOldMenuState;
3367 mOldMenuState = EMPTY_MENU;
3368 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003369 mCustomViewCallback.onCustomViewHidden();
3370 // Show the content view.
3371 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003372 }
3373
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003374 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003375 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003376 * @param url the URL that exceeded the quota
3377 * @param databaseIdentifier the identifier of the database on
3378 * which the transaction that caused the quota overflow was run
3379 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003380 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003381 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003382 * @param quotaUpdater The callback to run when a decision to allow or
3383 * deny quota has been made. Don't forget to call this!
3384 */
3385 @Override
3386 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003387 String databaseIdentifier, long currentQuota, long estimatedSize,
3388 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003389 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003390 url, databaseIdentifier, currentQuota, estimatedSize,
3391 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003392 }
3393
3394 /**
3395 * The Application Cache has exceeded its max size.
3396 * @param spaceNeeded is the amount of disk space that would be needed
3397 * in order for the last appcache operation to succeed.
3398 * @param totalUsedQuota is the sum of all origins' quota.
3399 * @param quotaUpdater A callback to inform the WebCore thread that a new
3400 * app cache size is available. This callback must always be executed at
3401 * some point to ensure that the sleeping WebCore thread is woken up.
3402 */
3403 @Override
3404 public void onReachedMaxAppCacheSize(long spaceNeeded,
3405 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3406 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3407 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003408 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003409
Steve Block2bc69912009-07-30 14:45:13 +01003410 /**
3411 * Instructs the browser to show a prompt to ask the user to set the
3412 * Geolocation permission state for the specified origin.
3413 * @param origin The origin for which Geolocation permissions are
3414 * requested.
3415 * @param callback The callback to call once the user has set the
3416 * Geolocation permission state.
3417 */
3418 @Override
3419 public void onGeolocationPermissionsShowPrompt(String origin,
3420 GeolocationPermissions.Callback callback) {
3421 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3422 origin, callback);
3423 }
3424
3425 /**
3426 * Instructs the browser to hide the Geolocation permissions prompt.
3427 */
3428 @Override
3429 public void onGeolocationPermissionsHidePrompt() {
3430 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3431 }
3432
Ben Murdochc44c7a62009-11-19 18:16:04 +00003433 /* Adds a JavaScript error message to the system log and if the JS
3434 * console is enabled in the about:debug options, to that console
3435 * also.
Ben Murdoch7db26342009-06-03 18:21:19 +01003436 * @param message The error message to report.
3437 * @param lineNumber The line number of the error.
3438 * @param sourceID The name of the source file that caused the error.
3439 */
3440 @Override
Ben Murdochc44c7a62009-11-19 18:16:04 +00003441 public void onConsoleMessage(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003442 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3443 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3444 if (mShouldShowErrorConsole &&
3445 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3446 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3447 }
3448 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003449 }
Andrei Popescu540035d2009-09-18 18:59:20 +01003450
3451 /**
3452 * Ask the browser for an icon to represent a <video> element.
3453 * This icon will be used if the Web page did not specify a poster attribute.
3454 *
3455 * @return Bitmap The icon or null if no such icon is available.
3456 * @hide pending API Council approval
3457 */
3458 @Override
3459 public Bitmap getDefaultVideoPoster() {
3460 if (mDefaultVideoPoster == null) {
3461 mDefaultVideoPoster = BitmapFactory.decodeResource(
3462 getResources(), R.drawable.default_video_poster);
3463 }
3464 return mDefaultVideoPoster;
3465 }
3466
3467 /**
3468 * Ask the host application for a custom progress view to show while
3469 * a <video> is loading.
3470 *
3471 * @return View The progress view.
3472 * @hide pending API Council approval
3473 */
3474 @Override
3475 public View getVideoLoadingProgressView() {
3476 if (mVideoProgressView == null) {
3477 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
3478 mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
3479 }
3480 return mVideoProgressView;
3481 }
Leon Clarkecb6cc862009-09-29 18:35:13 +01003482
3483 /**
3484 * Deliver a list of already-visited URLs
3485 * @hide pending API Council approval
3486 */
3487 @Override
3488 public void getVisitedHistory(final ValueCallback<String[]> callback) {
3489 AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
3490 public String[] doInBackground(Void... unused) {
3491 return Browser.getVisitedHistory(getContentResolver());
3492 }
3493
3494 public void onPostExecute(String[] result) {
3495 callback.onReceiveValue(result);
3496
3497 };
3498 };
3499 task.execute();
3500 };
The Android Open Source Project0c908882009-03-03 19:32:16 -08003501 };
3502
3503 /**
3504 * Notify the host application a download should be done, or that
3505 * the data should be streamed if a streaming viewer is available.
3506 * @param url The full url to the content that should be downloaded
3507 * @param contentDisposition Content-disposition http header, if
3508 * present.
3509 * @param mimetype The mimetype of the content reported by the server
3510 * @param contentLength The file size reported by the server
3511 */
3512 public void onDownloadStart(String url, String userAgent,
3513 String contentDisposition, String mimetype, long contentLength) {
3514 // if we're dealing wih A/V content that's not explicitly marked
3515 // for download, check if it's streamable.
3516 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003517 || !contentDisposition.regionMatches(
3518 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003519 // query the package manager to see if there's a registered handler
3520 // that matches.
3521 Intent intent = new Intent(Intent.ACTION_VIEW);
3522 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003523 ResolveInfo info = getPackageManager().resolveActivity(intent,
3524 PackageManager.MATCH_DEFAULT_ONLY);
3525 if (info != null) {
3526 ComponentName myName = getComponentName();
3527 // If we resolved to ourselves, we don't want to attempt to
3528 // load the url only to try and download it again.
3529 if (!myName.getPackageName().equals(
3530 info.activityInfo.packageName)
3531 || !myName.getClassName().equals(
3532 info.activityInfo.name)) {
3533 // someone (other than us) knows how to handle this mime
3534 // type with this scheme, don't download.
3535 try {
3536 startActivity(intent);
3537 return;
3538 } catch (ActivityNotFoundException ex) {
3539 if (LOGD_ENABLED) {
3540 Log.d(LOGTAG, "activity not found for " + mimetype
3541 + " over " + Uri.parse(url).getScheme(),
3542 ex);
3543 }
3544 // Best behavior is to fall back to a download in this
3545 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003546 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003547 }
3548 }
3549 }
3550 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3551 }
3552
3553 /**
3554 * Notify the host application a download should be done, even if there
3555 * is a streaming viewer available for thise type.
3556 * @param url The full url to the content that should be downloaded
3557 * @param contentDisposition Content-disposition http header, if
3558 * present.
3559 * @param mimetype The mimetype of the content reported by the server
3560 * @param contentLength The file size reported by the server
3561 */
3562 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3563 String contentDisposition, String mimetype, long contentLength) {
3564
3565 String filename = URLUtil.guessFileName(url,
3566 contentDisposition, mimetype);
3567
3568 // Check to see if we have an SDCard
3569 String status = Environment.getExternalStorageState();
3570 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3571 int title;
3572 String msg;
3573
3574 // Check to see if the SDCard is busy, same as the music app
3575 if (status.equals(Environment.MEDIA_SHARED)) {
3576 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3577 title = R.string.download_sdcard_busy_dlg_title;
3578 } else {
3579 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3580 title = R.string.download_no_sdcard_dlg_title;
3581 }
3582
3583 new AlertDialog.Builder(this)
3584 .setTitle(title)
3585 .setIcon(android.R.drawable.ic_dialog_alert)
3586 .setMessage(msg)
3587 .setPositiveButton(R.string.ok, null)
3588 .show();
3589 return;
3590 }
3591
3592 // java.net.URI is a lot stricter than KURL so we have to undo
3593 // KURL's percent-encoding and redo the encoding using java.net.URI.
3594 URI uri = null;
3595 try {
3596 // Undo the percent-encoding that KURL may have done.
3597 String newUrl = new String(URLUtil.decode(url.getBytes()));
3598 // Parse the url into pieces
3599 WebAddress w = new WebAddress(newUrl);
3600 String frag = null;
3601 String query = null;
3602 String path = w.mPath;
3603 // Break the path into path, query, and fragment
3604 if (path.length() > 0) {
3605 // Strip the fragment
3606 int idx = path.lastIndexOf('#');
3607 if (idx != -1) {
3608 frag = path.substring(idx + 1);
3609 path = path.substring(0, idx);
3610 }
3611 idx = path.lastIndexOf('?');
3612 if (idx != -1) {
3613 query = path.substring(idx + 1);
3614 path = path.substring(0, idx);
3615 }
3616 }
3617 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3618 query, frag);
3619 } catch (Exception e) {
3620 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3621 return;
3622 }
3623
3624 // XXX: Have to use the old url since the cookies were stored using the
3625 // old percent-encoded url.
3626 String cookies = CookieManager.getInstance().getCookie(url);
3627
3628 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003629 values.put(Downloads.COLUMN_URI, uri.toString());
3630 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3631 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3632 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003633 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003634 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003635 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003636 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3637 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3638 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3639 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003640 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003641 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003642 }
3643 if (mimetype == null) {
3644 // We must have long pressed on a link or image to download it. We
3645 // are not sure of the mimetype in this case, so do a head request
3646 new FetchUrlMimeType(this).execute(values);
3647 } else {
3648 final Uri contentUri =
3649 getContentResolver().insert(Downloads.CONTENT_URI, values);
3650 viewDownloads(contentUri);
3651 }
3652
3653 }
3654
3655 /**
3656 * Resets the lock icon. This method is called when we start a new load and
3657 * know the url to be loaded.
3658 */
3659 private void resetLockIcon(String url) {
3660 // Save the lock-icon state (we revert to it if the load gets cancelled)
3661 saveLockIcon();
3662
3663 mLockIconType = LOCK_ICON_UNSECURE;
3664 if (URLUtil.isHttpsUrl(url)) {
3665 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003666 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003667 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3668 " reset lock icon to " + mLockIconType);
3669 }
3670 }
3671
3672 updateLockIconImage(LOCK_ICON_UNSECURE);
3673 }
3674
Grace Klobaeb6eef42009-09-15 17:56:32 -07003675 /* package */ void setLockIconType(int type) {
3676 mLockIconType = type;
3677 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003678
Grace Klobaeb6eef42009-09-15 17:56:32 -07003679 /* package */ int getLockIconType() {
3680 return mLockIconType;
3681 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003682
Grace Klobaeb6eef42009-09-15 17:56:32 -07003683 /* package */ void setPrevLockType(int type) {
3684 mPrevLockType = type;
3685 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003686
Grace Klobaeb6eef42009-09-15 17:56:32 -07003687 /* package */ int getPrevLockType() {
3688 return mPrevLockType;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003689 }
3690
3691 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003692 * Update the lock icon to correspond to our latest state.
3693 */
3694 /* package */ void updateLockIconToLatest() {
3695 updateLockIconImage(mLockIconType);
3696 }
3697
3698 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003699 * Updates the lock-icon image in the title-bar.
3700 */
3701 private void updateLockIconImage(int lockIconType) {
3702 Drawable d = null;
3703 if (lockIconType == LOCK_ICON_SECURE) {
3704 d = mSecLockIcon;
3705 } else if (lockIconType == LOCK_ICON_MIXED) {
3706 d = mMixLockIcon;
3707 }
Leon Scroggins68579392009-09-15 15:31:54 -04003708 mTitleBar.setLock(d);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003709 if (mFakeTitleBar != null) {
3710 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003711 }
3712 }
3713
3714 /**
3715 * Displays a page-info dialog.
3716 * @param tab The tab to show info about
3717 * @param fromShowSSLCertificateOnError The flag that indicates whether
3718 * this dialog was opened from the SSL-certificate-on-error dialog or
3719 * not. This is important, since we need to know whether to return to
3720 * the parent dialog or simply dismiss.
3721 */
3722 private void showPageInfo(final TabControl.Tab tab,
3723 final boolean fromShowSSLCertificateOnError) {
3724 final LayoutInflater factory = LayoutInflater
3725 .from(this);
3726
3727 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3728
3729 final WebView view = tab.getWebView();
3730
3731 String url = null;
3732 String title = null;
3733
3734 if (view == null) {
3735 url = tab.getUrl();
3736 title = tab.getTitle();
3737 } else if (view == mTabControl.getCurrentWebView()) {
3738 // Use the cached title and url if this is the current WebView
3739 url = mUrl;
3740 title = mTitle;
3741 } else {
3742 url = view.getUrl();
3743 title = view.getTitle();
3744 }
3745
3746 if (url == null) {
3747 url = "";
3748 }
3749 if (title == null) {
3750 title = "";
3751 }
3752
3753 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3754 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3755
3756 mPageInfoView = tab;
Henrik Baard4e0b6182010-04-21 12:31:47 +02003757 mPageInfoFromShowSSLCertificateOnError = Boolean.valueOf(fromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003758
3759 AlertDialog.Builder alertDialogBuilder =
3760 new AlertDialog.Builder(this)
3761 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3762 .setView(pageInfoView)
3763 .setPositiveButton(
3764 R.string.ok,
3765 new DialogInterface.OnClickListener() {
3766 public void onClick(DialogInterface dialog,
3767 int whichButton) {
3768 mPageInfoDialog = null;
3769 mPageInfoView = null;
3770 mPageInfoFromShowSSLCertificateOnError = null;
3771
3772 // if we came here from the SSL error dialog
3773 if (fromShowSSLCertificateOnError) {
3774 // go back to the SSL error dialog
3775 showSSLCertificateOnError(
3776 mSSLCertificateOnErrorView,
3777 mSSLCertificateOnErrorHandler,
3778 mSSLCertificateOnErrorError);
3779 }
3780 }
3781 })
3782 .setOnCancelListener(
3783 new DialogInterface.OnCancelListener() {
3784 public void onCancel(DialogInterface dialog) {
3785 mPageInfoDialog = null;
3786 mPageInfoView = null;
3787 mPageInfoFromShowSSLCertificateOnError = null;
3788
3789 // if we came here from the SSL error dialog
3790 if (fromShowSSLCertificateOnError) {
3791 // go back to the SSL error dialog
3792 showSSLCertificateOnError(
3793 mSSLCertificateOnErrorView,
3794 mSSLCertificateOnErrorHandler,
3795 mSSLCertificateOnErrorError);
3796 }
3797 }
3798 });
3799
3800 // if we have a main top-level page SSL certificate set or a certificate
3801 // error
3802 if (fromShowSSLCertificateOnError ||
3803 (view != null && view.getCertificate() != null)) {
3804 // add a 'View Certificate' button
3805 alertDialogBuilder.setNeutralButton(
3806 R.string.view_certificate,
3807 new DialogInterface.OnClickListener() {
3808 public void onClick(DialogInterface dialog,
3809 int whichButton) {
3810 mPageInfoDialog = null;
3811 mPageInfoView = null;
3812 mPageInfoFromShowSSLCertificateOnError = null;
3813
3814 // if we came here from the SSL error dialog
3815 if (fromShowSSLCertificateOnError) {
3816 // go back to the SSL error dialog
3817 showSSLCertificateOnError(
3818 mSSLCertificateOnErrorView,
3819 mSSLCertificateOnErrorHandler,
3820 mSSLCertificateOnErrorError);
3821 } else {
3822 // otherwise, display the top-most certificate from
3823 // the chain
3824 if (view.getCertificate() != null) {
3825 showSSLCertificate(tab);
3826 }
3827 }
3828 }
3829 });
3830 }
3831
3832 mPageInfoDialog = alertDialogBuilder.show();
3833 }
3834
3835 /**
3836 * Displays the main top-level page SSL certificate dialog
3837 * (accessible from the Page-Info dialog).
3838 * @param tab The tab to show certificate for.
3839 */
3840 private void showSSLCertificate(final TabControl.Tab tab) {
3841 final View certificateView =
3842 inflateCertificateView(tab.getWebView().getCertificate());
3843 if (certificateView == null) {
3844 return;
3845 }
3846
3847 LayoutInflater factory = LayoutInflater.from(this);
3848
3849 final LinearLayout placeholder =
3850 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3851
3852 LinearLayout ll = (LinearLayout) factory.inflate(
3853 R.layout.ssl_success, placeholder);
3854 ((TextView)ll.findViewById(R.id.success))
3855 .setText(R.string.ssl_certificate_is_valid);
3856
3857 mSSLCertificateView = tab;
3858 mSSLCertificateDialog =
3859 new AlertDialog.Builder(this)
3860 .setTitle(R.string.ssl_certificate).setIcon(
3861 R.drawable.ic_dialog_browser_certificate_secure)
3862 .setView(certificateView)
3863 .setPositiveButton(R.string.ok,
3864 new DialogInterface.OnClickListener() {
3865 public void onClick(DialogInterface dialog,
3866 int whichButton) {
3867 mSSLCertificateDialog = null;
3868 mSSLCertificateView = null;
3869
3870 showPageInfo(tab, false);
3871 }
3872 })
3873 .setOnCancelListener(
3874 new DialogInterface.OnCancelListener() {
3875 public void onCancel(DialogInterface dialog) {
3876 mSSLCertificateDialog = null;
3877 mSSLCertificateView = null;
3878
3879 showPageInfo(tab, false);
3880 }
3881 })
3882 .show();
3883 }
3884
3885 /**
3886 * Displays the SSL error certificate dialog.
3887 * @param view The target web-view.
3888 * @param handler The SSL error handler responsible for cancelling the
3889 * connection that resulted in an SSL error or proceeding per user request.
3890 * @param error The SSL error object.
3891 */
3892 private void showSSLCertificateOnError(
3893 final WebView view, final SslErrorHandler handler, final SslError error) {
3894
3895 final View certificateView =
3896 inflateCertificateView(error.getCertificate());
3897 if (certificateView == null) {
3898 return;
3899 }
3900
3901 LayoutInflater factory = LayoutInflater.from(this);
3902
3903 final LinearLayout placeholder =
3904 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3905
3906 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3907 LinearLayout ll = (LinearLayout)factory
3908 .inflate(R.layout.ssl_warning, placeholder);
3909 ((TextView)ll.findViewById(R.id.warning))
3910 .setText(R.string.ssl_untrusted);
3911 }
3912
3913 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3914 LinearLayout ll = (LinearLayout)factory
3915 .inflate(R.layout.ssl_warning, placeholder);
3916 ((TextView)ll.findViewById(R.id.warning))
3917 .setText(R.string.ssl_mismatch);
3918 }
3919
3920 if (error.hasError(SslError.SSL_EXPIRED)) {
3921 LinearLayout ll = (LinearLayout)factory
3922 .inflate(R.layout.ssl_warning, placeholder);
3923 ((TextView)ll.findViewById(R.id.warning))
3924 .setText(R.string.ssl_expired);
3925 }
3926
3927 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3928 LinearLayout ll = (LinearLayout)factory
3929 .inflate(R.layout.ssl_warning, placeholder);
3930 ((TextView)ll.findViewById(R.id.warning))
3931 .setText(R.string.ssl_not_yet_valid);
3932 }
3933
3934 mSSLCertificateOnErrorHandler = handler;
3935 mSSLCertificateOnErrorView = view;
3936 mSSLCertificateOnErrorError = error;
3937 mSSLCertificateOnErrorDialog =
3938 new AlertDialog.Builder(this)
3939 .setTitle(R.string.ssl_certificate).setIcon(
3940 R.drawable.ic_dialog_browser_certificate_partially_secure)
3941 .setView(certificateView)
3942 .setPositiveButton(R.string.ok,
3943 new DialogInterface.OnClickListener() {
3944 public void onClick(DialogInterface dialog,
3945 int whichButton) {
3946 mSSLCertificateOnErrorDialog = null;
3947 mSSLCertificateOnErrorView = null;
3948 mSSLCertificateOnErrorHandler = null;
3949 mSSLCertificateOnErrorError = null;
3950
3951 mWebViewClient.onReceivedSslError(
3952 view, handler, error);
3953 }
3954 })
3955 .setNeutralButton(R.string.page_info_view,
3956 new DialogInterface.OnClickListener() {
3957 public void onClick(DialogInterface dialog,
3958 int whichButton) {
3959 mSSLCertificateOnErrorDialog = null;
3960
3961 // do not clear the dialog state: we will
3962 // need to show the dialog again once the
3963 // user is done exploring the page-info details
3964
3965 showPageInfo(mTabControl.getTabFromView(view),
3966 true);
3967 }
3968 })
3969 .setOnCancelListener(
3970 new DialogInterface.OnCancelListener() {
3971 public void onCancel(DialogInterface dialog) {
3972 mSSLCertificateOnErrorDialog = null;
3973 mSSLCertificateOnErrorView = null;
3974 mSSLCertificateOnErrorHandler = null;
3975 mSSLCertificateOnErrorError = null;
3976
3977 mWebViewClient.onReceivedSslError(
3978 view, handler, error);
3979 }
3980 })
3981 .show();
3982 }
3983
3984 /**
3985 * Inflates the SSL certificate view (helper method).
3986 * @param certificate The SSL certificate.
3987 * @return The resultant certificate view with issued-to, issued-by,
3988 * issued-on, expires-on, and possibly other fields set.
3989 * If the input certificate is null, returns null.
3990 */
3991 private View inflateCertificateView(SslCertificate certificate) {
3992 if (certificate == null) {
3993 return null;
3994 }
3995
3996 LayoutInflater factory = LayoutInflater.from(this);
3997
3998 View certificateView = factory.inflate(
3999 R.layout.ssl_certificate, null);
4000
4001 // issued to:
4002 SslCertificate.DName issuedTo = certificate.getIssuedTo();
4003 if (issuedTo != null) {
4004 ((TextView) certificateView.findViewById(R.id.to_common))
4005 .setText(issuedTo.getCName());
4006 ((TextView) certificateView.findViewById(R.id.to_org))
4007 .setText(issuedTo.getOName());
4008 ((TextView) certificateView.findViewById(R.id.to_org_unit))
4009 .setText(issuedTo.getUName());
4010 }
4011
4012 // issued by:
4013 SslCertificate.DName issuedBy = certificate.getIssuedBy();
4014 if (issuedBy != null) {
4015 ((TextView) certificateView.findViewById(R.id.by_common))
4016 .setText(issuedBy.getCName());
4017 ((TextView) certificateView.findViewById(R.id.by_org))
4018 .setText(issuedBy.getOName());
4019 ((TextView) certificateView.findViewById(R.id.by_org_unit))
4020 .setText(issuedBy.getUName());
4021 }
4022
4023 // issued on:
4024 String issuedOn = reformatCertificateDate(
4025 certificate.getValidNotBefore());
4026 ((TextView) certificateView.findViewById(R.id.issued_on))
4027 .setText(issuedOn);
4028
4029 // expires on:
4030 String expiresOn = reformatCertificateDate(
4031 certificate.getValidNotAfter());
4032 ((TextView) certificateView.findViewById(R.id.expires_on))
4033 .setText(expiresOn);
4034
4035 return certificateView;
4036 }
4037
4038 /**
4039 * Re-formats the certificate date (Date.toString()) string to
4040 * a properly localized date string.
4041 * @return Properly localized version of the certificate date string and
4042 * the original certificate date string if fails to localize.
4043 * If the original string is null, returns an empty string "".
4044 */
4045 private String reformatCertificateDate(String certificateDate) {
4046 String reformattedDate = null;
4047
4048 if (certificateDate != null) {
4049 Date date = null;
4050 try {
4051 date = java.text.DateFormat.getInstance().parse(certificateDate);
4052 } catch (ParseException e) {
4053 date = null;
4054 }
4055
4056 if (date != null) {
4057 reformattedDate =
4058 DateFormat.getDateFormat(this).format(date);
4059 }
4060 }
4061
4062 return reformattedDate != null ? reformattedDate :
4063 (certificateDate != null ? certificateDate : "");
4064 }
4065
4066 /**
4067 * Displays an http-authentication dialog.
4068 */
4069 private void showHttpAuthentication(final HttpAuthHandler handler,
4070 final String host, final String realm, final String title,
4071 final String name, final String password, int focusId) {
4072 LayoutInflater factory = LayoutInflater.from(this);
4073 final View v = factory
4074 .inflate(R.layout.http_authentication, null);
4075 if (name != null) {
4076 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4077 }
4078 if (password != null) {
4079 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4080 }
4081
4082 String titleText = title;
4083 if (titleText == null) {
4084 titleText = getText(R.string.sign_in_to).toString().replace(
4085 "%s1", host).replace("%s2", realm);
4086 }
4087
4088 mHttpAuthHandler = handler;
4089 AlertDialog dialog = new AlertDialog.Builder(this)
4090 .setTitle(titleText)
4091 .setIcon(android.R.drawable.ic_dialog_alert)
4092 .setView(v)
4093 .setPositiveButton(R.string.action,
4094 new DialogInterface.OnClickListener() {
4095 public void onClick(DialogInterface dialog,
4096 int whichButton) {
4097 String nm = ((EditText) v
4098 .findViewById(R.id.username_edit))
4099 .getText().toString();
4100 String pw = ((EditText) v
4101 .findViewById(R.id.password_edit))
4102 .getText().toString();
4103 BrowserActivity.this.setHttpAuthUsernamePassword
4104 (host, realm, nm, pw);
4105 handler.proceed(nm, pw);
4106 mHttpAuthenticationDialog = null;
4107 mHttpAuthHandler = null;
4108 }})
4109 .setNegativeButton(R.string.cancel,
4110 new DialogInterface.OnClickListener() {
4111 public void onClick(DialogInterface dialog,
4112 int whichButton) {
4113 handler.cancel();
4114 BrowserActivity.this.resetTitleAndRevertLockIcon();
4115 mHttpAuthenticationDialog = null;
4116 mHttpAuthHandler = null;
4117 }})
4118 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4119 public void onCancel(DialogInterface dialog) {
4120 handler.cancel();
4121 BrowserActivity.this.resetTitleAndRevertLockIcon();
4122 mHttpAuthenticationDialog = null;
4123 mHttpAuthHandler = null;
4124 }})
4125 .create();
4126 // Make the IME appear when the dialog is displayed if applicable.
4127 dialog.getWindow().setSoftInputMode(
4128 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4129 dialog.show();
4130 if (focusId != 0) {
4131 dialog.findViewById(focusId).requestFocus();
4132 } else {
4133 v.findViewById(R.id.username_edit).requestFocus();
4134 }
4135 mHttpAuthenticationDialog = dialog;
4136 }
4137
4138 public int getProgress() {
4139 WebView w = mTabControl.getCurrentWebView();
4140 if (w != null) {
4141 return w.getProgress();
4142 } else {
4143 return 100;
4144 }
4145 }
4146
4147 /**
4148 * Set HTTP authentication password.
4149 *
4150 * @param host The host for the password
4151 * @param realm The realm for the password
4152 * @param username The username for the password. If it is null, it means
4153 * password can't be saved.
4154 * @param password The password
4155 */
4156 public void setHttpAuthUsernamePassword(String host, String realm,
4157 String username,
4158 String password) {
4159 WebView w = mTabControl.getCurrentWebView();
4160 if (w != null) {
4161 w.setHttpAuthUsernamePassword(host, realm, username, password);
4162 }
4163 }
4164
4165 /**
4166 * connectivity manager says net has come or gone... inform the user
4167 * @param up true if net has come up, false if net has gone down
4168 */
4169 public void onNetworkToggle(boolean up) {
4170 if (up == mIsNetworkUp) {
4171 return;
4172 } else if (up) {
4173 mIsNetworkUp = true;
4174 if (mAlertDialog != null) {
4175 mAlertDialog.cancel();
4176 mAlertDialog = null;
4177 }
4178 } else {
4179 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004180 if (mInLoad) {
4181 createAndShowNetworkDialog();
4182 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004183 }
4184 WebView w = mTabControl.getCurrentWebView();
4185 if (w != null) {
4186 w.setNetworkAvailable(up);
4187 }
4188 }
4189
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004190 // This method shows the network dialog alerting the user that the net is
4191 // down. It will only show the dialog if mAlertDialog is null.
4192 private void createAndShowNetworkDialog() {
4193 if (mAlertDialog == null) {
4194 mAlertDialog = new AlertDialog.Builder(this)
4195 .setTitle(R.string.loadSuspendedTitle)
4196 .setMessage(R.string.loadSuspended)
4197 .setPositiveButton(R.string.ok, null)
4198 .show();
4199 }
4200 }
4201
The Android Open Source Project0c908882009-03-03 19:32:16 -08004202 @Override
4203 protected void onActivityResult(int requestCode, int resultCode,
4204 Intent intent) {
4205 switch (requestCode) {
4206 case COMBO_PAGE:
4207 if (resultCode == RESULT_OK && intent != null) {
4208 String data = intent.getAction();
4209 Bundle extras = intent.getExtras();
4210 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04004211 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004212 } else {
4213 final TabControl.Tab currentTab =
4214 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04004215 dismissSubWindow(currentTab);
4216 if (data != null && data.length() != 0) {
4217 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004218 }
4219 }
4220 }
4221 break;
4222 default:
4223 break;
4224 }
Leon Scroggins30444232009-09-04 18:36:20 -04004225 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004226 }
4227
4228 /*
4229 * This method is called as a result of the user selecting the options
4230 * menu to see the download window, or when a download changes state. It
4231 * shows the download window ontop of the current window.
4232 */
4233 /* package */ void viewDownloads(Uri downloadRecord) {
4234 Intent intent = new Intent(this,
4235 BrowserDownloadPage.class);
4236 intent.setData(downloadRecord);
Christian Mehlmauerfdf5c2d2010-05-25 19:52:28 +02004237 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004238
4239 }
4240
Leon Scroggins160a7e72009-08-14 18:28:01 -04004241 /**
4242 * Open the Go page.
4243 * @param startWithHistory If true, open starting on the history tab.
4244 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004245 */
Leon Scroggins30444232009-09-04 18:36:20 -04004246 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004247 WebView current = mTabControl.getCurrentWebView();
4248 if (current == null) {
4249 return;
4250 }
4251 Intent intent = new Intent(this,
4252 CombinedBookmarkHistoryActivity.class);
4253 String title = current.getTitle();
4254 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004255 Bitmap thumbnail = createScreenshot(current);
4256
The Android Open Source Project0c908882009-03-03 19:32:16 -08004257 // Just in case the user opens bookmarks before a page finishes loading
4258 // so the current history item, and therefore the page, is null.
4259 if (null == url) {
4260 url = mLastEnteredUrl;
4261 // This can happen.
4262 if (null == url) {
4263 url = mSettings.getHomePage();
4264 }
4265 }
4266 // In case the web page has not yet received its associated title.
4267 if (title == null) {
4268 title = url;
4269 }
4270 intent.putExtra("title", title);
4271 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004272 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04004273 // Disable opening in a new window if we have maxed out the windows
4274 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4275 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004276 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004277 if (startWithHistory) {
4278 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4279 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4280 }
4281 startActivityForResult(intent, COMBO_PAGE);
4282 }
4283
4284 // Called when loading from context menu or LOAD_URL message
4285 private void loadURL(WebView view, String url) {
4286 // In case the user enters nothing.
4287 if (url != null && url.length() != 0 && view != null) {
4288 url = smartUrlFilter(url);
4289 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4290 view.loadUrl(url);
4291 }
4292 }
4293 }
4294
The Android Open Source Project0c908882009-03-03 19:32:16 -08004295 private String smartUrlFilter(Uri inUri) {
4296 if (inUri != null) {
4297 return smartUrlFilter(inUri.toString());
4298 }
4299 return null;
4300 }
4301
4302
4303 // get window count
4304
4305 int getWindowCount(){
4306 if(mTabControl != null){
4307 return mTabControl.getTabCount();
4308 }
4309 return 0;
4310 }
4311
Feng Qianb34f87a2009-03-24 21:27:26 -07004312 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004313 "(?i)" + // switch on case insensitive matching
4314 "(" + // begin group for schema
4315 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004316 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004317 ")" +
4318 "(.*)" );
4319
4320 /**
4321 * Attempts to determine whether user input is a URL or search
4322 * terms. Anything with a space is passed to search.
4323 *
4324 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4325 * "Http://" converts to "http://"
4326 *
4327 * @return Original or modified URL
4328 *
4329 */
4330 String smartUrlFilter(String url) {
4331
4332 String inUrl = url.trim();
4333 boolean hasSpace = inUrl.indexOf(' ') != -1;
4334
4335 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4336 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004337 // force scheme to lowercase
4338 String scheme = matcher.group(1);
4339 String lcScheme = scheme.toLowerCase();
4340 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004341 inUrl = lcScheme + matcher.group(2);
4342 }
4343 if (hasSpace) {
4344 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004345 }
4346 return inUrl;
4347 }
4348 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004349 // FIXME: Is this the correct place to add to searches?
4350 // what if someone else calls this function?
4351 int shortcut = parseUrlShortcut(inUrl);
4352 if (shortcut != SHORTCUT_INVALID) {
4353 Browser.addSearchUrl(mResolver, inUrl);
4354 String query = inUrl.substring(2);
4355 switch (shortcut) {
4356 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004357 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004358 case SHORTCUT_WIKIPEDIA_SEARCH:
4359 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4360 case SHORTCUT_DICTIONARY_SEARCH:
4361 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4362 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004363 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004364 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004365 }
4366 }
4367 } else {
4368 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4369 return URLUtil.guessUrl(inUrl);
4370 }
4371 }
4372
4373 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004374 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004375 }
4376
Ben Murdochbff2d602009-07-01 20:19:05 +01004377 /* package */ void setShouldShowErrorConsole(boolean flag) {
4378 if (flag == mShouldShowErrorConsole) {
4379 // Nothing to do.
4380 return;
4381 }
4382
4383 mShouldShowErrorConsole = flag;
4384
4385 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4386
4387 if (flag) {
4388 // Setting the show state of the console will cause it's the layout to be inflated.
4389 if (errorConsole.numberOfErrors() > 0) {
4390 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4391 } else {
4392 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4393 }
4394
4395 // Now we can add it to the main view.
4396 mErrorConsoleContainer.addView(errorConsole,
4397 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4398 ViewGroup.LayoutParams.WRAP_CONTENT));
4399 } else {
4400 mErrorConsoleContainer.removeView(errorConsole);
4401 }
4402
4403 }
4404
Grace Klobaeb6eef42009-09-15 17:56:32 -07004405 final static int LOCK_ICON_UNSECURE = 0;
4406 final static int LOCK_ICON_SECURE = 1;
4407 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004408
4409 private int mLockIconType = LOCK_ICON_UNSECURE;
4410 private int mPrevLockType = LOCK_ICON_UNSECURE;
4411
4412 private BrowserSettings mSettings;
4413 private TabControl mTabControl;
4414 private ContentResolver mResolver;
4415 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004416 private View mCustomView;
4417 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004418 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004419
4420 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4421 // view, we should rewrite this.
4422 private int mCurrentMenuState = 0;
4423 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004424 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004425 private static final int EMPTY_MENU = -1;
4426 private Menu mMenu;
4427
4428 private FindDialog mFindDialog;
4429 // Used to prevent chording to result in firing two shortcuts immediately
4430 // one after another. Fixes bug 1211714.
4431 boolean mCanChord;
4432
4433 private boolean mInLoad;
4434 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004435 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004436
4437 private boolean mPageStarted;
4438 private boolean mActivityInPause = true;
4439
4440 private boolean mMenuIsDown;
4441
The Android Open Source Project0c908882009-03-03 19:32:16 -08004442 private static boolean mInTrace;
4443
4444 // Performance probe
4445 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4446 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4447 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4448 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4449 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4450 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4451 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4452 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4453 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4454 };
4455
4456 private long mStart;
4457 private long mProcessStart;
4458 private long mUserStart;
4459 private long mSystemStart;
4460 private long mIdleStart;
4461 private long mIrqStart;
4462
4463 private long mUiStart;
4464
4465 private Drawable mMixLockIcon;
4466 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004467
4468 /* hold a ref so we can auto-cancel if necessary */
4469 private AlertDialog mAlertDialog;
4470
4471 // Wait for credentials before loading google.com
4472 private ProgressDialog mCredsDlg;
4473
4474 // The up-to-date URL and title (these can be different from those stored
4475 // in WebView, since it takes some time for the information in WebView to
4476 // get updated)
4477 private String mUrl;
4478 private String mTitle;
4479
4480 // As PageInfo has different style for landscape / portrait, we have
4481 // to re-open it when configuration changed
4482 private AlertDialog mPageInfoDialog;
4483 private TabControl.Tab mPageInfoView;
4484 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4485 // dialog, we should not just dismiss it, but should get back to the
4486 // SSL-certificate-on-error dialog. This flag is used to store this state
4487 private Boolean mPageInfoFromShowSSLCertificateOnError;
4488
4489 // as SSLCertificateOnError has different style for landscape / portrait,
4490 // we have to re-open it when configuration changed
4491 private AlertDialog mSSLCertificateOnErrorDialog;
4492 private WebView mSSLCertificateOnErrorView;
4493 private SslErrorHandler mSSLCertificateOnErrorHandler;
4494 private SslError mSSLCertificateOnErrorError;
4495
4496 // as SSLCertificate has different style for landscape / portrait, we
4497 // have to re-open it when configuration changed
4498 private AlertDialog mSSLCertificateDialog;
4499 private TabControl.Tab mSSLCertificateView;
4500
4501 // as HttpAuthentication has different style for landscape / portrait, we
4502 // have to re-open it when configuration changed
4503 private AlertDialog mHttpAuthenticationDialog;
4504 private HttpAuthHandler mHttpAuthHandler;
4505
4506 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4507 new FrameLayout.LayoutParams(
4508 ViewGroup.LayoutParams.FILL_PARENT,
4509 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004510 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4511 new FrameLayout.LayoutParams(
4512 ViewGroup.LayoutParams.FILL_PARENT,
4513 ViewGroup.LayoutParams.FILL_PARENT,
4514 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004515 // Google search
4516 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004517 // Wikipedia search
4518 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4519 // Dictionary search
4520 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4521 // Google Mobile Local search
4522 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4523
4524 final static String QUERY_PLACE_HOLDER = "%s";
4525
4526 // "source" parameter for Google search through search key
4527 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4528 // "source" parameter for Google search through goto menu
4529 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4530 // "source" parameter for Google search through simplily type
4531 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4532 // "source" parameter for Google search suggested by the browser
4533 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4534 // "source" parameter for Google search from unknown source
4535 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4536
4537 private final static String LOGTAG = "browser";
4538
The Android Open Source Project0c908882009-03-03 19:32:16 -08004539 private String mLastEnteredUrl;
4540
4541 private PowerManager.WakeLock mWakeLock;
4542 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4543
4544 private Toast mStopToast;
4545
Leon Scroggins68579392009-09-15 15:31:54 -04004546 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004547
Ben Murdochbff2d602009-07-01 20:19:05 +01004548 private LinearLayout mErrorConsoleContainer = null;
4549 private boolean mShouldShowErrorConsole = false;
4550
The Android Open Source Project0c908882009-03-03 19:32:16 -08004551 // As the ids are dynamically created, we can't guarantee that they will
4552 // be in sequence, so this static array maps ids to a window number.
4553 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4554 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4555 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4556 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4557
4558 // monitor platform changes
4559 private IntentFilter mNetworkStateChangedFilter;
4560 private BroadcastReceiver mNetworkStateIntentReceiver;
4561
Grace Klobab4da0ad2009-05-14 14:45:40 -07004562 private BroadcastReceiver mPackageInstallationReceiver;
4563
Patrick Scott59ce8302009-09-18 16:29:38 -04004564 // AsyncTask for downloading touch icons
4565 /* package */ DownloadTouchIcon mTouchIconLoader;
4566
The Android Open Source Project0c908882009-03-03 19:32:16 -08004567 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004568 final static int COMBO_PAGE = 1;
4569 final static int DOWNLOAD_PAGE = 2;
4570 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004571
Andrei Popescu540035d2009-09-18 18:59:20 +01004572 // the default <video> poster
4573 private Bitmap mDefaultVideoPoster;
4574 // the video progress view
4575 private View mVideoProgressView;
4576
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004577 /**
4578 * A UrlData class to abstract how the content will be set to WebView.
4579 * This base class uses loadUrl to show the content.
4580 */
4581 private static class UrlData {
4582 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004583 byte[] mPostData;
4584
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004585 UrlData(String url) {
4586 this.mUrl = url;
4587 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004588
4589 void setPostData(byte[] postData) {
4590 mPostData = postData;
4591 }
4592
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004593 boolean isEmpty() {
4594 return mUrl == null || mUrl.length() == 0;
4595 }
4596
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004597 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004598 if (mPostData != null) {
4599 webView.postUrl(mUrl, mPostData);
4600 } else {
4601 webView.loadUrl(mUrl);
4602 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004603 }
4604 };
4605
4606 /**
4607 * A subclass of UrlData class that can display inlined content using
4608 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4609 */
4610 private static class InlinedUrlData extends UrlData {
4611 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4612 super(failUrl);
4613 mInlined = inlined;
4614 mMimeType = mimeType;
4615 mEncoding = encoding;
4616 }
4617 String mMimeType;
4618 String mInlined;
4619 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004620 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004621 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004622 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004623 }
4624
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004625 @Override
4626 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004627 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4628 }
4629 }
4630
Leon Scroggins1f005d32009-08-10 17:36:42 -04004631 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004632}