blob: 65b7911ef5ee1ede88c7130df04fe352a7791363 [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;
133import java.io.FileInputStream;
134import java.io.FileOutputStream;
135import java.io.IOException;
136import java.io.InputStream;
137import java.net.MalformedURLException;
138import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700139import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800140import java.net.URL;
141import java.net.URLEncoder;
142import java.text.ParseException;
143import java.util.Date;
144import java.util.Enumeration;
145import java.util.HashMap;
Patrick Scott37911c72009-03-24 18:02:58 -0700146import java.util.LinkedList;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800147import java.util.Vector;
148import java.util.regex.Matcher;
149import java.util.regex.Pattern;
150import java.util.zip.ZipEntry;
151import java.util.zip.ZipFile;
152
153public class BrowserActivity extends Activity
Grace Kloba5942df02009-09-18 11:48:29 -0700154 implements View.OnCreateContextMenuListener,
The Android Open Source Project0c908882009-03-03 19:32:16 -0800155 DownloadListener {
156
Dave Bort31a6d1c2009-04-13 15:56:49 -0700157 /* Define some aliases to make these debugging flags easier to refer to.
158 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
159 */
160 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
161 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
162 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
163
The Android Open Source Project0c908882009-03-03 19:32:16 -0800164 private IGoogleLoginService mGls = null;
165 private ServiceConnection mGlsConnection = null;
166
167 private SensorManager mSensorManager = null;
168
Satish Sampath565505b2009-05-29 15:37:27 +0100169 // These are single-character shortcuts for searching popular sources.
170 private static final int SHORTCUT_INVALID = 0;
171 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
172 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
173 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
174 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
175
The Android Open Source Project0c908882009-03-03 19:32:16 -0800176 /* Whitelisted webpages
177 private static HashSet<String> sWhiteList;
178
179 static {
180 sWhiteList = new HashSet<String>();
181 sWhiteList.add("cnn.com/");
182 sWhiteList.add("espn.go.com/");
183 sWhiteList.add("nytimes.com/");
184 sWhiteList.add("engadget.com/");
185 sWhiteList.add("yahoo.com/");
186 sWhiteList.add("msn.com/");
187 sWhiteList.add("amazon.com/");
188 sWhiteList.add("consumerist.com/");
189 sWhiteList.add("google.com/m/news");
190 }
191 */
192
193 private void setupHomePage() {
194 final Runnable getAccount = new Runnable() {
195 public void run() {
196 // Lower priority
197 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
198 // get the default home page
199 String homepage = mSettings.getHomePage();
200
201 try {
202 if (mGls == null) return;
203
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700204 if (!homepage.startsWith("http://www.google.")) return;
205 if (homepage.indexOf('?') == -1) return;
206
The Android Open Source Project0c908882009-03-03 19:32:16 -0800207 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
208 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
209
210 // three cases:
211 //
212 // hostedUser == googleUser
213 // The device has only a google account
214 //
215 // hostedUser != googleUser
216 // The device has a hosted account and a google account
217 //
218 // hostedUser != null, googleUser == null
219 // The device has only a hosted account (so far)
220
221 // developers might have no accounts at all
222 if (hostedUser == null) return;
223
224 if (googleUser == null || !hostedUser.equals(googleUser)) {
225 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700226 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800227 }
228 } catch (RemoteException ignore) {
229 // Login service died; carry on
230 } catch (RuntimeException ignore) {
231 // Login service died; carry on
232 } finally {
233 finish(homepage);
234 }
235 }
236
237 private void finish(final String homepage) {
238 mHandler.post(new Runnable() {
239 public void run() {
240 mSettings.setHomePage(BrowserActivity.this, homepage);
241 resumeAfterCredentials();
242
243 // as this is running in a separate thread,
244 // BrowserActivity's onDestroy() may have been called,
245 // which also calls unbindService().
246 if (mGlsConnection != null) {
247 // we no longer need to keep GLS open
248 unbindService(mGlsConnection);
249 mGlsConnection = null;
250 }
251 } });
252 } };
253
254 final boolean[] done = { false };
255
256 // Open a connection to the Google Login Service. The first
257 // time the connection is established, set up the homepage depending on
258 // the account in a background thread.
259 mGlsConnection = new ServiceConnection() {
260 public void onServiceConnected(ComponentName className, IBinder service) {
261 mGls = IGoogleLoginService.Stub.asInterface(service);
262 if (done[0] == false) {
263 done[0] = true;
264 Thread account = new Thread(getAccount);
265 account.setName("GLSAccount");
266 account.start();
267 }
268 }
269 public void onServiceDisconnected(ComponentName className) {
270 mGls = null;
271 }
272 };
273
274 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
275 mGlsConnection, Context.BIND_AUTO_CREATE);
276 }
277
Cary Clarka9771242009-08-11 16:42:26 -0400278 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800279 @Override
280 public Void doInBackground(File... files) {
281 if (files != null) {
282 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400283 if (!f.delete()) {
284 Log.e(LOGTAG, f.getPath() + " was not deleted");
285 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800286 }
287 }
288 return null;
289 }
290 }
291
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400292 /**
293 * This layout holds everything you see below the status bar, including the
294 * error console, the custom view container, and the webviews.
295 */
296 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400297
The Android Open Source Project0c908882009-03-03 19:32:16 -0800298 @Override public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700299 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800300 Log.v(LOGTAG, this + " onStart");
301 }
302 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800303 // test the browser in OpenGL
304 // requestWindowFeature(Window.FEATURE_OPENGL);
305
306 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
307
308 mResolver = getContentResolver();
309
Grace Kloba0923d692009-09-23 21:37:25 -0700310 // If this was a web search request, pass it on to the default web
311 // search provider and finish this activity.
312 if (handleWebSearchIntent(getIntent())) {
313 finish();
314 return;
315 }
316
The Android Open Source Project0c908882009-03-03 19:32:16 -0800317 //
318 // start MASF proxy service
319 //
320 //Intent proxyServiceIntent = new Intent();
321 //proxyServiceIntent.setComponent
322 // (new ComponentName(
323 // "com.android.masfproxyservice",
324 // "com.android.masfproxyservice.MasfProxyService"));
325 //startService(proxyServiceIntent, null);
326
327 mSecLockIcon = Resources.getSystem().getDrawable(
328 android.R.drawable.ic_secure);
329 mMixLockIcon = Resources.getSystem().getDrawable(
330 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800331
Leon Scroggins81db3662009-06-04 17:45:11 -0400332 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
333 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400334 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
335 .inflate(R.layout.custom_screen, null);
336 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
337 R.id.main_content);
338 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
339 .findViewById(R.id.error_console);
340 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
341 .findViewById(R.id.fullscreen_custom_content);
342 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400343 mTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800344
345 // Create the tab control and our initial tab
346 mTabControl = new TabControl(this);
347
348 // Open the icon database and retain all the bookmark urls for favicons
349 retainIconsOnStartup();
350
351 // Keep a settings instance handy.
352 mSettings = BrowserSettings.getInstance();
353 mSettings.setTabControl(mTabControl);
354 mSettings.loadFromDb(this);
355
356 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
357 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
358
Grace Klobaa34f6862009-07-31 16:28:17 -0700359 /* enables registration for changes in network status from
360 http stack */
361 mNetworkStateChangedFilter = new IntentFilter();
362 mNetworkStateChangedFilter.addAction(
363 ConnectivityManager.CONNECTIVITY_ACTION);
364 mNetworkStateIntentReceiver = new BroadcastReceiver() {
365 @Override
366 public void onReceive(Context context, Intent intent) {
367 if (intent.getAction().equals(
368 ConnectivityManager.CONNECTIVITY_ACTION)) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -0400369 NetworkInfo info =
370 (NetworkInfo) intent.getParcelableExtra(
371 ConnectivityManager.EXTRA_NETWORK_INFO);
372 onNetworkToggle(
373 (info != null) ? info.isConnected() : false);
Grace Klobaa34f6862009-07-31 16:28:17 -0700374 }
375 }
376 };
377
Grace Kloba615c6c92009-08-03 10:22:44 -0700378 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
379 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
380 filter.addDataScheme("package");
381 mPackageInstallationReceiver = new BroadcastReceiver() {
382 @Override
383 public void onReceive(Context context, Intent intent) {
384 final String action = intent.getAction();
385 final String packageName = intent.getData()
386 .getSchemeSpecificPart();
387 final boolean replacing = intent.getBooleanExtra(
388 Intent.EXTRA_REPLACING, false);
389 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
390 // if it is replacing, refreshPlugins() when adding
391 return;
392 }
393 PackageManager pm = BrowserActivity.this.getPackageManager();
394 PackageInfo pkgInfo = null;
395 try {
396 pkgInfo = pm.getPackageInfo(packageName,
397 PackageManager.GET_PERMISSIONS);
398 } catch (PackageManager.NameNotFoundException e) {
399 return;
400 }
401 if (pkgInfo != null) {
402 String permissions[] = pkgInfo.requestedPermissions;
403 if (permissions == null) {
404 return;
405 }
406 boolean permissionOk = false;
407 for (String permit : permissions) {
408 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
409 permissionOk = true;
410 break;
411 }
412 }
413 if (permissionOk) {
414 PluginManager.getInstance(BrowserActivity.this)
415 .refreshPlugins(
416 Intent.ACTION_PACKAGE_ADDED
417 .equals(action));
418 }
419 }
420 }
421 };
422 registerReceiver(mPackageInstallationReceiver, filter);
423
The Android Open Source Project0c908882009-03-03 19:32:16 -0800424 if (!mTabControl.restoreState(icicle)) {
425 // clear up the thumbnail directory if we can't restore the state as
426 // none of the files in the directory are referenced any more.
427 new ClearThumbnails().execute(
428 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700429 // there is no quit on Android. But if we can't restore the state,
430 // we can treat it as a new Browser, remove the old session cookies.
431 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800432 final Intent intent = getIntent();
433 final Bundle extra = intent.getExtras();
434 // Create an initial tab.
435 // If the intent is ACTION_VIEW and data is not null, the Browser is
436 // invoked to view the content by another application. In this case,
437 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700438 UrlData urlData = getUrlDataFromIntent(intent);
439
The Android Open Source Project0c908882009-03-03 19:32:16 -0800440 final TabControl.Tab t = mTabControl.createNewTab(
441 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700442 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700443 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800444 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800445 attachTabToContentView(t);
446 WebView webView = t.getWebView();
447 if (extra != null) {
448 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
449 if (scale > 0 && scale <= 1000) {
450 webView.setInitialScale(scale);
451 }
452 }
453 // If we are not restoring from an icicle, then there is a high
454 // likely hood this is the first run. So, check to see if the
455 // homepage needs to be configured and copy any plugins from our
456 // asset directory to the data partition.
457 if ((extra == null || !extra.getBoolean("testing"))
458 && !mSettings.isLoginInitialized()) {
459 setupHomePage();
460 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800461
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700462 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400463 if (mSettings.isLoginInitialized()) {
464 webView.loadUrl(mSettings.getHomePage());
465 } else {
466 waitForCredentials();
467 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800468 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700469 if (extra != null) {
470 urlData.setPostData(extra
471 .getByteArray(Browser.EXTRA_POST_DATA));
472 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700473 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800474 }
475 } else {
476 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400477 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800478 attachTabToContentView(mTabControl.getCurrentTab());
479 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700480
Feng Qianb3c02da2009-06-29 15:58:08 -0700481 // Read JavaScript flags if it exists.
482 String jsFlags = mSettings.getJsFlags();
483 if (jsFlags.trim().length() != 0) {
484 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
485 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800486 }
487
488 @Override
489 protected void onNewIntent(Intent intent) {
490 TabControl.Tab current = mTabControl.getCurrentTab();
491 // When a tab is closed on exit, the current tab index is set to -1.
492 // Reset before proceed as Browser requires the current tab to be set.
493 if (current == null) {
494 // Try to reset the tab in case the index was incorrect.
495 current = mTabControl.getTab(0);
496 if (current == null) {
497 // No tabs at all so just ignore this intent.
498 return;
499 }
500 mTabControl.setCurrentTab(current);
501 attachTabToContentView(current);
502 resetTitleAndIcon(current.getWebView());
503 }
504 final String action = intent.getAction();
505 final int flags = intent.getFlags();
506 if (Intent.ACTION_MAIN.equals(action) ||
507 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
508 // just resume the browser
509 return;
510 }
511 if (Intent.ACTION_VIEW.equals(action)
512 || Intent.ACTION_SEARCH.equals(action)
513 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
514 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100515 // If this was a search request (e.g. search query directly typed into the address bar),
516 // pass it on to the default web search provider.
517 if (handleWebSearchIntent(intent)) {
518 return;
519 }
520
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700521 UrlData urlData = getUrlDataFromIntent(intent);
522 if (urlData.isEmpty()) {
523 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800524 }
Grace Kloba81678d92009-06-30 07:09:56 -0700525 urlData.setPostData(intent
526 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700527
Grace Klobacc634032009-07-28 15:58:19 -0700528 final String appId = intent
529 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
530 if (Intent.ACTION_VIEW.equals(action)
531 && !getPackageName().equals(appId)
532 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Patrick Scottcd115892009-07-16 09:42:58 -0400533 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700534 if (appTab != null) {
535 Log.i(LOGTAG, "Reusing tab for " + appId);
536 // Dismiss the subwindow if applicable.
537 dismissSubWindow(appTab);
538 // Since we might kill the WebView, remove it from the
539 // content view first.
540 removeTabFromContentView(appTab);
541 // Recreate the main WebView after destroying the old one.
542 // If the WebView has the same original url and is on that
543 // page, it can be reused.
544 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700545 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100546
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700547 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400548 switchToTab(mTabControl.getTabIndex(appTab));
549 if (needsLoad) {
550 urlData.loadIn(appTab.getWebView());
551 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700552 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400553 // If the tab was the current tab, we have to attach
554 // it to the view system again.
555 attachTabToContentView(appTab);
556 if (needsLoad) {
557 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700558 }
559 }
560 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400561 } else {
562 // No matching application tab, try to find a regular tab
563 // with a matching url.
564 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400565 if (appTab != null) {
566 if (current != appTab) {
567 switchToTab(mTabControl.getTabIndex(appTab));
568 }
569 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400570 } else {
571 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
572 // will be opened in a new tab unless we have reached
573 // MAX_TABS. Then the url will be opened in the current
574 // tab. If a new tab is created, it will have "true" for
575 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400576 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400577 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700578 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800579 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700580 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800581 mSettings.toggleDebugSettings();
582 return;
583 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400584 // Get rid of the subwindow if it exists
585 dismissSubWindow(current);
586 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800587 }
588 }
589 }
590
Satish Sampath565505b2009-05-29 15:37:27 +0100591 private int parseUrlShortcut(String url) {
592 if (url == null) return SHORTCUT_INVALID;
593
594 // FIXME: quick search, need to be customized by setting
595 if (url.length() > 2 && url.charAt(1) == ' ') {
596 switch (url.charAt(0)) {
597 case 'g': return SHORTCUT_GOOGLE_SEARCH;
598 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
599 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
600 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
601 }
602 }
603 return SHORTCUT_INVALID;
604 }
605
606 /**
607 * Launches the default web search activity with the query parameters if the given intent's data
608 * are identified as plain search terms and not URLs/shortcuts.
609 * @return true if the intent was handled and web search activity was launched, false if not.
610 */
611 private boolean handleWebSearchIntent(Intent intent) {
612 if (intent == null) return false;
613
614 String url = null;
615 final String action = intent.getAction();
616 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700617 Uri data = intent.getData();
618 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100619 } else if (Intent.ACTION_SEARCH.equals(action)
620 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
621 || Intent.ACTION_WEB_SEARCH.equals(action)) {
622 url = intent.getStringExtra(SearchManager.QUERY);
623 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100624 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
625 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100626 }
627
628 /**
629 * Launches the default web search activity with the query parameters if the given url string
630 * was identified as plain search terms and not URL/shortcut.
631 * @return true if the request was handled and web search activity was launched, false if not.
632 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100633 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100634 if (inUrl == null) return false;
635
636 // In general, we shouldn't modify URL from Intent.
637 // But currently, we get the user-typed URL from search box as well.
638 String url = fixUrl(inUrl).trim();
639
640 // URLs and site specific search shortcuts are handled by the regular flow of control, so
641 // return early.
642 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100643 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100644 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
645 return false;
646 }
647
648 Browser.updateVisitedHistory(mResolver, url, false);
649 Browser.addSearchUrl(mResolver, url);
650
651 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
652 intent.addCategory(Intent.CATEGORY_DEFAULT);
653 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100654 if (appData != null) {
655 intent.putExtra(SearchManager.APP_DATA, appData);
656 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100657 if (extraData != null) {
658 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
659 }
Grace Klobacc634032009-07-28 15:58:19 -0700660 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100661 startActivity(intent);
662
663 return true;
664 }
665
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700666 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800667 String url = null;
668 if (intent != null) {
669 final String action = intent.getAction();
670 if (Intent.ACTION_VIEW.equals(action)) {
671 url = smartUrlFilter(intent.getData());
672 if (url != null && url.startsWith("content:")) {
673 /* Append mimetype so webview knows how to display */
674 String mimeType = intent.resolveType(getContentResolver());
675 if (mimeType != null) {
676 url += "?" + mimeType;
677 }
678 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700679 if ("inline:".equals(url)) {
680 return new InlinedUrlData(
681 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
682 intent.getType(),
683 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
684 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
685 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800686 } else if (Intent.ACTION_SEARCH.equals(action)
687 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
688 || Intent.ACTION_WEB_SEARCH.equals(action)) {
689 url = intent.getStringExtra(SearchManager.QUERY);
690 if (url != null) {
691 mLastEnteredUrl = url;
692 // Don't add Urls, just search terms.
693 // Urls will get added when the page is loaded.
694 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
695 Browser.updateVisitedHistory(mResolver, url, false);
696 }
697 // In general, we shouldn't modify URL from Intent.
698 // But currently, we get the user-typed URL from search box as well.
699 url = fixUrl(url);
700 url = smartUrlFilter(url);
701 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
702 if (url.contains(searchSource)) {
703 String source = null;
704 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
705 if (appData != null) {
706 source = appData.getString(SearchManager.SOURCE);
707 }
708 if (TextUtils.isEmpty(source)) {
709 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
710 }
711 url = url.replace(searchSource, "&source=android-"+source+"&");
712 }
713 }
714 }
715 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700716 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800717 }
718
719 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400720 // FIXME: Converting the url to lower case
721 // duplicates functionality in smartUrlFilter().
722 // However, changing all current callers of fixUrl to
723 // call smartUrlFilter in addition may have unwanted
724 // consequences, and is deferred for now.
725 int colon = inUrl.indexOf(':');
726 boolean allLower = true;
727 for (int index = 0; index < colon; index++) {
728 char ch = inUrl.charAt(index);
729 if (!Character.isLetter(ch)) {
730 break;
731 }
732 allLower &= Character.isLowerCase(ch);
733 if (index == colon - 1 && !allLower) {
734 inUrl = inUrl.substring(0, colon).toLowerCase()
735 + inUrl.substring(colon);
736 }
737 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800738 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
739 return inUrl;
740 if (inUrl.startsWith("http:") ||
741 inUrl.startsWith("https:")) {
742 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
743 inUrl = inUrl.replaceFirst("/", "//");
744 } else inUrl = inUrl.replaceFirst(":", "://");
745 }
746 return inUrl;
747 }
748
749 /**
750 * Looking for the pattern like this
751 *
752 * *
753 * * *
754 * *** * *******
755 * * *
756 * * *
757 * *
758 */
759 private final SensorListener mSensorListener = new SensorListener() {
760 private long mLastGestureTime;
761 private float[] mPrev = new float[3];
762 private float[] mPrevDiff = new float[3];
763 private float[] mDiff = new float[3];
764 private float[] mRevertDiff = new float[3];
765
766 public void onSensorChanged(int sensor, float[] values) {
767 boolean show = false;
768 float[] diff = new float[3];
769
770 for (int i = 0; i < 3; i++) {
771 diff[i] = values[i] - mPrev[i];
772 if (Math.abs(diff[i]) > 1) {
773 show = true;
774 }
775 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
776 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
777 // start track when there is a big move, or revert
778 mRevertDiff[i] = mDiff[i];
779 mDiff[i] = 0;
780 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
781 // reset when it is flat
782 mDiff[i] = mRevertDiff[i] = 0;
783 }
784 mDiff[i] += diff[i];
785 mPrevDiff[i] = diff[i];
786 mPrev[i] = values[i];
787 }
788
789 if (false) {
790 // only shows if we think the delta is big enough, in an attempt
791 // to detect "serious" moves left/right or up/down
792 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
793 + values[0] + ", " + values[1] + ", " + values[2] + ")"
794 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
795 + ")");
796 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
797 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
798 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
799 + mRevertDiff[2] + ")");
800 }
801
802 long now = android.os.SystemClock.uptimeMillis();
803 if (now - mLastGestureTime > 1000) {
804 mLastGestureTime = 0;
805
806 float y = mDiff[1];
807 float z = mDiff[2];
808 float ay = Math.abs(y);
809 float az = Math.abs(z);
810 float ry = mRevertDiff[1];
811 float rz = mRevertDiff[2];
812 float ary = Math.abs(ry);
813 float arz = Math.abs(rz);
814 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
815 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
816
817 if ((gestY || gestZ) && !(gestY && gestZ)) {
818 WebView view = mTabControl.getCurrentWebView();
819
820 if (view != null) {
821 if (gestZ) {
822 if (z < 0) {
823 view.zoomOut();
824 } else {
825 view.zoomIn();
826 }
827 } else {
828 view.flingScroll(0, Math.round(y * 100));
829 }
830 }
831 mLastGestureTime = now;
832 }
833 }
834 }
835
836 public void onAccuracyChanged(int sensor, int accuracy) {
837 // TODO Auto-generated method stub
838
839 }
840 };
841
842 @Override protected void onResume() {
843 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700844 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800845 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
846 }
847
848 if (!mActivityInPause) {
849 Log.e(LOGTAG, "BrowserActivity is already resumed.");
850 return;
851 }
852
Mike Reed7bfa63b2009-05-28 11:08:32 -0400853 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800854 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400855 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800856
857 if (mWakeLock.isHeld()) {
858 mHandler.removeMessages(RELEASE_WAKELOCK);
859 mWakeLock.release();
860 }
861
862 if (mCredsDlg != null) {
863 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
864 // In case credential request never comes back
865 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
866 }
867 }
868
869 registerReceiver(mNetworkStateIntentReceiver,
870 mNetworkStateChangedFilter);
871 WebView.enablePlatformNotifications();
872
873 if (mSettings.doFlick()) {
874 if (mSensorManager == null) {
875 mSensorManager = (SensorManager) getSystemService(
876 Context.SENSOR_SERVICE);
877 }
878 mSensorManager.registerListener(mSensorListener,
879 SensorManager.SENSOR_ACCELEROMETER,
880 SensorManager.SENSOR_DELAY_FASTEST);
881 } else {
882 mSensorManager = null;
883 }
884 }
885
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400886 /**
887 * Since the actual title bar is embedded in the WebView, and removing it
888 * would change its appearance, create a temporary title bar to go at
889 * the top of the screen while the menu is open.
890 */
891 private TitleBar mFakeTitleBar;
892
893 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400894 * Holder for the fake title bar. It will have a foreground shadow, as well
895 * as a white background, so the fake title bar looks like the real one.
896 */
897 private ViewGroup mFakeTitleBarHolder;
898
899 /**
900 * Layout parameters for the fake title bar within mFakeTitleBarHolder
901 */
902 private FrameLayout.LayoutParams mFakeTitleBarParams
903 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400904 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400905 ViewGroup.LayoutParams.WRAP_CONTENT);
906 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400907 * Keeps track of whether the options menu is open. This is important in
908 * determining whether to show or hide the title bar overlay.
909 */
910 private boolean mOptionsMenuOpen;
911
912 /**
913 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
914 * of whether the configuration has changed. The first onMenuOpened call
915 * after a configuration change is simply a reopening of the same menu
916 * (i.e. mIconView did not change).
917 */
918 private boolean mConfigChanged;
919
920 /**
921 * Whether or not the options menu is in its smaller, icon menu form. When
922 * true, we want the title bar overlay to be up. When false, we do not.
923 * Only meaningful if mOptionsMenuOpen is true.
924 */
925 private boolean mIconView;
926
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400927 @Override
928 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400929 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
930 if (mOptionsMenuOpen) {
931 if (mConfigChanged) {
932 // We do not need to make any changes to the state of the
933 // title bar, since the only thing that happened was a
934 // change in orientation
935 mConfigChanged = false;
936 } else {
937 if (mIconView) {
938 // Switching the menu to expanded view, so hide the
939 // title bar.
940 hideFakeTitleBar();
941 mIconView = false;
942 } else {
943 // Switching the menu back to icon view, so show the
944 // title bar once again.
945 showFakeTitleBar();
946 mIconView = true;
947 }
948 }
949 } else {
950 // The options menu is closed, so open it, and show the title
951 showFakeTitleBar();
952 mOptionsMenuOpen = true;
953 mConfigChanged = false;
954 mIconView = true;
955 }
956 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400957 return true;
958 }
959
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400960 /**
961 * Special class used exclusively for the shadow drawn underneath the fake
962 * title bar. The shadow does not need to be drawn if the WebView
963 * underneath is scrolled to the top, because it will draw directly on top
964 * of the embedded shadow.
965 */
966 private static class Shadow extends View {
967 private WebView mWebView;
968
969 public Shadow(Context context, AttributeSet attrs) {
970 super(context, attrs);
971 }
972
973 public void setWebView(WebView view) {
974 mWebView = view;
975 }
976
977 @Override
978 public void draw(Canvas canvas) {
979 // In general onDraw is the method to override, but we care about
980 // whether or not the background gets drawn, which happens in draw()
981 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
982 super.draw(canvas);
983 }
984 // Need to invalidate so that if the scroll position changes, we
985 // still draw as appropriate.
986 invalidate();
987 }
988 }
989
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400990 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400991 final View decor = getWindow().peekDecorView();
Leon Scroggins4d7e4062009-09-15 15:49:45 -0400992 if (mFakeTitleBar == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400993 && !mActivityInPause && decor != null
994 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400995 Rect visRect = new Rect();
996 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
997 if (LOGD_ENABLED) {
998 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
999 }
1000 return;
1001 }
Leon Scrogginsf4bb18a2009-09-11 18:37:53 -04001002 final WebView webView = getTopWindow();
Leon Scroggins68579392009-09-15 15:31:54 -04001003 mFakeTitleBar = new TitleBar(this);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001004 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
1005 mFakeTitleBar.setProgress(webView.getProgress());
1006 mFakeTitleBar.setFavicon(webView.getFavicon());
1007 updateLockIconToLatest();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001008
1009 WindowManager manager
1010 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
1011
1012 // Add the title bar to the window manager so it can receive touches
1013 // while the menu is up
1014 WindowManager.LayoutParams params
1015 = new WindowManager.LayoutParams(
1016 ViewGroup.LayoutParams.FILL_PARENT,
1017 ViewGroup.LayoutParams.WRAP_CONTENT,
1018 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
1019 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -04001020 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001021 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04001022 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -04001023 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -04001024 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001025 // XXX : Without providing an offset, the fake title bar will be
1026 // placed underneath the status bar. Use the global visible rect
1027 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -04001028 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -04001029 // Add a holder for the title bar. It also holds a shadow to show
1030 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001031 if (mFakeTitleBarHolder == null) {
1032 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
1033 .inflate(R.layout.title_bar_bg, null);
1034 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -04001035 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
1036 R.id.shadow);
1037 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -04001038 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001039 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001040 }
1041 }
1042
1043 @Override
1044 public void onOptionsMenuClosed(Menu menu) {
1045 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04001046 if (!mInLoad) {
1047 hideFakeTitleBar();
1048 } else if (!mIconView) {
1049 // The page is currently loading, and we are in expanded mode, so
1050 // we were not showing the menu. Show it once again. It will be
1051 // removed when the page finishes.
1052 showFakeTitleBar();
1053 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001054 }
1055 private void hideFakeTitleBar() {
1056 if (mFakeTitleBar == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -04001057 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
1058 mFakeTitleBarHolder.getLayoutParams();
1059 WebView mainView = mTabControl.getCurrentWebView();
1060 // Although we decided whether or not to animate based on the current
1061 // scroll position, the scroll position may have changed since the
1062 // fake title bar was displayed. Make sure it has the appropriate
1063 // animation/lack thereof before removing.
1064 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -04001065 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001066 WindowManager manager
1067 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -04001068 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001069 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1070 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001071 mFakeTitleBar = null;
1072 }
1073
The Android Open Source Project0c908882009-03-03 19:32:16 -08001074 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001075 * Special method for the fake title bar to call when displaying its context
1076 * menu, since it is in its own Window, and its parent does not show a
1077 * context menu.
1078 */
1079 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -04001080 if (null == mTitleBar.getParent()) {
1081 return;
1082 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001083 openContextMenu(mTitleBar);
1084 }
1085
1086 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001087 * onSaveInstanceState(Bundle map)
1088 * onSaveInstanceState is called right before onStop(). The map contains
1089 * the saved state.
1090 */
1091 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001092 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001093 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1094 }
1095 // the default implementation requires each view to have an id. As the
1096 // browser handles the state itself and it doesn't use id for the views,
1097 // don't call the default implementation. Otherwise it will trigger the
1098 // warning like this, "couldn't save which view has focus because the
1099 // focused view XXX has no id".
1100
1101 // Save all the tabs
1102 mTabControl.saveState(outState);
1103 }
1104
1105 @Override protected void onPause() {
1106 super.onPause();
1107
1108 if (mActivityInPause) {
1109 Log.e(LOGTAG, "BrowserActivity is already paused.");
1110 return;
1111 }
1112
Mike Reed7bfa63b2009-05-28 11:08:32 -04001113 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001114 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001115 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001116 mWakeLock.acquire();
1117 mHandler.sendMessageDelayed(mHandler
1118 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1119 }
1120
1121 // Clear the credentials toast if it is up
1122 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1123 mCredsDlg.dismiss();
1124 }
1125 mCredsDlg = null;
1126
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001127 // FIXME: This removes the active tabs page and resets the menu to
1128 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1129 // but then we would need to save it in onSaveInstanceState and restore
1130 // it in onCreate/onRestoreInstanceState
1131 if (mActiveTabsPage != null) {
1132 removeActiveTabPage(true);
1133 }
1134
The Android Open Source Project0c908882009-03-03 19:32:16 -08001135 cancelStopToast();
1136
1137 // unregister network state listener
1138 unregisterReceiver(mNetworkStateIntentReceiver);
1139 WebView.disablePlatformNotifications();
1140
1141 if (mSensorManager != null) {
1142 mSensorManager.unregisterListener(mSensorListener);
1143 }
1144 }
1145
1146 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001147 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001148 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1149 }
1150 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001151
1152 if (mTabControl == null) return;
1153
The Android Open Source Project0c908882009-03-03 19:32:16 -08001154 // Remove the current tab and sub window
1155 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001156 if (t != null) {
1157 dismissSubWindow(t);
1158 removeTabFromContentView(t);
1159 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001160 // Destroy all the tabs
1161 mTabControl.destroy();
1162 WebIconDatabase.getInstance().close();
1163 if (mGlsConnection != null) {
1164 unbindService(mGlsConnection);
1165 mGlsConnection = null;
1166 }
1167
1168 //
1169 // stop MASF proxy service
1170 //
1171 //Intent proxyServiceIntent = new Intent();
1172 //proxyServiceIntent.setComponent
1173 // (new ComponentName(
1174 // "com.android.masfproxyservice",
1175 // "com.android.masfproxyservice.MasfProxyService"));
1176 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001177
1178 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001179 }
1180
1181 @Override
1182 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001183 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001184 super.onConfigurationChanged(newConfig);
1185
1186 if (mPageInfoDialog != null) {
1187 mPageInfoDialog.dismiss();
1188 showPageInfo(
1189 mPageInfoView,
1190 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1191 }
1192 if (mSSLCertificateDialog != null) {
1193 mSSLCertificateDialog.dismiss();
1194 showSSLCertificate(
1195 mSSLCertificateView);
1196 }
1197 if (mSSLCertificateOnErrorDialog != null) {
1198 mSSLCertificateOnErrorDialog.dismiss();
1199 showSSLCertificateOnError(
1200 mSSLCertificateOnErrorView,
1201 mSSLCertificateOnErrorHandler,
1202 mSSLCertificateOnErrorError);
1203 }
1204 if (mHttpAuthenticationDialog != null) {
1205 String title = ((TextView) mHttpAuthenticationDialog
1206 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1207 .toString();
1208 String name = ((TextView) mHttpAuthenticationDialog
1209 .findViewById(R.id.username_edit)).getText().toString();
1210 String password = ((TextView) mHttpAuthenticationDialog
1211 .findViewById(R.id.password_edit)).getText().toString();
1212 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1213 .getId();
1214 mHttpAuthenticationDialog.dismiss();
1215 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1216 name, password, focusId);
1217 }
1218 if (mFindDialog != null && mFindDialog.isShowing()) {
1219 mFindDialog.onConfigurationChanged(newConfig);
1220 }
1221 }
1222
1223 @Override public void onLowMemory() {
1224 super.onLowMemory();
1225 mTabControl.freeMemory();
1226 }
1227
Mike Reed7bfa63b2009-05-28 11:08:32 -04001228 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001229 if ((!mActivityInPause && !mPageStarted) ||
1230 (mActivityInPause && mPageStarted)) {
1231 CookieSyncManager.getInstance().startSync();
1232 WebView w = mTabControl.getCurrentWebView();
1233 if (w != null) {
1234 w.resumeTimers();
1235 }
1236 return true;
1237 } else {
1238 return false;
1239 }
1240 }
1241
Mike Reed7bfa63b2009-05-28 11:08:32 -04001242 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001243 if (mActivityInPause && !mPageStarted) {
1244 CookieSyncManager.getInstance().stopSync();
1245 WebView w = mTabControl.getCurrentWebView();
1246 if (w != null) {
1247 w.pauseTimers();
1248 }
1249 return true;
1250 } else {
1251 return false;
1252 }
1253 }
1254
Leon Scroggins1f005d32009-08-10 17:36:42 -04001255 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001256 /*
1257 * This function is called when we are launching for the first time. We
1258 * are waiting for the login credentials before loading Google home
1259 * pages. This way the user will be logged in straight away.
1260 */
1261 private void waitForCredentials() {
1262 // Show a toast
1263 mCredsDlg = new ProgressDialog(this);
1264 mCredsDlg.setIndeterminate(true);
1265 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1266 // If the user cancels the operation, then cancel the Google
1267 // Credentials request.
1268 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1269 mCredsDlg.show();
1270
1271 // We set a timeout for the retrieval of credentials in onResume()
1272 // as that is when we have freed up some CPU time to get
1273 // the login credentials.
1274 }
1275
1276 /*
1277 * If we have received the credentials or we have timed out and we are
1278 * showing the credentials dialog, then it is time to move on.
1279 */
1280 private void resumeAfterCredentials() {
1281 if (mCredsDlg == null) {
1282 return;
1283 }
1284
1285 // Clear the toast
1286 if (mCredsDlg.isShowing()) {
1287 mCredsDlg.dismiss();
1288 }
1289 mCredsDlg = null;
1290
1291 // Clear any pending timeout
1292 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1293
1294 // Load the page
1295 WebView w = mTabControl.getCurrentWebView();
1296 if (w != null) {
1297 w.loadUrl(mSettings.getHomePage());
1298 }
1299
1300 // Update the settings, need to do this last as it can take a moment
1301 // to persist the settings. In the mean time we could be loading
1302 // content.
1303 mSettings.setLoginInitialized(this);
1304 }
1305
1306 // Open the icon database and retain all the icons for visited sites.
1307 private void retainIconsOnStartup() {
1308 final WebIconDatabase db = WebIconDatabase.getInstance();
1309 db.open(getDir("icons", 0).getPath());
1310 try {
1311 Cursor c = Browser.getAllBookmarks(mResolver);
1312 if (!c.moveToFirst()) {
1313 c.deactivate();
1314 return;
1315 }
1316 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1317 do {
1318 String url = c.getString(urlIndex);
1319 db.retainIconForPageUrl(url);
1320 } while (c.moveToNext());
1321 c.deactivate();
1322 } catch (IllegalStateException e) {
1323 Log.e(LOGTAG, "retainIconsOnStartup", e);
1324 }
1325 }
1326
1327 // Helper method for getting the top window.
1328 WebView getTopWindow() {
1329 return mTabControl.getCurrentTopWebView();
1330 }
1331
1332 @Override
1333 public boolean onCreateOptionsMenu(Menu menu) {
1334 super.onCreateOptionsMenu(menu);
1335
1336 MenuInflater inflater = getMenuInflater();
1337 inflater.inflate(R.menu.browser, menu);
1338 mMenu = menu;
1339 updateInLoadMenuItems();
1340 return true;
1341 }
1342
1343 /**
1344 * As the menu can be open when loading state changes
1345 * we must manually update the state of the stop/reload menu
1346 * item
1347 */
1348 private void updateInLoadMenuItems() {
1349 if (mMenu == null) {
1350 return;
1351 }
1352 MenuItem src = mInLoad ?
1353 mMenu.findItem(R.id.stop_menu_id):
1354 mMenu.findItem(R.id.reload_menu_id);
1355 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1356 dest.setIcon(src.getIcon());
1357 dest.setTitle(src.getTitle());
1358 }
1359
1360 @Override
1361 public boolean onContextItemSelected(MenuItem item) {
1362 // chording is not an issue with context menus, but we use the same
1363 // options selector, so set mCanChord to true so we can access them.
1364 mCanChord = true;
1365 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001366 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001367 // For the context menu from the title bar
1368 case R.id.title_bar_share_page_url:
1369 case R.id.title_bar_copy_page_url:
1370 WebView mainView = mTabControl.getCurrentWebView();
1371 if (null == mainView) {
1372 return false;
1373 }
1374 if (id == R.id.title_bar_share_page_url) {
1375 Browser.sendString(this, mainView.getUrl());
1376 } else {
1377 copy(mainView.getUrl());
1378 }
1379 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001380 // -- Browser context menu
1381 case R.id.open_context_menu_id:
1382 case R.id.open_newtab_context_menu_id:
1383 case R.id.bookmark_context_menu_id:
1384 case R.id.save_link_context_menu_id:
1385 case R.id.share_link_context_menu_id:
1386 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001387 final WebView webView = getTopWindow();
1388 if (null == webView) {
1389 return false;
1390 }
1391 final HashMap hrefMap = new HashMap();
1392 hrefMap.put("webview", webView);
1393 final Message msg = mHandler.obtainMessage(
1394 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001395 webView.requestFocusNodeHref(msg);
1396 break;
1397
1398 default:
1399 // For other context menus
1400 return onOptionsItemSelected(item);
1401 }
1402 mCanChord = false;
1403 return true;
1404 }
1405
1406 private Bundle createGoogleSearchSourceBundle(String source) {
1407 Bundle bundle = new Bundle();
1408 bundle.putString(SearchManager.SOURCE, source);
1409 return bundle;
1410 }
1411
1412 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001413 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001414 */
1415 @Override
1416 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001417 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001418 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001419 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001420 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001421 return true;
1422 }
1423
1424 @Override
1425 public void startSearch(String initialQuery, boolean selectInitialQuery,
1426 Bundle appSearchData, boolean globalSearch) {
1427 if (appSearchData == null) {
1428 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1429 }
1430 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1431 }
1432
Leon Scroggins1f005d32009-08-10 17:36:42 -04001433 /**
1434 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1435 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001436 * @param index Index of the tab to change to, as defined by
1437 * mTabControl.getTabIndex(Tab t).
1438 * @return boolean True if we successfully switched to a different tab. If
1439 * the indexth tab is null, or if that tab is the same as
1440 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001441 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001442 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001443 TabControl.Tab tab = mTabControl.getTab(index);
1444 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1445 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001446 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001447 }
1448 if (currentTab != null) {
1449 // currentTab may be null if it was just removed. In that case,
1450 // we do not need to remove it
1451 removeTabFromContentView(currentTab);
1452 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001453 mTabControl.setCurrentTab(tab);
1454 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001455 resetTitleIconAndProgress();
1456 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001457 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001458 }
1459
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001460 /* package */ TabControl.Tab openTabToHomePage() {
1461 return openTabAndShow(mSettings.getHomePage(), false, null);
1462 }
1463
Leon Scroggins1f005d32009-08-10 17:36:42 -04001464 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001465 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001466 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001467 // This is the last tab. Open a new one, with the home
1468 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001469 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001470 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001471 return;
1472 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001473 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001474 int indexToShow = -1;
1475 if (parent != null) {
1476 indexToShow = mTabControl.getTabIndex(parent);
1477 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001478 final int currentIndex = mTabControl.getCurrentIndex();
1479 // Try to move to the tab to the right
1480 indexToShow = currentIndex + 1;
1481 if (indexToShow > mTabControl.getTabCount() - 1) {
1482 // Try to move to the tab to the left
1483 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001484 }
1485 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001486 if (switchToTab(indexToShow)) {
1487 // Close window
1488 closeTab(current);
1489 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001490 }
1491
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001492 private ActiveTabsPage mActiveTabsPage;
1493
1494 /**
1495 * Remove the active tabs page.
1496 * @param needToAttach If true, the active tabs page did not attach a tab
1497 * to the content view, so we need to do that here.
1498 */
1499 /* package */ void removeActiveTabPage(boolean needToAttach) {
1500 mContentView.removeView(mActiveTabsPage);
1501 mActiveTabsPage = null;
1502 mMenuState = R.id.MAIN_MENU;
1503 if (needToAttach) {
1504 attachTabToContentView(mTabControl.getCurrentTab());
1505 }
1506 getTopWindow().requestFocus();
1507 }
1508
The Android Open Source Project0c908882009-03-03 19:32:16 -08001509 @Override
1510 public boolean onOptionsItemSelected(MenuItem item) {
1511 if (!mCanChord) {
1512 // The user has already fired a shortcut with this hold down of the
1513 // menu key.
1514 return false;
1515 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001516 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001517 return false;
1518 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001519 if (mMenuIsDown) {
1520 // The shortcut action consumes the MENU. Even if it is still down,
1521 // it won't trigger the next shortcut action. In the case of the
1522 // shortcut action triggering a new activity, like Bookmarks, we
1523 // won't get onKeyUp for MENU. So it is important to reset it here.
1524 mMenuIsDown = false;
1525 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001526 switch (item.getItemId()) {
1527 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001528 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001529 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001530 break;
1531
Leon Scroggins64b80f32009-08-07 12:03:34 -04001532 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001533 onSearchRequested();
1534 break;
1535
1536 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001537 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001538 break;
1539
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001540 case R.id.active_tabs_menu_id:
1541 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1542 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001543 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001544 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1545 mActiveTabsPage.requestFocus();
1546 mMenuState = EMPTY_MENU;
1547 break;
1548
Leon Scroggins1f005d32009-08-10 17:36:42 -04001549 case R.id.add_bookmark_menu_id:
1550 Intent i = new Intent(BrowserActivity.this,
1551 AddBookmarkPage.class);
1552 WebView w = getTopWindow();
1553 i.putExtra("url", w.getUrl());
1554 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001555 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001556 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001557 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001558 break;
1559
1560 case R.id.stop_reload_menu_id:
1561 if (mInLoad) {
1562 stopLoading();
1563 } else {
1564 getTopWindow().reload();
1565 }
1566 break;
1567
1568 case R.id.back_menu_id:
1569 getTopWindow().goBack();
1570 break;
1571
1572 case R.id.forward_menu_id:
1573 getTopWindow().goForward();
1574 break;
1575
1576 case R.id.close_menu_id:
1577 // Close the subwindow if it exists.
1578 if (mTabControl.getCurrentSubWindow() != null) {
1579 dismissSubWindow(mTabControl.getCurrentTab());
1580 break;
1581 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001582 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001583 break;
1584
1585 case R.id.homepage_menu_id:
1586 TabControl.Tab current = mTabControl.getCurrentTab();
1587 if (current != null) {
1588 dismissSubWindow(current);
1589 current.getWebView().loadUrl(mSettings.getHomePage());
1590 }
1591 break;
1592
1593 case R.id.preferences_menu_id:
1594 Intent intent = new Intent(this,
1595 BrowserPreferencesPage.class);
1596 startActivityForResult(intent, PREFERENCES_PAGE);
1597 break;
1598
1599 case R.id.find_menu_id:
1600 if (null == mFindDialog) {
1601 mFindDialog = new FindDialog(this);
1602 }
1603 mFindDialog.setWebView(getTopWindow());
1604 mFindDialog.show();
1605 mMenuState = EMPTY_MENU;
1606 break;
1607
1608 case R.id.select_text_id:
1609 getTopWindow().emulateShiftHeld();
1610 break;
1611 case R.id.page_info_menu_id:
1612 showPageInfo(mTabControl.getCurrentTab(), false);
1613 break;
1614
1615 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001616 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001617 break;
1618
1619 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001620 Browser.sendString(this, getTopWindow().getUrl(),
1621 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001622 break;
1623
1624 case R.id.dump_nav_menu_id:
1625 getTopWindow().debugDump();
1626 break;
1627
1628 case R.id.zoom_in_menu_id:
1629 getTopWindow().zoomIn();
1630 break;
1631
1632 case R.id.zoom_out_menu_id:
1633 getTopWindow().zoomOut();
1634 break;
1635
1636 case R.id.view_downloads_menu_id:
1637 viewDownloads(null);
1638 break;
1639
The Android Open Source Project0c908882009-03-03 19:32:16 -08001640 case R.id.window_one_menu_id:
1641 case R.id.window_two_menu_id:
1642 case R.id.window_three_menu_id:
1643 case R.id.window_four_menu_id:
1644 case R.id.window_five_menu_id:
1645 case R.id.window_six_menu_id:
1646 case R.id.window_seven_menu_id:
1647 case R.id.window_eight_menu_id:
1648 {
1649 int menuid = item.getItemId();
1650 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1651 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1652 TabControl.Tab desiredTab = mTabControl.getTab(id);
1653 if (desiredTab != null &&
1654 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001655 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001656 }
1657 break;
1658 }
1659 }
1660 }
1661 break;
1662
1663 default:
1664 if (!super.onOptionsItemSelected(item)) {
1665 return false;
1666 }
1667 // Otherwise fall through.
1668 }
1669 mCanChord = false;
1670 return true;
1671 }
1672
1673 public void closeFind() {
1674 mMenuState = R.id.MAIN_MENU;
1675 }
1676
1677 @Override public boolean onPrepareOptionsMenu(Menu menu)
1678 {
1679 // This happens when the user begins to hold down the menu key, so
1680 // allow them to chord to get a shortcut.
1681 mCanChord = true;
1682 // Note: setVisible will decide whether an item is visible; while
1683 // setEnabled() will decide whether an item is enabled, which also means
1684 // whether the matching shortcut key will function.
1685 super.onPrepareOptionsMenu(menu);
1686 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001687 case EMPTY_MENU:
1688 if (mCurrentMenuState != mMenuState) {
1689 menu.setGroupVisible(R.id.MAIN_MENU, false);
1690 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1691 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001692 }
1693 break;
1694 default:
1695 if (mCurrentMenuState != mMenuState) {
1696 menu.setGroupVisible(R.id.MAIN_MENU, true);
1697 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1698 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001699 }
1700 final WebView w = getTopWindow();
1701 boolean canGoBack = false;
1702 boolean canGoForward = false;
1703 boolean isHome = false;
1704 if (w != null) {
1705 canGoBack = w.canGoBack();
1706 canGoForward = w.canGoForward();
1707 isHome = mSettings.getHomePage().equals(w.getUrl());
1708 }
1709 final MenuItem back = menu.findItem(R.id.back_menu_id);
1710 back.setEnabled(canGoBack);
1711
1712 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1713 home.setEnabled(!isHome);
1714
1715 menu.findItem(R.id.forward_menu_id)
1716 .setEnabled(canGoForward);
1717
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001718 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1719 mTabControl.getTabCount() < TabControl.MAX_TABS);
1720
The Android Open Source Project0c908882009-03-03 19:32:16 -08001721 // decide whether to show the share link option
1722 PackageManager pm = getPackageManager();
1723 Intent send = new Intent(Intent.ACTION_SEND);
1724 send.setType("text/plain");
1725 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1726 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1727
The Android Open Source Project0c908882009-03-03 19:32:16 -08001728 boolean isNavDump = mSettings.isNavDump();
1729 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1730 nav.setVisible(isNavDump);
1731 nav.setEnabled(isNavDump);
1732 break;
1733 }
1734 mCurrentMenuState = mMenuState;
1735 return true;
1736 }
1737
1738 @Override
1739 public void onCreateContextMenu(ContextMenu menu, View v,
1740 ContextMenuInfo menuInfo) {
1741 WebView webview = (WebView) v;
1742 WebView.HitTestResult result = webview.getHitTestResult();
1743 if (result == null) {
1744 return;
1745 }
1746
1747 int type = result.getType();
1748 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1749 Log.w(LOGTAG,
1750 "We should not show context menu when nothing is touched");
1751 return;
1752 }
1753 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1754 // let TextView handles context menu
1755 return;
1756 }
1757
1758 // Note, http://b/issue?id=1106666 is requesting that
1759 // an inflated menu can be used again. This is not available
1760 // yet, so inflate each time (yuk!)
1761 MenuInflater inflater = getMenuInflater();
1762 inflater.inflate(R.menu.browsercontext, menu);
1763
1764 // Show the correct menu group
1765 String extra = result.getExtra();
1766 menu.setGroupVisible(R.id.PHONE_MENU,
1767 type == WebView.HitTestResult.PHONE_TYPE);
1768 menu.setGroupVisible(R.id.EMAIL_MENU,
1769 type == WebView.HitTestResult.EMAIL_TYPE);
1770 menu.setGroupVisible(R.id.GEO_MENU,
1771 type == WebView.HitTestResult.GEO_TYPE);
1772 menu.setGroupVisible(R.id.IMAGE_MENU,
1773 type == WebView.HitTestResult.IMAGE_TYPE
1774 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1775 menu.setGroupVisible(R.id.ANCHOR_MENU,
1776 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1777 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1778
1779 // Setup custom handling depending on the type
1780 switch (type) {
1781 case WebView.HitTestResult.PHONE_TYPE:
1782 menu.setHeaderTitle(Uri.decode(extra));
1783 menu.findItem(R.id.dial_context_menu_id).setIntent(
1784 new Intent(Intent.ACTION_VIEW, Uri
1785 .parse(WebView.SCHEME_TEL + extra)));
1786 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1787 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001788 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001789 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1790 addIntent);
1791 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1792 new Copy(extra));
1793 break;
1794
1795 case WebView.HitTestResult.EMAIL_TYPE:
1796 menu.setHeaderTitle(extra);
1797 menu.findItem(R.id.email_context_menu_id).setIntent(
1798 new Intent(Intent.ACTION_VIEW, Uri
1799 .parse(WebView.SCHEME_MAILTO + extra)));
1800 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1801 new Copy(extra));
1802 break;
1803
1804 case WebView.HitTestResult.GEO_TYPE:
1805 menu.setHeaderTitle(extra);
1806 menu.findItem(R.id.map_context_menu_id).setIntent(
1807 new Intent(Intent.ACTION_VIEW, Uri
1808 .parse(WebView.SCHEME_GEO
1809 + URLEncoder.encode(extra))));
1810 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1811 new Copy(extra));
1812 break;
1813
1814 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1815 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1816 TextView titleView = (TextView) LayoutInflater.from(this)
1817 .inflate(android.R.layout.browser_link_context_header,
1818 null);
1819 titleView.setText(extra);
1820 menu.setHeaderView(titleView);
1821 // decide whether to show the open link in new tab option
1822 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1823 mTabControl.getTabCount() < TabControl.MAX_TABS);
1824 PackageManager pm = getPackageManager();
1825 Intent send = new Intent(Intent.ACTION_SEND);
1826 send.setType("text/plain");
1827 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1828 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1829 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1830 break;
1831 }
1832 // otherwise fall through to handle image part
1833 case WebView.HitTestResult.IMAGE_TYPE:
1834 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1835 menu.setHeaderTitle(extra);
1836 }
1837 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1838 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1839 menu.findItem(R.id.download_context_menu_id).
1840 setOnMenuItemClickListener(new Download(extra));
1841 break;
1842
1843 default:
1844 Log.w(LOGTAG, "We should not get here.");
1845 break;
1846 }
1847 }
1848
The Android Open Source Project0c908882009-03-03 19:32:16 -08001849 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001850 // this should only be called for the current tab.
The Android Open Source Project0c908882009-03-03 19:32:16 -08001851 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001852 // Attach the container that contains the main WebView and any other UI
1853 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001854 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001855
1856 if (mShouldShowErrorConsole) {
1857 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1858 if (errorConsole.numberOfErrors() == 0) {
1859 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1860 } else {
1861 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1862 }
1863
1864 mErrorConsoleContainer.addView(errorConsole,
1865 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1866 ViewGroup.LayoutParams.WRAP_CONTENT));
1867 }
1868
Grace Klobac928c302009-09-17 11:51:21 -07001869 setLockIconType(t.getLockIconType());
1870 setPrevLockType(t.getPrevLockIconType());
1871
1872 // this is to match the code in removeTabFromContentView()
1873 if (!mPageStarted && t.getTopWindow().getProgress() < 100) {
1874 mPageStarted = true;
Grace Klobaeb6eef42009-09-15 17:56:32 -07001875 }
1876
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001877 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001878 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001879 // Request focus on the top window.
1880 t.getTopWindow().requestFocus();
1881 }
1882
1883 // Attach a sub window to the main WebView of the given tab.
1884 private void attachSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001885 t.attachSubWindow(mContentView);
1886 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001887 }
1888
1889 // Remove the given tab from the content view.
1890 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001891 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001892 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001893
1894 if (mTabControl.getCurrentErrorConsole(false) != null) {
1895 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1896 }
1897
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001898 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001899 if (view != null) {
1900 view.setEmbeddedTitleBar(null);
1901 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001902
Grace Klobac928c302009-09-17 11:51:21 -07001903 // unlike attachTabToContentView(), removeTabFromContentView() can be
1904 // called for the non-current tab. Need to add the check.
Grace Klobaeb6eef42009-09-15 17:56:32 -07001905 if (t == mTabControl.getCurrentTab()) {
1906 t.setLockIconType(getLockIconType());
1907 t.setPrevLockIconType(getPrevLockType());
Grace Klobac928c302009-09-17 11:51:21 -07001908
1909 // this is not a perfect solution. But currently there is one
1910 // WebViewClient for all the WebView. if user switches from an
1911 // in-load window to an already loaded window, mPageStarted will not
1912 // be set to false. If user leaves the Browser, pauseWebViewTimers()
1913 // won't do anything and leaves the timer running even Browser is in
1914 // the background.
1915 if (mPageStarted) {
1916 mPageStarted = false;
1917 }
Grace Klobaeb6eef42009-09-15 17:56:32 -07001918 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001919 }
1920
1921 // Remove the sub window if it exists. Also called by TabControl when the
1922 // user clicks the 'X' to dismiss a sub window.
1923 /* package */ void dismissSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001924 t.removeSubWindow(mContentView);
1925 // Tell the TabControl to dismiss the subwindow. This will destroy
1926 // the WebView.
1927 mTabControl.dismissSubWindow(t);
1928 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001929 }
1930
Leon Scroggins1f005d32009-08-10 17:36:42 -04001931 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001932 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001933 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1934 String appId) {
1935 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001936 }
1937
1938 // This method does a ton of stuff. It will attempt to create a new tab
1939 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001940 // url isn't null, it will load the given url.
1941 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001942 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001943 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1944 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1945 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001946 final TabControl.Tab tab = mTabControl.createNewTab(
1947 closeOnExit, appId, urlData.mUrl);
1948 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001949 // If the last tab was removed from the active tabs page, currentTab
1950 // will be null.
1951 if (currentTab != null) {
1952 removeTabFromContentView(currentTab);
1953 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001954 // We must set the new tab as the current tab to reflect the old
1955 // animation behavior.
1956 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001957 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001958 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001959 urlData.loadIn(webview);
1960 }
1961 return tab;
1962 } else {
1963 // Get rid of the subwindow if it exists
1964 dismissSubWindow(currentTab);
1965 if (!urlData.isEmpty()) {
1966 // Load the given url.
1967 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001968 }
1969 }
Grace Klobac9181842009-04-14 08:53:22 -07001970 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001971 }
1972
Grace Klobac9181842009-04-14 08:53:22 -07001973 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001974 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001975 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001976 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001977 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001978 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001979 }
Grace Klobac9181842009-04-14 08:53:22 -07001980 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001981 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001982 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001983 }
1984 }
1985
1986 private class Copy implements OnMenuItemClickListener {
1987 private CharSequence mText;
1988
1989 public boolean onMenuItemClick(MenuItem item) {
1990 copy(mText);
1991 return true;
1992 }
1993
1994 public Copy(CharSequence toCopy) {
1995 mText = toCopy;
1996 }
1997 }
1998
1999 private class Download implements OnMenuItemClickListener {
2000 private String mText;
2001
2002 public boolean onMenuItemClick(MenuItem item) {
2003 onDownloadStartNoStream(mText, null, null, null, -1);
2004 return true;
2005 }
2006
2007 public Download(String toDownload) {
2008 mText = toDownload;
2009 }
2010 }
2011
2012 private void copy(CharSequence text) {
2013 try {
2014 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2015 if (clip != null) {
2016 clip.setClipboardText(text);
2017 }
2018 } catch (android.os.RemoteException e) {
2019 Log.e(LOGTAG, "Copy failed", e);
2020 }
2021 }
2022
2023 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002024 * Resets the browser title-view to whatever it must be
2025 * (for example, if we had a loading error)
2026 * When we have a new page, we call resetTitle, when we
2027 * have to reset the titlebar to whatever it used to be
2028 * (for example, if the user chose to stop loading), we
2029 * call resetTitleAndRevertLockIcon.
2030 */
2031 /* package */ void resetTitleAndRevertLockIcon() {
2032 revertLockIcon();
2033 resetTitleIconAndProgress();
2034 }
2035
2036 /**
2037 * Reset the title, favicon, and progress.
2038 */
2039 private void resetTitleIconAndProgress() {
2040 WebView current = mTabControl.getCurrentWebView();
2041 if (current == null) {
2042 return;
2043 }
2044 resetTitleAndIcon(current);
2045 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002046 mWebChromeClient.onProgressChanged(current, progress);
2047 }
2048
2049 // Reset the title and the icon based on the given item.
2050 private void resetTitleAndIcon(WebView view) {
2051 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2052 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002053 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002054 setFavicon(item.getFavicon());
2055 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002056 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002057 setFavicon(null);
2058 }
2059 }
2060
2061 /**
2062 * Sets a title composed of the URL and the title string.
2063 * @param url The URL of the site being loaded.
2064 * @param title The title of the site being loaded.
2065 */
Leon Scroggins68579392009-09-15 15:31:54 -04002066 private void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002067 mUrl = url;
2068 mTitle = title;
2069
Leon Scroggins68579392009-09-15 15:31:54 -04002070 mTitleBar.setTitleAndUrl(title, url);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002071 if (mFakeTitleBar != null) {
2072 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002073 }
2074 }
2075
2076 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002077 * @param url The URL to build a title version of the URL from.
2078 * @return The title version of the URL or null if fails.
2079 * The title version of the URL can be either the URL hostname,
2080 * or the hostname with an "https://" prefix (for secure URLs),
2081 * or an empty string if, for example, the URL in question is a
2082 * file:// URL with no hostname.
2083 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002084 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002085 String titleUrl = null;
2086
2087 if (url != null) {
2088 try {
2089 // parse the url string
2090 URL urlObj = new URL(url);
2091 if (urlObj != null) {
2092 titleUrl = "";
2093
2094 String protocol = urlObj.getProtocol();
2095 String host = urlObj.getHost();
2096
2097 if (host != null && 0 < host.length()) {
2098 titleUrl = host;
2099 if (protocol != null) {
2100 // if a secure site, add an "https://" prefix!
2101 if (protocol.equalsIgnoreCase("https")) {
2102 titleUrl = protocol + "://" + host;
2103 }
2104 }
2105 }
2106 }
2107 } catch (MalformedURLException e) {}
2108 }
2109
2110 return titleUrl;
2111 }
2112
2113 // Set the favicon in the title bar.
2114 private void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002115 mTitleBar.setFavicon(icon);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002116 if (mFakeTitleBar != null) {
2117 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002118 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002119 }
2120
2121 /**
2122 * Saves the current lock-icon state before resetting
2123 * the lock icon. If we have an error, we may need to
2124 * roll back to the previous state.
2125 */
2126 private void saveLockIcon() {
2127 mPrevLockType = mLockIconType;
2128 }
2129
2130 /**
2131 * Reverts the lock-icon state to the last saved state,
2132 * for example, if we had an error, and need to cancel
2133 * the load.
2134 */
2135 private void revertLockIcon() {
2136 mLockIconType = mPrevLockType;
2137
Dave Bort31a6d1c2009-04-13 15:56:49 -07002138 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002139 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2140 " revert lock icon to " + mLockIconType);
2141 }
2142
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002143 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002144 }
2145
Leon Scroggins1f005d32009-08-10 17:36:42 -04002146 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002147 * Close the tab, remove its associated title bar, and adjust mTabControl's
2148 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002149 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002150 /* package */ void closeTab(TabControl.Tab t) {
2151 int currentIndex = mTabControl.getCurrentIndex();
2152 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002153 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002154 if (currentIndex >= removeIndex && currentIndex != 0) {
2155 currentIndex--;
2156 }
2157 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002158 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002159 }
2160
2161 private void goBackOnePageOrQuit() {
2162 TabControl.Tab current = mTabControl.getCurrentTab();
2163 if (current == null) {
2164 /*
2165 * Instead of finishing the activity, simply push this to the back
2166 * of the stack and let ActivityManager to choose the foreground
2167 * activity. As BrowserActivity is singleTask, it will be always the
2168 * root of the task. So we can use either true or false for
2169 * moveTaskToBack().
2170 */
2171 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002172 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002173 }
2174 WebView w = current.getWebView();
2175 if (w.canGoBack()) {
2176 w.goBack();
2177 } else {
2178 // Check to see if we are closing a window that was created by
2179 // another window. If so, we switch back to that window.
2180 TabControl.Tab parent = current.getParentTab();
2181 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002182 switchToTab(mTabControl.getTabIndex(parent));
2183 // Now we close the other tab
2184 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002185 } else {
2186 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002187 // force mPageStarted to be false as we are going to either
2188 // finish the activity or remove the tab. This will ensure
2189 // pauseWebView() taking action.
2190 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002191 if (mTabControl.getTabCount() == 1) {
2192 finish();
2193 return;
2194 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002195 // call pauseWebViewTimers() now, we won't be able to call
2196 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002197 // Temporarily change mActivityInPause to be true as
2198 // pauseWebViewTimers() will do nothing if mActivityInPause
2199 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002200 boolean savedState = mActivityInPause;
2201 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002202 Log.e(LOGTAG, "BrowserActivity is already paused "
2203 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002204 }
2205 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002206 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002207 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002208 removeTabFromContentView(current);
2209 mTabControl.removeTab(current);
2210 }
2211 /*
2212 * Instead of finishing the activity, simply push this to the back
2213 * of the stack and let ActivityManager to choose the foreground
2214 * activity. As BrowserActivity is singleTask, it will be always the
2215 * root of the task. So we can use either true or false for
2216 * moveTaskToBack().
2217 */
2218 moveTaskToBack(true);
2219 }
2220 }
2221 }
2222
Grace Kloba5942df02009-09-18 11:48:29 -07002223 @Override
2224 public boolean onKeyDown(int keyCode, KeyEvent event) {
2225 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2226 // still down, we don't want to trigger the search. Pretend to consume
2227 // the key and do nothing.
2228 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002229
Grace Kloba5942df02009-09-18 11:48:29 -07002230 switch(keyCode) {
2231 case KeyEvent.KEYCODE_MENU:
2232 mMenuIsDown = true;
2233 break;
2234 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002235 // WebView/WebTextView handle the keys in the KeyDown. As
2236 // the Activity's shortcut keys are only handled when WebView
2237 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2238 if (event.isShiftPressed()) {
2239 getTopWindow().pageUp(false);
2240 } else {
2241 getTopWindow().pageDown(false);
2242 }
Grace Kloba5942df02009-09-18 11:48:29 -07002243 return true;
2244 case KeyEvent.KEYCODE_BACK:
2245 if (event.getRepeatCount() == 0) {
2246 event.startTracking();
2247 return true;
2248 } else if (mCustomView == null && mActiveTabsPage == null
2249 && event.isLongPress()) {
2250 bookmarksOrHistoryPicker(true);
2251 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002252 }
Grace Kloba5942df02009-09-18 11:48:29 -07002253 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002254 }
Grace Kloba5942df02009-09-18 11:48:29 -07002255 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002256 }
2257
Grace Kloba5942df02009-09-18 11:48:29 -07002258 @Override
2259 public boolean onKeyUp(int keyCode, KeyEvent event) {
2260 switch(keyCode) {
2261 case KeyEvent.KEYCODE_MENU:
2262 mMenuIsDown = false;
2263 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002264 case KeyEvent.KEYCODE_BACK:
2265 if (event.isTracking() && !event.isCanceled()) {
2266 if (mCustomView != null) {
2267 // if a custom view is showing, hide it
2268 mWebChromeClient.onHideCustomView();
2269 } else if (mActiveTabsPage != null) {
2270 // if tab page is showing, hide it
2271 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002272 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002273 WebView subwindow = mTabControl.getCurrentSubWindow();
2274 if (subwindow != null) {
2275 if (subwindow.canGoBack()) {
2276 subwindow.goBack();
2277 } else {
2278 dismissSubWindow(mTabControl.getCurrentTab());
2279 }
2280 } else {
2281 goBackOnePageOrQuit();
2282 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002283 }
Grace Kloba5942df02009-09-18 11:48:29 -07002284 return true;
2285 }
2286 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002287 }
Grace Kloba5942df02009-09-18 11:48:29 -07002288 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002289 }
2290
Leon Scroggins68579392009-09-15 15:31:54 -04002291 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002292 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002293 resetTitleAndRevertLockIcon();
2294 WebView w = getTopWindow();
2295 w.stopLoading();
2296 mWebViewClient.onPageFinished(w, w.getUrl());
2297
2298 cancelStopToast();
2299 mStopToast = Toast
2300 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2301 mStopToast.show();
2302 }
2303
2304 private void cancelStopToast() {
2305 if (mStopToast != null) {
2306 mStopToast.cancel();
2307 mStopToast = null;
2308 }
2309 }
2310
2311 // called by a non-UI thread to post the message
2312 public void postMessage(int what, int arg1, int arg2, Object obj) {
2313 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2314 }
2315
2316 // public message ids
2317 public final static int LOAD_URL = 1001;
2318 public final static int STOP_LOAD = 1002;
2319
2320 // Message Ids
2321 private static final int FOCUS_NODE_HREF = 102;
2322 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002323 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002324
Ben Murdoch2694e232009-09-29 09:41:11 +01002325 private static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
2326
The Android Open Source Project0c908882009-03-03 19:32:16 -08002327 // Private handler for handling javascript and saving passwords
2328 private Handler mHandler = new Handler() {
2329
2330 public void handleMessage(Message msg) {
2331 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002332 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002333 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002334 String url = (String) msg.getData().get("url");
2335 if (url == null || url.length() == 0) {
2336 break;
2337 }
2338 HashMap focusNodeMap = (HashMap) msg.obj;
2339 WebView view = (WebView) focusNodeMap.get("webview");
2340 // Only apply the action if the top window did not change.
2341 if (getTopWindow() != view) {
2342 break;
2343 }
2344 switch (msg.arg1) {
2345 case R.id.open_context_menu_id:
2346 case R.id.view_image_context_menu_id:
2347 loadURL(getTopWindow(), url);
2348 break;
2349 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002350 final TabControl.Tab parent = mTabControl
2351 .getCurrentTab();
2352 final TabControl.Tab newTab = openTab(url);
2353 if (newTab != parent) {
2354 parent.addChildTab(newTab);
2355 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002356 break;
2357 case R.id.bookmark_context_menu_id:
2358 Intent intent = new Intent(BrowserActivity.this,
2359 AddBookmarkPage.class);
2360 intent.putExtra("url", url);
2361 startActivity(intent);
2362 break;
2363 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002364 Browser.sendString(BrowserActivity.this, url,
2365 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002366 break;
2367 case R.id.copy_link_context_menu_id:
2368 copy(url);
2369 break;
2370 case R.id.save_link_context_menu_id:
2371 case R.id.download_context_menu_id:
2372 onDownloadStartNoStream(url, null, null, null, -1);
2373 break;
2374 }
2375 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002376 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002377
2378 case LOAD_URL:
2379 loadURL(getTopWindow(), (String) msg.obj);
2380 break;
2381
2382 case STOP_LOAD:
2383 stopLoading();
2384 break;
2385
2386 case CANCEL_CREDS_REQUEST:
2387 resumeAfterCredentials();
2388 break;
2389
The Android Open Source Project0c908882009-03-03 19:32:16 -08002390 case RELEASE_WAKELOCK:
2391 if (mWakeLock.isHeld()) {
2392 mWakeLock.release();
2393 }
2394 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002395
2396 case UPDATE_BOOKMARK_THUMBNAIL:
2397 WebView view = (WebView) msg.obj;
2398 if (view != null) {
2399 updateScreenshot(view);
2400 }
2401 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002402 }
2403 }
2404 };
2405
Leon Scroggins89c6d362009-07-15 16:54:37 -04002406 private void updateScreenshot(WebView view) {
2407 // If this is a bookmarked site, add a screenshot to the database.
2408 // FIXME: When should we update? Every time?
2409 // FIXME: Would like to make sure there is actually something to
2410 // draw, but the API for that (WebViewCore.pictureReady()) is not
2411 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002412
Patrick Scott3918d442009-08-04 13:22:29 -04002413 ContentResolver cr = getContentResolver();
2414 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002415 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002416 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002417 boolean succeed = c.moveToFirst();
2418 ContentValues values = null;
2419 while (succeed) {
2420 if (values == null) {
2421 final ByteArrayOutputStream os
2422 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002423 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002424 if (bm == null) {
2425 c.close();
2426 return;
2427 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002428 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2429 values = new ContentValues();
2430 values.put(Browser.BookmarkColumns.THUMBNAIL,
2431 os.toByteArray());
2432 }
2433 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2434 c.getInt(0)), values, null, null);
2435 succeed = c.moveToNext();
2436 }
2437 c.close();
2438 }
2439 }
2440
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002441 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002442 * Values for the size of the thumbnail created when taking a screenshot.
2443 * Lazily initialized. Instead of using these directly, use
2444 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002445 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002446 private static int THUMBNAIL_WIDTH = 0;
2447 private static int THUMBNAIL_HEIGHT = 0;
2448
2449 /**
2450 * Return the desired width for thumbnail screenshots, which are stored in
2451 * the database, and used on the bookmarks screen.
2452 * @param context Context for finding out the density of the screen.
2453 * @return int desired width for thumbnail screenshot.
2454 */
2455 /* package */ static int getDesiredThumbnailWidth(Context context) {
2456 if (THUMBNAIL_WIDTH == 0) {
2457 float density = context.getResources().getDisplayMetrics().density;
2458 THUMBNAIL_WIDTH = (int) (90 * density);
2459 THUMBNAIL_HEIGHT = (int) (80 * density);
2460 }
2461 return THUMBNAIL_WIDTH;
2462 }
2463
2464 /**
2465 * Return the desired height for thumbnail screenshots, which are stored in
2466 * the database, and used on the bookmarks screen.
2467 * @param context Context for finding out the density of the screen.
2468 * @return int desired height for thumbnail screenshot.
2469 */
2470 /* package */ static int getDesiredThumbnailHeight(Context context) {
2471 // To ensure that they are both initialized.
2472 getDesiredThumbnailWidth(context);
2473 return THUMBNAIL_HEIGHT;
2474 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002475
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002476 private Bitmap createScreenshot(WebView view) {
2477 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002478 if (thumbnail == null) {
2479 return null;
2480 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002481 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2482 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002483 Canvas canvas = new Canvas(bm);
2484 // May need to tweak these values to determine what is the
2485 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002486 int thumbnailWidth = thumbnail.getWidth();
2487 if (thumbnailWidth > 0) {
2488 float scaleFactor = (float) getDesiredThumbnailWidth(this) /
2489 (float)thumbnailWidth;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002490 canvas.scale(scaleFactor, scaleFactor);
2491 }
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002492 thumbnail.draw(canvas);
2493 return bm;
2494 }
2495
The Android Open Source Project0c908882009-03-03 19:32:16 -08002496 // -------------------------------------------------------------------------
2497 // WebViewClient implementation.
2498 //-------------------------------------------------------------------------
2499
2500 // Use in overrideUrlLoading
2501 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2502 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2503 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2504 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2505
2506 /* package */ WebViewClient getWebViewClient() {
2507 return mWebViewClient;
2508 }
2509
Patrick Scott3918d442009-08-04 13:22:29 -04002510 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002511 if (icon != null) {
2512 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott15525d42009-09-21 13:39:37 -04002513 view.getOriginalUrl(), view.getUrl(), icon);
2514 }
2515 setFavicon(icon);
2516 }
2517
2518 private void updateIcon(String url, Bitmap icon) {
2519 if (icon != null) {
2520 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2521 null, url, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002522 }
2523 setFavicon(icon);
2524 }
2525
2526 private final WebViewClient mWebViewClient = new WebViewClient() {
2527 @Override
2528 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2529 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002530 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002531
Ben Murdoch2694e232009-09-29 09:41:11 +01002532 // We've started to load a new page. If there was a pending message
2533 // to save a screenshot then we will now take the new page and
2534 // save an incorrect screenshot. Therefore, remove any pending
2535 // thumbnail messages from the queue.
2536 mHandler.removeMessages(UPDATE_BOOKMARK_THUMBNAIL);
2537
Patrick Scott59ce8302009-09-18 16:29:38 -04002538 // If we start a touch icon load and then load a new page, we don't
2539 // want to cancel the current touch icon loader. But, we do want to
2540 // create a new one when the touch icon url is known.
2541 if (mTouchIconLoader != null) {
2542 mTouchIconLoader.mActivity = null;
2543 mTouchIconLoader = null;
2544 }
2545
Ben Murdochbff2d602009-07-01 20:19:05 +01002546 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2547 if (errorConsole != null) {
2548 errorConsole.clearErrorMessages();
2549 if (mShouldShowErrorConsole) {
2550 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2551 }
2552 }
2553
The Android Open Source Project0c908882009-03-03 19:32:16 -08002554 // Call updateIcon instead of setFavicon so the bookmark
2555 // database can be updated.
Patrick Scott15525d42009-09-21 13:39:37 -04002556 updateIcon(url, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002557
Grace Kloba4d7880f2009-08-12 09:35:42 -07002558 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002559 String host;
2560 try {
2561 WebAddress uri = new WebAddress(url);
2562 host = uri.mHost;
2563 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002564 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002565 }
2566 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002567 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002568 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002569 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002570 }
2571
2572 // Performance probe
2573 if (false) {
2574 mStart = SystemClock.uptimeMillis();
2575 mProcessStart = Process.getElapsedCpuTime();
2576 long[] sysCpu = new long[7];
2577 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2578 sysCpu, null)) {
2579 mUserStart = sysCpu[0] + sysCpu[1];
2580 mSystemStart = sysCpu[2];
2581 mIdleStart = sysCpu[3];
2582 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2583 }
2584 mUiStart = SystemClock.currentThreadTimeMillis();
2585 }
2586
2587 if (!mPageStarted) {
2588 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002589 // if onResume() has been called, resumeWebViewTimers() does
2590 // nothing.
2591 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002592 }
2593
2594 // reset sync timer to avoid sync starts during loading a page
2595 CookieSyncManager.getInstance().resetSync();
2596
2597 mInLoad = true;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002598 mDidStopLoad = false;
Leon Scroggins184f5e32009-09-21 10:38:24 -04002599 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002600 updateInLoadMenuItems();
2601 if (!mIsNetworkUp) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04002602 createAndShowNetworkDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002603 if (view != null) {
2604 view.setNetworkAvailable(false);
2605 }
2606 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002607 }
2608
2609 @Override
2610 public void onPageFinished(WebView view, String url) {
2611 // Reset the title and icon in case we stopped a provisional
2612 // load.
2613 resetTitleAndIcon(view);
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002614
2615 if (!mDidStopLoad) {
2616 // Only update the bookmark screenshot if the user did not
2617 // cancel the load early.
Ben Murdoch2694e232009-09-29 09:41:11 +01002618 Message updateScreenshot = Message.obtain(mHandler, UPDATE_BOOKMARK_THUMBNAIL, view);
2619 mHandler.sendMessageDelayed(updateScreenshot, 500);
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002620 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002621
2622 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002623 updateLockIconToLatest();
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002624
The Android Open Source Project0c908882009-03-03 19:32:16 -08002625 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002626 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002627 long[] sysCpu = new long[7];
2628 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2629 sysCpu, null)) {
2630 String uiInfo = "UI thread used "
2631 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2632 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002633 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002634 Log.d(LOGTAG, uiInfo);
2635 }
2636 //The string that gets written to the log
2637 String performanceString = "It took total "
2638 + (SystemClock.uptimeMillis() - mStart)
2639 + " ms clock time to load the page."
2640 + "\nbrowser process used "
2641 + (Process.getElapsedCpuTime() - mProcessStart)
2642 + " ms, user processes used "
2643 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2644 + " ms, kernel used "
2645 + (sysCpu[2] - mSystemStart) * 10
2646 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2647 + " ms and irq took "
2648 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2649 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002650 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002651 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2652 }
2653 if (url != null) {
2654 // strip the url to maintain consistency
2655 String newUrl = new String(url);
2656 if (newUrl.startsWith("http://www.")) {
2657 newUrl = newUrl.substring(11);
2658 } else if (newUrl.startsWith("http://")) {
2659 newUrl = newUrl.substring(7);
2660 } else if (newUrl.startsWith("https://www.")) {
2661 newUrl = newUrl.substring(12);
2662 } else if (newUrl.startsWith("https://")) {
2663 newUrl = newUrl.substring(8);
2664 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002665 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002666 Log.d(LOGTAG, newUrl + " loaded");
2667 }
2668 /*
2669 if (sWhiteList.contains(newUrl)) {
2670 // The string that gets pushed to the statistcs
2671 // service
2672 performanceString = performanceString
2673 + "\nWebpage: "
2674 + newUrl
2675 + "\nCarrier: "
2676 + android.os.SystemProperties
2677 .get("gsm.sim.operator.alpha");
2678 if (mWebView != null
2679 && mWebView.getContext() != null
2680 && mWebView.getContext().getSystemService(
2681 Context.CONNECTIVITY_SERVICE) != null) {
2682 ConnectivityManager cManager =
2683 (ConnectivityManager) mWebView
2684 .getContext().getSystemService(
2685 Context.CONNECTIVITY_SERVICE);
2686 NetworkInfo nInfo = cManager
2687 .getActiveNetworkInfo();
2688 if (nInfo != null) {
2689 performanceString = performanceString
2690 + "\nNetwork Type: "
2691 + nInfo.getType().toString();
2692 }
2693 }
2694 Checkin.logEvent(mResolver,
2695 Checkin.Events.Tag.WEBPAGE_LOAD,
2696 performanceString);
2697 Log.w(LOGTAG, "pushed to the statistics service");
2698 }
2699 */
2700 }
2701 }
2702 }
2703
2704 if (mInTrace) {
2705 mInTrace = false;
2706 Debug.stopMethodTracing();
2707 }
2708
2709 if (mPageStarted) {
2710 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002711 // pauseWebViewTimers() will do nothing and return false if
2712 // onPause() is not called yet.
2713 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002714 if (mWakeLock.isHeld()) {
2715 mHandler.removeMessages(RELEASE_WAKELOCK);
2716 mWakeLock.release();
2717 }
2718 }
2719 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002720 }
2721
2722 // return true if want to hijack the url to let another app to handle it
2723 @Override
2724 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2725 if (url.startsWith(SCHEME_WTAI)) {
2726 // wtai://wp/mc;number
2727 // number=string(phone-number)
2728 if (url.startsWith(SCHEME_WTAI_MC)) {
2729 Intent intent = new Intent(Intent.ACTION_VIEW,
2730 Uri.parse(WebView.SCHEME_TEL +
2731 url.substring(SCHEME_WTAI_MC.length())));
2732 startActivity(intent);
2733 return true;
2734 }
2735 // wtai://wp/sd;dtmf
2736 // dtmf=string(dialstring)
2737 if (url.startsWith(SCHEME_WTAI_SD)) {
2738 // TODO
2739 // only send when there is active voice connection
2740 return false;
2741 }
2742 // wtai://wp/ap;number;name
2743 // number=string(phone-number)
2744 // name=string
2745 if (url.startsWith(SCHEME_WTAI_AP)) {
2746 // TODO
2747 return false;
2748 }
2749 }
2750
Dianne Hackborn99189432009-06-17 18:06:18 -07002751 // The "about:" schemes are internal to the browser; don't
2752 // want these to be dispatched to other apps.
2753 if (url.startsWith("about:")) {
2754 return false;
2755 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002756
Dianne Hackborn99189432009-06-17 18:06:18 -07002757 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002758
Dianne Hackborn99189432009-06-17 18:06:18 -07002759 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002760 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002761 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2762 } catch (URISyntaxException ex) {
2763 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002764 return false;
2765 }
2766
Grace Kloba5b078b52009-06-24 20:23:41 -07002767 // check whether the intent can be resolved. If not, we will see
2768 // whether we can download it from the Market.
2769 if (getPackageManager().resolveActivity(intent, 0) == null) {
2770 String packagename = intent.getPackage();
2771 if (packagename != null) {
2772 intent = new Intent(Intent.ACTION_VIEW, Uri
2773 .parse("market://search?q=pname:" + packagename));
2774 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2775 startActivity(intent);
2776 return true;
2777 } else {
2778 return false;
2779 }
2780 }
2781
Dianne Hackborn99189432009-06-17 18:06:18 -07002782 // sanitize the Intent, ensuring web pages can not bypass browser
2783 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002784 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002785 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002786 try {
2787 if (startActivityIfNeeded(intent, -1)) {
2788 return true;
2789 }
2790 } catch (ActivityNotFoundException ex) {
2791 // ignore the error. If no application can handle the URL,
2792 // eg about:blank, assume the browser can handle it.
2793 }
2794
2795 if (mMenuIsDown) {
2796 openTab(url);
2797 closeOptionsMenu();
2798 return true;
2799 }
2800
2801 return false;
2802 }
2803
2804 /**
2805 * Updates the lock icon. This method is called when we discover another
2806 * resource to be loaded for this page (for example, javascript). While
2807 * we update the icon type, we do not update the lock icon itself until
2808 * we are done loading, it is slightly more secure this way.
2809 */
2810 @Override
2811 public void onLoadResource(WebView view, String url) {
2812 if (url != null && url.length() > 0) {
2813 // It is only if the page claims to be secure
2814 // that we may have to update the lock:
2815 if (mLockIconType == LOCK_ICON_SECURE) {
2816 // If NOT a 'safe' url, change the lock to mixed content!
2817 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2818 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002819 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002820 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2821 " updated lock icon to " + mLockIconType + " due to " + url);
2822 }
2823 }
2824 }
2825 }
2826 }
2827
2828 /**
2829 * Show the dialog, asking the user if they would like to continue after
2830 * an excessive number of HTTP redirects.
2831 */
2832 @Override
2833 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2834 final Message continueMsg) {
2835 new AlertDialog.Builder(BrowserActivity.this)
2836 .setTitle(R.string.browserFrameRedirect)
2837 .setMessage(R.string.browserFrame307Post)
2838 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2839 public void onClick(DialogInterface dialog, int which) {
2840 continueMsg.sendToTarget();
2841 }})
2842 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2843 public void onClick(DialogInterface dialog, int which) {
2844 cancelMsg.sendToTarget();
2845 }})
2846 .setOnCancelListener(new OnCancelListener() {
2847 public void onCancel(DialogInterface dialog) {
2848 cancelMsg.sendToTarget();
2849 }})
2850 .show();
2851 }
2852
Patrick Scott37911c72009-03-24 18:02:58 -07002853 // Container class for the next error dialog that needs to be
2854 // displayed.
2855 class ErrorDialog {
2856 public final int mTitle;
2857 public final String mDescription;
2858 public final int mError;
2859 ErrorDialog(int title, String desc, int error) {
2860 mTitle = title;
2861 mDescription = desc;
2862 mError = error;
2863 }
2864 };
2865
2866 private void processNextError() {
2867 if (mQueuedErrors == null) {
2868 return;
2869 }
2870 // The first one is currently displayed so just remove it.
2871 mQueuedErrors.removeFirst();
2872 if (mQueuedErrors.size() == 0) {
2873 mQueuedErrors = null;
2874 return;
2875 }
2876 showError(mQueuedErrors.getFirst());
2877 }
2878
2879 private DialogInterface.OnDismissListener mDialogListener =
2880 new DialogInterface.OnDismissListener() {
2881 public void onDismiss(DialogInterface d) {
2882 processNextError();
2883 }
2884 };
2885 private LinkedList<ErrorDialog> mQueuedErrors;
2886
2887 private void queueError(int err, String desc) {
2888 if (mQueuedErrors == null) {
2889 mQueuedErrors = new LinkedList<ErrorDialog>();
2890 }
2891 for (ErrorDialog d : mQueuedErrors) {
2892 if (d.mError == err) {
2893 // Already saw a similar error, ignore the new one.
2894 return;
2895 }
2896 }
2897 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002898 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002899 R.string.browserFrameFileErrorLabel :
2900 R.string.browserFrameNetworkErrorLabel,
2901 desc, err);
2902 mQueuedErrors.addLast(errDialog);
2903
2904 // Show the dialog now if the queue was empty.
2905 if (mQueuedErrors.size() == 1) {
2906 showError(errDialog);
2907 }
2908 }
2909
2910 private void showError(ErrorDialog errDialog) {
2911 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2912 .setTitle(errDialog.mTitle)
2913 .setMessage(errDialog.mDescription)
2914 .setPositiveButton(R.string.ok, null)
2915 .create();
2916 d.setOnDismissListener(mDialogListener);
2917 d.show();
2918 }
2919
The Android Open Source Project0c908882009-03-03 19:32:16 -08002920 /**
2921 * Show a dialog informing the user of the network error reported by
2922 * WebCore.
2923 */
2924 @Override
2925 public void onReceivedError(WebView view, int errorCode,
2926 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002927 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2928 errorCode != WebViewClient.ERROR_CONNECT &&
2929 errorCode != WebViewClient.ERROR_BAD_URL &&
2930 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2931 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002932 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002933 }
Patrick Scott37911c72009-03-24 18:02:58 -07002934 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2935 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002936
2937 // We need to reset the title after an error.
2938 resetTitleAndRevertLockIcon();
2939 }
2940
2941 /**
2942 * Check with the user if it is ok to resend POST data as the page they
2943 * are trying to navigate to is the result of a POST.
2944 */
2945 @Override
2946 public void onFormResubmission(WebView view, final Message dontResend,
2947 final Message resend) {
2948 new AlertDialog.Builder(BrowserActivity.this)
2949 .setTitle(R.string.browserFrameFormResubmitLabel)
2950 .setMessage(R.string.browserFrameFormResubmitMessage)
2951 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2952 public void onClick(DialogInterface dialog, int which) {
2953 resend.sendToTarget();
2954 }})
2955 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2956 public void onClick(DialogInterface dialog, int which) {
2957 dontResend.sendToTarget();
2958 }})
2959 .setOnCancelListener(new OnCancelListener() {
2960 public void onCancel(DialogInterface dialog) {
2961 dontResend.sendToTarget();
2962 }})
2963 .show();
2964 }
2965
2966 /**
2967 * Insert the url into the visited history database.
2968 * @param url The url to be inserted.
2969 * @param isReload True if this url is being reloaded.
2970 * FIXME: Not sure what to do when reloading the page.
2971 */
2972 @Override
2973 public void doUpdateVisitedHistory(WebView view, String url,
2974 boolean isReload) {
2975 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2976 return;
2977 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002978 // remove "client" before updating it to the history so that it wont
2979 // show up in the auto-complete list.
2980 int index = url.indexOf("client=ms-");
2981 if (index > 0 && url.contains(".google.")) {
2982 int end = url.indexOf('&', index);
2983 if (end > 0) {
Grace Klobaef292152009-10-07 19:15:59 -07002984 url = url.substring(0, index)
2985 .concat(url.substring(end + 1));
Grace Kloba6b52a552009-09-03 16:29:56 -07002986 } else {
Grace Klobaef292152009-10-07 19:15:59 -07002987 // the url.charAt(index-1) should be either '?' or '&'
Grace Kloba6b52a552009-09-03 16:29:56 -07002988 url = url.substring(0, index-1);
2989 }
2990 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002991 Browser.updateVisitedHistory(mResolver, url, true);
2992 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2993 }
2994
2995 /**
2996 * Displays SSL error(s) dialog to the user.
2997 */
2998 @Override
2999 public void onReceivedSslError(
3000 final WebView view, final SslErrorHandler handler, final SslError error) {
3001
3002 if (mSettings.showSecurityWarnings()) {
3003 final LayoutInflater factory =
3004 LayoutInflater.from(BrowserActivity.this);
3005 final View warningsView =
3006 factory.inflate(R.layout.ssl_warnings, null);
3007 final LinearLayout placeholder =
3008 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3009
3010 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3011 LinearLayout ll = (LinearLayout)factory
3012 .inflate(R.layout.ssl_warning, null);
3013 ((TextView)ll.findViewById(R.id.warning))
3014 .setText(R.string.ssl_untrusted);
3015 placeholder.addView(ll);
3016 }
3017
3018 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3019 LinearLayout ll = (LinearLayout)factory
3020 .inflate(R.layout.ssl_warning, null);
3021 ((TextView)ll.findViewById(R.id.warning))
3022 .setText(R.string.ssl_mismatch);
3023 placeholder.addView(ll);
3024 }
3025
3026 if (error.hasError(SslError.SSL_EXPIRED)) {
3027 LinearLayout ll = (LinearLayout)factory
3028 .inflate(R.layout.ssl_warning, null);
3029 ((TextView)ll.findViewById(R.id.warning))
3030 .setText(R.string.ssl_expired);
3031 placeholder.addView(ll);
3032 }
3033
3034 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3035 LinearLayout ll = (LinearLayout)factory
3036 .inflate(R.layout.ssl_warning, null);
3037 ((TextView)ll.findViewById(R.id.warning))
3038 .setText(R.string.ssl_not_yet_valid);
3039 placeholder.addView(ll);
3040 }
3041
3042 new AlertDialog.Builder(BrowserActivity.this)
3043 .setTitle(R.string.security_warning)
3044 .setIcon(android.R.drawable.ic_dialog_alert)
3045 .setView(warningsView)
3046 .setPositiveButton(R.string.ssl_continue,
3047 new DialogInterface.OnClickListener() {
3048 public void onClick(DialogInterface dialog, int whichButton) {
3049 handler.proceed();
3050 }
3051 })
3052 .setNeutralButton(R.string.view_certificate,
3053 new DialogInterface.OnClickListener() {
3054 public void onClick(DialogInterface dialog, int whichButton) {
3055 showSSLCertificateOnError(view, handler, error);
3056 }
3057 })
3058 .setNegativeButton(R.string.cancel,
3059 new DialogInterface.OnClickListener() {
3060 public void onClick(DialogInterface dialog, int whichButton) {
3061 handler.cancel();
3062 BrowserActivity.this.resetTitleAndRevertLockIcon();
3063 }
3064 })
3065 .setOnCancelListener(
3066 new DialogInterface.OnCancelListener() {
3067 public void onCancel(DialogInterface dialog) {
3068 handler.cancel();
3069 BrowserActivity.this.resetTitleAndRevertLockIcon();
3070 }
3071 })
3072 .show();
3073 } else {
3074 handler.proceed();
3075 }
3076 }
3077
3078 /**
3079 * Handles an HTTP authentication request.
3080 *
3081 * @param handler The authentication handler
3082 * @param host The host
3083 * @param realm The realm
3084 */
3085 @Override
3086 public void onReceivedHttpAuthRequest(WebView view,
3087 final HttpAuthHandler handler, final String host, final String realm) {
3088 String username = null;
3089 String password = null;
3090
3091 boolean reuseHttpAuthUsernamePassword =
3092 handler.useHttpAuthUsernamePassword();
3093
3094 if (reuseHttpAuthUsernamePassword &&
3095 (mTabControl.getCurrentWebView() != null)) {
3096 String[] credentials =
3097 mTabControl.getCurrentWebView()
3098 .getHttpAuthUsernamePassword(host, realm);
3099 if (credentials != null && credentials.length == 2) {
3100 username = credentials[0];
3101 password = credentials[1];
3102 }
3103 }
3104
3105 if (username != null && password != null) {
3106 handler.proceed(username, password);
3107 } else {
3108 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3109 }
3110 }
3111
3112 @Override
3113 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3114 if (mMenuIsDown) {
3115 // only check shortcut key when MENU is held
3116 return getWindow().isShortcutKey(event.getKeyCode(), event);
3117 } else {
3118 return false;
3119 }
3120 }
3121
3122 @Override
3123 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3124 if (view != mTabControl.getCurrentTopWebView()) {
3125 return;
3126 }
3127 if (event.isDown()) {
3128 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3129 } else {
3130 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3131 }
3132 }
3133 };
3134
3135 //--------------------------------------------------------------------------
3136 // WebChromeClient implementation
3137 //--------------------------------------------------------------------------
3138
3139 /* package */ WebChromeClient getWebChromeClient() {
3140 return mWebChromeClient;
3141 }
3142
3143 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3144 // Helper method to create a new tab or sub window.
3145 private void createWindow(final boolean dialog, final Message msg) {
3146 if (dialog) {
3147 mTabControl.createSubWindow();
3148 final TabControl.Tab t = mTabControl.getCurrentTab();
3149 attachSubWindow(t);
3150 WebView.WebViewTransport transport =
3151 (WebView.WebViewTransport) msg.obj;
3152 transport.setWebView(t.getSubWebView());
3153 msg.sendToTarget();
3154 } else {
3155 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003156 final TabControl.Tab newTab
3157 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07003158 if (newTab != parent) {
3159 parent.addChildTab(newTab);
3160 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003161 WebView.WebViewTransport transport =
3162 (WebView.WebViewTransport) msg.obj;
3163 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04003164 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003165 }
3166 }
3167
3168 @Override
3169 public boolean onCreateWindow(WebView view, final boolean dialog,
3170 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003171 // Short-circuit if we can't create any more tabs or sub windows.
3172 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3173 new AlertDialog.Builder(BrowserActivity.this)
3174 .setTitle(R.string.too_many_subwindows_dialog_title)
3175 .setIcon(android.R.drawable.ic_dialog_alert)
3176 .setMessage(R.string.too_many_subwindows_dialog_message)
3177 .setPositiveButton(R.string.ok, null)
3178 .show();
3179 return false;
3180 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3181 new AlertDialog.Builder(BrowserActivity.this)
3182 .setTitle(R.string.too_many_windows_dialog_title)
3183 .setIcon(android.R.drawable.ic_dialog_alert)
3184 .setMessage(R.string.too_many_windows_dialog_message)
3185 .setPositiveButton(R.string.ok, null)
3186 .show();
3187 return false;
3188 }
3189
3190 // Short-circuit if this was a user gesture.
3191 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003192 createWindow(dialog, resultMsg);
3193 return true;
3194 }
3195
3196 // Allow the popup and create the appropriate window.
3197 final AlertDialog.OnClickListener allowListener =
3198 new AlertDialog.OnClickListener() {
3199 public void onClick(DialogInterface d,
3200 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003201 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003202 }
3203 };
3204
3205 // Block the popup by returning a null WebView.
3206 final AlertDialog.OnClickListener blockListener =
3207 new AlertDialog.OnClickListener() {
3208 public void onClick(DialogInterface d, int which) {
3209 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003210 }
3211 };
3212
3213 // Build a confirmation dialog to display to the user.
3214 final AlertDialog d =
3215 new AlertDialog.Builder(BrowserActivity.this)
3216 .setTitle(R.string.attention)
3217 .setIcon(android.R.drawable.ic_dialog_alert)
3218 .setMessage(R.string.popup_window_attempt)
3219 .setPositiveButton(R.string.allow, allowListener)
3220 .setNegativeButton(R.string.block, blockListener)
3221 .setCancelable(false)
3222 .create();
3223
3224 // Show the confirmation dialog.
3225 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003226 return true;
3227 }
3228
3229 @Override
3230 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003231 final TabControl.Tab current = mTabControl.getCurrentTab();
3232 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003233 if (parent != null) {
3234 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003235 switchToTab(mTabControl.getTabIndex(parent));
3236 // Now we need to close the window
3237 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003238 }
3239 }
3240
3241 @Override
3242 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003243 mTitleBar.setProgress(newProgress);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003244 if (mFakeTitleBar != null) {
3245 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003246 }
3247
3248 if (newProgress == 100) {
Ben Murdochaac7aa62009-09-17 16:57:40 +01003249 // onProgressChanged() may continue to be called after the main
3250 // frame has finished loading, as any remaining sub frames
3251 // continue to load. We'll only get called once though with
3252 // newProgress as 100 when everything is loaded.
3253 // (onPageFinished is called once when the main frame completes
3254 // loading regardless of the state of any sub frames so calls
3255 // to onProgressChanges may continue after onPageFinished has
3256 // executed)
3257
3258 // sync cookies and cache promptly here.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003259 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003260 if (mInLoad) {
3261 mInLoad = false;
3262 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003263 // If the options menu is open, leave the title bar
3264 if (!mOptionsMenuOpen || !mIconView) {
3265 hideFakeTitleBar();
3266 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003267 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003268 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003269 // onPageFinished may have already been called but a subframe
3270 // is still loading and updating the progress. Reset mInLoad
3271 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003272 mInLoad = true;
3273 updateInLoadMenuItems();
Leon Scroggins184f5e32009-09-21 10:38:24 -04003274 if (!mOptionsMenuOpen || mIconView) {
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003275 // This page has begun to load, so show the title bar
3276 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003277 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003278 }
3279 }
3280
3281 @Override
3282 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003283 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003284
3285 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003286 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003287
3288 if (url == null ||
3289 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3290 return;
3291 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003292 // See if we can find the current url in our history database and
3293 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003294 if (url.startsWith("http://www.")) {
3295 url = url.substring(11);
3296 } else if (url.startsWith("http://")) {
3297 url = url.substring(4);
3298 }
3299 try {
3300 url = "%" + url;
3301 String [] selArgs = new String[] { url };
3302
3303 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3304 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3305 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3306 Browser.HISTORY_PROJECTION, where, selArgs, null);
3307 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003308 // Current implementation of database only has one entry per
3309 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003310 ContentValues map = new ContentValues();
3311 map.put(Browser.BookmarkColumns.TITLE, title);
3312 mResolver.update(Browser.BOOKMARKS_URI, map,
3313 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003314 }
3315 c.close();
3316 } catch (IllegalStateException e) {
3317 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3318 } catch (SQLiteException ex) {
3319 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3320 }
3321 }
3322
3323 @Override
3324 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003325 updateIcon(view, icon);
3326 }
3327
3328 @Override
Patrick Scott59ce8302009-09-18 16:29:38 -04003329 public void onReceivedTouchIconUrl(WebView view, String url,
3330 boolean precomposed) {
Patrick Scott3918d442009-08-04 13:22:29 -04003331 final ContentResolver cr = getContentResolver();
3332 final Cursor c =
3333 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003334 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003335 if (c != null) {
3336 if (c.getCount() > 0) {
Patrick Scott59ce8302009-09-18 16:29:38 -04003337 // Let precomposed icons take precedence over non-composed
3338 // icons.
3339 if (precomposed && mTouchIconLoader != null) {
3340 mTouchIconLoader.cancel(false);
3341 mTouchIconLoader = null;
3342 }
3343 // Have only one async task at a time.
3344 if (mTouchIconLoader == null) {
3345 mTouchIconLoader = new DownloadTouchIcon(
3346 BrowserActivity.this, cr, c, view);
3347 mTouchIconLoader.execute(url);
3348 }
Patrick Scott3918d442009-08-04 13:22:29 -04003349 } else {
3350 c.close();
3351 }
3352 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003353 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003354
Andrei Popescuadc008d2009-06-26 14:11:30 +01003355 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003356 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003357 if (mCustomView != null)
3358 return;
3359
3360 // Add the custom view to its container.
3361 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3362 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003363 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003364 // Save the menu state and set it to empty while the custom
3365 // view is showing.
3366 mOldMenuState = mMenuState;
3367 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003368 // Hide the content view.
3369 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003370 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003371 mCustomViewContainer.setVisibility(View.VISIBLE);
3372 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003373 }
3374
3375 @Override
3376 public void onHideCustomView() {
3377 if (mCustomView == null)
3378 return;
3379
Andrei Popescuc9b55562009-07-07 10:51:15 +01003380 // Hide the custom view.
3381 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003382 // Remove the custom view from its container.
3383 mCustomViewContainer.removeView(mCustomView);
3384 mCustomView = null;
3385 // Reset the old menu state.
3386 mMenuState = mOldMenuState;
3387 mOldMenuState = EMPTY_MENU;
3388 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003389 mCustomViewCallback.onCustomViewHidden();
3390 // Show the content view.
3391 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003392 }
3393
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003394 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003395 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003396 * @param url the URL that exceeded the quota
3397 * @param databaseIdentifier the identifier of the database on
3398 * which the transaction that caused the quota overflow was run
3399 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003400 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003401 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003402 * @param quotaUpdater The callback to run when a decision to allow or
3403 * deny quota has been made. Don't forget to call this!
3404 */
3405 @Override
3406 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003407 String databaseIdentifier, long currentQuota, long estimatedSize,
3408 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003409 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003410 url, databaseIdentifier, currentQuota, estimatedSize,
3411 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003412 }
3413
3414 /**
3415 * The Application Cache has exceeded its max size.
3416 * @param spaceNeeded is the amount of disk space that would be needed
3417 * in order for the last appcache operation to succeed.
3418 * @param totalUsedQuota is the sum of all origins' quota.
3419 * @param quotaUpdater A callback to inform the WebCore thread that a new
3420 * app cache size is available. This callback must always be executed at
3421 * some point to ensure that the sleeping WebCore thread is woken up.
3422 */
3423 @Override
3424 public void onReachedMaxAppCacheSize(long spaceNeeded,
3425 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3426 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3427 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003428 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003429
Steve Block2bc69912009-07-30 14:45:13 +01003430 /**
3431 * Instructs the browser to show a prompt to ask the user to set the
3432 * Geolocation permission state for the specified origin.
3433 * @param origin The origin for which Geolocation permissions are
3434 * requested.
3435 * @param callback The callback to call once the user has set the
3436 * Geolocation permission state.
3437 */
3438 @Override
3439 public void onGeolocationPermissionsShowPrompt(String origin,
3440 GeolocationPermissions.Callback callback) {
3441 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3442 origin, callback);
3443 }
3444
3445 /**
3446 * Instructs the browser to hide the Geolocation permissions prompt.
3447 */
3448 @Override
3449 public void onGeolocationPermissionsHidePrompt() {
3450 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3451 }
3452
Ben Murdoch7db26342009-06-03 18:21:19 +01003453 /* Adds a JavaScript error message to the system log.
3454 * @param message The error message to report.
3455 * @param lineNumber The line number of the error.
3456 * @param sourceID The name of the source file that caused the error.
3457 */
3458 @Override
3459 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003460 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3461 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3462 if (mShouldShowErrorConsole &&
3463 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3464 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3465 }
3466 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003467 }
Andrei Popescu540035d2009-09-18 18:59:20 +01003468
3469 /**
3470 * Ask the browser for an icon to represent a <video> element.
3471 * This icon will be used if the Web page did not specify a poster attribute.
3472 *
3473 * @return Bitmap The icon or null if no such icon is available.
3474 * @hide pending API Council approval
3475 */
3476 @Override
3477 public Bitmap getDefaultVideoPoster() {
3478 if (mDefaultVideoPoster == null) {
3479 mDefaultVideoPoster = BitmapFactory.decodeResource(
3480 getResources(), R.drawable.default_video_poster);
3481 }
3482 return mDefaultVideoPoster;
3483 }
3484
3485 /**
3486 * Ask the host application for a custom progress view to show while
3487 * a <video> is loading.
3488 *
3489 * @return View The progress view.
3490 * @hide pending API Council approval
3491 */
3492 @Override
3493 public View getVideoLoadingProgressView() {
3494 if (mVideoProgressView == null) {
3495 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
3496 mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
3497 }
3498 return mVideoProgressView;
3499 }
Leon Clarkecb6cc862009-09-29 18:35:13 +01003500
3501 /**
3502 * Deliver a list of already-visited URLs
3503 * @hide pending API Council approval
3504 */
3505 @Override
3506 public void getVisitedHistory(final ValueCallback<String[]> callback) {
3507 AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
3508 public String[] doInBackground(Void... unused) {
3509 return Browser.getVisitedHistory(getContentResolver());
3510 }
3511
3512 public void onPostExecute(String[] result) {
3513 callback.onReceiveValue(result);
3514
3515 };
3516 };
3517 task.execute();
3518 };
The Android Open Source Project0c908882009-03-03 19:32:16 -08003519 };
3520
3521 /**
3522 * Notify the host application a download should be done, or that
3523 * the data should be streamed if a streaming viewer is available.
3524 * @param url The full url to the content that should be downloaded
3525 * @param contentDisposition Content-disposition http header, if
3526 * present.
3527 * @param mimetype The mimetype of the content reported by the server
3528 * @param contentLength The file size reported by the server
3529 */
3530 public void onDownloadStart(String url, String userAgent,
3531 String contentDisposition, String mimetype, long contentLength) {
3532 // if we're dealing wih A/V content that's not explicitly marked
3533 // for download, check if it's streamable.
3534 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003535 || !contentDisposition.regionMatches(
3536 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003537 // query the package manager to see if there's a registered handler
3538 // that matches.
3539 Intent intent = new Intent(Intent.ACTION_VIEW);
3540 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003541 ResolveInfo info = getPackageManager().resolveActivity(intent,
3542 PackageManager.MATCH_DEFAULT_ONLY);
3543 if (info != null) {
3544 ComponentName myName = getComponentName();
3545 // If we resolved to ourselves, we don't want to attempt to
3546 // load the url only to try and download it again.
3547 if (!myName.getPackageName().equals(
3548 info.activityInfo.packageName)
3549 || !myName.getClassName().equals(
3550 info.activityInfo.name)) {
3551 // someone (other than us) knows how to handle this mime
3552 // type with this scheme, don't download.
3553 try {
3554 startActivity(intent);
3555 return;
3556 } catch (ActivityNotFoundException ex) {
3557 if (LOGD_ENABLED) {
3558 Log.d(LOGTAG, "activity not found for " + mimetype
3559 + " over " + Uri.parse(url).getScheme(),
3560 ex);
3561 }
3562 // Best behavior is to fall back to a download in this
3563 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003564 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003565 }
3566 }
3567 }
3568 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3569 }
3570
3571 /**
3572 * Notify the host application a download should be done, even if there
3573 * is a streaming viewer available for thise type.
3574 * @param url The full url to the content that should be downloaded
3575 * @param contentDisposition Content-disposition http header, if
3576 * present.
3577 * @param mimetype The mimetype of the content reported by the server
3578 * @param contentLength The file size reported by the server
3579 */
3580 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3581 String contentDisposition, String mimetype, long contentLength) {
3582
3583 String filename = URLUtil.guessFileName(url,
3584 contentDisposition, mimetype);
3585
3586 // Check to see if we have an SDCard
3587 String status = Environment.getExternalStorageState();
3588 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3589 int title;
3590 String msg;
3591
3592 // Check to see if the SDCard is busy, same as the music app
3593 if (status.equals(Environment.MEDIA_SHARED)) {
3594 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3595 title = R.string.download_sdcard_busy_dlg_title;
3596 } else {
3597 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3598 title = R.string.download_no_sdcard_dlg_title;
3599 }
3600
3601 new AlertDialog.Builder(this)
3602 .setTitle(title)
3603 .setIcon(android.R.drawable.ic_dialog_alert)
3604 .setMessage(msg)
3605 .setPositiveButton(R.string.ok, null)
3606 .show();
3607 return;
3608 }
3609
3610 // java.net.URI is a lot stricter than KURL so we have to undo
3611 // KURL's percent-encoding and redo the encoding using java.net.URI.
3612 URI uri = null;
3613 try {
3614 // Undo the percent-encoding that KURL may have done.
3615 String newUrl = new String(URLUtil.decode(url.getBytes()));
3616 // Parse the url into pieces
3617 WebAddress w = new WebAddress(newUrl);
3618 String frag = null;
3619 String query = null;
3620 String path = w.mPath;
3621 // Break the path into path, query, and fragment
3622 if (path.length() > 0) {
3623 // Strip the fragment
3624 int idx = path.lastIndexOf('#');
3625 if (idx != -1) {
3626 frag = path.substring(idx + 1);
3627 path = path.substring(0, idx);
3628 }
3629 idx = path.lastIndexOf('?');
3630 if (idx != -1) {
3631 query = path.substring(idx + 1);
3632 path = path.substring(0, idx);
3633 }
3634 }
3635 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3636 query, frag);
3637 } catch (Exception e) {
3638 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3639 return;
3640 }
3641
3642 // XXX: Have to use the old url since the cookies were stored using the
3643 // old percent-encoded url.
3644 String cookies = CookieManager.getInstance().getCookie(url);
3645
3646 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003647 values.put(Downloads.COLUMN_URI, uri.toString());
3648 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3649 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3650 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003651 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003652 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003653 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003654 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3655 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3656 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3657 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003658 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003659 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003660 }
3661 if (mimetype == null) {
3662 // We must have long pressed on a link or image to download it. We
3663 // are not sure of the mimetype in this case, so do a head request
3664 new FetchUrlMimeType(this).execute(values);
3665 } else {
3666 final Uri contentUri =
3667 getContentResolver().insert(Downloads.CONTENT_URI, values);
3668 viewDownloads(contentUri);
3669 }
3670
3671 }
3672
3673 /**
3674 * Resets the lock icon. This method is called when we start a new load and
3675 * know the url to be loaded.
3676 */
3677 private void resetLockIcon(String url) {
3678 // Save the lock-icon state (we revert to it if the load gets cancelled)
3679 saveLockIcon();
3680
3681 mLockIconType = LOCK_ICON_UNSECURE;
3682 if (URLUtil.isHttpsUrl(url)) {
3683 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003684 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003685 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3686 " reset lock icon to " + mLockIconType);
3687 }
3688 }
3689
3690 updateLockIconImage(LOCK_ICON_UNSECURE);
3691 }
3692
Grace Klobaeb6eef42009-09-15 17:56:32 -07003693 /* package */ void setLockIconType(int type) {
3694 mLockIconType = type;
3695 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003696
Grace Klobaeb6eef42009-09-15 17:56:32 -07003697 /* package */ int getLockIconType() {
3698 return mLockIconType;
3699 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003700
Grace Klobaeb6eef42009-09-15 17:56:32 -07003701 /* package */ void setPrevLockType(int type) {
3702 mPrevLockType = type;
3703 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003704
Grace Klobaeb6eef42009-09-15 17:56:32 -07003705 /* package */ int getPrevLockType() {
3706 return mPrevLockType;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003707 }
3708
3709 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003710 * Update the lock icon to correspond to our latest state.
3711 */
3712 /* package */ void updateLockIconToLatest() {
3713 updateLockIconImage(mLockIconType);
3714 }
3715
3716 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003717 * Updates the lock-icon image in the title-bar.
3718 */
3719 private void updateLockIconImage(int lockIconType) {
3720 Drawable d = null;
3721 if (lockIconType == LOCK_ICON_SECURE) {
3722 d = mSecLockIcon;
3723 } else if (lockIconType == LOCK_ICON_MIXED) {
3724 d = mMixLockIcon;
3725 }
Leon Scroggins68579392009-09-15 15:31:54 -04003726 mTitleBar.setLock(d);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003727 if (mFakeTitleBar != null) {
3728 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003729 }
3730 }
3731
3732 /**
3733 * Displays a page-info dialog.
3734 * @param tab The tab to show info about
3735 * @param fromShowSSLCertificateOnError The flag that indicates whether
3736 * this dialog was opened from the SSL-certificate-on-error dialog or
3737 * not. This is important, since we need to know whether to return to
3738 * the parent dialog or simply dismiss.
3739 */
3740 private void showPageInfo(final TabControl.Tab tab,
3741 final boolean fromShowSSLCertificateOnError) {
3742 final LayoutInflater factory = LayoutInflater
3743 .from(this);
3744
3745 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3746
3747 final WebView view = tab.getWebView();
3748
3749 String url = null;
3750 String title = null;
3751
3752 if (view == null) {
3753 url = tab.getUrl();
3754 title = tab.getTitle();
3755 } else if (view == mTabControl.getCurrentWebView()) {
3756 // Use the cached title and url if this is the current WebView
3757 url = mUrl;
3758 title = mTitle;
3759 } else {
3760 url = view.getUrl();
3761 title = view.getTitle();
3762 }
3763
3764 if (url == null) {
3765 url = "";
3766 }
3767 if (title == null) {
3768 title = "";
3769 }
3770
3771 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3772 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3773
3774 mPageInfoView = tab;
3775 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3776
3777 AlertDialog.Builder alertDialogBuilder =
3778 new AlertDialog.Builder(this)
3779 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3780 .setView(pageInfoView)
3781 .setPositiveButton(
3782 R.string.ok,
3783 new DialogInterface.OnClickListener() {
3784 public void onClick(DialogInterface dialog,
3785 int whichButton) {
3786 mPageInfoDialog = null;
3787 mPageInfoView = null;
3788 mPageInfoFromShowSSLCertificateOnError = null;
3789
3790 // if we came here from the SSL error dialog
3791 if (fromShowSSLCertificateOnError) {
3792 // go back to the SSL error dialog
3793 showSSLCertificateOnError(
3794 mSSLCertificateOnErrorView,
3795 mSSLCertificateOnErrorHandler,
3796 mSSLCertificateOnErrorError);
3797 }
3798 }
3799 })
3800 .setOnCancelListener(
3801 new DialogInterface.OnCancelListener() {
3802 public void onCancel(DialogInterface dialog) {
3803 mPageInfoDialog = null;
3804 mPageInfoView = null;
3805 mPageInfoFromShowSSLCertificateOnError = null;
3806
3807 // if we came here from the SSL error dialog
3808 if (fromShowSSLCertificateOnError) {
3809 // go back to the SSL error dialog
3810 showSSLCertificateOnError(
3811 mSSLCertificateOnErrorView,
3812 mSSLCertificateOnErrorHandler,
3813 mSSLCertificateOnErrorError);
3814 }
3815 }
3816 });
3817
3818 // if we have a main top-level page SSL certificate set or a certificate
3819 // error
3820 if (fromShowSSLCertificateOnError ||
3821 (view != null && view.getCertificate() != null)) {
3822 // add a 'View Certificate' button
3823 alertDialogBuilder.setNeutralButton(
3824 R.string.view_certificate,
3825 new DialogInterface.OnClickListener() {
3826 public void onClick(DialogInterface dialog,
3827 int whichButton) {
3828 mPageInfoDialog = null;
3829 mPageInfoView = null;
3830 mPageInfoFromShowSSLCertificateOnError = null;
3831
3832 // if we came here from the SSL error dialog
3833 if (fromShowSSLCertificateOnError) {
3834 // go back to the SSL error dialog
3835 showSSLCertificateOnError(
3836 mSSLCertificateOnErrorView,
3837 mSSLCertificateOnErrorHandler,
3838 mSSLCertificateOnErrorError);
3839 } else {
3840 // otherwise, display the top-most certificate from
3841 // the chain
3842 if (view.getCertificate() != null) {
3843 showSSLCertificate(tab);
3844 }
3845 }
3846 }
3847 });
3848 }
3849
3850 mPageInfoDialog = alertDialogBuilder.show();
3851 }
3852
3853 /**
3854 * Displays the main top-level page SSL certificate dialog
3855 * (accessible from the Page-Info dialog).
3856 * @param tab The tab to show certificate for.
3857 */
3858 private void showSSLCertificate(final TabControl.Tab tab) {
3859 final View certificateView =
3860 inflateCertificateView(tab.getWebView().getCertificate());
3861 if (certificateView == null) {
3862 return;
3863 }
3864
3865 LayoutInflater factory = LayoutInflater.from(this);
3866
3867 final LinearLayout placeholder =
3868 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3869
3870 LinearLayout ll = (LinearLayout) factory.inflate(
3871 R.layout.ssl_success, placeholder);
3872 ((TextView)ll.findViewById(R.id.success))
3873 .setText(R.string.ssl_certificate_is_valid);
3874
3875 mSSLCertificateView = tab;
3876 mSSLCertificateDialog =
3877 new AlertDialog.Builder(this)
3878 .setTitle(R.string.ssl_certificate).setIcon(
3879 R.drawable.ic_dialog_browser_certificate_secure)
3880 .setView(certificateView)
3881 .setPositiveButton(R.string.ok,
3882 new DialogInterface.OnClickListener() {
3883 public void onClick(DialogInterface dialog,
3884 int whichButton) {
3885 mSSLCertificateDialog = null;
3886 mSSLCertificateView = null;
3887
3888 showPageInfo(tab, false);
3889 }
3890 })
3891 .setOnCancelListener(
3892 new DialogInterface.OnCancelListener() {
3893 public void onCancel(DialogInterface dialog) {
3894 mSSLCertificateDialog = null;
3895 mSSLCertificateView = null;
3896
3897 showPageInfo(tab, false);
3898 }
3899 })
3900 .show();
3901 }
3902
3903 /**
3904 * Displays the SSL error certificate dialog.
3905 * @param view The target web-view.
3906 * @param handler The SSL error handler responsible for cancelling the
3907 * connection that resulted in an SSL error or proceeding per user request.
3908 * @param error The SSL error object.
3909 */
3910 private void showSSLCertificateOnError(
3911 final WebView view, final SslErrorHandler handler, final SslError error) {
3912
3913 final View certificateView =
3914 inflateCertificateView(error.getCertificate());
3915 if (certificateView == null) {
3916 return;
3917 }
3918
3919 LayoutInflater factory = LayoutInflater.from(this);
3920
3921 final LinearLayout placeholder =
3922 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3923
3924 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3925 LinearLayout ll = (LinearLayout)factory
3926 .inflate(R.layout.ssl_warning, placeholder);
3927 ((TextView)ll.findViewById(R.id.warning))
3928 .setText(R.string.ssl_untrusted);
3929 }
3930
3931 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3932 LinearLayout ll = (LinearLayout)factory
3933 .inflate(R.layout.ssl_warning, placeholder);
3934 ((TextView)ll.findViewById(R.id.warning))
3935 .setText(R.string.ssl_mismatch);
3936 }
3937
3938 if (error.hasError(SslError.SSL_EXPIRED)) {
3939 LinearLayout ll = (LinearLayout)factory
3940 .inflate(R.layout.ssl_warning, placeholder);
3941 ((TextView)ll.findViewById(R.id.warning))
3942 .setText(R.string.ssl_expired);
3943 }
3944
3945 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3946 LinearLayout ll = (LinearLayout)factory
3947 .inflate(R.layout.ssl_warning, placeholder);
3948 ((TextView)ll.findViewById(R.id.warning))
3949 .setText(R.string.ssl_not_yet_valid);
3950 }
3951
3952 mSSLCertificateOnErrorHandler = handler;
3953 mSSLCertificateOnErrorView = view;
3954 mSSLCertificateOnErrorError = error;
3955 mSSLCertificateOnErrorDialog =
3956 new AlertDialog.Builder(this)
3957 .setTitle(R.string.ssl_certificate).setIcon(
3958 R.drawable.ic_dialog_browser_certificate_partially_secure)
3959 .setView(certificateView)
3960 .setPositiveButton(R.string.ok,
3961 new DialogInterface.OnClickListener() {
3962 public void onClick(DialogInterface dialog,
3963 int whichButton) {
3964 mSSLCertificateOnErrorDialog = null;
3965 mSSLCertificateOnErrorView = null;
3966 mSSLCertificateOnErrorHandler = null;
3967 mSSLCertificateOnErrorError = null;
3968
3969 mWebViewClient.onReceivedSslError(
3970 view, handler, error);
3971 }
3972 })
3973 .setNeutralButton(R.string.page_info_view,
3974 new DialogInterface.OnClickListener() {
3975 public void onClick(DialogInterface dialog,
3976 int whichButton) {
3977 mSSLCertificateOnErrorDialog = null;
3978
3979 // do not clear the dialog state: we will
3980 // need to show the dialog again once the
3981 // user is done exploring the page-info details
3982
3983 showPageInfo(mTabControl.getTabFromView(view),
3984 true);
3985 }
3986 })
3987 .setOnCancelListener(
3988 new DialogInterface.OnCancelListener() {
3989 public void onCancel(DialogInterface dialog) {
3990 mSSLCertificateOnErrorDialog = null;
3991 mSSLCertificateOnErrorView = null;
3992 mSSLCertificateOnErrorHandler = null;
3993 mSSLCertificateOnErrorError = null;
3994
3995 mWebViewClient.onReceivedSslError(
3996 view, handler, error);
3997 }
3998 })
3999 .show();
4000 }
4001
4002 /**
4003 * Inflates the SSL certificate view (helper method).
4004 * @param certificate The SSL certificate.
4005 * @return The resultant certificate view with issued-to, issued-by,
4006 * issued-on, expires-on, and possibly other fields set.
4007 * If the input certificate is null, returns null.
4008 */
4009 private View inflateCertificateView(SslCertificate certificate) {
4010 if (certificate == null) {
4011 return null;
4012 }
4013
4014 LayoutInflater factory = LayoutInflater.from(this);
4015
4016 View certificateView = factory.inflate(
4017 R.layout.ssl_certificate, null);
4018
4019 // issued to:
4020 SslCertificate.DName issuedTo = certificate.getIssuedTo();
4021 if (issuedTo != null) {
4022 ((TextView) certificateView.findViewById(R.id.to_common))
4023 .setText(issuedTo.getCName());
4024 ((TextView) certificateView.findViewById(R.id.to_org))
4025 .setText(issuedTo.getOName());
4026 ((TextView) certificateView.findViewById(R.id.to_org_unit))
4027 .setText(issuedTo.getUName());
4028 }
4029
4030 // issued by:
4031 SslCertificate.DName issuedBy = certificate.getIssuedBy();
4032 if (issuedBy != null) {
4033 ((TextView) certificateView.findViewById(R.id.by_common))
4034 .setText(issuedBy.getCName());
4035 ((TextView) certificateView.findViewById(R.id.by_org))
4036 .setText(issuedBy.getOName());
4037 ((TextView) certificateView.findViewById(R.id.by_org_unit))
4038 .setText(issuedBy.getUName());
4039 }
4040
4041 // issued on:
4042 String issuedOn = reformatCertificateDate(
4043 certificate.getValidNotBefore());
4044 ((TextView) certificateView.findViewById(R.id.issued_on))
4045 .setText(issuedOn);
4046
4047 // expires on:
4048 String expiresOn = reformatCertificateDate(
4049 certificate.getValidNotAfter());
4050 ((TextView) certificateView.findViewById(R.id.expires_on))
4051 .setText(expiresOn);
4052
4053 return certificateView;
4054 }
4055
4056 /**
4057 * Re-formats the certificate date (Date.toString()) string to
4058 * a properly localized date string.
4059 * @return Properly localized version of the certificate date string and
4060 * the original certificate date string if fails to localize.
4061 * If the original string is null, returns an empty string "".
4062 */
4063 private String reformatCertificateDate(String certificateDate) {
4064 String reformattedDate = null;
4065
4066 if (certificateDate != null) {
4067 Date date = null;
4068 try {
4069 date = java.text.DateFormat.getInstance().parse(certificateDate);
4070 } catch (ParseException e) {
4071 date = null;
4072 }
4073
4074 if (date != null) {
4075 reformattedDate =
4076 DateFormat.getDateFormat(this).format(date);
4077 }
4078 }
4079
4080 return reformattedDate != null ? reformattedDate :
4081 (certificateDate != null ? certificateDate : "");
4082 }
4083
4084 /**
4085 * Displays an http-authentication dialog.
4086 */
4087 private void showHttpAuthentication(final HttpAuthHandler handler,
4088 final String host, final String realm, final String title,
4089 final String name, final String password, int focusId) {
4090 LayoutInflater factory = LayoutInflater.from(this);
4091 final View v = factory
4092 .inflate(R.layout.http_authentication, null);
4093 if (name != null) {
4094 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4095 }
4096 if (password != null) {
4097 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4098 }
4099
4100 String titleText = title;
4101 if (titleText == null) {
4102 titleText = getText(R.string.sign_in_to).toString().replace(
4103 "%s1", host).replace("%s2", realm);
4104 }
4105
4106 mHttpAuthHandler = handler;
4107 AlertDialog dialog = new AlertDialog.Builder(this)
4108 .setTitle(titleText)
4109 .setIcon(android.R.drawable.ic_dialog_alert)
4110 .setView(v)
4111 .setPositiveButton(R.string.action,
4112 new DialogInterface.OnClickListener() {
4113 public void onClick(DialogInterface dialog,
4114 int whichButton) {
4115 String nm = ((EditText) v
4116 .findViewById(R.id.username_edit))
4117 .getText().toString();
4118 String pw = ((EditText) v
4119 .findViewById(R.id.password_edit))
4120 .getText().toString();
4121 BrowserActivity.this.setHttpAuthUsernamePassword
4122 (host, realm, nm, pw);
4123 handler.proceed(nm, pw);
4124 mHttpAuthenticationDialog = null;
4125 mHttpAuthHandler = null;
4126 }})
4127 .setNegativeButton(R.string.cancel,
4128 new DialogInterface.OnClickListener() {
4129 public void onClick(DialogInterface dialog,
4130 int whichButton) {
4131 handler.cancel();
4132 BrowserActivity.this.resetTitleAndRevertLockIcon();
4133 mHttpAuthenticationDialog = null;
4134 mHttpAuthHandler = null;
4135 }})
4136 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4137 public void onCancel(DialogInterface dialog) {
4138 handler.cancel();
4139 BrowserActivity.this.resetTitleAndRevertLockIcon();
4140 mHttpAuthenticationDialog = null;
4141 mHttpAuthHandler = null;
4142 }})
4143 .create();
4144 // Make the IME appear when the dialog is displayed if applicable.
4145 dialog.getWindow().setSoftInputMode(
4146 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4147 dialog.show();
4148 if (focusId != 0) {
4149 dialog.findViewById(focusId).requestFocus();
4150 } else {
4151 v.findViewById(R.id.username_edit).requestFocus();
4152 }
4153 mHttpAuthenticationDialog = dialog;
4154 }
4155
4156 public int getProgress() {
4157 WebView w = mTabControl.getCurrentWebView();
4158 if (w != null) {
4159 return w.getProgress();
4160 } else {
4161 return 100;
4162 }
4163 }
4164
4165 /**
4166 * Set HTTP authentication password.
4167 *
4168 * @param host The host for the password
4169 * @param realm The realm for the password
4170 * @param username The username for the password. If it is null, it means
4171 * password can't be saved.
4172 * @param password The password
4173 */
4174 public void setHttpAuthUsernamePassword(String host, String realm,
4175 String username,
4176 String password) {
4177 WebView w = mTabControl.getCurrentWebView();
4178 if (w != null) {
4179 w.setHttpAuthUsernamePassword(host, realm, username, password);
4180 }
4181 }
4182
4183 /**
4184 * connectivity manager says net has come or gone... inform the user
4185 * @param up true if net has come up, false if net has gone down
4186 */
4187 public void onNetworkToggle(boolean up) {
4188 if (up == mIsNetworkUp) {
4189 return;
4190 } else if (up) {
4191 mIsNetworkUp = true;
4192 if (mAlertDialog != null) {
4193 mAlertDialog.cancel();
4194 mAlertDialog = null;
4195 }
4196 } else {
4197 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004198 if (mInLoad) {
4199 createAndShowNetworkDialog();
4200 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004201 }
4202 WebView w = mTabControl.getCurrentWebView();
4203 if (w != null) {
4204 w.setNetworkAvailable(up);
4205 }
4206 }
4207
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004208 // This method shows the network dialog alerting the user that the net is
4209 // down. It will only show the dialog if mAlertDialog is null.
4210 private void createAndShowNetworkDialog() {
4211 if (mAlertDialog == null) {
4212 mAlertDialog = new AlertDialog.Builder(this)
4213 .setTitle(R.string.loadSuspendedTitle)
4214 .setMessage(R.string.loadSuspended)
4215 .setPositiveButton(R.string.ok, null)
4216 .show();
4217 }
4218 }
4219
The Android Open Source Project0c908882009-03-03 19:32:16 -08004220 @Override
4221 protected void onActivityResult(int requestCode, int resultCode,
4222 Intent intent) {
4223 switch (requestCode) {
4224 case COMBO_PAGE:
4225 if (resultCode == RESULT_OK && intent != null) {
4226 String data = intent.getAction();
4227 Bundle extras = intent.getExtras();
4228 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04004229 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004230 } else {
4231 final TabControl.Tab currentTab =
4232 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04004233 dismissSubWindow(currentTab);
4234 if (data != null && data.length() != 0) {
4235 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004236 }
4237 }
4238 }
4239 break;
4240 default:
4241 break;
4242 }
Leon Scroggins30444232009-09-04 18:36:20 -04004243 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004244 }
4245
4246 /*
4247 * This method is called as a result of the user selecting the options
4248 * menu to see the download window, or when a download changes state. It
4249 * shows the download window ontop of the current window.
4250 */
4251 /* package */ void viewDownloads(Uri downloadRecord) {
4252 Intent intent = new Intent(this,
4253 BrowserDownloadPage.class);
4254 intent.setData(downloadRecord);
4255 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4256
4257 }
4258
Leon Scroggins160a7e72009-08-14 18:28:01 -04004259 /**
4260 * Open the Go page.
4261 * @param startWithHistory If true, open starting on the history tab.
4262 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004263 */
Leon Scroggins30444232009-09-04 18:36:20 -04004264 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004265 WebView current = mTabControl.getCurrentWebView();
4266 if (current == null) {
4267 return;
4268 }
4269 Intent intent = new Intent(this,
4270 CombinedBookmarkHistoryActivity.class);
4271 String title = current.getTitle();
4272 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004273 Bitmap thumbnail = createScreenshot(current);
4274
The Android Open Source Project0c908882009-03-03 19:32:16 -08004275 // Just in case the user opens bookmarks before a page finishes loading
4276 // so the current history item, and therefore the page, is null.
4277 if (null == url) {
4278 url = mLastEnteredUrl;
4279 // This can happen.
4280 if (null == url) {
4281 url = mSettings.getHomePage();
4282 }
4283 }
4284 // In case the web page has not yet received its associated title.
4285 if (title == null) {
4286 title = url;
4287 }
4288 intent.putExtra("title", title);
4289 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004290 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04004291 // Disable opening in a new window if we have maxed out the windows
4292 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4293 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004294 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004295 if (startWithHistory) {
4296 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4297 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4298 }
4299 startActivityForResult(intent, COMBO_PAGE);
4300 }
4301
4302 // Called when loading from context menu or LOAD_URL message
4303 private void loadURL(WebView view, String url) {
4304 // In case the user enters nothing.
4305 if (url != null && url.length() != 0 && view != null) {
4306 url = smartUrlFilter(url);
4307 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4308 view.loadUrl(url);
4309 }
4310 }
4311 }
4312
The Android Open Source Project0c908882009-03-03 19:32:16 -08004313 private String smartUrlFilter(Uri inUri) {
4314 if (inUri != null) {
4315 return smartUrlFilter(inUri.toString());
4316 }
4317 return null;
4318 }
4319
4320
4321 // get window count
4322
4323 int getWindowCount(){
4324 if(mTabControl != null){
4325 return mTabControl.getTabCount();
4326 }
4327 return 0;
4328 }
4329
Feng Qianb34f87a2009-03-24 21:27:26 -07004330 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004331 "(?i)" + // switch on case insensitive matching
4332 "(" + // begin group for schema
4333 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004334 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004335 ")" +
4336 "(.*)" );
4337
4338 /**
4339 * Attempts to determine whether user input is a URL or search
4340 * terms. Anything with a space is passed to search.
4341 *
4342 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4343 * "Http://" converts to "http://"
4344 *
4345 * @return Original or modified URL
4346 *
4347 */
4348 String smartUrlFilter(String url) {
4349
4350 String inUrl = url.trim();
4351 boolean hasSpace = inUrl.indexOf(' ') != -1;
4352
4353 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4354 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004355 // force scheme to lowercase
4356 String scheme = matcher.group(1);
4357 String lcScheme = scheme.toLowerCase();
4358 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004359 inUrl = lcScheme + matcher.group(2);
4360 }
4361 if (hasSpace) {
4362 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004363 }
4364 return inUrl;
4365 }
4366 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004367 // FIXME: Is this the correct place to add to searches?
4368 // what if someone else calls this function?
4369 int shortcut = parseUrlShortcut(inUrl);
4370 if (shortcut != SHORTCUT_INVALID) {
4371 Browser.addSearchUrl(mResolver, inUrl);
4372 String query = inUrl.substring(2);
4373 switch (shortcut) {
4374 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004375 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004376 case SHORTCUT_WIKIPEDIA_SEARCH:
4377 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4378 case SHORTCUT_DICTIONARY_SEARCH:
4379 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4380 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004381 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004382 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004383 }
4384 }
4385 } else {
4386 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4387 return URLUtil.guessUrl(inUrl);
4388 }
4389 }
4390
4391 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004392 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004393 }
4394
Ben Murdochbff2d602009-07-01 20:19:05 +01004395 /* package */ void setShouldShowErrorConsole(boolean flag) {
4396 if (flag == mShouldShowErrorConsole) {
4397 // Nothing to do.
4398 return;
4399 }
4400
4401 mShouldShowErrorConsole = flag;
4402
4403 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4404
4405 if (flag) {
4406 // Setting the show state of the console will cause it's the layout to be inflated.
4407 if (errorConsole.numberOfErrors() > 0) {
4408 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4409 } else {
4410 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4411 }
4412
4413 // Now we can add it to the main view.
4414 mErrorConsoleContainer.addView(errorConsole,
4415 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4416 ViewGroup.LayoutParams.WRAP_CONTENT));
4417 } else {
4418 mErrorConsoleContainer.removeView(errorConsole);
4419 }
4420
4421 }
4422
Grace Klobaeb6eef42009-09-15 17:56:32 -07004423 final static int LOCK_ICON_UNSECURE = 0;
4424 final static int LOCK_ICON_SECURE = 1;
4425 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004426
4427 private int mLockIconType = LOCK_ICON_UNSECURE;
4428 private int mPrevLockType = LOCK_ICON_UNSECURE;
4429
4430 private BrowserSettings mSettings;
4431 private TabControl mTabControl;
4432 private ContentResolver mResolver;
4433 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004434 private View mCustomView;
4435 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004436 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004437
4438 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4439 // view, we should rewrite this.
4440 private int mCurrentMenuState = 0;
4441 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004442 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004443 private static final int EMPTY_MENU = -1;
4444 private Menu mMenu;
4445
4446 private FindDialog mFindDialog;
4447 // Used to prevent chording to result in firing two shortcuts immediately
4448 // one after another. Fixes bug 1211714.
4449 boolean mCanChord;
4450
4451 private boolean mInLoad;
4452 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004453 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004454
4455 private boolean mPageStarted;
4456 private boolean mActivityInPause = true;
4457
4458 private boolean mMenuIsDown;
4459
The Android Open Source Project0c908882009-03-03 19:32:16 -08004460 private static boolean mInTrace;
4461
4462 // Performance probe
4463 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4464 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4465 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4466 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4467 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4468 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4469 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4470 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4471 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4472 };
4473
4474 private long mStart;
4475 private long mProcessStart;
4476 private long mUserStart;
4477 private long mSystemStart;
4478 private long mIdleStart;
4479 private long mIrqStart;
4480
4481 private long mUiStart;
4482
4483 private Drawable mMixLockIcon;
4484 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004485
4486 /* hold a ref so we can auto-cancel if necessary */
4487 private AlertDialog mAlertDialog;
4488
4489 // Wait for credentials before loading google.com
4490 private ProgressDialog mCredsDlg;
4491
4492 // The up-to-date URL and title (these can be different from those stored
4493 // in WebView, since it takes some time for the information in WebView to
4494 // get updated)
4495 private String mUrl;
4496 private String mTitle;
4497
4498 // As PageInfo has different style for landscape / portrait, we have
4499 // to re-open it when configuration changed
4500 private AlertDialog mPageInfoDialog;
4501 private TabControl.Tab mPageInfoView;
4502 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4503 // dialog, we should not just dismiss it, but should get back to the
4504 // SSL-certificate-on-error dialog. This flag is used to store this state
4505 private Boolean mPageInfoFromShowSSLCertificateOnError;
4506
4507 // as SSLCertificateOnError has different style for landscape / portrait,
4508 // we have to re-open it when configuration changed
4509 private AlertDialog mSSLCertificateOnErrorDialog;
4510 private WebView mSSLCertificateOnErrorView;
4511 private SslErrorHandler mSSLCertificateOnErrorHandler;
4512 private SslError mSSLCertificateOnErrorError;
4513
4514 // as SSLCertificate has different style for landscape / portrait, we
4515 // have to re-open it when configuration changed
4516 private AlertDialog mSSLCertificateDialog;
4517 private TabControl.Tab mSSLCertificateView;
4518
4519 // as HttpAuthentication has different style for landscape / portrait, we
4520 // have to re-open it when configuration changed
4521 private AlertDialog mHttpAuthenticationDialog;
4522 private HttpAuthHandler mHttpAuthHandler;
4523
4524 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4525 new FrameLayout.LayoutParams(
4526 ViewGroup.LayoutParams.FILL_PARENT,
4527 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004528 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4529 new FrameLayout.LayoutParams(
4530 ViewGroup.LayoutParams.FILL_PARENT,
4531 ViewGroup.LayoutParams.FILL_PARENT,
4532 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004533 // Google search
4534 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004535 // Wikipedia search
4536 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4537 // Dictionary search
4538 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4539 // Google Mobile Local search
4540 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4541
4542 final static String QUERY_PLACE_HOLDER = "%s";
4543
4544 // "source" parameter for Google search through search key
4545 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4546 // "source" parameter for Google search through goto menu
4547 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4548 // "source" parameter for Google search through simplily type
4549 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4550 // "source" parameter for Google search suggested by the browser
4551 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4552 // "source" parameter for Google search from unknown source
4553 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4554
4555 private final static String LOGTAG = "browser";
4556
The Android Open Source Project0c908882009-03-03 19:32:16 -08004557 private String mLastEnteredUrl;
4558
4559 private PowerManager.WakeLock mWakeLock;
4560 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4561
4562 private Toast mStopToast;
4563
Leon Scroggins68579392009-09-15 15:31:54 -04004564 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004565
Ben Murdochbff2d602009-07-01 20:19:05 +01004566 private LinearLayout mErrorConsoleContainer = null;
4567 private boolean mShouldShowErrorConsole = false;
4568
The Android Open Source Project0c908882009-03-03 19:32:16 -08004569 // As the ids are dynamically created, we can't guarantee that they will
4570 // be in sequence, so this static array maps ids to a window number.
4571 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4572 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4573 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4574 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4575
4576 // monitor platform changes
4577 private IntentFilter mNetworkStateChangedFilter;
4578 private BroadcastReceiver mNetworkStateIntentReceiver;
4579
Grace Klobab4da0ad2009-05-14 14:45:40 -07004580 private BroadcastReceiver mPackageInstallationReceiver;
4581
Patrick Scott59ce8302009-09-18 16:29:38 -04004582 // AsyncTask for downloading touch icons
4583 /* package */ DownloadTouchIcon mTouchIconLoader;
4584
The Android Open Source Project0c908882009-03-03 19:32:16 -08004585 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004586 final static int COMBO_PAGE = 1;
4587 final static int DOWNLOAD_PAGE = 2;
4588 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004589
Andrei Popescu540035d2009-09-18 18:59:20 +01004590 // the default <video> poster
4591 private Bitmap mDefaultVideoPoster;
4592 // the video progress view
4593 private View mVideoProgressView;
4594
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004595 /**
4596 * A UrlData class to abstract how the content will be set to WebView.
4597 * This base class uses loadUrl to show the content.
4598 */
4599 private static class UrlData {
4600 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004601 byte[] mPostData;
4602
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004603 UrlData(String url) {
4604 this.mUrl = url;
4605 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004606
4607 void setPostData(byte[] postData) {
4608 mPostData = postData;
4609 }
4610
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004611 boolean isEmpty() {
4612 return mUrl == null || mUrl.length() == 0;
4613 }
4614
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004615 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004616 if (mPostData != null) {
4617 webView.postUrl(mUrl, mPostData);
4618 } else {
4619 webView.loadUrl(mUrl);
4620 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004621 }
4622 };
4623
4624 /**
4625 * A subclass of UrlData class that can display inlined content using
4626 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4627 */
4628 private static class InlinedUrlData extends UrlData {
4629 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4630 super(failUrl);
4631 mInlined = inlined;
4632 mMimeType = mimeType;
4633 mEncoding = encoding;
4634 }
4635 String mMimeType;
4636 String mInlined;
4637 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004638 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004639 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004640 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004641 }
4642
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004643 @Override
4644 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004645 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4646 }
4647 }
4648
Leon Scroggins1f005d32009-08-10 17:36:42 -04004649 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004650}