blob: 0eeb60f680c748e6d37ada398db06e181a816283 [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
19import com.google.android.googleapps.IGoogleLoginService;
20import com.google.android.googlelogin.GoogleLoginServiceConstants;
21
22import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080023import android.app.AlertDialog;
24import android.app.ProgressDialog;
25import android.app.SearchManager;
26import android.content.ActivityNotFoundException;
27import android.content.BroadcastReceiver;
28import android.content.ComponentName;
29import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040030import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080031import android.content.ContentValues;
32import android.content.Context;
33import android.content.DialogInterface;
34import android.content.Intent;
35import android.content.IntentFilter;
36import android.content.ServiceConnection;
37import android.content.DialogInterface.OnCancelListener;
Grace Klobab4da0ad2009-05-14 14:45:40 -070038import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080039import android.content.pm.PackageManager;
40import android.content.pm.ResolveInfo;
41import android.content.res.AssetManager;
42import android.content.res.Configuration;
43import android.content.res.Resources;
44import android.database.Cursor;
45import android.database.sqlite.SQLiteDatabase;
46import android.database.sqlite.SQLiteException;
47import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010048import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.graphics.DrawFilter;
51import android.graphics.Paint;
52import android.graphics.PaintFlagsDrawFilter;
53import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040054import android.graphics.PixelFormat;
55import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080056import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080057import android.hardware.SensorListener;
58import android.hardware.SensorManager;
59import android.net.ConnectivityManager;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -040060import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080061import android.net.Uri;
62import android.net.WebAddress;
63import android.net.http.EventHandler;
64import android.net.http.SslCertificate;
65import android.net.http.SslError;
66import android.os.AsyncTask;
67import android.os.Bundle;
68import android.os.Debug;
69import android.os.Environment;
70import android.os.Handler;
71import android.os.IBinder;
72import android.os.Message;
73import android.os.PowerManager;
74import android.os.Process;
75import android.os.RemoteException;
76import android.os.ServiceManager;
77import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080078import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040079import android.provider.ContactsContract;
80import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080081import android.provider.Downloads;
82import android.provider.MediaStore;
The Android Open Source Project0c908882009-03-03 19:32:16 -080083import android.text.IClipboard;
84import android.text.TextUtils;
85import android.text.format.DateFormat;
86import android.text.util.Regex;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040087import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080088import android.util.Log;
89import android.view.ContextMenu;
90import android.view.Gravity;
91import android.view.KeyEvent;
92import android.view.LayoutInflater;
93import android.view.Menu;
94import android.view.MenuInflater;
95import android.view.MenuItem;
96import android.view.View;
97import android.view.ViewGroup;
98import android.view.Window;
99import android.view.WindowManager;
100import android.view.ContextMenu.ContextMenuInfo;
101import android.view.MenuItem.OnMenuItemClickListener;
102import android.view.animation.AlphaAnimation;
103import android.view.animation.Animation;
104import android.view.animation.AnimationSet;
105import android.view.animation.DecelerateInterpolator;
106import android.view.animation.ScaleAnimation;
107import android.view.animation.TranslateAnimation;
108import android.webkit.CookieManager;
109import android.webkit.CookieSyncManager;
110import android.webkit.DownloadListener;
Steve Block2bc69912009-07-30 14:45:13 +0100111import android.webkit.GeolocationPermissions;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800112import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -0700113import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800114import android.webkit.SslErrorHandler;
115import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +0100116import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import android.webkit.WebChromeClient;
Andrei Popescuc9b55562009-07-07 10:51:15 +0100118import android.webkit.WebChromeClient.CustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800119import android.webkit.WebHistoryItem;
120import android.webkit.WebIconDatabase;
Ben Murdoch092dd5d2009-04-22 12:34:12 +0100121import android.webkit.WebStorage;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800122import android.webkit.WebView;
123import android.webkit.WebViewClient;
124import android.widget.EditText;
125import android.widget.FrameLayout;
126import android.widget.LinearLayout;
127import android.widget.TextView;
128import android.widget.Toast;
129
130import java.io.BufferedOutputStream;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400131import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800132import java.io.File;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800133import java.io.IOException;
134import java.io.InputStream;
135import java.net.MalformedURLException;
136import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700137import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800138import java.net.URL;
139import java.net.URLEncoder;
140import java.text.ParseException;
141import java.util.Date;
142import java.util.Enumeration;
143import java.util.HashMap;
Patrick Scott37911c72009-03-24 18:02:58 -0700144import java.util.LinkedList;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800145import java.util.Vector;
146import java.util.regex.Matcher;
147import java.util.regex.Pattern;
148import java.util.zip.ZipEntry;
149import java.util.zip.ZipFile;
150
151public class BrowserActivity extends Activity
Grace Kloba5942df02009-09-18 11:48:29 -0700152 implements View.OnCreateContextMenuListener,
The Android Open Source Project0c908882009-03-03 19:32:16 -0800153 DownloadListener {
154
Dave Bort31a6d1c2009-04-13 15:56:49 -0700155 /* Define some aliases to make these debugging flags easier to refer to.
156 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
157 */
158 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
159 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
160 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
161
The Android Open Source Project0c908882009-03-03 19:32:16 -0800162 private IGoogleLoginService mGls = null;
163 private ServiceConnection mGlsConnection = null;
164
165 private SensorManager mSensorManager = null;
166
Satish Sampath565505b2009-05-29 15:37:27 +0100167 // These are single-character shortcuts for searching popular sources.
168 private static final int SHORTCUT_INVALID = 0;
169 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
170 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
171 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
172 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
173
The Android Open Source Project0c908882009-03-03 19:32:16 -0800174 /* Whitelisted webpages
175 private static HashSet<String> sWhiteList;
176
177 static {
178 sWhiteList = new HashSet<String>();
179 sWhiteList.add("cnn.com/");
180 sWhiteList.add("espn.go.com/");
181 sWhiteList.add("nytimes.com/");
182 sWhiteList.add("engadget.com/");
183 sWhiteList.add("yahoo.com/");
184 sWhiteList.add("msn.com/");
185 sWhiteList.add("amazon.com/");
186 sWhiteList.add("consumerist.com/");
187 sWhiteList.add("google.com/m/news");
188 }
189 */
190
191 private void setupHomePage() {
192 final Runnable getAccount = new Runnable() {
193 public void run() {
194 // Lower priority
195 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
196 // get the default home page
197 String homepage = mSettings.getHomePage();
198
199 try {
200 if (mGls == null) return;
201
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700202 if (!homepage.startsWith("http://www.google.")) return;
203 if (homepage.indexOf('?') == -1) return;
204
The Android Open Source Project0c908882009-03-03 19:32:16 -0800205 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
206 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
207
208 // three cases:
209 //
210 // hostedUser == googleUser
211 // The device has only a google account
212 //
213 // hostedUser != googleUser
214 // The device has a hosted account and a google account
215 //
216 // hostedUser != null, googleUser == null
217 // The device has only a hosted account (so far)
218
219 // developers might have no accounts at all
220 if (hostedUser == null) return;
221
222 if (googleUser == null || !hostedUser.equals(googleUser)) {
223 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700224 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800225 }
226 } catch (RemoteException ignore) {
227 // Login service died; carry on
228 } catch (RuntimeException ignore) {
229 // Login service died; carry on
230 } finally {
231 finish(homepage);
232 }
233 }
234
235 private void finish(final String homepage) {
236 mHandler.post(new Runnable() {
237 public void run() {
238 mSettings.setHomePage(BrowserActivity.this, homepage);
239 resumeAfterCredentials();
240
241 // as this is running in a separate thread,
242 // BrowserActivity's onDestroy() may have been called,
243 // which also calls unbindService().
244 if (mGlsConnection != null) {
245 // we no longer need to keep GLS open
246 unbindService(mGlsConnection);
247 mGlsConnection = null;
248 }
249 } });
250 } };
251
252 final boolean[] done = { false };
253
254 // Open a connection to the Google Login Service. The first
255 // time the connection is established, set up the homepage depending on
256 // the account in a background thread.
257 mGlsConnection = new ServiceConnection() {
258 public void onServiceConnected(ComponentName className, IBinder service) {
259 mGls = IGoogleLoginService.Stub.asInterface(service);
260 if (done[0] == false) {
261 done[0] = true;
262 Thread account = new Thread(getAccount);
263 account.setName("GLSAccount");
264 account.start();
265 }
266 }
267 public void onServiceDisconnected(ComponentName className) {
268 mGls = null;
269 }
270 };
271
272 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
273 mGlsConnection, Context.BIND_AUTO_CREATE);
274 }
275
Cary Clarka9771242009-08-11 16:42:26 -0400276 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800277 @Override
278 public Void doInBackground(File... files) {
279 if (files != null) {
280 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400281 if (!f.delete()) {
282 Log.e(LOGTAG, f.getPath() + " was not deleted");
283 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800284 }
285 }
286 return null;
287 }
288 }
289
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400290 /**
291 * This layout holds everything you see below the status bar, including the
292 * error console, the custom view container, and the webviews.
293 */
294 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400295
The Android Open Source Project0c908882009-03-03 19:32:16 -0800296 @Override public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700297 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800298 Log.v(LOGTAG, this + " onStart");
299 }
300 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800301 // test the browser in OpenGL
302 // requestWindowFeature(Window.FEATURE_OPENGL);
303
304 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
305
306 mResolver = getContentResolver();
307
Grace Kloba0923d692009-09-23 21:37:25 -0700308 // If this was a web search request, pass it on to the default web
309 // search provider and finish this activity.
310 if (handleWebSearchIntent(getIntent())) {
311 finish();
312 return;
313 }
314
The Android Open Source Project0c908882009-03-03 19:32:16 -0800315 //
316 // start MASF proxy service
317 //
318 //Intent proxyServiceIntent = new Intent();
319 //proxyServiceIntent.setComponent
320 // (new ComponentName(
321 // "com.android.masfproxyservice",
322 // "com.android.masfproxyservice.MasfProxyService"));
323 //startService(proxyServiceIntent, null);
324
325 mSecLockIcon = Resources.getSystem().getDrawable(
326 android.R.drawable.ic_secure);
327 mMixLockIcon = Resources.getSystem().getDrawable(
328 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800329
Leon Scroggins81db3662009-06-04 17:45:11 -0400330 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
331 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400332 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
333 .inflate(R.layout.custom_screen, null);
334 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
335 R.id.main_content);
336 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
337 .findViewById(R.id.error_console);
338 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
339 .findViewById(R.id.fullscreen_custom_content);
340 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400341 mTitleBar = new TitleBar(this);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400342 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800343
344 // Create the tab control and our initial tab
345 mTabControl = new TabControl(this);
346
347 // Open the icon database and retain all the bookmark urls for favicons
348 retainIconsOnStartup();
349
350 // Keep a settings instance handy.
351 mSettings = BrowserSettings.getInstance();
352 mSettings.setTabControl(mTabControl);
353 mSettings.loadFromDb(this);
354
355 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
356 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
357
Grace Klobaa34f6862009-07-31 16:28:17 -0700358 /* enables registration for changes in network status from
359 http stack */
360 mNetworkStateChangedFilter = new IntentFilter();
361 mNetworkStateChangedFilter.addAction(
362 ConnectivityManager.CONNECTIVITY_ACTION);
363 mNetworkStateIntentReceiver = new BroadcastReceiver() {
364 @Override
365 public void onReceive(Context context, Intent intent) {
366 if (intent.getAction().equals(
367 ConnectivityManager.CONNECTIVITY_ACTION)) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -0400368 NetworkInfo info =
369 (NetworkInfo) intent.getParcelableExtra(
370 ConnectivityManager.EXTRA_NETWORK_INFO);
371 onNetworkToggle(
372 (info != null) ? info.isConnected() : false);
Grace Klobaa34f6862009-07-31 16:28:17 -0700373 }
374 }
375 };
376
Grace Kloba615c6c92009-08-03 10:22:44 -0700377 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
378 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
379 filter.addDataScheme("package");
380 mPackageInstallationReceiver = new BroadcastReceiver() {
381 @Override
382 public void onReceive(Context context, Intent intent) {
383 final String action = intent.getAction();
384 final String packageName = intent.getData()
385 .getSchemeSpecificPart();
386 final boolean replacing = intent.getBooleanExtra(
387 Intent.EXTRA_REPLACING, false);
388 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
389 // if it is replacing, refreshPlugins() when adding
390 return;
391 }
392 PackageManager pm = BrowserActivity.this.getPackageManager();
393 PackageInfo pkgInfo = null;
394 try {
395 pkgInfo = pm.getPackageInfo(packageName,
396 PackageManager.GET_PERMISSIONS);
397 } catch (PackageManager.NameNotFoundException e) {
398 return;
399 }
400 if (pkgInfo != null) {
401 String permissions[] = pkgInfo.requestedPermissions;
402 if (permissions == null) {
403 return;
404 }
405 boolean permissionOk = false;
406 for (String permit : permissions) {
407 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
408 permissionOk = true;
409 break;
410 }
411 }
412 if (permissionOk) {
413 PluginManager.getInstance(BrowserActivity.this)
414 .refreshPlugins(
415 Intent.ACTION_PACKAGE_ADDED
416 .equals(action));
417 }
418 }
419 }
420 };
421 registerReceiver(mPackageInstallationReceiver, filter);
422
The Android Open Source Project0c908882009-03-03 19:32:16 -0800423 if (!mTabControl.restoreState(icicle)) {
424 // clear up the thumbnail directory if we can't restore the state as
425 // none of the files in the directory are referenced any more.
426 new ClearThumbnails().execute(
427 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700428 // there is no quit on Android. But if we can't restore the state,
429 // we can treat it as a new Browser, remove the old session cookies.
430 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800431 final Intent intent = getIntent();
432 final Bundle extra = intent.getExtras();
433 // Create an initial tab.
434 // If the intent is ACTION_VIEW and data is not null, the Browser is
435 // invoked to view the content by another application. In this case,
436 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700437 UrlData urlData = getUrlDataFromIntent(intent);
438
The Android Open Source Project0c908882009-03-03 19:32:16 -0800439 final TabControl.Tab t = mTabControl.createNewTab(
440 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700441 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700442 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800443 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800444 attachTabToContentView(t);
445 WebView webView = t.getWebView();
446 if (extra != null) {
447 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
448 if (scale > 0 && scale <= 1000) {
449 webView.setInitialScale(scale);
450 }
451 }
452 // If we are not restoring from an icicle, then there is a high
453 // likely hood this is the first run. So, check to see if the
454 // homepage needs to be configured and copy any plugins from our
455 // asset directory to the data partition.
456 if ((extra == null || !extra.getBoolean("testing"))
457 && !mSettings.isLoginInitialized()) {
458 setupHomePage();
459 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800460
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700461 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400462 if (mSettings.isLoginInitialized()) {
463 webView.loadUrl(mSettings.getHomePage());
464 } else {
465 waitForCredentials();
466 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800467 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700468 if (extra != null) {
469 urlData.setPostData(extra
470 .getByteArray(Browser.EXTRA_POST_DATA));
471 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700472 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800473 }
474 } else {
475 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400476 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800477 attachTabToContentView(mTabControl.getCurrentTab());
478 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700479
Feng Qianb3c02da2009-06-29 15:58:08 -0700480 // Read JavaScript flags if it exists.
481 String jsFlags = mSettings.getJsFlags();
482 if (jsFlags.trim().length() != 0) {
483 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
484 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800485 }
486
487 @Override
488 protected void onNewIntent(Intent intent) {
489 TabControl.Tab current = mTabControl.getCurrentTab();
490 // When a tab is closed on exit, the current tab index is set to -1.
491 // Reset before proceed as Browser requires the current tab to be set.
492 if (current == null) {
493 // Try to reset the tab in case the index was incorrect.
494 current = mTabControl.getTab(0);
495 if (current == null) {
496 // No tabs at all so just ignore this intent.
497 return;
498 }
499 mTabControl.setCurrentTab(current);
500 attachTabToContentView(current);
501 resetTitleAndIcon(current.getWebView());
502 }
503 final String action = intent.getAction();
504 final int flags = intent.getFlags();
505 if (Intent.ACTION_MAIN.equals(action) ||
506 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
507 // just resume the browser
508 return;
509 }
510 if (Intent.ACTION_VIEW.equals(action)
511 || Intent.ACTION_SEARCH.equals(action)
512 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
513 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100514 // If this was a search request (e.g. search query directly typed into the address bar),
515 // pass it on to the default web search provider.
516 if (handleWebSearchIntent(intent)) {
517 return;
518 }
519
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700520 UrlData urlData = getUrlDataFromIntent(intent);
521 if (urlData.isEmpty()) {
522 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800523 }
Grace Kloba81678d92009-06-30 07:09:56 -0700524 urlData.setPostData(intent
525 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700526
Grace Klobacc634032009-07-28 15:58:19 -0700527 final String appId = intent
528 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
529 if (Intent.ACTION_VIEW.equals(action)
530 && !getPackageName().equals(appId)
531 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Patrick Scottcd115892009-07-16 09:42:58 -0400532 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700533 if (appTab != null) {
534 Log.i(LOGTAG, "Reusing tab for " + appId);
535 // Dismiss the subwindow if applicable.
536 dismissSubWindow(appTab);
537 // Since we might kill the WebView, remove it from the
538 // content view first.
539 removeTabFromContentView(appTab);
540 // Recreate the main WebView after destroying the old one.
541 // If the WebView has the same original url and is on that
542 // page, it can be reused.
543 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700544 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100545
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700546 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400547 switchToTab(mTabControl.getTabIndex(appTab));
548 if (needsLoad) {
549 urlData.loadIn(appTab.getWebView());
550 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700551 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400552 // If the tab was the current tab, we have to attach
553 // it to the view system again.
554 attachTabToContentView(appTab);
555 if (needsLoad) {
556 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700557 }
558 }
559 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400560 } else {
561 // No matching application tab, try to find a regular tab
562 // with a matching url.
563 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400564 if (appTab != null) {
565 if (current != appTab) {
566 switchToTab(mTabControl.getTabIndex(appTab));
567 }
568 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400569 } else {
570 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
571 // will be opened in a new tab unless we have reached
572 // MAX_TABS. Then the url will be opened in the current
573 // tab. If a new tab is created, it will have "true" for
574 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400575 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400576 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700577 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800578 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700579 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800580 mSettings.toggleDebugSettings();
581 return;
582 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400583 // Get rid of the subwindow if it exists
584 dismissSubWindow(current);
585 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800586 }
587 }
588 }
589
Satish Sampath565505b2009-05-29 15:37:27 +0100590 private int parseUrlShortcut(String url) {
591 if (url == null) return SHORTCUT_INVALID;
592
593 // FIXME: quick search, need to be customized by setting
594 if (url.length() > 2 && url.charAt(1) == ' ') {
595 switch (url.charAt(0)) {
596 case 'g': return SHORTCUT_GOOGLE_SEARCH;
597 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
598 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
599 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
600 }
601 }
602 return SHORTCUT_INVALID;
603 }
604
605 /**
606 * Launches the default web search activity with the query parameters if the given intent's data
607 * are identified as plain search terms and not URLs/shortcuts.
608 * @return true if the intent was handled and web search activity was launched, false if not.
609 */
610 private boolean handleWebSearchIntent(Intent intent) {
611 if (intent == null) return false;
612
613 String url = null;
614 final String action = intent.getAction();
615 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700616 Uri data = intent.getData();
617 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100618 } else if (Intent.ACTION_SEARCH.equals(action)
619 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
620 || Intent.ACTION_WEB_SEARCH.equals(action)) {
621 url = intent.getStringExtra(SearchManager.QUERY);
622 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100623 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
624 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100625 }
626
627 /**
628 * Launches the default web search activity with the query parameters if the given url string
629 * was identified as plain search terms and not URL/shortcut.
630 * @return true if the request was handled and web search activity was launched, false if not.
631 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100632 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100633 if (inUrl == null) return false;
634
635 // In general, we shouldn't modify URL from Intent.
636 // But currently, we get the user-typed URL from search box as well.
637 String url = fixUrl(inUrl).trim();
638
639 // URLs and site specific search shortcuts are handled by the regular flow of control, so
640 // return early.
641 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100642 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100643 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
644 return false;
645 }
646
647 Browser.updateVisitedHistory(mResolver, url, false);
648 Browser.addSearchUrl(mResolver, url);
649
650 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
651 intent.addCategory(Intent.CATEGORY_DEFAULT);
652 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100653 if (appData != null) {
654 intent.putExtra(SearchManager.APP_DATA, appData);
655 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100656 if (extraData != null) {
657 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
658 }
Grace Klobacc634032009-07-28 15:58:19 -0700659 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100660 startActivity(intent);
661
662 return true;
663 }
664
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700665 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800666 String url = null;
667 if (intent != null) {
668 final String action = intent.getAction();
669 if (Intent.ACTION_VIEW.equals(action)) {
670 url = smartUrlFilter(intent.getData());
671 if (url != null && url.startsWith("content:")) {
672 /* Append mimetype so webview knows how to display */
673 String mimeType = intent.resolveType(getContentResolver());
674 if (mimeType != null) {
675 url += "?" + mimeType;
676 }
677 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700678 if ("inline:".equals(url)) {
679 return new InlinedUrlData(
680 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
681 intent.getType(),
682 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
683 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
684 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800685 } else if (Intent.ACTION_SEARCH.equals(action)
686 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
687 || Intent.ACTION_WEB_SEARCH.equals(action)) {
688 url = intent.getStringExtra(SearchManager.QUERY);
689 if (url != null) {
690 mLastEnteredUrl = url;
691 // Don't add Urls, just search terms.
692 // Urls will get added when the page is loaded.
693 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
694 Browser.updateVisitedHistory(mResolver, url, false);
695 }
696 // In general, we shouldn't modify URL from Intent.
697 // But currently, we get the user-typed URL from search box as well.
698 url = fixUrl(url);
699 url = smartUrlFilter(url);
700 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
701 if (url.contains(searchSource)) {
702 String source = null;
703 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
704 if (appData != null) {
705 source = appData.getString(SearchManager.SOURCE);
706 }
707 if (TextUtils.isEmpty(source)) {
708 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
709 }
710 url = url.replace(searchSource, "&source=android-"+source+"&");
711 }
712 }
713 }
714 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700715 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800716 }
717
718 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400719 // FIXME: Converting the url to lower case
720 // duplicates functionality in smartUrlFilter().
721 // However, changing all current callers of fixUrl to
722 // call smartUrlFilter in addition may have unwanted
723 // consequences, and is deferred for now.
724 int colon = inUrl.indexOf(':');
725 boolean allLower = true;
726 for (int index = 0; index < colon; index++) {
727 char ch = inUrl.charAt(index);
728 if (!Character.isLetter(ch)) {
729 break;
730 }
731 allLower &= Character.isLowerCase(ch);
732 if (index == colon - 1 && !allLower) {
733 inUrl = inUrl.substring(0, colon).toLowerCase()
734 + inUrl.substring(colon);
735 }
736 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800737 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
738 return inUrl;
739 if (inUrl.startsWith("http:") ||
740 inUrl.startsWith("https:")) {
741 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
742 inUrl = inUrl.replaceFirst("/", "//");
743 } else inUrl = inUrl.replaceFirst(":", "://");
744 }
745 return inUrl;
746 }
747
748 /**
749 * Looking for the pattern like this
750 *
751 * *
752 * * *
753 * *** * *******
754 * * *
755 * * *
756 * *
757 */
758 private final SensorListener mSensorListener = new SensorListener() {
759 private long mLastGestureTime;
760 private float[] mPrev = new float[3];
761 private float[] mPrevDiff = new float[3];
762 private float[] mDiff = new float[3];
763 private float[] mRevertDiff = new float[3];
764
765 public void onSensorChanged(int sensor, float[] values) {
766 boolean show = false;
767 float[] diff = new float[3];
768
769 for (int i = 0; i < 3; i++) {
770 diff[i] = values[i] - mPrev[i];
771 if (Math.abs(diff[i]) > 1) {
772 show = true;
773 }
774 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
775 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
776 // start track when there is a big move, or revert
777 mRevertDiff[i] = mDiff[i];
778 mDiff[i] = 0;
779 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
780 // reset when it is flat
781 mDiff[i] = mRevertDiff[i] = 0;
782 }
783 mDiff[i] += diff[i];
784 mPrevDiff[i] = diff[i];
785 mPrev[i] = values[i];
786 }
787
788 if (false) {
789 // only shows if we think the delta is big enough, in an attempt
790 // to detect "serious" moves left/right or up/down
791 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
792 + values[0] + ", " + values[1] + ", " + values[2] + ")"
793 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
794 + ")");
795 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
796 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
797 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
798 + mRevertDiff[2] + ")");
799 }
800
801 long now = android.os.SystemClock.uptimeMillis();
802 if (now - mLastGestureTime > 1000) {
803 mLastGestureTime = 0;
804
805 float y = mDiff[1];
806 float z = mDiff[2];
807 float ay = Math.abs(y);
808 float az = Math.abs(z);
809 float ry = mRevertDiff[1];
810 float rz = mRevertDiff[2];
811 float ary = Math.abs(ry);
812 float arz = Math.abs(rz);
813 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
814 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
815
816 if ((gestY || gestZ) && !(gestY && gestZ)) {
817 WebView view = mTabControl.getCurrentWebView();
818
819 if (view != null) {
820 if (gestZ) {
821 if (z < 0) {
822 view.zoomOut();
823 } else {
824 view.zoomIn();
825 }
826 } else {
827 view.flingScroll(0, Math.round(y * 100));
828 }
829 }
830 mLastGestureTime = now;
831 }
832 }
833 }
834
835 public void onAccuracyChanged(int sensor, int accuracy) {
836 // TODO Auto-generated method stub
837
838 }
839 };
840
841 @Override protected void onResume() {
842 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700843 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800844 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
845 }
846
847 if (!mActivityInPause) {
848 Log.e(LOGTAG, "BrowserActivity is already resumed.");
849 return;
850 }
851
Mike Reed7bfa63b2009-05-28 11:08:32 -0400852 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800853 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400854 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800855
856 if (mWakeLock.isHeld()) {
857 mHandler.removeMessages(RELEASE_WAKELOCK);
858 mWakeLock.release();
859 }
860
861 if (mCredsDlg != null) {
862 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
863 // In case credential request never comes back
864 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
865 }
866 }
867
868 registerReceiver(mNetworkStateIntentReceiver,
869 mNetworkStateChangedFilter);
870 WebView.enablePlatformNotifications();
871
872 if (mSettings.doFlick()) {
873 if (mSensorManager == null) {
874 mSensorManager = (SensorManager) getSystemService(
875 Context.SENSOR_SERVICE);
876 }
877 mSensorManager.registerListener(mSensorListener,
878 SensorManager.SENSOR_ACCELEROMETER,
879 SensorManager.SENSOR_DELAY_FASTEST);
880 } else {
881 mSensorManager = null;
882 }
883 }
884
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400885 /**
886 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400887 * would change its appearance, use a different TitleBar to show overlayed
888 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400889 */
890 private TitleBar mFakeTitleBar;
891
892 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400893 * Holder for the fake title bar. It will have a foreground shadow, as well
894 * as a white background, so the fake title bar looks like the real one.
895 */
896 private ViewGroup mFakeTitleBarHolder;
897
898 /**
899 * Layout parameters for the fake title bar within mFakeTitleBarHolder
900 */
901 private FrameLayout.LayoutParams mFakeTitleBarParams
902 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400903 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400904 ViewGroup.LayoutParams.WRAP_CONTENT);
905 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400906 * Keeps track of whether the options menu is open. This is important in
907 * determining whether to show or hide the title bar overlay.
908 */
909 private boolean mOptionsMenuOpen;
910
911 /**
912 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
913 * of whether the configuration has changed. The first onMenuOpened call
914 * after a configuration change is simply a reopening of the same menu
915 * (i.e. mIconView did not change).
916 */
917 private boolean mConfigChanged;
918
919 /**
920 * Whether or not the options menu is in its smaller, icon menu form. When
921 * true, we want the title bar overlay to be up. When false, we do not.
922 * Only meaningful if mOptionsMenuOpen is true.
923 */
924 private boolean mIconView;
925
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400926 @Override
927 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400928 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
929 if (mOptionsMenuOpen) {
930 if (mConfigChanged) {
931 // We do not need to make any changes to the state of the
932 // title bar, since the only thing that happened was a
933 // change in orientation
934 mConfigChanged = false;
935 } else {
936 if (mIconView) {
937 // Switching the menu to expanded view, so hide the
938 // title bar.
939 hideFakeTitleBar();
940 mIconView = false;
941 } else {
942 // Switching the menu back to icon view, so show the
943 // title bar once again.
944 showFakeTitleBar();
945 mIconView = true;
946 }
947 }
948 } else {
949 // The options menu is closed, so open it, and show the title
950 showFakeTitleBar();
951 mOptionsMenuOpen = true;
952 mConfigChanged = false;
953 mIconView = true;
954 }
955 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400956 return true;
957 }
958
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400959 /**
960 * Special class used exclusively for the shadow drawn underneath the fake
961 * title bar. The shadow does not need to be drawn if the WebView
962 * underneath is scrolled to the top, because it will draw directly on top
963 * of the embedded shadow.
964 */
965 private static class Shadow extends View {
966 private WebView mWebView;
967
968 public Shadow(Context context, AttributeSet attrs) {
969 super(context, attrs);
970 }
971
972 public void setWebView(WebView view) {
973 mWebView = view;
974 }
975
976 @Override
977 public void draw(Canvas canvas) {
978 // In general onDraw is the method to override, but we care about
979 // whether or not the background gets drawn, which happens in draw()
980 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
981 super.draw(canvas);
982 }
983 // Need to invalidate so that if the scroll position changes, we
984 // still draw as appropriate.
985 invalidate();
986 }
987 }
988
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400989 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400990 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400991 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400992 && !mActivityInPause && decor != null
993 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400994 Rect visRect = new Rect();
995 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
996 if (LOGD_ENABLED) {
997 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
998 }
999 return;
1000 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001001
1002 WindowManager manager
1003 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
1004
1005 // Add the title bar to the window manager so it can receive touches
1006 // while the menu is up
1007 WindowManager.LayoutParams params
1008 = new WindowManager.LayoutParams(
1009 ViewGroup.LayoutParams.FILL_PARENT,
1010 ViewGroup.LayoutParams.WRAP_CONTENT,
1011 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
1012 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -04001013 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001014 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04001015 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -04001016 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -04001017 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001018 // XXX : Without providing an offset, the fake title bar will be
1019 // placed underneath the status bar. Use the global visible rect
1020 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -04001021 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -04001022 // Add a holder for the title bar. It also holds a shadow to show
1023 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001024 if (mFakeTitleBarHolder == null) {
1025 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
1026 .inflate(R.layout.title_bar_bg, null);
1027 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -04001028 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
1029 R.id.shadow);
1030 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -04001031 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001032 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001033 }
1034 }
1035
1036 @Override
1037 public void onOptionsMenuClosed(Menu menu) {
1038 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04001039 if (!mInLoad) {
1040 hideFakeTitleBar();
1041 } else if (!mIconView) {
1042 // The page is currently loading, and we are in expanded mode, so
1043 // we were not showing the menu. Show it once again. It will be
1044 // removed when the page finishes.
1045 showFakeTitleBar();
1046 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001047 }
1048 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001049 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -04001050 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
1051 mFakeTitleBarHolder.getLayoutParams();
1052 WebView mainView = mTabControl.getCurrentWebView();
1053 // Although we decided whether or not to animate based on the current
1054 // scroll position, the scroll position may have changed since the
1055 // fake title bar was displayed. Make sure it has the appropriate
1056 // animation/lack thereof before removing.
1057 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -04001058 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001059 WindowManager manager
1060 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -04001061 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001062 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1063 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001064 }
1065
The Android Open Source Project0c908882009-03-03 19:32:16 -08001066 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001067 * Special method for the fake title bar to call when displaying its context
1068 * menu, since it is in its own Window, and its parent does not show a
1069 * context menu.
1070 */
1071 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -04001072 if (null == mTitleBar.getParent()) {
1073 return;
1074 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001075 openContextMenu(mTitleBar);
1076 }
1077
1078 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001079 * onSaveInstanceState(Bundle map)
1080 * onSaveInstanceState is called right before onStop(). The map contains
1081 * the saved state.
1082 */
1083 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001084 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001085 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1086 }
1087 // the default implementation requires each view to have an id. As the
1088 // browser handles the state itself and it doesn't use id for the views,
1089 // don't call the default implementation. Otherwise it will trigger the
1090 // warning like this, "couldn't save which view has focus because the
1091 // focused view XXX has no id".
1092
1093 // Save all the tabs
1094 mTabControl.saveState(outState);
1095 }
1096
1097 @Override protected void onPause() {
1098 super.onPause();
1099
1100 if (mActivityInPause) {
1101 Log.e(LOGTAG, "BrowserActivity is already paused.");
1102 return;
1103 }
1104
Mike Reed7bfa63b2009-05-28 11:08:32 -04001105 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001106 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001107 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001108 mWakeLock.acquire();
1109 mHandler.sendMessageDelayed(mHandler
1110 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1111 }
1112
1113 // Clear the credentials toast if it is up
1114 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1115 mCredsDlg.dismiss();
1116 }
1117 mCredsDlg = null;
1118
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001119 // FIXME: This removes the active tabs page and resets the menu to
1120 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1121 // but then we would need to save it in onSaveInstanceState and restore
1122 // it in onCreate/onRestoreInstanceState
1123 if (mActiveTabsPage != null) {
1124 removeActiveTabPage(true);
1125 }
1126
The Android Open Source Project0c908882009-03-03 19:32:16 -08001127 cancelStopToast();
1128
1129 // unregister network state listener
1130 unregisterReceiver(mNetworkStateIntentReceiver);
1131 WebView.disablePlatformNotifications();
1132
1133 if (mSensorManager != null) {
1134 mSensorManager.unregisterListener(mSensorListener);
1135 }
1136 }
1137
1138 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001139 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001140 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1141 }
1142 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001143
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001144 if (mUploadMessage != null) {
1145 mUploadMessage.onReceiveValue(null);
1146 mUploadMessage = null;
1147 }
1148
Grace Kloba0923d692009-09-23 21:37:25 -07001149 if (mTabControl == null) return;
1150
The Android Open Source Project0c908882009-03-03 19:32:16 -08001151 // Remove the current tab and sub window
1152 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001153 if (t != null) {
1154 dismissSubWindow(t);
1155 removeTabFromContentView(t);
1156 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001157 // Destroy all the tabs
1158 mTabControl.destroy();
1159 WebIconDatabase.getInstance().close();
1160 if (mGlsConnection != null) {
1161 unbindService(mGlsConnection);
1162 mGlsConnection = null;
1163 }
1164
1165 //
1166 // stop MASF proxy service
1167 //
1168 //Intent proxyServiceIntent = new Intent();
1169 //proxyServiceIntent.setComponent
1170 // (new ComponentName(
1171 // "com.android.masfproxyservice",
1172 // "com.android.masfproxyservice.MasfProxyService"));
1173 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001174
1175 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001176 }
1177
1178 @Override
1179 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001180 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001181 super.onConfigurationChanged(newConfig);
1182
1183 if (mPageInfoDialog != null) {
1184 mPageInfoDialog.dismiss();
1185 showPageInfo(
1186 mPageInfoView,
1187 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1188 }
1189 if (mSSLCertificateDialog != null) {
1190 mSSLCertificateDialog.dismiss();
1191 showSSLCertificate(
1192 mSSLCertificateView);
1193 }
1194 if (mSSLCertificateOnErrorDialog != null) {
1195 mSSLCertificateOnErrorDialog.dismiss();
1196 showSSLCertificateOnError(
1197 mSSLCertificateOnErrorView,
1198 mSSLCertificateOnErrorHandler,
1199 mSSLCertificateOnErrorError);
1200 }
1201 if (mHttpAuthenticationDialog != null) {
1202 String title = ((TextView) mHttpAuthenticationDialog
1203 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1204 .toString();
1205 String name = ((TextView) mHttpAuthenticationDialog
1206 .findViewById(R.id.username_edit)).getText().toString();
1207 String password = ((TextView) mHttpAuthenticationDialog
1208 .findViewById(R.id.password_edit)).getText().toString();
1209 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1210 .getId();
1211 mHttpAuthenticationDialog.dismiss();
1212 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1213 name, password, focusId);
1214 }
1215 if (mFindDialog != null && mFindDialog.isShowing()) {
1216 mFindDialog.onConfigurationChanged(newConfig);
1217 }
1218 }
1219
1220 @Override public void onLowMemory() {
1221 super.onLowMemory();
1222 mTabControl.freeMemory();
1223 }
1224
Mike Reed7bfa63b2009-05-28 11:08:32 -04001225 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001226 if ((!mActivityInPause && !mPageStarted) ||
1227 (mActivityInPause && mPageStarted)) {
1228 CookieSyncManager.getInstance().startSync();
1229 WebView w = mTabControl.getCurrentWebView();
1230 if (w != null) {
1231 w.resumeTimers();
1232 }
1233 return true;
1234 } else {
1235 return false;
1236 }
1237 }
1238
Mike Reed7bfa63b2009-05-28 11:08:32 -04001239 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001240 if (mActivityInPause && !mPageStarted) {
1241 CookieSyncManager.getInstance().stopSync();
1242 WebView w = mTabControl.getCurrentWebView();
1243 if (w != null) {
1244 w.pauseTimers();
1245 }
1246 return true;
1247 } else {
1248 return false;
1249 }
1250 }
1251
Leon Scroggins1f005d32009-08-10 17:36:42 -04001252 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001253 /*
1254 * This function is called when we are launching for the first time. We
1255 * are waiting for the login credentials before loading Google home
1256 * pages. This way the user will be logged in straight away.
1257 */
1258 private void waitForCredentials() {
1259 // Show a toast
1260 mCredsDlg = new ProgressDialog(this);
1261 mCredsDlg.setIndeterminate(true);
1262 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1263 // If the user cancels the operation, then cancel the Google
1264 // Credentials request.
1265 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1266 mCredsDlg.show();
1267
1268 // We set a timeout for the retrieval of credentials in onResume()
1269 // as that is when we have freed up some CPU time to get
1270 // the login credentials.
1271 }
1272
1273 /*
1274 * If we have received the credentials or we have timed out and we are
1275 * showing the credentials dialog, then it is time to move on.
1276 */
1277 private void resumeAfterCredentials() {
1278 if (mCredsDlg == null) {
1279 return;
1280 }
1281
1282 // Clear the toast
1283 if (mCredsDlg.isShowing()) {
1284 mCredsDlg.dismiss();
1285 }
1286 mCredsDlg = null;
1287
1288 // Clear any pending timeout
1289 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1290
1291 // Load the page
1292 WebView w = mTabControl.getCurrentWebView();
1293 if (w != null) {
1294 w.loadUrl(mSettings.getHomePage());
1295 }
1296
1297 // Update the settings, need to do this last as it can take a moment
1298 // to persist the settings. In the mean time we could be loading
1299 // content.
1300 mSettings.setLoginInitialized(this);
1301 }
1302
1303 // Open the icon database and retain all the icons for visited sites.
1304 private void retainIconsOnStartup() {
1305 final WebIconDatabase db = WebIconDatabase.getInstance();
1306 db.open(getDir("icons", 0).getPath());
1307 try {
1308 Cursor c = Browser.getAllBookmarks(mResolver);
1309 if (!c.moveToFirst()) {
1310 c.deactivate();
1311 return;
1312 }
1313 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1314 do {
1315 String url = c.getString(urlIndex);
1316 db.retainIconForPageUrl(url);
1317 } while (c.moveToNext());
1318 c.deactivate();
1319 } catch (IllegalStateException e) {
1320 Log.e(LOGTAG, "retainIconsOnStartup", e);
1321 }
1322 }
1323
1324 // Helper method for getting the top window.
1325 WebView getTopWindow() {
1326 return mTabControl.getCurrentTopWebView();
1327 }
1328
1329 @Override
1330 public boolean onCreateOptionsMenu(Menu menu) {
1331 super.onCreateOptionsMenu(menu);
1332
1333 MenuInflater inflater = getMenuInflater();
1334 inflater.inflate(R.menu.browser, menu);
1335 mMenu = menu;
1336 updateInLoadMenuItems();
1337 return true;
1338 }
1339
1340 /**
1341 * As the menu can be open when loading state changes
1342 * we must manually update the state of the stop/reload menu
1343 * item
1344 */
1345 private void updateInLoadMenuItems() {
1346 if (mMenu == null) {
1347 return;
1348 }
1349 MenuItem src = mInLoad ?
1350 mMenu.findItem(R.id.stop_menu_id):
1351 mMenu.findItem(R.id.reload_menu_id);
1352 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1353 dest.setIcon(src.getIcon());
1354 dest.setTitle(src.getTitle());
1355 }
1356
1357 @Override
1358 public boolean onContextItemSelected(MenuItem item) {
1359 // chording is not an issue with context menus, but we use the same
1360 // options selector, so set mCanChord to true so we can access them.
1361 mCanChord = true;
1362 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001363 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001364 // For the context menu from the title bar
1365 case R.id.title_bar_share_page_url:
1366 case R.id.title_bar_copy_page_url:
1367 WebView mainView = mTabControl.getCurrentWebView();
1368 if (null == mainView) {
1369 return false;
1370 }
1371 if (id == R.id.title_bar_share_page_url) {
1372 Browser.sendString(this, mainView.getUrl());
1373 } else {
1374 copy(mainView.getUrl());
1375 }
1376 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001377 // -- Browser context menu
1378 case R.id.open_context_menu_id:
1379 case R.id.open_newtab_context_menu_id:
1380 case R.id.bookmark_context_menu_id:
1381 case R.id.save_link_context_menu_id:
1382 case R.id.share_link_context_menu_id:
1383 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001384 final WebView webView = getTopWindow();
1385 if (null == webView) {
1386 return false;
1387 }
1388 final HashMap hrefMap = new HashMap();
1389 hrefMap.put("webview", webView);
1390 final Message msg = mHandler.obtainMessage(
1391 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001392 webView.requestFocusNodeHref(msg);
1393 break;
1394
1395 default:
1396 // For other context menus
1397 return onOptionsItemSelected(item);
1398 }
1399 mCanChord = false;
1400 return true;
1401 }
1402
1403 private Bundle createGoogleSearchSourceBundle(String source) {
1404 Bundle bundle = new Bundle();
1405 bundle.putString(SearchManager.SOURCE, source);
1406 return bundle;
1407 }
1408
1409 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001410 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001411 */
1412 @Override
1413 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001414 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001415 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001416 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001417 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001418 return true;
1419 }
1420
1421 @Override
1422 public void startSearch(String initialQuery, boolean selectInitialQuery,
1423 Bundle appSearchData, boolean globalSearch) {
1424 if (appSearchData == null) {
1425 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1426 }
1427 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1428 }
1429
Leon Scroggins1f005d32009-08-10 17:36:42 -04001430 /**
1431 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1432 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001433 * @param index Index of the tab to change to, as defined by
1434 * mTabControl.getTabIndex(Tab t).
1435 * @return boolean True if we successfully switched to a different tab. If
1436 * the indexth tab is null, or if that tab is the same as
1437 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001438 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001439 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001440 TabControl.Tab tab = mTabControl.getTab(index);
1441 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1442 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001443 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001444 }
1445 if (currentTab != null) {
1446 // currentTab may be null if it was just removed. In that case,
1447 // we do not need to remove it
1448 removeTabFromContentView(currentTab);
1449 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001450 mTabControl.setCurrentTab(tab);
1451 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001452 resetTitleIconAndProgress();
1453 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001454 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001455 }
1456
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001457 /* package */ TabControl.Tab openTabToHomePage() {
1458 return openTabAndShow(mSettings.getHomePage(), false, null);
1459 }
1460
Leon Scroggins1f005d32009-08-10 17:36:42 -04001461 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001462 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001463 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001464 // This is the last tab. Open a new one, with the home
1465 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001466 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001467 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001468 return;
1469 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001470 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001471 int indexToShow = -1;
1472 if (parent != null) {
1473 indexToShow = mTabControl.getTabIndex(parent);
1474 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001475 final int currentIndex = mTabControl.getCurrentIndex();
1476 // Try to move to the tab to the right
1477 indexToShow = currentIndex + 1;
1478 if (indexToShow > mTabControl.getTabCount() - 1) {
1479 // Try to move to the tab to the left
1480 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001481 }
1482 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001483 if (switchToTab(indexToShow)) {
1484 // Close window
1485 closeTab(current);
1486 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001487 }
1488
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001489 private ActiveTabsPage mActiveTabsPage;
1490
1491 /**
1492 * Remove the active tabs page.
1493 * @param needToAttach If true, the active tabs page did not attach a tab
1494 * to the content view, so we need to do that here.
1495 */
1496 /* package */ void removeActiveTabPage(boolean needToAttach) {
1497 mContentView.removeView(mActiveTabsPage);
1498 mActiveTabsPage = null;
1499 mMenuState = R.id.MAIN_MENU;
1500 if (needToAttach) {
1501 attachTabToContentView(mTabControl.getCurrentTab());
1502 }
1503 getTopWindow().requestFocus();
1504 }
1505
The Android Open Source Project0c908882009-03-03 19:32:16 -08001506 @Override
1507 public boolean onOptionsItemSelected(MenuItem item) {
1508 if (!mCanChord) {
1509 // The user has already fired a shortcut with this hold down of the
1510 // menu key.
1511 return false;
1512 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001513 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001514 return false;
1515 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001516 if (mMenuIsDown) {
1517 // The shortcut action consumes the MENU. Even if it is still down,
1518 // it won't trigger the next shortcut action. In the case of the
1519 // shortcut action triggering a new activity, like Bookmarks, we
1520 // won't get onKeyUp for MENU. So it is important to reset it here.
1521 mMenuIsDown = false;
1522 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001523 switch (item.getItemId()) {
1524 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001525 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001526 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001527 break;
1528
Leon Scroggins64b80f32009-08-07 12:03:34 -04001529 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001530 onSearchRequested();
1531 break;
1532
1533 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001534 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001535 break;
1536
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001537 case R.id.active_tabs_menu_id:
1538 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1539 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001540 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001541 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1542 mActiveTabsPage.requestFocus();
1543 mMenuState = EMPTY_MENU;
1544 break;
1545
Leon Scroggins1f005d32009-08-10 17:36:42 -04001546 case R.id.add_bookmark_menu_id:
1547 Intent i = new Intent(BrowserActivity.this,
1548 AddBookmarkPage.class);
1549 WebView w = getTopWindow();
1550 i.putExtra("url", w.getUrl());
1551 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001552 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001553 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001554 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001555 break;
1556
1557 case R.id.stop_reload_menu_id:
1558 if (mInLoad) {
1559 stopLoading();
1560 } else {
1561 getTopWindow().reload();
1562 }
1563 break;
1564
1565 case R.id.back_menu_id:
1566 getTopWindow().goBack();
1567 break;
1568
1569 case R.id.forward_menu_id:
1570 getTopWindow().goForward();
1571 break;
1572
1573 case R.id.close_menu_id:
1574 // Close the subwindow if it exists.
1575 if (mTabControl.getCurrentSubWindow() != null) {
1576 dismissSubWindow(mTabControl.getCurrentTab());
1577 break;
1578 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001579 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001580 break;
1581
1582 case R.id.homepage_menu_id:
1583 TabControl.Tab current = mTabControl.getCurrentTab();
1584 if (current != null) {
1585 dismissSubWindow(current);
1586 current.getWebView().loadUrl(mSettings.getHomePage());
1587 }
1588 break;
1589
1590 case R.id.preferences_menu_id:
1591 Intent intent = new Intent(this,
1592 BrowserPreferencesPage.class);
1593 startActivityForResult(intent, PREFERENCES_PAGE);
1594 break;
1595
1596 case R.id.find_menu_id:
1597 if (null == mFindDialog) {
1598 mFindDialog = new FindDialog(this);
1599 }
1600 mFindDialog.setWebView(getTopWindow());
1601 mFindDialog.show();
1602 mMenuState = EMPTY_MENU;
1603 break;
1604
1605 case R.id.select_text_id:
1606 getTopWindow().emulateShiftHeld();
1607 break;
1608 case R.id.page_info_menu_id:
1609 showPageInfo(mTabControl.getCurrentTab(), false);
1610 break;
1611
1612 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001613 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001614 break;
1615
1616 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001617 Browser.sendString(this, getTopWindow().getUrl(),
1618 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001619 break;
1620
1621 case R.id.dump_nav_menu_id:
1622 getTopWindow().debugDump();
1623 break;
1624
1625 case R.id.zoom_in_menu_id:
1626 getTopWindow().zoomIn();
1627 break;
1628
1629 case R.id.zoom_out_menu_id:
1630 getTopWindow().zoomOut();
1631 break;
1632
1633 case R.id.view_downloads_menu_id:
1634 viewDownloads(null);
1635 break;
1636
The Android Open Source Project0c908882009-03-03 19:32:16 -08001637 case R.id.window_one_menu_id:
1638 case R.id.window_two_menu_id:
1639 case R.id.window_three_menu_id:
1640 case R.id.window_four_menu_id:
1641 case R.id.window_five_menu_id:
1642 case R.id.window_six_menu_id:
1643 case R.id.window_seven_menu_id:
1644 case R.id.window_eight_menu_id:
1645 {
1646 int menuid = item.getItemId();
1647 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1648 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1649 TabControl.Tab desiredTab = mTabControl.getTab(id);
1650 if (desiredTab != null &&
1651 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001652 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001653 }
1654 break;
1655 }
1656 }
1657 }
1658 break;
1659
1660 default:
1661 if (!super.onOptionsItemSelected(item)) {
1662 return false;
1663 }
1664 // Otherwise fall through.
1665 }
1666 mCanChord = false;
1667 return true;
1668 }
1669
1670 public void closeFind() {
1671 mMenuState = R.id.MAIN_MENU;
1672 }
1673
1674 @Override public boolean onPrepareOptionsMenu(Menu menu)
1675 {
1676 // This happens when the user begins to hold down the menu key, so
1677 // allow them to chord to get a shortcut.
1678 mCanChord = true;
1679 // Note: setVisible will decide whether an item is visible; while
1680 // setEnabled() will decide whether an item is enabled, which also means
1681 // whether the matching shortcut key will function.
1682 super.onPrepareOptionsMenu(menu);
1683 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001684 case EMPTY_MENU:
1685 if (mCurrentMenuState != mMenuState) {
1686 menu.setGroupVisible(R.id.MAIN_MENU, false);
1687 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1688 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001689 }
1690 break;
1691 default:
1692 if (mCurrentMenuState != mMenuState) {
1693 menu.setGroupVisible(R.id.MAIN_MENU, true);
1694 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1695 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001696 }
1697 final WebView w = getTopWindow();
1698 boolean canGoBack = false;
1699 boolean canGoForward = false;
1700 boolean isHome = false;
1701 if (w != null) {
1702 canGoBack = w.canGoBack();
1703 canGoForward = w.canGoForward();
1704 isHome = mSettings.getHomePage().equals(w.getUrl());
1705 }
1706 final MenuItem back = menu.findItem(R.id.back_menu_id);
1707 back.setEnabled(canGoBack);
1708
1709 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1710 home.setEnabled(!isHome);
1711
1712 menu.findItem(R.id.forward_menu_id)
1713 .setEnabled(canGoForward);
1714
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001715 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1716 mTabControl.getTabCount() < TabControl.MAX_TABS);
1717
The Android Open Source Project0c908882009-03-03 19:32:16 -08001718 // decide whether to show the share link option
1719 PackageManager pm = getPackageManager();
1720 Intent send = new Intent(Intent.ACTION_SEND);
1721 send.setType("text/plain");
1722 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1723 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1724
The Android Open Source Project0c908882009-03-03 19:32:16 -08001725 boolean isNavDump = mSettings.isNavDump();
1726 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1727 nav.setVisible(isNavDump);
1728 nav.setEnabled(isNavDump);
1729 break;
1730 }
1731 mCurrentMenuState = mMenuState;
1732 return true;
1733 }
1734
1735 @Override
1736 public void onCreateContextMenu(ContextMenu menu, View v,
1737 ContextMenuInfo menuInfo) {
1738 WebView webview = (WebView) v;
1739 WebView.HitTestResult result = webview.getHitTestResult();
1740 if (result == null) {
1741 return;
1742 }
1743
1744 int type = result.getType();
1745 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1746 Log.w(LOGTAG,
1747 "We should not show context menu when nothing is touched");
1748 return;
1749 }
1750 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1751 // let TextView handles context menu
1752 return;
1753 }
1754
1755 // Note, http://b/issue?id=1106666 is requesting that
1756 // an inflated menu can be used again. This is not available
1757 // yet, so inflate each time (yuk!)
1758 MenuInflater inflater = getMenuInflater();
1759 inflater.inflate(R.menu.browsercontext, menu);
1760
1761 // Show the correct menu group
1762 String extra = result.getExtra();
1763 menu.setGroupVisible(R.id.PHONE_MENU,
1764 type == WebView.HitTestResult.PHONE_TYPE);
1765 menu.setGroupVisible(R.id.EMAIL_MENU,
1766 type == WebView.HitTestResult.EMAIL_TYPE);
1767 menu.setGroupVisible(R.id.GEO_MENU,
1768 type == WebView.HitTestResult.GEO_TYPE);
1769 menu.setGroupVisible(R.id.IMAGE_MENU,
1770 type == WebView.HitTestResult.IMAGE_TYPE
1771 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1772 menu.setGroupVisible(R.id.ANCHOR_MENU,
1773 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1774 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1775
1776 // Setup custom handling depending on the type
1777 switch (type) {
1778 case WebView.HitTestResult.PHONE_TYPE:
1779 menu.setHeaderTitle(Uri.decode(extra));
1780 menu.findItem(R.id.dial_context_menu_id).setIntent(
1781 new Intent(Intent.ACTION_VIEW, Uri
1782 .parse(WebView.SCHEME_TEL + extra)));
1783 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1784 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001785 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001786 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1787 addIntent);
1788 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1789 new Copy(extra));
1790 break;
1791
1792 case WebView.HitTestResult.EMAIL_TYPE:
1793 menu.setHeaderTitle(extra);
1794 menu.findItem(R.id.email_context_menu_id).setIntent(
1795 new Intent(Intent.ACTION_VIEW, Uri
1796 .parse(WebView.SCHEME_MAILTO + extra)));
1797 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1798 new Copy(extra));
1799 break;
1800
1801 case WebView.HitTestResult.GEO_TYPE:
1802 menu.setHeaderTitle(extra);
1803 menu.findItem(R.id.map_context_menu_id).setIntent(
1804 new Intent(Intent.ACTION_VIEW, Uri
1805 .parse(WebView.SCHEME_GEO
1806 + URLEncoder.encode(extra))));
1807 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1808 new Copy(extra));
1809 break;
1810
1811 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1812 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1813 TextView titleView = (TextView) LayoutInflater.from(this)
1814 .inflate(android.R.layout.browser_link_context_header,
1815 null);
1816 titleView.setText(extra);
1817 menu.setHeaderView(titleView);
1818 // decide whether to show the open link in new tab option
1819 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1820 mTabControl.getTabCount() < TabControl.MAX_TABS);
1821 PackageManager pm = getPackageManager();
1822 Intent send = new Intent(Intent.ACTION_SEND);
1823 send.setType("text/plain");
1824 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1825 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1826 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1827 break;
1828 }
1829 // otherwise fall through to handle image part
1830 case WebView.HitTestResult.IMAGE_TYPE:
1831 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1832 menu.setHeaderTitle(extra);
1833 }
1834 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1835 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1836 menu.findItem(R.id.download_context_menu_id).
1837 setOnMenuItemClickListener(new Download(extra));
1838 break;
1839
1840 default:
1841 Log.w(LOGTAG, "We should not get here.");
1842 break;
1843 }
1844 }
1845
The Android Open Source Project0c908882009-03-03 19:32:16 -08001846 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001847 // this should only be called for the current tab.
The Android Open Source Project0c908882009-03-03 19:32:16 -08001848 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001849 // Attach the container that contains the main WebView and any other UI
1850 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001851 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001852
1853 if (mShouldShowErrorConsole) {
1854 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1855 if (errorConsole.numberOfErrors() == 0) {
1856 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1857 } else {
1858 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1859 }
1860
1861 mErrorConsoleContainer.addView(errorConsole,
1862 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1863 ViewGroup.LayoutParams.WRAP_CONTENT));
1864 }
1865
Grace Klobac928c302009-09-17 11:51:21 -07001866 setLockIconType(t.getLockIconType());
1867 setPrevLockType(t.getPrevLockIconType());
1868
1869 // this is to match the code in removeTabFromContentView()
1870 if (!mPageStarted && t.getTopWindow().getProgress() < 100) {
1871 mPageStarted = true;
Grace Klobaeb6eef42009-09-15 17:56:32 -07001872 }
1873
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001874 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001875 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001876 // Request focus on the top window.
1877 t.getTopWindow().requestFocus();
1878 }
1879
1880 // Attach a sub window to the main WebView of the given tab.
1881 private void attachSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001882 t.attachSubWindow(mContentView);
1883 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001884 }
1885
1886 // Remove the given tab from the content view.
1887 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001888 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001889 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001890
1891 if (mTabControl.getCurrentErrorConsole(false) != null) {
1892 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1893 }
1894
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001895 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001896 if (view != null) {
1897 view.setEmbeddedTitleBar(null);
1898 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001899
Grace Klobac928c302009-09-17 11:51:21 -07001900 // unlike attachTabToContentView(), removeTabFromContentView() can be
1901 // called for the non-current tab. Need to add the check.
Grace Klobaeb6eef42009-09-15 17:56:32 -07001902 if (t == mTabControl.getCurrentTab()) {
1903 t.setLockIconType(getLockIconType());
1904 t.setPrevLockIconType(getPrevLockType());
Grace Klobac928c302009-09-17 11:51:21 -07001905
1906 // this is not a perfect solution. But currently there is one
1907 // WebViewClient for all the WebView. if user switches from an
1908 // in-load window to an already loaded window, mPageStarted will not
1909 // be set to false. If user leaves the Browser, pauseWebViewTimers()
1910 // won't do anything and leaves the timer running even Browser is in
1911 // the background.
1912 if (mPageStarted) {
1913 mPageStarted = false;
1914 }
Grace Klobaeb6eef42009-09-15 17:56:32 -07001915 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001916 }
1917
1918 // Remove the sub window if it exists. Also called by TabControl when the
1919 // user clicks the 'X' to dismiss a sub window.
1920 /* package */ void dismissSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001921 t.removeSubWindow(mContentView);
1922 // Tell the TabControl to dismiss the subwindow. This will destroy
1923 // the WebView.
1924 mTabControl.dismissSubWindow(t);
1925 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001926 }
1927
Leon Scroggins1f005d32009-08-10 17:36:42 -04001928 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001929 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001930 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1931 String appId) {
1932 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001933 }
1934
1935 // This method does a ton of stuff. It will attempt to create a new tab
1936 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001937 // url isn't null, it will load the given url.
1938 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001939 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001940 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1941 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1942 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001943 final TabControl.Tab tab = mTabControl.createNewTab(
1944 closeOnExit, appId, urlData.mUrl);
1945 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001946 // If the last tab was removed from the active tabs page, currentTab
1947 // will be null.
1948 if (currentTab != null) {
1949 removeTabFromContentView(currentTab);
1950 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001951 // We must set the new tab as the current tab to reflect the old
1952 // animation behavior.
1953 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001954 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001955 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001956 urlData.loadIn(webview);
1957 }
1958 return tab;
1959 } else {
1960 // Get rid of the subwindow if it exists
1961 dismissSubWindow(currentTab);
1962 if (!urlData.isEmpty()) {
1963 // Load the given url.
1964 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001965 }
1966 }
Grace Klobac9181842009-04-14 08:53:22 -07001967 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001968 }
1969
Grace Klobac9181842009-04-14 08:53:22 -07001970 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001971 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001972 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001973 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001974 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001975 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001976 }
Grace Klobac9181842009-04-14 08:53:22 -07001977 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001978 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001979 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001980 }
1981 }
1982
1983 private class Copy implements OnMenuItemClickListener {
1984 private CharSequence mText;
1985
1986 public boolean onMenuItemClick(MenuItem item) {
1987 copy(mText);
1988 return true;
1989 }
1990
1991 public Copy(CharSequence toCopy) {
1992 mText = toCopy;
1993 }
1994 }
1995
1996 private class Download implements OnMenuItemClickListener {
1997 private String mText;
1998
1999 public boolean onMenuItemClick(MenuItem item) {
2000 onDownloadStartNoStream(mText, null, null, null, -1);
2001 return true;
2002 }
2003
2004 public Download(String toDownload) {
2005 mText = toDownload;
2006 }
2007 }
2008
2009 private void copy(CharSequence text) {
2010 try {
2011 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2012 if (clip != null) {
2013 clip.setClipboardText(text);
2014 }
2015 } catch (android.os.RemoteException e) {
2016 Log.e(LOGTAG, "Copy failed", e);
2017 }
2018 }
2019
2020 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002021 * Resets the browser title-view to whatever it must be
2022 * (for example, if we had a loading error)
2023 * When we have a new page, we call resetTitle, when we
2024 * have to reset the titlebar to whatever it used to be
2025 * (for example, if the user chose to stop loading), we
2026 * call resetTitleAndRevertLockIcon.
2027 */
2028 /* package */ void resetTitleAndRevertLockIcon() {
2029 revertLockIcon();
2030 resetTitleIconAndProgress();
2031 }
2032
2033 /**
2034 * Reset the title, favicon, and progress.
2035 */
2036 private void resetTitleIconAndProgress() {
2037 WebView current = mTabControl.getCurrentWebView();
2038 if (current == null) {
2039 return;
2040 }
2041 resetTitleAndIcon(current);
2042 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002043 mWebChromeClient.onProgressChanged(current, progress);
2044 }
2045
2046 // Reset the title and the icon based on the given item.
2047 private void resetTitleAndIcon(WebView view) {
2048 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2049 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002050 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002051 setFavicon(item.getFavicon());
2052 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002053 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002054 setFavicon(null);
2055 }
2056 }
2057
2058 /**
2059 * Sets a title composed of the URL and the title string.
2060 * @param url The URL of the site being loaded.
2061 * @param title The title of the site being loaded.
2062 */
Leon Scroggins68579392009-09-15 15:31:54 -04002063 private void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002064 mUrl = url;
2065 mTitle = title;
2066
Leon Scroggins68579392009-09-15 15:31:54 -04002067 mTitleBar.setTitleAndUrl(title, url);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002068 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002069 }
2070
2071 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002072 * @param url The URL to build a title version of the URL from.
2073 * @return The title version of the URL or null if fails.
2074 * The title version of the URL can be either the URL hostname,
2075 * or the hostname with an "https://" prefix (for secure URLs),
2076 * or an empty string if, for example, the URL in question is a
2077 * file:// URL with no hostname.
2078 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002079 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002080 String titleUrl = null;
2081
2082 if (url != null) {
2083 try {
2084 // parse the url string
2085 URL urlObj = new URL(url);
2086 if (urlObj != null) {
2087 titleUrl = "";
2088
2089 String protocol = urlObj.getProtocol();
2090 String host = urlObj.getHost();
2091
2092 if (host != null && 0 < host.length()) {
2093 titleUrl = host;
2094 if (protocol != null) {
2095 // if a secure site, add an "https://" prefix!
2096 if (protocol.equalsIgnoreCase("https")) {
2097 titleUrl = protocol + "://" + host;
2098 }
2099 }
2100 }
2101 }
2102 } catch (MalformedURLException e) {}
2103 }
2104
2105 return titleUrl;
2106 }
2107
2108 // Set the favicon in the title bar.
2109 private void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002110 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002111 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002112 }
2113
2114 /**
2115 * Saves the current lock-icon state before resetting
2116 * the lock icon. If we have an error, we may need to
2117 * roll back to the previous state.
2118 */
2119 private void saveLockIcon() {
2120 mPrevLockType = mLockIconType;
2121 }
2122
2123 /**
2124 * Reverts the lock-icon state to the last saved state,
2125 * for example, if we had an error, and need to cancel
2126 * the load.
2127 */
2128 private void revertLockIcon() {
2129 mLockIconType = mPrevLockType;
2130
Dave Bort31a6d1c2009-04-13 15:56:49 -07002131 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002132 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2133 " revert lock icon to " + mLockIconType);
2134 }
2135
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002136 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002137 }
2138
Leon Scroggins1f005d32009-08-10 17:36:42 -04002139 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002140 * Close the tab, remove its associated title bar, and adjust mTabControl's
2141 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002142 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002143 /* package */ void closeTab(TabControl.Tab t) {
2144 int currentIndex = mTabControl.getCurrentIndex();
2145 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002146 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002147 if (currentIndex >= removeIndex && currentIndex != 0) {
2148 currentIndex--;
2149 }
2150 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002151 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002152 }
2153
2154 private void goBackOnePageOrQuit() {
2155 TabControl.Tab current = mTabControl.getCurrentTab();
2156 if (current == null) {
2157 /*
2158 * Instead of finishing the activity, simply push this to the back
2159 * of the stack and let ActivityManager to choose the foreground
2160 * activity. As BrowserActivity is singleTask, it will be always the
2161 * root of the task. So we can use either true or false for
2162 * moveTaskToBack().
2163 */
2164 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002165 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002166 }
2167 WebView w = current.getWebView();
2168 if (w.canGoBack()) {
2169 w.goBack();
2170 } else {
2171 // Check to see if we are closing a window that was created by
2172 // another window. If so, we switch back to that window.
2173 TabControl.Tab parent = current.getParentTab();
2174 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002175 switchToTab(mTabControl.getTabIndex(parent));
2176 // Now we close the other tab
2177 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002178 } else {
2179 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002180 // force mPageStarted to be false as we are going to either
2181 // finish the activity or remove the tab. This will ensure
2182 // pauseWebView() taking action.
2183 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002184 if (mTabControl.getTabCount() == 1) {
2185 finish();
2186 return;
2187 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002188 // call pauseWebViewTimers() now, we won't be able to call
2189 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002190 // Temporarily change mActivityInPause to be true as
2191 // pauseWebViewTimers() will do nothing if mActivityInPause
2192 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002193 boolean savedState = mActivityInPause;
2194 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002195 Log.e(LOGTAG, "BrowserActivity is already paused "
2196 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002197 }
2198 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002199 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002200 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002201 removeTabFromContentView(current);
2202 mTabControl.removeTab(current);
2203 }
2204 /*
2205 * Instead of finishing the activity, simply push this to the back
2206 * of the stack and let ActivityManager to choose the foreground
2207 * activity. As BrowserActivity is singleTask, it will be always the
2208 * root of the task. So we can use either true or false for
2209 * moveTaskToBack().
2210 */
2211 moveTaskToBack(true);
2212 }
2213 }
2214 }
2215
Grace Kloba5942df02009-09-18 11:48:29 -07002216 @Override
2217 public boolean onKeyDown(int keyCode, KeyEvent event) {
2218 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2219 // still down, we don't want to trigger the search. Pretend to consume
2220 // the key and do nothing.
2221 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002222
Grace Kloba5942df02009-09-18 11:48:29 -07002223 switch(keyCode) {
2224 case KeyEvent.KEYCODE_MENU:
2225 mMenuIsDown = true;
2226 break;
2227 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002228 // WebView/WebTextView handle the keys in the KeyDown. As
2229 // the Activity's shortcut keys are only handled when WebView
2230 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2231 if (event.isShiftPressed()) {
2232 getTopWindow().pageUp(false);
2233 } else {
2234 getTopWindow().pageDown(false);
2235 }
Grace Kloba5942df02009-09-18 11:48:29 -07002236 return true;
2237 case KeyEvent.KEYCODE_BACK:
2238 if (event.getRepeatCount() == 0) {
2239 event.startTracking();
2240 return true;
2241 } else if (mCustomView == null && mActiveTabsPage == null
2242 && event.isLongPress()) {
2243 bookmarksOrHistoryPicker(true);
2244 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002245 }
Grace Kloba5942df02009-09-18 11:48:29 -07002246 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002247 }
Grace Kloba5942df02009-09-18 11:48:29 -07002248 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002249 }
2250
Grace Kloba5942df02009-09-18 11:48:29 -07002251 @Override
2252 public boolean onKeyUp(int keyCode, KeyEvent event) {
2253 switch(keyCode) {
2254 case KeyEvent.KEYCODE_MENU:
2255 mMenuIsDown = false;
2256 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002257 case KeyEvent.KEYCODE_BACK:
2258 if (event.isTracking() && !event.isCanceled()) {
2259 if (mCustomView != null) {
2260 // if a custom view is showing, hide it
2261 mWebChromeClient.onHideCustomView();
2262 } else if (mActiveTabsPage != null) {
2263 // if tab page is showing, hide it
2264 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002265 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002266 WebView subwindow = mTabControl.getCurrentSubWindow();
2267 if (subwindow != null) {
2268 if (subwindow.canGoBack()) {
2269 subwindow.goBack();
2270 } else {
2271 dismissSubWindow(mTabControl.getCurrentTab());
2272 }
2273 } else {
2274 goBackOnePageOrQuit();
2275 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002276 }
Grace Kloba5942df02009-09-18 11:48:29 -07002277 return true;
2278 }
2279 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002280 }
Grace Kloba5942df02009-09-18 11:48:29 -07002281 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002282 }
2283
Leon Scroggins68579392009-09-15 15:31:54 -04002284 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002285 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002286 resetTitleAndRevertLockIcon();
2287 WebView w = getTopWindow();
2288 w.stopLoading();
2289 mWebViewClient.onPageFinished(w, w.getUrl());
2290
2291 cancelStopToast();
2292 mStopToast = Toast
2293 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2294 mStopToast.show();
2295 }
2296
2297 private void cancelStopToast() {
2298 if (mStopToast != null) {
2299 mStopToast.cancel();
2300 mStopToast = null;
2301 }
2302 }
2303
2304 // called by a non-UI thread to post the message
2305 public void postMessage(int what, int arg1, int arg2, Object obj) {
2306 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2307 }
2308
2309 // public message ids
2310 public final static int LOAD_URL = 1001;
2311 public final static int STOP_LOAD = 1002;
2312
2313 // Message Ids
2314 private static final int FOCUS_NODE_HREF = 102;
2315 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002316 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002317
Ben Murdoch2694e232009-09-29 09:41:11 +01002318 private static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
2319
The Android Open Source Project0c908882009-03-03 19:32:16 -08002320 // Private handler for handling javascript and saving passwords
2321 private Handler mHandler = new Handler() {
2322
2323 public void handleMessage(Message msg) {
2324 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002325 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002326 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002327 String url = (String) msg.getData().get("url");
2328 if (url == null || url.length() == 0) {
2329 break;
2330 }
2331 HashMap focusNodeMap = (HashMap) msg.obj;
2332 WebView view = (WebView) focusNodeMap.get("webview");
2333 // Only apply the action if the top window did not change.
2334 if (getTopWindow() != view) {
2335 break;
2336 }
2337 switch (msg.arg1) {
2338 case R.id.open_context_menu_id:
2339 case R.id.view_image_context_menu_id:
2340 loadURL(getTopWindow(), url);
2341 break;
2342 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002343 final TabControl.Tab parent = mTabControl
2344 .getCurrentTab();
2345 final TabControl.Tab newTab = openTab(url);
2346 if (newTab != parent) {
2347 parent.addChildTab(newTab);
2348 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002349 break;
2350 case R.id.bookmark_context_menu_id:
2351 Intent intent = new Intent(BrowserActivity.this,
2352 AddBookmarkPage.class);
2353 intent.putExtra("url", url);
2354 startActivity(intent);
2355 break;
2356 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002357 Browser.sendString(BrowserActivity.this, url,
2358 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002359 break;
2360 case R.id.copy_link_context_menu_id:
2361 copy(url);
2362 break;
2363 case R.id.save_link_context_menu_id:
2364 case R.id.download_context_menu_id:
2365 onDownloadStartNoStream(url, null, null, null, -1);
2366 break;
2367 }
2368 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002369 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002370
2371 case LOAD_URL:
2372 loadURL(getTopWindow(), (String) msg.obj);
2373 break;
2374
2375 case STOP_LOAD:
2376 stopLoading();
2377 break;
2378
2379 case CANCEL_CREDS_REQUEST:
2380 resumeAfterCredentials();
2381 break;
2382
The Android Open Source Project0c908882009-03-03 19:32:16 -08002383 case RELEASE_WAKELOCK:
2384 if (mWakeLock.isHeld()) {
2385 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002386 // if we reach here, Browser should be still in the
2387 // background loading after WAKELOCK_TIMEOUT (5-min).
2388 // To avoid burning the battery, stop loading.
2389 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002390 }
2391 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002392
2393 case UPDATE_BOOKMARK_THUMBNAIL:
2394 WebView view = (WebView) msg.obj;
2395 if (view != null) {
2396 updateScreenshot(view);
2397 }
2398 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002399 }
2400 }
2401 };
2402
Leon Scroggins89c6d362009-07-15 16:54:37 -04002403 private void updateScreenshot(WebView view) {
2404 // If this is a bookmarked site, add a screenshot to the database.
2405 // FIXME: When should we update? Every time?
2406 // FIXME: Would like to make sure there is actually something to
2407 // draw, but the API for that (WebViewCore.pictureReady()) is not
2408 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002409
Patrick Scott3918d442009-08-04 13:22:29 -04002410 ContentResolver cr = getContentResolver();
2411 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002412 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002413 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002414 boolean succeed = c.moveToFirst();
2415 ContentValues values = null;
2416 while (succeed) {
2417 if (values == null) {
2418 final ByteArrayOutputStream os
2419 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002420 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002421 if (bm == null) {
2422 c.close();
2423 return;
2424 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002425 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2426 values = new ContentValues();
2427 values.put(Browser.BookmarkColumns.THUMBNAIL,
2428 os.toByteArray());
2429 }
2430 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2431 c.getInt(0)), values, null, null);
2432 succeed = c.moveToNext();
2433 }
2434 c.close();
2435 }
2436 }
2437
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002438 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002439 * Values for the size of the thumbnail created when taking a screenshot.
2440 * Lazily initialized. Instead of using these directly, use
2441 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002442 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002443 private static int THUMBNAIL_WIDTH = 0;
2444 private static int THUMBNAIL_HEIGHT = 0;
2445
2446 /**
2447 * Return the desired width for thumbnail screenshots, which are stored in
2448 * the database, and used on the bookmarks screen.
2449 * @param context Context for finding out the density of the screen.
2450 * @return int desired width for thumbnail screenshot.
2451 */
2452 /* package */ static int getDesiredThumbnailWidth(Context context) {
2453 if (THUMBNAIL_WIDTH == 0) {
2454 float density = context.getResources().getDisplayMetrics().density;
2455 THUMBNAIL_WIDTH = (int) (90 * density);
2456 THUMBNAIL_HEIGHT = (int) (80 * density);
2457 }
2458 return THUMBNAIL_WIDTH;
2459 }
2460
2461 /**
2462 * Return the desired height for thumbnail screenshots, which are stored in
2463 * the database, and used on the bookmarks screen.
2464 * @param context Context for finding out the density of the screen.
2465 * @return int desired height for thumbnail screenshot.
2466 */
2467 /* package */ static int getDesiredThumbnailHeight(Context context) {
2468 // To ensure that they are both initialized.
2469 getDesiredThumbnailWidth(context);
2470 return THUMBNAIL_HEIGHT;
2471 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002472
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002473 private Bitmap createScreenshot(WebView view) {
2474 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002475 if (thumbnail == null) {
2476 return null;
2477 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002478 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2479 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002480 Canvas canvas = new Canvas(bm);
2481 // May need to tweak these values to determine what is the
2482 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002483 int thumbnailWidth = thumbnail.getWidth();
2484 if (thumbnailWidth > 0) {
2485 float scaleFactor = (float) getDesiredThumbnailWidth(this) /
2486 (float)thumbnailWidth;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002487 canvas.scale(scaleFactor, scaleFactor);
2488 }
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002489 thumbnail.draw(canvas);
2490 return bm;
2491 }
2492
The Android Open Source Project0c908882009-03-03 19:32:16 -08002493 // -------------------------------------------------------------------------
2494 // WebViewClient implementation.
2495 //-------------------------------------------------------------------------
2496
2497 // Use in overrideUrlLoading
2498 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2499 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2500 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2501 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2502
2503 /* package */ WebViewClient getWebViewClient() {
2504 return mWebViewClient;
2505 }
2506
Patrick Scott3918d442009-08-04 13:22:29 -04002507 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002508 if (icon != null) {
2509 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott15525d42009-09-21 13:39:37 -04002510 view.getOriginalUrl(), view.getUrl(), icon);
2511 }
2512 setFavicon(icon);
2513 }
2514
2515 private void updateIcon(String url, Bitmap icon) {
2516 if (icon != null) {
2517 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2518 null, url, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002519 }
2520 setFavicon(icon);
2521 }
2522
2523 private final WebViewClient mWebViewClient = new WebViewClient() {
2524 @Override
2525 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2526 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002527 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002528
Ben Murdoch2694e232009-09-29 09:41:11 +01002529 // We've started to load a new page. If there was a pending message
2530 // to save a screenshot then we will now take the new page and
2531 // save an incorrect screenshot. Therefore, remove any pending
2532 // thumbnail messages from the queue.
2533 mHandler.removeMessages(UPDATE_BOOKMARK_THUMBNAIL);
2534
Patrick Scott59ce8302009-09-18 16:29:38 -04002535 // If we start a touch icon load and then load a new page, we don't
2536 // want to cancel the current touch icon loader. But, we do want to
2537 // create a new one when the touch icon url is known.
2538 if (mTouchIconLoader != null) {
2539 mTouchIconLoader.mActivity = null;
2540 mTouchIconLoader = null;
2541 }
2542
Ben Murdochbff2d602009-07-01 20:19:05 +01002543 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2544 if (errorConsole != null) {
2545 errorConsole.clearErrorMessages();
2546 if (mShouldShowErrorConsole) {
2547 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2548 }
2549 }
2550
The Android Open Source Project0c908882009-03-03 19:32:16 -08002551 // Call updateIcon instead of setFavicon so the bookmark
2552 // database can be updated.
Patrick Scott15525d42009-09-21 13:39:37 -04002553 updateIcon(url, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002554
Grace Kloba4d7880f2009-08-12 09:35:42 -07002555 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002556 String host;
2557 try {
2558 WebAddress uri = new WebAddress(url);
2559 host = uri.mHost;
2560 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002561 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002562 }
2563 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002564 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002565 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002566 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002567 }
2568
2569 // Performance probe
2570 if (false) {
2571 mStart = SystemClock.uptimeMillis();
2572 mProcessStart = Process.getElapsedCpuTime();
2573 long[] sysCpu = new long[7];
2574 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2575 sysCpu, null)) {
2576 mUserStart = sysCpu[0] + sysCpu[1];
2577 mSystemStart = sysCpu[2];
2578 mIdleStart = sysCpu[3];
2579 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2580 }
2581 mUiStart = SystemClock.currentThreadTimeMillis();
2582 }
2583
2584 if (!mPageStarted) {
2585 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002586 // if onResume() has been called, resumeWebViewTimers() does
2587 // nothing.
2588 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002589 }
2590
2591 // reset sync timer to avoid sync starts during loading a page
2592 CookieSyncManager.getInstance().resetSync();
2593
2594 mInLoad = true;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002595 mDidStopLoad = false;
Leon Scroggins184f5e32009-09-21 10:38:24 -04002596 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002597 updateInLoadMenuItems();
2598 if (!mIsNetworkUp) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04002599 createAndShowNetworkDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002600 if (view != null) {
2601 view.setNetworkAvailable(false);
2602 }
2603 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002604 }
2605
2606 @Override
2607 public void onPageFinished(WebView view, String url) {
2608 // Reset the title and icon in case we stopped a provisional
2609 // load.
2610 resetTitleAndIcon(view);
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002611
2612 if (!mDidStopLoad) {
2613 // Only update the bookmark screenshot if the user did not
2614 // cancel the load early.
Ben Murdoch2694e232009-09-29 09:41:11 +01002615 Message updateScreenshot = Message.obtain(mHandler, UPDATE_BOOKMARK_THUMBNAIL, view);
2616 mHandler.sendMessageDelayed(updateScreenshot, 500);
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002617 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002618
2619 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002620 updateLockIconToLatest();
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002621
The Android Open Source Project0c908882009-03-03 19:32:16 -08002622 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002623 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002624 long[] sysCpu = new long[7];
2625 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2626 sysCpu, null)) {
2627 String uiInfo = "UI thread used "
2628 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2629 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002630 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002631 Log.d(LOGTAG, uiInfo);
2632 }
2633 //The string that gets written to the log
2634 String performanceString = "It took total "
2635 + (SystemClock.uptimeMillis() - mStart)
2636 + " ms clock time to load the page."
2637 + "\nbrowser process used "
2638 + (Process.getElapsedCpuTime() - mProcessStart)
2639 + " ms, user processes used "
2640 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2641 + " ms, kernel used "
2642 + (sysCpu[2] - mSystemStart) * 10
2643 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2644 + " ms and irq took "
2645 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2646 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002647 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002648 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2649 }
2650 if (url != null) {
2651 // strip the url to maintain consistency
2652 String newUrl = new String(url);
2653 if (newUrl.startsWith("http://www.")) {
2654 newUrl = newUrl.substring(11);
2655 } else if (newUrl.startsWith("http://")) {
2656 newUrl = newUrl.substring(7);
2657 } else if (newUrl.startsWith("https://www.")) {
2658 newUrl = newUrl.substring(12);
2659 } else if (newUrl.startsWith("https://")) {
2660 newUrl = newUrl.substring(8);
2661 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002662 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002663 Log.d(LOGTAG, newUrl + " loaded");
2664 }
2665 /*
2666 if (sWhiteList.contains(newUrl)) {
2667 // The string that gets pushed to the statistcs
2668 // service
2669 performanceString = performanceString
2670 + "\nWebpage: "
2671 + newUrl
2672 + "\nCarrier: "
2673 + android.os.SystemProperties
2674 .get("gsm.sim.operator.alpha");
2675 if (mWebView != null
2676 && mWebView.getContext() != null
2677 && mWebView.getContext().getSystemService(
2678 Context.CONNECTIVITY_SERVICE) != null) {
2679 ConnectivityManager cManager =
2680 (ConnectivityManager) mWebView
2681 .getContext().getSystemService(
2682 Context.CONNECTIVITY_SERVICE);
2683 NetworkInfo nInfo = cManager
2684 .getActiveNetworkInfo();
2685 if (nInfo != null) {
2686 performanceString = performanceString
2687 + "\nNetwork Type: "
2688 + nInfo.getType().toString();
2689 }
2690 }
2691 Checkin.logEvent(mResolver,
2692 Checkin.Events.Tag.WEBPAGE_LOAD,
2693 performanceString);
2694 Log.w(LOGTAG, "pushed to the statistics service");
2695 }
2696 */
2697 }
2698 }
2699 }
2700
2701 if (mInTrace) {
2702 mInTrace = false;
2703 Debug.stopMethodTracing();
2704 }
2705
2706 if (mPageStarted) {
2707 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002708 // pauseWebViewTimers() will do nothing and return false if
2709 // onPause() is not called yet.
2710 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002711 if (mWakeLock.isHeld()) {
2712 mHandler.removeMessages(RELEASE_WAKELOCK);
2713 mWakeLock.release();
2714 }
2715 }
2716 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002717 }
2718
2719 // return true if want to hijack the url to let another app to handle it
2720 @Override
2721 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2722 if (url.startsWith(SCHEME_WTAI)) {
2723 // wtai://wp/mc;number
2724 // number=string(phone-number)
2725 if (url.startsWith(SCHEME_WTAI_MC)) {
2726 Intent intent = new Intent(Intent.ACTION_VIEW,
2727 Uri.parse(WebView.SCHEME_TEL +
2728 url.substring(SCHEME_WTAI_MC.length())));
2729 startActivity(intent);
2730 return true;
2731 }
2732 // wtai://wp/sd;dtmf
2733 // dtmf=string(dialstring)
2734 if (url.startsWith(SCHEME_WTAI_SD)) {
2735 // TODO
2736 // only send when there is active voice connection
2737 return false;
2738 }
2739 // wtai://wp/ap;number;name
2740 // number=string(phone-number)
2741 // name=string
2742 if (url.startsWith(SCHEME_WTAI_AP)) {
2743 // TODO
2744 return false;
2745 }
2746 }
2747
Dianne Hackborn99189432009-06-17 18:06:18 -07002748 // The "about:" schemes are internal to the browser; don't
2749 // want these to be dispatched to other apps.
2750 if (url.startsWith("about:")) {
2751 return false;
2752 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002753
Dianne Hackborn99189432009-06-17 18:06:18 -07002754 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002755
Dianne Hackborn99189432009-06-17 18:06:18 -07002756 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002757 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002758 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2759 } catch (URISyntaxException ex) {
2760 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002761 return false;
2762 }
2763
Grace Kloba5b078b52009-06-24 20:23:41 -07002764 // check whether the intent can be resolved. If not, we will see
2765 // whether we can download it from the Market.
2766 if (getPackageManager().resolveActivity(intent, 0) == null) {
2767 String packagename = intent.getPackage();
2768 if (packagename != null) {
2769 intent = new Intent(Intent.ACTION_VIEW, Uri
2770 .parse("market://search?q=pname:" + packagename));
2771 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2772 startActivity(intent);
2773 return true;
2774 } else {
2775 return false;
2776 }
2777 }
2778
Dianne Hackborn99189432009-06-17 18:06:18 -07002779 // sanitize the Intent, ensuring web pages can not bypass browser
2780 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002781 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002782 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002783 try {
2784 if (startActivityIfNeeded(intent, -1)) {
2785 return true;
2786 }
2787 } catch (ActivityNotFoundException ex) {
2788 // ignore the error. If no application can handle the URL,
2789 // eg about:blank, assume the browser can handle it.
2790 }
2791
2792 if (mMenuIsDown) {
2793 openTab(url);
2794 closeOptionsMenu();
2795 return true;
2796 }
2797
2798 return false;
2799 }
2800
2801 /**
2802 * Updates the lock icon. This method is called when we discover another
2803 * resource to be loaded for this page (for example, javascript). While
2804 * we update the icon type, we do not update the lock icon itself until
2805 * we are done loading, it is slightly more secure this way.
2806 */
2807 @Override
2808 public void onLoadResource(WebView view, String url) {
2809 if (url != null && url.length() > 0) {
2810 // It is only if the page claims to be secure
2811 // that we may have to update the lock:
2812 if (mLockIconType == LOCK_ICON_SECURE) {
2813 // If NOT a 'safe' url, change the lock to mixed content!
2814 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2815 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002816 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002817 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2818 " updated lock icon to " + mLockIconType + " due to " + url);
2819 }
2820 }
2821 }
2822 }
2823 }
2824
2825 /**
2826 * Show the dialog, asking the user if they would like to continue after
2827 * an excessive number of HTTP redirects.
2828 */
2829 @Override
2830 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2831 final Message continueMsg) {
2832 new AlertDialog.Builder(BrowserActivity.this)
2833 .setTitle(R.string.browserFrameRedirect)
2834 .setMessage(R.string.browserFrame307Post)
2835 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2836 public void onClick(DialogInterface dialog, int which) {
2837 continueMsg.sendToTarget();
2838 }})
2839 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2840 public void onClick(DialogInterface dialog, int which) {
2841 cancelMsg.sendToTarget();
2842 }})
2843 .setOnCancelListener(new OnCancelListener() {
2844 public void onCancel(DialogInterface dialog) {
2845 cancelMsg.sendToTarget();
2846 }})
2847 .show();
2848 }
2849
Patrick Scott37911c72009-03-24 18:02:58 -07002850 // Container class for the next error dialog that needs to be
2851 // displayed.
2852 class ErrorDialog {
2853 public final int mTitle;
2854 public final String mDescription;
2855 public final int mError;
2856 ErrorDialog(int title, String desc, int error) {
2857 mTitle = title;
2858 mDescription = desc;
2859 mError = error;
2860 }
2861 };
2862
2863 private void processNextError() {
2864 if (mQueuedErrors == null) {
2865 return;
2866 }
2867 // The first one is currently displayed so just remove it.
2868 mQueuedErrors.removeFirst();
2869 if (mQueuedErrors.size() == 0) {
2870 mQueuedErrors = null;
2871 return;
2872 }
2873 showError(mQueuedErrors.getFirst());
2874 }
2875
2876 private DialogInterface.OnDismissListener mDialogListener =
2877 new DialogInterface.OnDismissListener() {
2878 public void onDismiss(DialogInterface d) {
2879 processNextError();
2880 }
2881 };
2882 private LinkedList<ErrorDialog> mQueuedErrors;
2883
2884 private void queueError(int err, String desc) {
2885 if (mQueuedErrors == null) {
2886 mQueuedErrors = new LinkedList<ErrorDialog>();
2887 }
2888 for (ErrorDialog d : mQueuedErrors) {
2889 if (d.mError == err) {
2890 // Already saw a similar error, ignore the new one.
2891 return;
2892 }
2893 }
2894 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002895 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002896 R.string.browserFrameFileErrorLabel :
2897 R.string.browserFrameNetworkErrorLabel,
2898 desc, err);
2899 mQueuedErrors.addLast(errDialog);
2900
2901 // Show the dialog now if the queue was empty.
2902 if (mQueuedErrors.size() == 1) {
2903 showError(errDialog);
2904 }
2905 }
2906
2907 private void showError(ErrorDialog errDialog) {
2908 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2909 .setTitle(errDialog.mTitle)
2910 .setMessage(errDialog.mDescription)
2911 .setPositiveButton(R.string.ok, null)
2912 .create();
2913 d.setOnDismissListener(mDialogListener);
2914 d.show();
2915 }
2916
The Android Open Source Project0c908882009-03-03 19:32:16 -08002917 /**
2918 * Show a dialog informing the user of the network error reported by
2919 * WebCore.
2920 */
2921 @Override
2922 public void onReceivedError(WebView view, int errorCode,
2923 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002924 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2925 errorCode != WebViewClient.ERROR_CONNECT &&
2926 errorCode != WebViewClient.ERROR_BAD_URL &&
2927 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2928 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002929 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002930 }
Patrick Scott37911c72009-03-24 18:02:58 -07002931 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2932 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002933
2934 // We need to reset the title after an error.
2935 resetTitleAndRevertLockIcon();
2936 }
2937
2938 /**
2939 * Check with the user if it is ok to resend POST data as the page they
2940 * are trying to navigate to is the result of a POST.
2941 */
2942 @Override
2943 public void onFormResubmission(WebView view, final Message dontResend,
2944 final Message resend) {
2945 new AlertDialog.Builder(BrowserActivity.this)
2946 .setTitle(R.string.browserFrameFormResubmitLabel)
2947 .setMessage(R.string.browserFrameFormResubmitMessage)
2948 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2949 public void onClick(DialogInterface dialog, int which) {
2950 resend.sendToTarget();
2951 }})
2952 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2953 public void onClick(DialogInterface dialog, int which) {
2954 dontResend.sendToTarget();
2955 }})
2956 .setOnCancelListener(new OnCancelListener() {
2957 public void onCancel(DialogInterface dialog) {
2958 dontResend.sendToTarget();
2959 }})
2960 .show();
2961 }
2962
2963 /**
2964 * Insert the url into the visited history database.
2965 * @param url The url to be inserted.
2966 * @param isReload True if this url is being reloaded.
2967 * FIXME: Not sure what to do when reloading the page.
2968 */
2969 @Override
2970 public void doUpdateVisitedHistory(WebView view, String url,
2971 boolean isReload) {
2972 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2973 return;
2974 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002975 // remove "client" before updating it to the history so that it wont
2976 // show up in the auto-complete list.
2977 int index = url.indexOf("client=ms-");
2978 if (index > 0 && url.contains(".google.")) {
2979 int end = url.indexOf('&', index);
2980 if (end > 0) {
Grace Klobaef292152009-10-07 19:15:59 -07002981 url = url.substring(0, index)
2982 .concat(url.substring(end + 1));
Grace Kloba6b52a552009-09-03 16:29:56 -07002983 } else {
Grace Klobaef292152009-10-07 19:15:59 -07002984 // the url.charAt(index-1) should be either '?' or '&'
Grace Kloba6b52a552009-09-03 16:29:56 -07002985 url = url.substring(0, index-1);
2986 }
2987 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002988 Browser.updateVisitedHistory(mResolver, url, true);
2989 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2990 }
2991
2992 /**
2993 * Displays SSL error(s) dialog to the user.
2994 */
2995 @Override
2996 public void onReceivedSslError(
2997 final WebView view, final SslErrorHandler handler, final SslError error) {
2998
2999 if (mSettings.showSecurityWarnings()) {
3000 final LayoutInflater factory =
3001 LayoutInflater.from(BrowserActivity.this);
3002 final View warningsView =
3003 factory.inflate(R.layout.ssl_warnings, null);
3004 final LinearLayout placeholder =
3005 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3006
3007 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3008 LinearLayout ll = (LinearLayout)factory
3009 .inflate(R.layout.ssl_warning, null);
3010 ((TextView)ll.findViewById(R.id.warning))
3011 .setText(R.string.ssl_untrusted);
3012 placeholder.addView(ll);
3013 }
3014
3015 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3016 LinearLayout ll = (LinearLayout)factory
3017 .inflate(R.layout.ssl_warning, null);
3018 ((TextView)ll.findViewById(R.id.warning))
3019 .setText(R.string.ssl_mismatch);
3020 placeholder.addView(ll);
3021 }
3022
3023 if (error.hasError(SslError.SSL_EXPIRED)) {
3024 LinearLayout ll = (LinearLayout)factory
3025 .inflate(R.layout.ssl_warning, null);
3026 ((TextView)ll.findViewById(R.id.warning))
3027 .setText(R.string.ssl_expired);
3028 placeholder.addView(ll);
3029 }
3030
3031 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3032 LinearLayout ll = (LinearLayout)factory
3033 .inflate(R.layout.ssl_warning, null);
3034 ((TextView)ll.findViewById(R.id.warning))
3035 .setText(R.string.ssl_not_yet_valid);
3036 placeholder.addView(ll);
3037 }
3038
3039 new AlertDialog.Builder(BrowserActivity.this)
3040 .setTitle(R.string.security_warning)
3041 .setIcon(android.R.drawable.ic_dialog_alert)
3042 .setView(warningsView)
3043 .setPositiveButton(R.string.ssl_continue,
3044 new DialogInterface.OnClickListener() {
3045 public void onClick(DialogInterface dialog, int whichButton) {
3046 handler.proceed();
3047 }
3048 })
3049 .setNeutralButton(R.string.view_certificate,
3050 new DialogInterface.OnClickListener() {
3051 public void onClick(DialogInterface dialog, int whichButton) {
3052 showSSLCertificateOnError(view, handler, error);
3053 }
3054 })
3055 .setNegativeButton(R.string.cancel,
3056 new DialogInterface.OnClickListener() {
3057 public void onClick(DialogInterface dialog, int whichButton) {
3058 handler.cancel();
3059 BrowserActivity.this.resetTitleAndRevertLockIcon();
3060 }
3061 })
3062 .setOnCancelListener(
3063 new DialogInterface.OnCancelListener() {
3064 public void onCancel(DialogInterface dialog) {
3065 handler.cancel();
3066 BrowserActivity.this.resetTitleAndRevertLockIcon();
3067 }
3068 })
3069 .show();
3070 } else {
3071 handler.proceed();
3072 }
3073 }
3074
3075 /**
3076 * Handles an HTTP authentication request.
3077 *
3078 * @param handler The authentication handler
3079 * @param host The host
3080 * @param realm The realm
3081 */
3082 @Override
3083 public void onReceivedHttpAuthRequest(WebView view,
3084 final HttpAuthHandler handler, final String host, final String realm) {
3085 String username = null;
3086 String password = null;
3087
3088 boolean reuseHttpAuthUsernamePassword =
3089 handler.useHttpAuthUsernamePassword();
3090
3091 if (reuseHttpAuthUsernamePassword &&
3092 (mTabControl.getCurrentWebView() != null)) {
3093 String[] credentials =
3094 mTabControl.getCurrentWebView()
3095 .getHttpAuthUsernamePassword(host, realm);
3096 if (credentials != null && credentials.length == 2) {
3097 username = credentials[0];
3098 password = credentials[1];
3099 }
3100 }
3101
3102 if (username != null && password != null) {
3103 handler.proceed(username, password);
3104 } else {
3105 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3106 }
3107 }
3108
3109 @Override
3110 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3111 if (mMenuIsDown) {
3112 // only check shortcut key when MENU is held
3113 return getWindow().isShortcutKey(event.getKeyCode(), event);
3114 } else {
3115 return false;
3116 }
3117 }
3118
3119 @Override
3120 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3121 if (view != mTabControl.getCurrentTopWebView()) {
3122 return;
3123 }
3124 if (event.isDown()) {
3125 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3126 } else {
3127 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3128 }
3129 }
3130 };
3131
3132 //--------------------------------------------------------------------------
3133 // WebChromeClient implementation
3134 //--------------------------------------------------------------------------
3135
3136 /* package */ WebChromeClient getWebChromeClient() {
3137 return mWebChromeClient;
3138 }
3139
3140 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3141 // Helper method to create a new tab or sub window.
3142 private void createWindow(final boolean dialog, final Message msg) {
3143 if (dialog) {
3144 mTabControl.createSubWindow();
3145 final TabControl.Tab t = mTabControl.getCurrentTab();
3146 attachSubWindow(t);
3147 WebView.WebViewTransport transport =
3148 (WebView.WebViewTransport) msg.obj;
3149 transport.setWebView(t.getSubWebView());
3150 msg.sendToTarget();
3151 } else {
3152 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003153 final TabControl.Tab newTab
3154 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07003155 if (newTab != parent) {
3156 parent.addChildTab(newTab);
3157 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003158 WebView.WebViewTransport transport =
3159 (WebView.WebViewTransport) msg.obj;
3160 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04003161 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003162 }
3163 }
3164
3165 @Override
3166 public boolean onCreateWindow(WebView view, final boolean dialog,
3167 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003168 // Short-circuit if we can't create any more tabs or sub windows.
3169 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3170 new AlertDialog.Builder(BrowserActivity.this)
3171 .setTitle(R.string.too_many_subwindows_dialog_title)
3172 .setIcon(android.R.drawable.ic_dialog_alert)
3173 .setMessage(R.string.too_many_subwindows_dialog_message)
3174 .setPositiveButton(R.string.ok, null)
3175 .show();
3176 return false;
3177 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3178 new AlertDialog.Builder(BrowserActivity.this)
3179 .setTitle(R.string.too_many_windows_dialog_title)
3180 .setIcon(android.R.drawable.ic_dialog_alert)
3181 .setMessage(R.string.too_many_windows_dialog_message)
3182 .setPositiveButton(R.string.ok, null)
3183 .show();
3184 return false;
3185 }
3186
3187 // Short-circuit if this was a user gesture.
3188 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003189 createWindow(dialog, resultMsg);
3190 return true;
3191 }
3192
3193 // Allow the popup and create the appropriate window.
3194 final AlertDialog.OnClickListener allowListener =
3195 new AlertDialog.OnClickListener() {
3196 public void onClick(DialogInterface d,
3197 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003198 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003199 }
3200 };
3201
3202 // Block the popup by returning a null WebView.
3203 final AlertDialog.OnClickListener blockListener =
3204 new AlertDialog.OnClickListener() {
3205 public void onClick(DialogInterface d, int which) {
3206 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003207 }
3208 };
3209
3210 // Build a confirmation dialog to display to the user.
3211 final AlertDialog d =
3212 new AlertDialog.Builder(BrowserActivity.this)
3213 .setTitle(R.string.attention)
3214 .setIcon(android.R.drawable.ic_dialog_alert)
3215 .setMessage(R.string.popup_window_attempt)
3216 .setPositiveButton(R.string.allow, allowListener)
3217 .setNegativeButton(R.string.block, blockListener)
3218 .setCancelable(false)
3219 .create();
3220
3221 // Show the confirmation dialog.
3222 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003223 return true;
3224 }
3225
3226 @Override
3227 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003228 final TabControl.Tab current = mTabControl.getCurrentTab();
3229 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003230 if (parent != null) {
3231 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003232 switchToTab(mTabControl.getTabIndex(parent));
3233 // Now we need to close the window
3234 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003235 }
3236 }
3237
3238 @Override
3239 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003240 mTitleBar.setProgress(newProgress);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003241 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003242
3243 if (newProgress == 100) {
Ben Murdochaac7aa62009-09-17 16:57:40 +01003244 // onProgressChanged() may continue to be called after the main
3245 // frame has finished loading, as any remaining sub frames
3246 // continue to load. We'll only get called once though with
3247 // newProgress as 100 when everything is loaded.
3248 // (onPageFinished is called once when the main frame completes
3249 // loading regardless of the state of any sub frames so calls
3250 // to onProgressChanges may continue after onPageFinished has
3251 // executed)
3252
3253 // sync cookies and cache promptly here.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003254 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003255 if (mInLoad) {
3256 mInLoad = false;
3257 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003258 // If the options menu is open, leave the title bar
3259 if (!mOptionsMenuOpen || !mIconView) {
3260 hideFakeTitleBar();
3261 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003262 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003263 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003264 // onPageFinished may have already been called but a subframe
3265 // is still loading and updating the progress. Reset mInLoad
3266 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003267 mInLoad = true;
3268 updateInLoadMenuItems();
Leon Scroggins184f5e32009-09-21 10:38:24 -04003269 if (!mOptionsMenuOpen || mIconView) {
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003270 // This page has begun to load, so show the title bar
3271 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003272 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003273 }
3274 }
3275
3276 @Override
3277 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003278 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003279
3280 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003281 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003282
3283 if (url == null ||
3284 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3285 return;
3286 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003287 // See if we can find the current url in our history database and
3288 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003289 if (url.startsWith("http://www.")) {
3290 url = url.substring(11);
3291 } else if (url.startsWith("http://")) {
3292 url = url.substring(4);
3293 }
3294 try {
3295 url = "%" + url;
3296 String [] selArgs = new String[] { url };
3297
3298 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3299 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3300 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3301 Browser.HISTORY_PROJECTION, where, selArgs, null);
3302 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003303 // Current implementation of database only has one entry per
3304 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003305 ContentValues map = new ContentValues();
3306 map.put(Browser.BookmarkColumns.TITLE, title);
3307 mResolver.update(Browser.BOOKMARKS_URI, map,
3308 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003309 }
3310 c.close();
3311 } catch (IllegalStateException e) {
3312 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3313 } catch (SQLiteException ex) {
3314 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3315 }
3316 }
3317
3318 @Override
3319 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003320 updateIcon(view, icon);
3321 }
3322
3323 @Override
Patrick Scott59ce8302009-09-18 16:29:38 -04003324 public void onReceivedTouchIconUrl(WebView view, String url,
3325 boolean precomposed) {
Patrick Scott3918d442009-08-04 13:22:29 -04003326 final ContentResolver cr = getContentResolver();
3327 final Cursor c =
3328 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003329 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003330 if (c != null) {
3331 if (c.getCount() > 0) {
Patrick Scott59ce8302009-09-18 16:29:38 -04003332 // Let precomposed icons take precedence over non-composed
3333 // icons.
3334 if (precomposed && mTouchIconLoader != null) {
3335 mTouchIconLoader.cancel(false);
3336 mTouchIconLoader = null;
3337 }
3338 // Have only one async task at a time.
3339 if (mTouchIconLoader == null) {
3340 mTouchIconLoader = new DownloadTouchIcon(
3341 BrowserActivity.this, cr, c, view);
3342 mTouchIconLoader.execute(url);
3343 }
Patrick Scott3918d442009-08-04 13:22:29 -04003344 } else {
3345 c.close();
3346 }
3347 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003348 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003349
Andrei Popescuadc008d2009-06-26 14:11:30 +01003350 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003351 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003352 if (mCustomView != null)
3353 return;
3354
3355 // Add the custom view to its container.
3356 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3357 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003358 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003359 // Save the menu state and set it to empty while the custom
3360 // view is showing.
3361 mOldMenuState = mMenuState;
3362 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003363 // Hide the content view.
3364 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003365 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003366 mCustomViewContainer.setVisibility(View.VISIBLE);
3367 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003368 }
3369
3370 @Override
3371 public void onHideCustomView() {
3372 if (mCustomView == null)
3373 return;
3374
Andrei Popescuc9b55562009-07-07 10:51:15 +01003375 // Hide the custom view.
3376 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003377 // Remove the custom view from its container.
3378 mCustomViewContainer.removeView(mCustomView);
3379 mCustomView = null;
3380 // Reset the old menu state.
3381 mMenuState = mOldMenuState;
3382 mOldMenuState = EMPTY_MENU;
3383 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003384 mCustomViewCallback.onCustomViewHidden();
3385 // Show the content view.
3386 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003387 }
3388
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003389 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003390 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003391 * @param url the URL that exceeded the quota
3392 * @param databaseIdentifier the identifier of the database on
3393 * which the transaction that caused the quota overflow was run
3394 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003395 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003396 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003397 * @param quotaUpdater The callback to run when a decision to allow or
3398 * deny quota has been made. Don't forget to call this!
3399 */
3400 @Override
3401 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003402 String databaseIdentifier, long currentQuota, long estimatedSize,
3403 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003404 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003405 url, databaseIdentifier, currentQuota, estimatedSize,
3406 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003407 }
3408
3409 /**
3410 * The Application Cache has exceeded its max size.
3411 * @param spaceNeeded is the amount of disk space that would be needed
3412 * in order for the last appcache operation to succeed.
3413 * @param totalUsedQuota is the sum of all origins' quota.
3414 * @param quotaUpdater A callback to inform the WebCore thread that a new
3415 * app cache size is available. This callback must always be executed at
3416 * some point to ensure that the sleeping WebCore thread is woken up.
3417 */
3418 @Override
3419 public void onReachedMaxAppCacheSize(long spaceNeeded,
3420 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3421 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3422 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003423 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003424
Steve Block2bc69912009-07-30 14:45:13 +01003425 /**
3426 * Instructs the browser to show a prompt to ask the user to set the
3427 * Geolocation permission state for the specified origin.
3428 * @param origin The origin for which Geolocation permissions are
3429 * requested.
3430 * @param callback The callback to call once the user has set the
3431 * Geolocation permission state.
3432 */
3433 @Override
3434 public void onGeolocationPermissionsShowPrompt(String origin,
3435 GeolocationPermissions.Callback callback) {
3436 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3437 origin, callback);
3438 }
3439
3440 /**
3441 * Instructs the browser to hide the Geolocation permissions prompt.
3442 */
3443 @Override
3444 public void onGeolocationPermissionsHidePrompt() {
3445 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3446 }
3447
Ben Murdoch7db26342009-06-03 18:21:19 +01003448 /* Adds a JavaScript error message to the system log.
3449 * @param message The error message to report.
3450 * @param lineNumber The line number of the error.
3451 * @param sourceID The name of the source file that caused the error.
3452 */
3453 @Override
3454 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003455 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3456 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3457 if (mShouldShowErrorConsole &&
3458 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3459 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3460 }
3461 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003462 }
Andrei Popescu540035d2009-09-18 18:59:20 +01003463
3464 /**
3465 * Ask the browser for an icon to represent a <video> element.
3466 * This icon will be used if the Web page did not specify a poster attribute.
3467 *
3468 * @return Bitmap The icon or null if no such icon is available.
3469 * @hide pending API Council approval
3470 */
3471 @Override
3472 public Bitmap getDefaultVideoPoster() {
3473 if (mDefaultVideoPoster == null) {
3474 mDefaultVideoPoster = BitmapFactory.decodeResource(
3475 getResources(), R.drawable.default_video_poster);
3476 }
3477 return mDefaultVideoPoster;
3478 }
3479
3480 /**
3481 * Ask the host application for a custom progress view to show while
3482 * a <video> is loading.
3483 *
3484 * @return View The progress view.
3485 * @hide pending API Council approval
3486 */
3487 @Override
3488 public View getVideoLoadingProgressView() {
3489 if (mVideoProgressView == null) {
3490 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
3491 mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
3492 }
3493 return mVideoProgressView;
3494 }
Leon Clarkecb6cc862009-09-29 18:35:13 +01003495
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003496 @Override
3497 public void openFileChooser(ValueCallback<Uri> uploadMsg) {
3498 if (mUploadMessage != null) return;
3499 mUploadMessage = uploadMsg;
3500 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
3501 i.addCategory(Intent.CATEGORY_OPENABLE);
3502 i.setType("*/*");
3503 BrowserActivity.this.startActivityForResult(
3504 Intent.createChooser(i, getString(R.string.choose_upload)),
3505 FILE_SELECTED);
3506 }
3507
Leon Clarkecb6cc862009-09-29 18:35:13 +01003508 /**
3509 * Deliver a list of already-visited URLs
3510 * @hide pending API Council approval
3511 */
3512 @Override
3513 public void getVisitedHistory(final ValueCallback<String[]> callback) {
3514 AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
3515 public String[] doInBackground(Void... unused) {
3516 return Browser.getVisitedHistory(getContentResolver());
3517 }
3518
3519 public void onPostExecute(String[] result) {
3520 callback.onReceiveValue(result);
3521
3522 };
3523 };
3524 task.execute();
3525 };
The Android Open Source Project0c908882009-03-03 19:32:16 -08003526 };
3527
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003528 /*
3529 * The Object used to inform the WebView of the file to upload.
3530 */
3531 private ValueCallback<Uri> mUploadMessage;
3532
The Android Open Source Project0c908882009-03-03 19:32:16 -08003533 /**
3534 * Notify the host application a download should be done, or that
3535 * the data should be streamed if a streaming viewer is available.
3536 * @param url The full url to the content that should be downloaded
3537 * @param contentDisposition Content-disposition http header, if
3538 * present.
3539 * @param mimetype The mimetype of the content reported by the server
3540 * @param contentLength The file size reported by the server
3541 */
3542 public void onDownloadStart(String url, String userAgent,
3543 String contentDisposition, String mimetype, long contentLength) {
3544 // if we're dealing wih A/V content that's not explicitly marked
3545 // for download, check if it's streamable.
3546 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003547 || !contentDisposition.regionMatches(
3548 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003549 // query the package manager to see if there's a registered handler
3550 // that matches.
3551 Intent intent = new Intent(Intent.ACTION_VIEW);
3552 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003553 ResolveInfo info = getPackageManager().resolveActivity(intent,
3554 PackageManager.MATCH_DEFAULT_ONLY);
3555 if (info != null) {
3556 ComponentName myName = getComponentName();
3557 // If we resolved to ourselves, we don't want to attempt to
3558 // load the url only to try and download it again.
3559 if (!myName.getPackageName().equals(
3560 info.activityInfo.packageName)
3561 || !myName.getClassName().equals(
3562 info.activityInfo.name)) {
3563 // someone (other than us) knows how to handle this mime
3564 // type with this scheme, don't download.
3565 try {
3566 startActivity(intent);
3567 return;
3568 } catch (ActivityNotFoundException ex) {
3569 if (LOGD_ENABLED) {
3570 Log.d(LOGTAG, "activity not found for " + mimetype
3571 + " over " + Uri.parse(url).getScheme(),
3572 ex);
3573 }
3574 // Best behavior is to fall back to a download in this
3575 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003576 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003577 }
3578 }
3579 }
3580 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3581 }
3582
3583 /**
3584 * Notify the host application a download should be done, even if there
3585 * is a streaming viewer available for thise type.
3586 * @param url The full url to the content that should be downloaded
3587 * @param contentDisposition Content-disposition http header, if
3588 * present.
3589 * @param mimetype The mimetype of the content reported by the server
3590 * @param contentLength The file size reported by the server
3591 */
3592 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3593 String contentDisposition, String mimetype, long contentLength) {
3594
3595 String filename = URLUtil.guessFileName(url,
3596 contentDisposition, mimetype);
3597
3598 // Check to see if we have an SDCard
3599 String status = Environment.getExternalStorageState();
3600 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3601 int title;
3602 String msg;
3603
3604 // Check to see if the SDCard is busy, same as the music app
3605 if (status.equals(Environment.MEDIA_SHARED)) {
3606 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3607 title = R.string.download_sdcard_busy_dlg_title;
3608 } else {
3609 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3610 title = R.string.download_no_sdcard_dlg_title;
3611 }
3612
3613 new AlertDialog.Builder(this)
3614 .setTitle(title)
3615 .setIcon(android.R.drawable.ic_dialog_alert)
3616 .setMessage(msg)
3617 .setPositiveButton(R.string.ok, null)
3618 .show();
3619 return;
3620 }
3621
3622 // java.net.URI is a lot stricter than KURL so we have to undo
3623 // KURL's percent-encoding and redo the encoding using java.net.URI.
3624 URI uri = null;
3625 try {
3626 // Undo the percent-encoding that KURL may have done.
3627 String newUrl = new String(URLUtil.decode(url.getBytes()));
3628 // Parse the url into pieces
3629 WebAddress w = new WebAddress(newUrl);
3630 String frag = null;
3631 String query = null;
3632 String path = w.mPath;
3633 // Break the path into path, query, and fragment
3634 if (path.length() > 0) {
3635 // Strip the fragment
3636 int idx = path.lastIndexOf('#');
3637 if (idx != -1) {
3638 frag = path.substring(idx + 1);
3639 path = path.substring(0, idx);
3640 }
3641 idx = path.lastIndexOf('?');
3642 if (idx != -1) {
3643 query = path.substring(idx + 1);
3644 path = path.substring(0, idx);
3645 }
3646 }
3647 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3648 query, frag);
3649 } catch (Exception e) {
3650 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3651 return;
3652 }
3653
3654 // XXX: Have to use the old url since the cookies were stored using the
3655 // old percent-encoded url.
3656 String cookies = CookieManager.getInstance().getCookie(url);
3657
3658 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003659 values.put(Downloads.COLUMN_URI, uri.toString());
3660 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3661 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3662 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003663 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003664 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003665 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003666 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3667 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3668 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3669 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003670 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003671 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003672 }
3673 if (mimetype == null) {
3674 // We must have long pressed on a link or image to download it. We
3675 // are not sure of the mimetype in this case, so do a head request
3676 new FetchUrlMimeType(this).execute(values);
3677 } else {
3678 final Uri contentUri =
3679 getContentResolver().insert(Downloads.CONTENT_URI, values);
3680 viewDownloads(contentUri);
3681 }
3682
3683 }
3684
3685 /**
3686 * Resets the lock icon. This method is called when we start a new load and
3687 * know the url to be loaded.
3688 */
3689 private void resetLockIcon(String url) {
3690 // Save the lock-icon state (we revert to it if the load gets cancelled)
3691 saveLockIcon();
3692
3693 mLockIconType = LOCK_ICON_UNSECURE;
3694 if (URLUtil.isHttpsUrl(url)) {
3695 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003696 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003697 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3698 " reset lock icon to " + mLockIconType);
3699 }
3700 }
3701
3702 updateLockIconImage(LOCK_ICON_UNSECURE);
3703 }
3704
Grace Klobaeb6eef42009-09-15 17:56:32 -07003705 /* package */ void setLockIconType(int type) {
3706 mLockIconType = type;
3707 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003708
Grace Klobaeb6eef42009-09-15 17:56:32 -07003709 /* package */ int getLockIconType() {
3710 return mLockIconType;
3711 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003712
Grace Klobaeb6eef42009-09-15 17:56:32 -07003713 /* package */ void setPrevLockType(int type) {
3714 mPrevLockType = type;
3715 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003716
Grace Klobaeb6eef42009-09-15 17:56:32 -07003717 /* package */ int getPrevLockType() {
3718 return mPrevLockType;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003719 }
3720
3721 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003722 * Update the lock icon to correspond to our latest state.
3723 */
3724 /* package */ void updateLockIconToLatest() {
3725 updateLockIconImage(mLockIconType);
3726 }
3727
3728 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003729 * Updates the lock-icon image in the title-bar.
3730 */
3731 private void updateLockIconImage(int lockIconType) {
3732 Drawable d = null;
3733 if (lockIconType == LOCK_ICON_SECURE) {
3734 d = mSecLockIcon;
3735 } else if (lockIconType == LOCK_ICON_MIXED) {
3736 d = mMixLockIcon;
3737 }
Leon Scroggins68579392009-09-15 15:31:54 -04003738 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003739 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003740 }
3741
3742 /**
3743 * Displays a page-info dialog.
3744 * @param tab The tab to show info about
3745 * @param fromShowSSLCertificateOnError The flag that indicates whether
3746 * this dialog was opened from the SSL-certificate-on-error dialog or
3747 * not. This is important, since we need to know whether to return to
3748 * the parent dialog or simply dismiss.
3749 */
3750 private void showPageInfo(final TabControl.Tab tab,
3751 final boolean fromShowSSLCertificateOnError) {
3752 final LayoutInflater factory = LayoutInflater
3753 .from(this);
3754
3755 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3756
3757 final WebView view = tab.getWebView();
3758
3759 String url = null;
3760 String title = null;
3761
3762 if (view == null) {
3763 url = tab.getUrl();
3764 title = tab.getTitle();
3765 } else if (view == mTabControl.getCurrentWebView()) {
3766 // Use the cached title and url if this is the current WebView
3767 url = mUrl;
3768 title = mTitle;
3769 } else {
3770 url = view.getUrl();
3771 title = view.getTitle();
3772 }
3773
3774 if (url == null) {
3775 url = "";
3776 }
3777 if (title == null) {
3778 title = "";
3779 }
3780
3781 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3782 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3783
3784 mPageInfoView = tab;
3785 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3786
3787 AlertDialog.Builder alertDialogBuilder =
3788 new AlertDialog.Builder(this)
3789 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3790 .setView(pageInfoView)
3791 .setPositiveButton(
3792 R.string.ok,
3793 new DialogInterface.OnClickListener() {
3794 public void onClick(DialogInterface dialog,
3795 int whichButton) {
3796 mPageInfoDialog = null;
3797 mPageInfoView = null;
3798 mPageInfoFromShowSSLCertificateOnError = null;
3799
3800 // if we came here from the SSL error dialog
3801 if (fromShowSSLCertificateOnError) {
3802 // go back to the SSL error dialog
3803 showSSLCertificateOnError(
3804 mSSLCertificateOnErrorView,
3805 mSSLCertificateOnErrorHandler,
3806 mSSLCertificateOnErrorError);
3807 }
3808 }
3809 })
3810 .setOnCancelListener(
3811 new DialogInterface.OnCancelListener() {
3812 public void onCancel(DialogInterface dialog) {
3813 mPageInfoDialog = null;
3814 mPageInfoView = null;
3815 mPageInfoFromShowSSLCertificateOnError = null;
3816
3817 // if we came here from the SSL error dialog
3818 if (fromShowSSLCertificateOnError) {
3819 // go back to the SSL error dialog
3820 showSSLCertificateOnError(
3821 mSSLCertificateOnErrorView,
3822 mSSLCertificateOnErrorHandler,
3823 mSSLCertificateOnErrorError);
3824 }
3825 }
3826 });
3827
3828 // if we have a main top-level page SSL certificate set or a certificate
3829 // error
3830 if (fromShowSSLCertificateOnError ||
3831 (view != null && view.getCertificate() != null)) {
3832 // add a 'View Certificate' button
3833 alertDialogBuilder.setNeutralButton(
3834 R.string.view_certificate,
3835 new DialogInterface.OnClickListener() {
3836 public void onClick(DialogInterface dialog,
3837 int whichButton) {
3838 mPageInfoDialog = null;
3839 mPageInfoView = null;
3840 mPageInfoFromShowSSLCertificateOnError = null;
3841
3842 // if we came here from the SSL error dialog
3843 if (fromShowSSLCertificateOnError) {
3844 // go back to the SSL error dialog
3845 showSSLCertificateOnError(
3846 mSSLCertificateOnErrorView,
3847 mSSLCertificateOnErrorHandler,
3848 mSSLCertificateOnErrorError);
3849 } else {
3850 // otherwise, display the top-most certificate from
3851 // the chain
3852 if (view.getCertificate() != null) {
3853 showSSLCertificate(tab);
3854 }
3855 }
3856 }
3857 });
3858 }
3859
3860 mPageInfoDialog = alertDialogBuilder.show();
3861 }
3862
3863 /**
3864 * Displays the main top-level page SSL certificate dialog
3865 * (accessible from the Page-Info dialog).
3866 * @param tab The tab to show certificate for.
3867 */
3868 private void showSSLCertificate(final TabControl.Tab tab) {
3869 final View certificateView =
3870 inflateCertificateView(tab.getWebView().getCertificate());
3871 if (certificateView == null) {
3872 return;
3873 }
3874
3875 LayoutInflater factory = LayoutInflater.from(this);
3876
3877 final LinearLayout placeholder =
3878 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3879
3880 LinearLayout ll = (LinearLayout) factory.inflate(
3881 R.layout.ssl_success, placeholder);
3882 ((TextView)ll.findViewById(R.id.success))
3883 .setText(R.string.ssl_certificate_is_valid);
3884
3885 mSSLCertificateView = tab;
3886 mSSLCertificateDialog =
3887 new AlertDialog.Builder(this)
3888 .setTitle(R.string.ssl_certificate).setIcon(
3889 R.drawable.ic_dialog_browser_certificate_secure)
3890 .setView(certificateView)
3891 .setPositiveButton(R.string.ok,
3892 new DialogInterface.OnClickListener() {
3893 public void onClick(DialogInterface dialog,
3894 int whichButton) {
3895 mSSLCertificateDialog = null;
3896 mSSLCertificateView = null;
3897
3898 showPageInfo(tab, false);
3899 }
3900 })
3901 .setOnCancelListener(
3902 new DialogInterface.OnCancelListener() {
3903 public void onCancel(DialogInterface dialog) {
3904 mSSLCertificateDialog = null;
3905 mSSLCertificateView = null;
3906
3907 showPageInfo(tab, false);
3908 }
3909 })
3910 .show();
3911 }
3912
3913 /**
3914 * Displays the SSL error certificate dialog.
3915 * @param view The target web-view.
3916 * @param handler The SSL error handler responsible for cancelling the
3917 * connection that resulted in an SSL error or proceeding per user request.
3918 * @param error The SSL error object.
3919 */
3920 private void showSSLCertificateOnError(
3921 final WebView view, final SslErrorHandler handler, final SslError error) {
3922
3923 final View certificateView =
3924 inflateCertificateView(error.getCertificate());
3925 if (certificateView == null) {
3926 return;
3927 }
3928
3929 LayoutInflater factory = LayoutInflater.from(this);
3930
3931 final LinearLayout placeholder =
3932 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3933
3934 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3935 LinearLayout ll = (LinearLayout)factory
3936 .inflate(R.layout.ssl_warning, placeholder);
3937 ((TextView)ll.findViewById(R.id.warning))
3938 .setText(R.string.ssl_untrusted);
3939 }
3940
3941 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3942 LinearLayout ll = (LinearLayout)factory
3943 .inflate(R.layout.ssl_warning, placeholder);
3944 ((TextView)ll.findViewById(R.id.warning))
3945 .setText(R.string.ssl_mismatch);
3946 }
3947
3948 if (error.hasError(SslError.SSL_EXPIRED)) {
3949 LinearLayout ll = (LinearLayout)factory
3950 .inflate(R.layout.ssl_warning, placeholder);
3951 ((TextView)ll.findViewById(R.id.warning))
3952 .setText(R.string.ssl_expired);
3953 }
3954
3955 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3956 LinearLayout ll = (LinearLayout)factory
3957 .inflate(R.layout.ssl_warning, placeholder);
3958 ((TextView)ll.findViewById(R.id.warning))
3959 .setText(R.string.ssl_not_yet_valid);
3960 }
3961
3962 mSSLCertificateOnErrorHandler = handler;
3963 mSSLCertificateOnErrorView = view;
3964 mSSLCertificateOnErrorError = error;
3965 mSSLCertificateOnErrorDialog =
3966 new AlertDialog.Builder(this)
3967 .setTitle(R.string.ssl_certificate).setIcon(
3968 R.drawable.ic_dialog_browser_certificate_partially_secure)
3969 .setView(certificateView)
3970 .setPositiveButton(R.string.ok,
3971 new DialogInterface.OnClickListener() {
3972 public void onClick(DialogInterface dialog,
3973 int whichButton) {
3974 mSSLCertificateOnErrorDialog = null;
3975 mSSLCertificateOnErrorView = null;
3976 mSSLCertificateOnErrorHandler = null;
3977 mSSLCertificateOnErrorError = null;
3978
3979 mWebViewClient.onReceivedSslError(
3980 view, handler, error);
3981 }
3982 })
3983 .setNeutralButton(R.string.page_info_view,
3984 new DialogInterface.OnClickListener() {
3985 public void onClick(DialogInterface dialog,
3986 int whichButton) {
3987 mSSLCertificateOnErrorDialog = null;
3988
3989 // do not clear the dialog state: we will
3990 // need to show the dialog again once the
3991 // user is done exploring the page-info details
3992
3993 showPageInfo(mTabControl.getTabFromView(view),
3994 true);
3995 }
3996 })
3997 .setOnCancelListener(
3998 new DialogInterface.OnCancelListener() {
3999 public void onCancel(DialogInterface dialog) {
4000 mSSLCertificateOnErrorDialog = null;
4001 mSSLCertificateOnErrorView = null;
4002 mSSLCertificateOnErrorHandler = null;
4003 mSSLCertificateOnErrorError = null;
4004
4005 mWebViewClient.onReceivedSslError(
4006 view, handler, error);
4007 }
4008 })
4009 .show();
4010 }
4011
4012 /**
4013 * Inflates the SSL certificate view (helper method).
4014 * @param certificate The SSL certificate.
4015 * @return The resultant certificate view with issued-to, issued-by,
4016 * issued-on, expires-on, and possibly other fields set.
4017 * If the input certificate is null, returns null.
4018 */
4019 private View inflateCertificateView(SslCertificate certificate) {
4020 if (certificate == null) {
4021 return null;
4022 }
4023
4024 LayoutInflater factory = LayoutInflater.from(this);
4025
4026 View certificateView = factory.inflate(
4027 R.layout.ssl_certificate, null);
4028
4029 // issued to:
4030 SslCertificate.DName issuedTo = certificate.getIssuedTo();
4031 if (issuedTo != null) {
4032 ((TextView) certificateView.findViewById(R.id.to_common))
4033 .setText(issuedTo.getCName());
4034 ((TextView) certificateView.findViewById(R.id.to_org))
4035 .setText(issuedTo.getOName());
4036 ((TextView) certificateView.findViewById(R.id.to_org_unit))
4037 .setText(issuedTo.getUName());
4038 }
4039
4040 // issued by:
4041 SslCertificate.DName issuedBy = certificate.getIssuedBy();
4042 if (issuedBy != null) {
4043 ((TextView) certificateView.findViewById(R.id.by_common))
4044 .setText(issuedBy.getCName());
4045 ((TextView) certificateView.findViewById(R.id.by_org))
4046 .setText(issuedBy.getOName());
4047 ((TextView) certificateView.findViewById(R.id.by_org_unit))
4048 .setText(issuedBy.getUName());
4049 }
4050
4051 // issued on:
4052 String issuedOn = reformatCertificateDate(
4053 certificate.getValidNotBefore());
4054 ((TextView) certificateView.findViewById(R.id.issued_on))
4055 .setText(issuedOn);
4056
4057 // expires on:
4058 String expiresOn = reformatCertificateDate(
4059 certificate.getValidNotAfter());
4060 ((TextView) certificateView.findViewById(R.id.expires_on))
4061 .setText(expiresOn);
4062
4063 return certificateView;
4064 }
4065
4066 /**
4067 * Re-formats the certificate date (Date.toString()) string to
4068 * a properly localized date string.
4069 * @return Properly localized version of the certificate date string and
4070 * the original certificate date string if fails to localize.
4071 * If the original string is null, returns an empty string "".
4072 */
4073 private String reformatCertificateDate(String certificateDate) {
4074 String reformattedDate = null;
4075
4076 if (certificateDate != null) {
4077 Date date = null;
4078 try {
4079 date = java.text.DateFormat.getInstance().parse(certificateDate);
4080 } catch (ParseException e) {
4081 date = null;
4082 }
4083
4084 if (date != null) {
4085 reformattedDate =
4086 DateFormat.getDateFormat(this).format(date);
4087 }
4088 }
4089
4090 return reformattedDate != null ? reformattedDate :
4091 (certificateDate != null ? certificateDate : "");
4092 }
4093
4094 /**
4095 * Displays an http-authentication dialog.
4096 */
4097 private void showHttpAuthentication(final HttpAuthHandler handler,
4098 final String host, final String realm, final String title,
4099 final String name, final String password, int focusId) {
4100 LayoutInflater factory = LayoutInflater.from(this);
4101 final View v = factory
4102 .inflate(R.layout.http_authentication, null);
4103 if (name != null) {
4104 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4105 }
4106 if (password != null) {
4107 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4108 }
4109
4110 String titleText = title;
4111 if (titleText == null) {
4112 titleText = getText(R.string.sign_in_to).toString().replace(
4113 "%s1", host).replace("%s2", realm);
4114 }
4115
4116 mHttpAuthHandler = handler;
4117 AlertDialog dialog = new AlertDialog.Builder(this)
4118 .setTitle(titleText)
4119 .setIcon(android.R.drawable.ic_dialog_alert)
4120 .setView(v)
4121 .setPositiveButton(R.string.action,
4122 new DialogInterface.OnClickListener() {
4123 public void onClick(DialogInterface dialog,
4124 int whichButton) {
4125 String nm = ((EditText) v
4126 .findViewById(R.id.username_edit))
4127 .getText().toString();
4128 String pw = ((EditText) v
4129 .findViewById(R.id.password_edit))
4130 .getText().toString();
4131 BrowserActivity.this.setHttpAuthUsernamePassword
4132 (host, realm, nm, pw);
4133 handler.proceed(nm, pw);
4134 mHttpAuthenticationDialog = null;
4135 mHttpAuthHandler = null;
4136 }})
4137 .setNegativeButton(R.string.cancel,
4138 new DialogInterface.OnClickListener() {
4139 public void onClick(DialogInterface dialog,
4140 int whichButton) {
4141 handler.cancel();
4142 BrowserActivity.this.resetTitleAndRevertLockIcon();
4143 mHttpAuthenticationDialog = null;
4144 mHttpAuthHandler = null;
4145 }})
4146 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4147 public void onCancel(DialogInterface dialog) {
4148 handler.cancel();
4149 BrowserActivity.this.resetTitleAndRevertLockIcon();
4150 mHttpAuthenticationDialog = null;
4151 mHttpAuthHandler = null;
4152 }})
4153 .create();
4154 // Make the IME appear when the dialog is displayed if applicable.
4155 dialog.getWindow().setSoftInputMode(
4156 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4157 dialog.show();
4158 if (focusId != 0) {
4159 dialog.findViewById(focusId).requestFocus();
4160 } else {
4161 v.findViewById(R.id.username_edit).requestFocus();
4162 }
4163 mHttpAuthenticationDialog = dialog;
4164 }
4165
4166 public int getProgress() {
4167 WebView w = mTabControl.getCurrentWebView();
4168 if (w != null) {
4169 return w.getProgress();
4170 } else {
4171 return 100;
4172 }
4173 }
4174
4175 /**
4176 * Set HTTP authentication password.
4177 *
4178 * @param host The host for the password
4179 * @param realm The realm for the password
4180 * @param username The username for the password. If it is null, it means
4181 * password can't be saved.
4182 * @param password The password
4183 */
4184 public void setHttpAuthUsernamePassword(String host, String realm,
4185 String username,
4186 String password) {
4187 WebView w = mTabControl.getCurrentWebView();
4188 if (w != null) {
4189 w.setHttpAuthUsernamePassword(host, realm, username, password);
4190 }
4191 }
4192
4193 /**
4194 * connectivity manager says net has come or gone... inform the user
4195 * @param up true if net has come up, false if net has gone down
4196 */
4197 public void onNetworkToggle(boolean up) {
4198 if (up == mIsNetworkUp) {
4199 return;
4200 } else if (up) {
4201 mIsNetworkUp = true;
4202 if (mAlertDialog != null) {
4203 mAlertDialog.cancel();
4204 mAlertDialog = null;
4205 }
4206 } else {
4207 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004208 if (mInLoad) {
4209 createAndShowNetworkDialog();
4210 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004211 }
4212 WebView w = mTabControl.getCurrentWebView();
4213 if (w != null) {
4214 w.setNetworkAvailable(up);
4215 }
4216 }
4217
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004218 // This method shows the network dialog alerting the user that the net is
4219 // down. It will only show the dialog if mAlertDialog is null.
4220 private void createAndShowNetworkDialog() {
4221 if (mAlertDialog == null) {
4222 mAlertDialog = new AlertDialog.Builder(this)
4223 .setTitle(R.string.loadSuspendedTitle)
4224 .setMessage(R.string.loadSuspended)
4225 .setPositiveButton(R.string.ok, null)
4226 .show();
4227 }
4228 }
4229
The Android Open Source Project0c908882009-03-03 19:32:16 -08004230 @Override
4231 protected void onActivityResult(int requestCode, int resultCode,
4232 Intent intent) {
4233 switch (requestCode) {
4234 case COMBO_PAGE:
4235 if (resultCode == RESULT_OK && intent != null) {
4236 String data = intent.getAction();
4237 Bundle extras = intent.getExtras();
4238 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04004239 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004240 } else {
4241 final TabControl.Tab currentTab =
4242 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04004243 dismissSubWindow(currentTab);
4244 if (data != null && data.length() != 0) {
4245 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004246 }
4247 }
4248 }
4249 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004250 // Choose a file from the file picker.
4251 case FILE_SELECTED:
4252 if (null == mUploadMessage) break;
4253 Uri result = intent == null || resultCode != RESULT_OK ? null
4254 : intent.getData();
4255 mUploadMessage.onReceiveValue(result);
4256 mUploadMessage = null;
4257 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004258 default:
4259 break;
4260 }
Leon Scroggins30444232009-09-04 18:36:20 -04004261 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004262 }
4263
4264 /*
4265 * This method is called as a result of the user selecting the options
4266 * menu to see the download window, or when a download changes state. It
4267 * shows the download window ontop of the current window.
4268 */
4269 /* package */ void viewDownloads(Uri downloadRecord) {
4270 Intent intent = new Intent(this,
4271 BrowserDownloadPage.class);
4272 intent.setData(downloadRecord);
4273 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4274
4275 }
4276
Leon Scroggins160a7e72009-08-14 18:28:01 -04004277 /**
4278 * Open the Go page.
4279 * @param startWithHistory If true, open starting on the history tab.
4280 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004281 */
Leon Scroggins30444232009-09-04 18:36:20 -04004282 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004283 WebView current = mTabControl.getCurrentWebView();
4284 if (current == null) {
4285 return;
4286 }
4287 Intent intent = new Intent(this,
4288 CombinedBookmarkHistoryActivity.class);
4289 String title = current.getTitle();
4290 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004291 Bitmap thumbnail = createScreenshot(current);
4292
The Android Open Source Project0c908882009-03-03 19:32:16 -08004293 // Just in case the user opens bookmarks before a page finishes loading
4294 // so the current history item, and therefore the page, is null.
4295 if (null == url) {
4296 url = mLastEnteredUrl;
4297 // This can happen.
4298 if (null == url) {
4299 url = mSettings.getHomePage();
4300 }
4301 }
4302 // In case the web page has not yet received its associated title.
4303 if (title == null) {
4304 title = url;
4305 }
4306 intent.putExtra("title", title);
4307 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004308 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04004309 // Disable opening in a new window if we have maxed out the windows
4310 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4311 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004312 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004313 if (startWithHistory) {
4314 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4315 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4316 }
4317 startActivityForResult(intent, COMBO_PAGE);
4318 }
4319
4320 // Called when loading from context menu or LOAD_URL message
4321 private void loadURL(WebView view, String url) {
4322 // In case the user enters nothing.
4323 if (url != null && url.length() != 0 && view != null) {
4324 url = smartUrlFilter(url);
4325 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4326 view.loadUrl(url);
4327 }
4328 }
4329 }
4330
The Android Open Source Project0c908882009-03-03 19:32:16 -08004331 private String smartUrlFilter(Uri inUri) {
4332 if (inUri != null) {
4333 return smartUrlFilter(inUri.toString());
4334 }
4335 return null;
4336 }
4337
4338
4339 // get window count
4340
4341 int getWindowCount(){
4342 if(mTabControl != null){
4343 return mTabControl.getTabCount();
4344 }
4345 return 0;
4346 }
4347
Feng Qianb34f87a2009-03-24 21:27:26 -07004348 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004349 "(?i)" + // switch on case insensitive matching
4350 "(" + // begin group for schema
4351 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004352 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004353 ")" +
4354 "(.*)" );
4355
4356 /**
4357 * Attempts to determine whether user input is a URL or search
4358 * terms. Anything with a space is passed to search.
4359 *
4360 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4361 * "Http://" converts to "http://"
4362 *
4363 * @return Original or modified URL
4364 *
4365 */
4366 String smartUrlFilter(String url) {
4367
4368 String inUrl = url.trim();
4369 boolean hasSpace = inUrl.indexOf(' ') != -1;
4370
4371 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4372 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004373 // force scheme to lowercase
4374 String scheme = matcher.group(1);
4375 String lcScheme = scheme.toLowerCase();
4376 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004377 inUrl = lcScheme + matcher.group(2);
4378 }
4379 if (hasSpace) {
4380 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004381 }
4382 return inUrl;
4383 }
4384 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004385 // FIXME: Is this the correct place to add to searches?
4386 // what if someone else calls this function?
4387 int shortcut = parseUrlShortcut(inUrl);
4388 if (shortcut != SHORTCUT_INVALID) {
4389 Browser.addSearchUrl(mResolver, inUrl);
4390 String query = inUrl.substring(2);
4391 switch (shortcut) {
4392 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004393 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004394 case SHORTCUT_WIKIPEDIA_SEARCH:
4395 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4396 case SHORTCUT_DICTIONARY_SEARCH:
4397 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4398 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004399 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004400 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004401 }
4402 }
4403 } else {
4404 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4405 return URLUtil.guessUrl(inUrl);
4406 }
4407 }
4408
4409 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004410 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004411 }
4412
Ben Murdochbff2d602009-07-01 20:19:05 +01004413 /* package */ void setShouldShowErrorConsole(boolean flag) {
4414 if (flag == mShouldShowErrorConsole) {
4415 // Nothing to do.
4416 return;
4417 }
4418
4419 mShouldShowErrorConsole = flag;
4420
4421 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4422
4423 if (flag) {
4424 // Setting the show state of the console will cause it's the layout to be inflated.
4425 if (errorConsole.numberOfErrors() > 0) {
4426 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4427 } else {
4428 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4429 }
4430
4431 // Now we can add it to the main view.
4432 mErrorConsoleContainer.addView(errorConsole,
4433 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4434 ViewGroup.LayoutParams.WRAP_CONTENT));
4435 } else {
4436 mErrorConsoleContainer.removeView(errorConsole);
4437 }
4438
4439 }
4440
Grace Klobaeb6eef42009-09-15 17:56:32 -07004441 final static int LOCK_ICON_UNSECURE = 0;
4442 final static int LOCK_ICON_SECURE = 1;
4443 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004444
4445 private int mLockIconType = LOCK_ICON_UNSECURE;
4446 private int mPrevLockType = LOCK_ICON_UNSECURE;
4447
4448 private BrowserSettings mSettings;
4449 private TabControl mTabControl;
4450 private ContentResolver mResolver;
4451 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004452 private View mCustomView;
4453 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004454 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004455
4456 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4457 // view, we should rewrite this.
4458 private int mCurrentMenuState = 0;
4459 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004460 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004461 private static final int EMPTY_MENU = -1;
4462 private Menu mMenu;
4463
4464 private FindDialog mFindDialog;
4465 // Used to prevent chording to result in firing two shortcuts immediately
4466 // one after another. Fixes bug 1211714.
4467 boolean mCanChord;
4468
4469 private boolean mInLoad;
4470 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004471 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004472
4473 private boolean mPageStarted;
4474 private boolean mActivityInPause = true;
4475
4476 private boolean mMenuIsDown;
4477
The Android Open Source Project0c908882009-03-03 19:32:16 -08004478 private static boolean mInTrace;
4479
4480 // Performance probe
4481 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4482 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4483 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4484 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4485 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4486 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4487 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4488 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4489 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4490 };
4491
4492 private long mStart;
4493 private long mProcessStart;
4494 private long mUserStart;
4495 private long mSystemStart;
4496 private long mIdleStart;
4497 private long mIrqStart;
4498
4499 private long mUiStart;
4500
4501 private Drawable mMixLockIcon;
4502 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004503
4504 /* hold a ref so we can auto-cancel if necessary */
4505 private AlertDialog mAlertDialog;
4506
4507 // Wait for credentials before loading google.com
4508 private ProgressDialog mCredsDlg;
4509
4510 // The up-to-date URL and title (these can be different from those stored
4511 // in WebView, since it takes some time for the information in WebView to
4512 // get updated)
4513 private String mUrl;
4514 private String mTitle;
4515
4516 // As PageInfo has different style for landscape / portrait, we have
4517 // to re-open it when configuration changed
4518 private AlertDialog mPageInfoDialog;
4519 private TabControl.Tab mPageInfoView;
4520 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4521 // dialog, we should not just dismiss it, but should get back to the
4522 // SSL-certificate-on-error dialog. This flag is used to store this state
4523 private Boolean mPageInfoFromShowSSLCertificateOnError;
4524
4525 // as SSLCertificateOnError has different style for landscape / portrait,
4526 // we have to re-open it when configuration changed
4527 private AlertDialog mSSLCertificateOnErrorDialog;
4528 private WebView mSSLCertificateOnErrorView;
4529 private SslErrorHandler mSSLCertificateOnErrorHandler;
4530 private SslError mSSLCertificateOnErrorError;
4531
4532 // as SSLCertificate has different style for landscape / portrait, we
4533 // have to re-open it when configuration changed
4534 private AlertDialog mSSLCertificateDialog;
4535 private TabControl.Tab mSSLCertificateView;
4536
4537 // as HttpAuthentication has different style for landscape / portrait, we
4538 // have to re-open it when configuration changed
4539 private AlertDialog mHttpAuthenticationDialog;
4540 private HttpAuthHandler mHttpAuthHandler;
4541
4542 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4543 new FrameLayout.LayoutParams(
4544 ViewGroup.LayoutParams.FILL_PARENT,
4545 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004546 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4547 new FrameLayout.LayoutParams(
4548 ViewGroup.LayoutParams.FILL_PARENT,
4549 ViewGroup.LayoutParams.FILL_PARENT,
4550 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004551 // Google search
4552 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004553 // Wikipedia search
4554 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4555 // Dictionary search
4556 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4557 // Google Mobile Local search
4558 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4559
4560 final static String QUERY_PLACE_HOLDER = "%s";
4561
4562 // "source" parameter for Google search through search key
4563 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4564 // "source" parameter for Google search through goto menu
4565 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4566 // "source" parameter for Google search through simplily type
4567 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4568 // "source" parameter for Google search suggested by the browser
4569 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4570 // "source" parameter for Google search from unknown source
4571 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4572
4573 private final static String LOGTAG = "browser";
4574
The Android Open Source Project0c908882009-03-03 19:32:16 -08004575 private String mLastEnteredUrl;
4576
4577 private PowerManager.WakeLock mWakeLock;
4578 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4579
4580 private Toast mStopToast;
4581
Leon Scroggins68579392009-09-15 15:31:54 -04004582 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004583
Ben Murdochbff2d602009-07-01 20:19:05 +01004584 private LinearLayout mErrorConsoleContainer = null;
4585 private boolean mShouldShowErrorConsole = false;
4586
The Android Open Source Project0c908882009-03-03 19:32:16 -08004587 // As the ids are dynamically created, we can't guarantee that they will
4588 // be in sequence, so this static array maps ids to a window number.
4589 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4590 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4591 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4592 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4593
4594 // monitor platform changes
4595 private IntentFilter mNetworkStateChangedFilter;
4596 private BroadcastReceiver mNetworkStateIntentReceiver;
4597
Grace Klobab4da0ad2009-05-14 14:45:40 -07004598 private BroadcastReceiver mPackageInstallationReceiver;
4599
Patrick Scott59ce8302009-09-18 16:29:38 -04004600 // AsyncTask for downloading touch icons
4601 /* package */ DownloadTouchIcon mTouchIconLoader;
4602
The Android Open Source Project0c908882009-03-03 19:32:16 -08004603 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004604 final static int COMBO_PAGE = 1;
4605 final static int DOWNLOAD_PAGE = 2;
4606 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004607 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004608
Andrei Popescu540035d2009-09-18 18:59:20 +01004609 // the default <video> poster
4610 private Bitmap mDefaultVideoPoster;
4611 // the video progress view
4612 private View mVideoProgressView;
4613
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004614 /**
4615 * A UrlData class to abstract how the content will be set to WebView.
4616 * This base class uses loadUrl to show the content.
4617 */
4618 private static class UrlData {
4619 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004620 byte[] mPostData;
4621
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004622 UrlData(String url) {
4623 this.mUrl = url;
4624 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004625
4626 void setPostData(byte[] postData) {
4627 mPostData = postData;
4628 }
4629
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004630 boolean isEmpty() {
4631 return mUrl == null || mUrl.length() == 0;
4632 }
4633
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004634 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004635 if (mPostData != null) {
4636 webView.postUrl(mUrl, mPostData);
4637 } else {
4638 webView.loadUrl(mUrl);
4639 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004640 }
4641 };
4642
4643 /**
4644 * A subclass of UrlData class that can display inlined content using
4645 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4646 */
4647 private static class InlinedUrlData extends UrlData {
4648 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4649 super(failUrl);
4650 mInlined = inlined;
4651 mMimeType = mimeType;
4652 mEncoding = encoding;
4653 }
4654 String mMimeType;
4655 String mInlined;
4656 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004657 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004658 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004659 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004660 }
4661
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004662 @Override
4663 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004664 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4665 }
4666 }
4667
Leon Scroggins1f005d32009-08-10 17:36:42 -04004668 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004669}