blob: 8e70355b670a51149aa5a4f945539cae184196f6 [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;
The Android Open Source Project0c908882009-03-03 19:32:16 -080087import android.util.Log;
88import android.view.ContextMenu;
89import android.view.Gravity;
90import android.view.KeyEvent;
91import android.view.LayoutInflater;
92import android.view.Menu;
93import android.view.MenuInflater;
94import android.view.MenuItem;
95import android.view.View;
96import android.view.ViewGroup;
97import android.view.Window;
98import android.view.WindowManager;
99import android.view.ContextMenu.ContextMenuInfo;
100import android.view.MenuItem.OnMenuItemClickListener;
101import android.view.animation.AlphaAnimation;
102import android.view.animation.Animation;
103import android.view.animation.AnimationSet;
104import android.view.animation.DecelerateInterpolator;
105import android.view.animation.ScaleAnimation;
106import android.view.animation.TranslateAnimation;
107import android.webkit.CookieManager;
108import android.webkit.CookieSyncManager;
109import android.webkit.DownloadListener;
Steve Block2bc69912009-07-30 14:45:13 +0100110import android.webkit.GeolocationPermissions;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800111import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -0700112import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113import android.webkit.SslErrorHandler;
114import android.webkit.URLUtil;
115import android.webkit.WebChromeClient;
Andrei Popescuc9b55562009-07-07 10:51:15 +0100116import android.webkit.WebChromeClient.CustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import android.webkit.WebHistoryItem;
118import android.webkit.WebIconDatabase;
Ben Murdoch092dd5d2009-04-22 12:34:12 +0100119import android.webkit.WebStorage;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import android.webkit.WebView;
121import android.webkit.WebViewClient;
122import android.widget.EditText;
123import android.widget.FrameLayout;
124import android.widget.LinearLayout;
125import android.widget.TextView;
126import android.widget.Toast;
127
128import java.io.BufferedOutputStream;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400129import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130import java.io.File;
131import java.io.FileInputStream;
132import java.io.FileOutputStream;
133import java.io.IOException;
134import java.io.InputStream;
135import java.net.MalformedURLException;
136import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700137import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800138import java.net.URL;
139import java.net.URLEncoder;
140import java.text.ParseException;
141import java.util.Date;
142import java.util.Enumeration;
143import java.util.HashMap;
Patrick Scott37911c72009-03-24 18:02:58 -0700144import java.util.LinkedList;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800145import java.util.Vector;
146import java.util.regex.Matcher;
147import java.util.regex.Pattern;
148import java.util.zip.ZipEntry;
149import java.util.zip.ZipFile;
150
151public class BrowserActivity extends Activity
Grace Kloba5942df02009-09-18 11:48:29 -0700152 implements View.OnCreateContextMenuListener,
The Android Open Source Project0c908882009-03-03 19:32:16 -0800153 DownloadListener {
154
Dave Bort31a6d1c2009-04-13 15:56:49 -0700155 /* Define some aliases to make these debugging flags easier to refer to.
156 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
157 */
158 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
159 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
160 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
161
The Android Open Source Project0c908882009-03-03 19:32:16 -0800162 private IGoogleLoginService mGls = null;
163 private ServiceConnection mGlsConnection = null;
164
165 private SensorManager mSensorManager = null;
166
Satish Sampath565505b2009-05-29 15:37:27 +0100167 // These are single-character shortcuts for searching popular sources.
168 private static final int SHORTCUT_INVALID = 0;
169 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
170 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
171 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
172 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
173
The Android Open Source Project0c908882009-03-03 19:32:16 -0800174 /* Whitelisted webpages
175 private static HashSet<String> sWhiteList;
176
177 static {
178 sWhiteList = new HashSet<String>();
179 sWhiteList.add("cnn.com/");
180 sWhiteList.add("espn.go.com/");
181 sWhiteList.add("nytimes.com/");
182 sWhiteList.add("engadget.com/");
183 sWhiteList.add("yahoo.com/");
184 sWhiteList.add("msn.com/");
185 sWhiteList.add("amazon.com/");
186 sWhiteList.add("consumerist.com/");
187 sWhiteList.add("google.com/m/news");
188 }
189 */
190
191 private void setupHomePage() {
192 final Runnable getAccount = new Runnable() {
193 public void run() {
194 // Lower priority
195 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
196 // get the default home page
197 String homepage = mSettings.getHomePage();
198
199 try {
200 if (mGls == null) return;
201
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700202 if (!homepage.startsWith("http://www.google.")) return;
203 if (homepage.indexOf('?') == -1) return;
204
The Android Open Source Project0c908882009-03-03 19:32:16 -0800205 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
206 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
207
208 // three cases:
209 //
210 // hostedUser == googleUser
211 // The device has only a google account
212 //
213 // hostedUser != googleUser
214 // The device has a hosted account and a google account
215 //
216 // hostedUser != null, googleUser == null
217 // The device has only a hosted account (so far)
218
219 // developers might have no accounts at all
220 if (hostedUser == null) return;
221
222 if (googleUser == null || !hostedUser.equals(googleUser)) {
223 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700224 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800225 }
226 } catch (RemoteException ignore) {
227 // Login service died; carry on
228 } catch (RuntimeException ignore) {
229 // Login service died; carry on
230 } finally {
231 finish(homepage);
232 }
233 }
234
235 private void finish(final String homepage) {
236 mHandler.post(new Runnable() {
237 public void run() {
238 mSettings.setHomePage(BrowserActivity.this, homepage);
239 resumeAfterCredentials();
240
241 // as this is running in a separate thread,
242 // BrowserActivity's onDestroy() may have been called,
243 // which also calls unbindService().
244 if (mGlsConnection != null) {
245 // we no longer need to keep GLS open
246 unbindService(mGlsConnection);
247 mGlsConnection = null;
248 }
249 } });
250 } };
251
252 final boolean[] done = { false };
253
254 // Open a connection to the Google Login Service. The first
255 // time the connection is established, set up the homepage depending on
256 // the account in a background thread.
257 mGlsConnection = new ServiceConnection() {
258 public void onServiceConnected(ComponentName className, IBinder service) {
259 mGls = IGoogleLoginService.Stub.asInterface(service);
260 if (done[0] == false) {
261 done[0] = true;
262 Thread account = new Thread(getAccount);
263 account.setName("GLSAccount");
264 account.start();
265 }
266 }
267 public void onServiceDisconnected(ComponentName className) {
268 mGls = null;
269 }
270 };
271
272 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
273 mGlsConnection, Context.BIND_AUTO_CREATE);
274 }
275
Cary Clarka9771242009-08-11 16:42:26 -0400276 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800277 @Override
278 public Void doInBackground(File... files) {
279 if (files != null) {
280 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400281 if (!f.delete()) {
282 Log.e(LOGTAG, f.getPath() + " was not deleted");
283 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800284 }
285 }
286 return null;
287 }
288 }
289
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400290 /**
291 * This layout holds everything you see below the status bar, including the
292 * error console, the custom view container, and the webviews.
293 */
294 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400295
The Android Open Source Project0c908882009-03-03 19:32:16 -0800296 @Override public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700297 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800298 Log.v(LOGTAG, this + " onStart");
299 }
300 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800301 // test the browser in OpenGL
302 // requestWindowFeature(Window.FEATURE_OPENGL);
303
304 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
305
306 mResolver = getContentResolver();
307
The Android Open Source Project0c908882009-03-03 19:32:16 -0800308 //
309 // start MASF proxy service
310 //
311 //Intent proxyServiceIntent = new Intent();
312 //proxyServiceIntent.setComponent
313 // (new ComponentName(
314 // "com.android.masfproxyservice",
315 // "com.android.masfproxyservice.MasfProxyService"));
316 //startService(proxyServiceIntent, null);
317
318 mSecLockIcon = Resources.getSystem().getDrawable(
319 android.R.drawable.ic_secure);
320 mMixLockIcon = Resources.getSystem().getDrawable(
321 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800322
Leon Scroggins81db3662009-06-04 17:45:11 -0400323 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
324 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400325 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
326 .inflate(R.layout.custom_screen, null);
327 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
328 R.id.main_content);
329 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
330 .findViewById(R.id.error_console);
331 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
332 .findViewById(R.id.fullscreen_custom_content);
333 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400334 mTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800335
336 // Create the tab control and our initial tab
337 mTabControl = new TabControl(this);
338
339 // Open the icon database and retain all the bookmark urls for favicons
340 retainIconsOnStartup();
341
342 // Keep a settings instance handy.
343 mSettings = BrowserSettings.getInstance();
344 mSettings.setTabControl(mTabControl);
345 mSettings.loadFromDb(this);
346
347 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
348 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
349
Grace Klobaa34f6862009-07-31 16:28:17 -0700350 /* enables registration for changes in network status from
351 http stack */
352 mNetworkStateChangedFilter = new IntentFilter();
353 mNetworkStateChangedFilter.addAction(
354 ConnectivityManager.CONNECTIVITY_ACTION);
355 mNetworkStateIntentReceiver = new BroadcastReceiver() {
356 @Override
357 public void onReceive(Context context, Intent intent) {
358 if (intent.getAction().equals(
359 ConnectivityManager.CONNECTIVITY_ACTION)) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -0400360 NetworkInfo info =
361 (NetworkInfo) intent.getParcelableExtra(
362 ConnectivityManager.EXTRA_NETWORK_INFO);
363 onNetworkToggle(
364 (info != null) ? info.isConnected() : false);
Grace Klobaa34f6862009-07-31 16:28:17 -0700365 }
366 }
367 };
368
Grace Kloba615c6c92009-08-03 10:22:44 -0700369 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
370 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
371 filter.addDataScheme("package");
372 mPackageInstallationReceiver = new BroadcastReceiver() {
373 @Override
374 public void onReceive(Context context, Intent intent) {
375 final String action = intent.getAction();
376 final String packageName = intent.getData()
377 .getSchemeSpecificPart();
378 final boolean replacing = intent.getBooleanExtra(
379 Intent.EXTRA_REPLACING, false);
380 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
381 // if it is replacing, refreshPlugins() when adding
382 return;
383 }
384 PackageManager pm = BrowserActivity.this.getPackageManager();
385 PackageInfo pkgInfo = null;
386 try {
387 pkgInfo = pm.getPackageInfo(packageName,
388 PackageManager.GET_PERMISSIONS);
389 } catch (PackageManager.NameNotFoundException e) {
390 return;
391 }
392 if (pkgInfo != null) {
393 String permissions[] = pkgInfo.requestedPermissions;
394 if (permissions == null) {
395 return;
396 }
397 boolean permissionOk = false;
398 for (String permit : permissions) {
399 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
400 permissionOk = true;
401 break;
402 }
403 }
404 if (permissionOk) {
405 PluginManager.getInstance(BrowserActivity.this)
406 .refreshPlugins(
407 Intent.ACTION_PACKAGE_ADDED
408 .equals(action));
409 }
410 }
411 }
412 };
413 registerReceiver(mPackageInstallationReceiver, filter);
414
Satish Sampath565505b2009-05-29 15:37:27 +0100415 // If this was a web search request, pass it on to the default web search provider.
416 if (handleWebSearchIntent(getIntent())) {
417 moveTaskToBack(true);
418 return;
419 }
420
The Android Open Source Project0c908882009-03-03 19:32:16 -0800421 if (!mTabControl.restoreState(icicle)) {
422 // clear up the thumbnail directory if we can't restore the state as
423 // none of the files in the directory are referenced any more.
424 new ClearThumbnails().execute(
425 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700426 // there is no quit on Android. But if we can't restore the state,
427 // we can treat it as a new Browser, remove the old session cookies.
428 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800429 final Intent intent = getIntent();
430 final Bundle extra = intent.getExtras();
431 // Create an initial tab.
432 // If the intent is ACTION_VIEW and data is not null, the Browser is
433 // invoked to view the content by another application. In this case,
434 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700435 UrlData urlData = getUrlDataFromIntent(intent);
436
The Android Open Source Project0c908882009-03-03 19:32:16 -0800437 final TabControl.Tab t = mTabControl.createNewTab(
438 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700439 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700440 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800441 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800442 attachTabToContentView(t);
443 WebView webView = t.getWebView();
444 if (extra != null) {
445 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
446 if (scale > 0 && scale <= 1000) {
447 webView.setInitialScale(scale);
448 }
449 }
450 // If we are not restoring from an icicle, then there is a high
451 // likely hood this is the first run. So, check to see if the
452 // homepage needs to be configured and copy any plugins from our
453 // asset directory to the data partition.
454 if ((extra == null || !extra.getBoolean("testing"))
455 && !mSettings.isLoginInitialized()) {
456 setupHomePage();
457 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800458
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700459 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400460 if (mSettings.isLoginInitialized()) {
461 webView.loadUrl(mSettings.getHomePage());
462 } else {
463 waitForCredentials();
464 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800465 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700466 if (extra != null) {
467 urlData.setPostData(extra
468 .getByteArray(Browser.EXTRA_POST_DATA));
469 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700470 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800471 }
472 } else {
473 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400474 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800475 attachTabToContentView(mTabControl.getCurrentTab());
476 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700477
Feng Qianb3c02da2009-06-29 15:58:08 -0700478 // Read JavaScript flags if it exists.
479 String jsFlags = mSettings.getJsFlags();
480 if (jsFlags.trim().length() != 0) {
481 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
482 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800483 }
484
485 @Override
486 protected void onNewIntent(Intent intent) {
487 TabControl.Tab current = mTabControl.getCurrentTab();
488 // When a tab is closed on exit, the current tab index is set to -1.
489 // Reset before proceed as Browser requires the current tab to be set.
490 if (current == null) {
491 // Try to reset the tab in case the index was incorrect.
492 current = mTabControl.getTab(0);
493 if (current == null) {
494 // No tabs at all so just ignore this intent.
495 return;
496 }
497 mTabControl.setCurrentTab(current);
498 attachTabToContentView(current);
499 resetTitleAndIcon(current.getWebView());
500 }
501 final String action = intent.getAction();
502 final int flags = intent.getFlags();
503 if (Intent.ACTION_MAIN.equals(action) ||
504 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
505 // just resume the browser
506 return;
507 }
508 if (Intent.ACTION_VIEW.equals(action)
509 || Intent.ACTION_SEARCH.equals(action)
510 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
511 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100512 // If this was a search request (e.g. search query directly typed into the address bar),
513 // pass it on to the default web search provider.
514 if (handleWebSearchIntent(intent)) {
515 return;
516 }
517
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700518 UrlData urlData = getUrlDataFromIntent(intent);
519 if (urlData.isEmpty()) {
520 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800521 }
Grace Kloba81678d92009-06-30 07:09:56 -0700522 urlData.setPostData(intent
523 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700524
Grace Klobacc634032009-07-28 15:58:19 -0700525 final String appId = intent
526 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
527 if (Intent.ACTION_VIEW.equals(action)
528 && !getPackageName().equals(appId)
529 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Patrick Scottcd115892009-07-16 09:42:58 -0400530 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700531 if (appTab != null) {
532 Log.i(LOGTAG, "Reusing tab for " + appId);
533 // Dismiss the subwindow if applicable.
534 dismissSubWindow(appTab);
535 // Since we might kill the WebView, remove it from the
536 // content view first.
537 removeTabFromContentView(appTab);
538 // Recreate the main WebView after destroying the old one.
539 // If the WebView has the same original url and is on that
540 // page, it can be reused.
541 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700542 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100543
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700544 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400545 switchToTab(mTabControl.getTabIndex(appTab));
546 if (needsLoad) {
547 urlData.loadIn(appTab.getWebView());
548 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700549 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400550 // If the tab was the current tab, we have to attach
551 // it to the view system again.
552 attachTabToContentView(appTab);
553 if (needsLoad) {
554 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700555 }
556 }
557 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400558 } else {
559 // No matching application tab, try to find a regular tab
560 // with a matching url.
561 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400562 if (appTab != null) {
563 if (current != appTab) {
564 switchToTab(mTabControl.getTabIndex(appTab));
565 }
566 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400567 } else {
568 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
569 // will be opened in a new tab unless we have reached
570 // MAX_TABS. Then the url will be opened in the current
571 // tab. If a new tab is created, it will have "true" for
572 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400573 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400574 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700575 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800576 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700577 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800578 mSettings.toggleDebugSettings();
579 return;
580 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400581 // Get rid of the subwindow if it exists
582 dismissSubWindow(current);
583 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800584 }
585 }
586 }
587
Satish Sampath565505b2009-05-29 15:37:27 +0100588 private int parseUrlShortcut(String url) {
589 if (url == null) return SHORTCUT_INVALID;
590
591 // FIXME: quick search, need to be customized by setting
592 if (url.length() > 2 && url.charAt(1) == ' ') {
593 switch (url.charAt(0)) {
594 case 'g': return SHORTCUT_GOOGLE_SEARCH;
595 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
596 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
597 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
598 }
599 }
600 return SHORTCUT_INVALID;
601 }
602
603 /**
604 * Launches the default web search activity with the query parameters if the given intent's data
605 * are identified as plain search terms and not URLs/shortcuts.
606 * @return true if the intent was handled and web search activity was launched, false if not.
607 */
608 private boolean handleWebSearchIntent(Intent intent) {
609 if (intent == null) return false;
610
611 String url = null;
612 final String action = intent.getAction();
613 if (Intent.ACTION_VIEW.equals(action)) {
614 url = intent.getData().toString();
615 } else if (Intent.ACTION_SEARCH.equals(action)
616 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
617 || Intent.ACTION_WEB_SEARCH.equals(action)) {
618 url = intent.getStringExtra(SearchManager.QUERY);
619 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100620 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
621 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100622 }
623
624 /**
625 * Launches the default web search activity with the query parameters if the given url string
626 * was identified as plain search terms and not URL/shortcut.
627 * @return true if the request was handled and web search activity was launched, false if not.
628 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100629 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100630 if (inUrl == null) return false;
631
632 // In general, we shouldn't modify URL from Intent.
633 // But currently, we get the user-typed URL from search box as well.
634 String url = fixUrl(inUrl).trim();
635
636 // URLs and site specific search shortcuts are handled by the regular flow of control, so
637 // return early.
638 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100639 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100640 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
641 return false;
642 }
643
644 Browser.updateVisitedHistory(mResolver, url, false);
645 Browser.addSearchUrl(mResolver, url);
646
647 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
648 intent.addCategory(Intent.CATEGORY_DEFAULT);
649 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100650 if (appData != null) {
651 intent.putExtra(SearchManager.APP_DATA, appData);
652 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100653 if (extraData != null) {
654 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
655 }
Grace Klobacc634032009-07-28 15:58:19 -0700656 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100657 startActivity(intent);
658
659 return true;
660 }
661
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700662 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800663 String url = null;
664 if (intent != null) {
665 final String action = intent.getAction();
666 if (Intent.ACTION_VIEW.equals(action)) {
667 url = smartUrlFilter(intent.getData());
668 if (url != null && url.startsWith("content:")) {
669 /* Append mimetype so webview knows how to display */
670 String mimeType = intent.resolveType(getContentResolver());
671 if (mimeType != null) {
672 url += "?" + mimeType;
673 }
674 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700675 if ("inline:".equals(url)) {
676 return new InlinedUrlData(
677 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
678 intent.getType(),
679 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
680 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
681 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800682 } else if (Intent.ACTION_SEARCH.equals(action)
683 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
684 || Intent.ACTION_WEB_SEARCH.equals(action)) {
685 url = intent.getStringExtra(SearchManager.QUERY);
686 if (url != null) {
687 mLastEnteredUrl = url;
688 // Don't add Urls, just search terms.
689 // Urls will get added when the page is loaded.
690 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
691 Browser.updateVisitedHistory(mResolver, url, false);
692 }
693 // In general, we shouldn't modify URL from Intent.
694 // But currently, we get the user-typed URL from search box as well.
695 url = fixUrl(url);
696 url = smartUrlFilter(url);
697 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
698 if (url.contains(searchSource)) {
699 String source = null;
700 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
701 if (appData != null) {
702 source = appData.getString(SearchManager.SOURCE);
703 }
704 if (TextUtils.isEmpty(source)) {
705 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
706 }
707 url = url.replace(searchSource, "&source=android-"+source+"&");
708 }
709 }
710 }
711 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700712 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800713 }
714
715 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400716 // FIXME: Converting the url to lower case
717 // duplicates functionality in smartUrlFilter().
718 // However, changing all current callers of fixUrl to
719 // call smartUrlFilter in addition may have unwanted
720 // consequences, and is deferred for now.
721 int colon = inUrl.indexOf(':');
722 boolean allLower = true;
723 for (int index = 0; index < colon; index++) {
724 char ch = inUrl.charAt(index);
725 if (!Character.isLetter(ch)) {
726 break;
727 }
728 allLower &= Character.isLowerCase(ch);
729 if (index == colon - 1 && !allLower) {
730 inUrl = inUrl.substring(0, colon).toLowerCase()
731 + inUrl.substring(colon);
732 }
733 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800734 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
735 return inUrl;
736 if (inUrl.startsWith("http:") ||
737 inUrl.startsWith("https:")) {
738 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
739 inUrl = inUrl.replaceFirst("/", "//");
740 } else inUrl = inUrl.replaceFirst(":", "://");
741 }
742 return inUrl;
743 }
744
745 /**
746 * Looking for the pattern like this
747 *
748 * *
749 * * *
750 * *** * *******
751 * * *
752 * * *
753 * *
754 */
755 private final SensorListener mSensorListener = new SensorListener() {
756 private long mLastGestureTime;
757 private float[] mPrev = new float[3];
758 private float[] mPrevDiff = new float[3];
759 private float[] mDiff = new float[3];
760 private float[] mRevertDiff = new float[3];
761
762 public void onSensorChanged(int sensor, float[] values) {
763 boolean show = false;
764 float[] diff = new float[3];
765
766 for (int i = 0; i < 3; i++) {
767 diff[i] = values[i] - mPrev[i];
768 if (Math.abs(diff[i]) > 1) {
769 show = true;
770 }
771 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
772 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
773 // start track when there is a big move, or revert
774 mRevertDiff[i] = mDiff[i];
775 mDiff[i] = 0;
776 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
777 // reset when it is flat
778 mDiff[i] = mRevertDiff[i] = 0;
779 }
780 mDiff[i] += diff[i];
781 mPrevDiff[i] = diff[i];
782 mPrev[i] = values[i];
783 }
784
785 if (false) {
786 // only shows if we think the delta is big enough, in an attempt
787 // to detect "serious" moves left/right or up/down
788 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
789 + values[0] + ", " + values[1] + ", " + values[2] + ")"
790 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
791 + ")");
792 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
793 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
794 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
795 + mRevertDiff[2] + ")");
796 }
797
798 long now = android.os.SystemClock.uptimeMillis();
799 if (now - mLastGestureTime > 1000) {
800 mLastGestureTime = 0;
801
802 float y = mDiff[1];
803 float z = mDiff[2];
804 float ay = Math.abs(y);
805 float az = Math.abs(z);
806 float ry = mRevertDiff[1];
807 float rz = mRevertDiff[2];
808 float ary = Math.abs(ry);
809 float arz = Math.abs(rz);
810 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
811 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
812
813 if ((gestY || gestZ) && !(gestY && gestZ)) {
814 WebView view = mTabControl.getCurrentWebView();
815
816 if (view != null) {
817 if (gestZ) {
818 if (z < 0) {
819 view.zoomOut();
820 } else {
821 view.zoomIn();
822 }
823 } else {
824 view.flingScroll(0, Math.round(y * 100));
825 }
826 }
827 mLastGestureTime = now;
828 }
829 }
830 }
831
832 public void onAccuracyChanged(int sensor, int accuracy) {
833 // TODO Auto-generated method stub
834
835 }
836 };
837
838 @Override protected void onResume() {
839 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700840 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800841 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
842 }
843
844 if (!mActivityInPause) {
845 Log.e(LOGTAG, "BrowserActivity is already resumed.");
846 return;
847 }
848
Mike Reed7bfa63b2009-05-28 11:08:32 -0400849 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800850 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400851 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800852
853 if (mWakeLock.isHeld()) {
854 mHandler.removeMessages(RELEASE_WAKELOCK);
855 mWakeLock.release();
856 }
857
858 if (mCredsDlg != null) {
859 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
860 // In case credential request never comes back
861 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
862 }
863 }
864
865 registerReceiver(mNetworkStateIntentReceiver,
866 mNetworkStateChangedFilter);
867 WebView.enablePlatformNotifications();
868
869 if (mSettings.doFlick()) {
870 if (mSensorManager == null) {
871 mSensorManager = (SensorManager) getSystemService(
872 Context.SENSOR_SERVICE);
873 }
874 mSensorManager.registerListener(mSensorListener,
875 SensorManager.SENSOR_ACCELEROMETER,
876 SensorManager.SENSOR_DELAY_FASTEST);
877 } else {
878 mSensorManager = null;
879 }
880 }
881
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400882 /**
883 * Since the actual title bar is embedded in the WebView, and removing it
884 * would change its appearance, create a temporary title bar to go at
885 * the top of the screen while the menu is open.
886 */
887 private TitleBar mFakeTitleBar;
888
889 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400890 * Holder for the fake title bar. It will have a foreground shadow, as well
891 * as a white background, so the fake title bar looks like the real one.
892 */
893 private ViewGroup mFakeTitleBarHolder;
894
895 /**
896 * Layout parameters for the fake title bar within mFakeTitleBarHolder
897 */
898 private FrameLayout.LayoutParams mFakeTitleBarParams
899 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400900 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400901 ViewGroup.LayoutParams.WRAP_CONTENT);
902 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400903 * Keeps track of whether the options menu is open. This is important in
904 * determining whether to show or hide the title bar overlay.
905 */
906 private boolean mOptionsMenuOpen;
907
908 /**
909 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
910 * of whether the configuration has changed. The first onMenuOpened call
911 * after a configuration change is simply a reopening of the same menu
912 * (i.e. mIconView did not change).
913 */
914 private boolean mConfigChanged;
915
916 /**
917 * Whether or not the options menu is in its smaller, icon menu form. When
918 * true, we want the title bar overlay to be up. When false, we do not.
919 * Only meaningful if mOptionsMenuOpen is true.
920 */
921 private boolean mIconView;
922
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400923 @Override
924 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400925 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
926 if (mOptionsMenuOpen) {
927 if (mConfigChanged) {
928 // We do not need to make any changes to the state of the
929 // title bar, since the only thing that happened was a
930 // change in orientation
931 mConfigChanged = false;
932 } else {
933 if (mIconView) {
934 // Switching the menu to expanded view, so hide the
935 // title bar.
936 hideFakeTitleBar();
937 mIconView = false;
938 } else {
939 // Switching the menu back to icon view, so show the
940 // title bar once again.
941 showFakeTitleBar();
942 mIconView = true;
943 }
944 }
945 } else {
946 // The options menu is closed, so open it, and show the title
947 showFakeTitleBar();
948 mOptionsMenuOpen = true;
949 mConfigChanged = false;
950 mIconView = true;
951 }
952 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400953 return true;
954 }
955
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400956 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400957 final View decor = getWindow().peekDecorView();
Leon Scroggins4d7e4062009-09-15 15:49:45 -0400958 if (mFakeTitleBar == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400959 && !mActivityInPause && decor != null
960 && decor.getWindowToken() != null) {
Leon Scrogginsf4bb18a2009-09-11 18:37:53 -0400961 final WebView webView = getTopWindow();
Leon Scroggins68579392009-09-15 15:31:54 -0400962 mFakeTitleBar = new TitleBar(this);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400963 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
964 mFakeTitleBar.setProgress(webView.getProgress());
965 mFakeTitleBar.setFavicon(webView.getFavicon());
966 updateLockIconToLatest();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400967
968 WindowManager manager
969 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
970
971 // Add the title bar to the window manager so it can receive touches
972 // while the menu is up
973 WindowManager.LayoutParams params
974 = new WindowManager.LayoutParams(
975 ViewGroup.LayoutParams.FILL_PARENT,
976 ViewGroup.LayoutParams.WRAP_CONTENT,
977 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
978 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400979 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400980 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400981 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400982 boolean atTop = mainView != null && mainView.getScrollY() == 0;
983 params.windowAnimations = atTop ? 0
984 : com.android.internal.R.style.Animation_DropDownDown;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400985 // XXX : Without providing an offset, the fake title bar will be
986 // placed underneath the status bar. Use the global visible rect
987 // of mBrowserFrameLayout to determine the bottom of the status bar
988 Rect rectangle = new Rect();
989 mBrowserFrameLayout.getGlobalVisibleRect(rectangle);
990 params.y = rectangle.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400991 // Add a holder for the title bar. It also holds a shadow to show
992 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400993 if (mFakeTitleBarHolder == null) {
994 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
995 .inflate(R.layout.title_bar_bg, null);
996 }
Leon Scroggins68549862009-09-21 16:02:01 -0400997 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400998 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400999 }
1000 }
1001
1002 @Override
1003 public void onOptionsMenuClosed(Menu menu) {
1004 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04001005 if (!mInLoad) {
1006 hideFakeTitleBar();
1007 } else if (!mIconView) {
1008 // The page is currently loading, and we are in expanded mode, so
1009 // we were not showing the menu. Show it once again. It will be
1010 // removed when the page finishes.
1011 showFakeTitleBar();
1012 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001013 }
1014 private void hideFakeTitleBar() {
1015 if (mFakeTitleBar == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -04001016 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
1017 mFakeTitleBarHolder.getLayoutParams();
1018 WebView mainView = mTabControl.getCurrentWebView();
1019 // Although we decided whether or not to animate based on the current
1020 // scroll position, the scroll position may have changed since the
1021 // fake title bar was displayed. Make sure it has the appropriate
1022 // animation/lack thereof before removing.
1023 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
1024 ? 0 : com.android.internal.R.style.Animation_DropDownDown;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001025 WindowManager manager
1026 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -04001027 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001028 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1029 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001030 mFakeTitleBar = null;
1031 }
1032
The Android Open Source Project0c908882009-03-03 19:32:16 -08001033 /**
1034 * onSaveInstanceState(Bundle map)
1035 * onSaveInstanceState is called right before onStop(). The map contains
1036 * the saved state.
1037 */
1038 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001039 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001040 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1041 }
1042 // the default implementation requires each view to have an id. As the
1043 // browser handles the state itself and it doesn't use id for the views,
1044 // don't call the default implementation. Otherwise it will trigger the
1045 // warning like this, "couldn't save which view has focus because the
1046 // focused view XXX has no id".
1047
1048 // Save all the tabs
1049 mTabControl.saveState(outState);
1050 }
1051
1052 @Override protected void onPause() {
1053 super.onPause();
1054
1055 if (mActivityInPause) {
1056 Log.e(LOGTAG, "BrowserActivity is already paused.");
1057 return;
1058 }
1059
Mike Reed7bfa63b2009-05-28 11:08:32 -04001060 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001061 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001062 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001063 mWakeLock.acquire();
1064 mHandler.sendMessageDelayed(mHandler
1065 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1066 }
1067
1068 // Clear the credentials toast if it is up
1069 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1070 mCredsDlg.dismiss();
1071 }
1072 mCredsDlg = null;
1073
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001074 // FIXME: This removes the active tabs page and resets the menu to
1075 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1076 // but then we would need to save it in onSaveInstanceState and restore
1077 // it in onCreate/onRestoreInstanceState
1078 if (mActiveTabsPage != null) {
1079 removeActiveTabPage(true);
1080 }
1081
The Android Open Source Project0c908882009-03-03 19:32:16 -08001082 cancelStopToast();
1083
1084 // unregister network state listener
1085 unregisterReceiver(mNetworkStateIntentReceiver);
1086 WebView.disablePlatformNotifications();
1087
1088 if (mSensorManager != null) {
1089 mSensorManager.unregisterListener(mSensorListener);
1090 }
1091 }
1092
1093 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001094 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001095 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1096 }
1097 super.onDestroy();
1098 // Remove the current tab and sub window
1099 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001100 if (t != null) {
1101 dismissSubWindow(t);
1102 removeTabFromContentView(t);
1103 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001104 // Destroy all the tabs
1105 mTabControl.destroy();
1106 WebIconDatabase.getInstance().close();
1107 if (mGlsConnection != null) {
1108 unbindService(mGlsConnection);
1109 mGlsConnection = null;
1110 }
1111
1112 //
1113 // stop MASF proxy service
1114 //
1115 //Intent proxyServiceIntent = new Intent();
1116 //proxyServiceIntent.setComponent
1117 // (new ComponentName(
1118 // "com.android.masfproxyservice",
1119 // "com.android.masfproxyservice.MasfProxyService"));
1120 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001121
1122 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001123 }
1124
1125 @Override
1126 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001127 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001128 super.onConfigurationChanged(newConfig);
1129
1130 if (mPageInfoDialog != null) {
1131 mPageInfoDialog.dismiss();
1132 showPageInfo(
1133 mPageInfoView,
1134 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1135 }
1136 if (mSSLCertificateDialog != null) {
1137 mSSLCertificateDialog.dismiss();
1138 showSSLCertificate(
1139 mSSLCertificateView);
1140 }
1141 if (mSSLCertificateOnErrorDialog != null) {
1142 mSSLCertificateOnErrorDialog.dismiss();
1143 showSSLCertificateOnError(
1144 mSSLCertificateOnErrorView,
1145 mSSLCertificateOnErrorHandler,
1146 mSSLCertificateOnErrorError);
1147 }
1148 if (mHttpAuthenticationDialog != null) {
1149 String title = ((TextView) mHttpAuthenticationDialog
1150 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1151 .toString();
1152 String name = ((TextView) mHttpAuthenticationDialog
1153 .findViewById(R.id.username_edit)).getText().toString();
1154 String password = ((TextView) mHttpAuthenticationDialog
1155 .findViewById(R.id.password_edit)).getText().toString();
1156 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1157 .getId();
1158 mHttpAuthenticationDialog.dismiss();
1159 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1160 name, password, focusId);
1161 }
1162 if (mFindDialog != null && mFindDialog.isShowing()) {
1163 mFindDialog.onConfigurationChanged(newConfig);
1164 }
1165 }
1166
1167 @Override public void onLowMemory() {
1168 super.onLowMemory();
1169 mTabControl.freeMemory();
1170 }
1171
Mike Reed7bfa63b2009-05-28 11:08:32 -04001172 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001173 if ((!mActivityInPause && !mPageStarted) ||
1174 (mActivityInPause && mPageStarted)) {
1175 CookieSyncManager.getInstance().startSync();
1176 WebView w = mTabControl.getCurrentWebView();
1177 if (w != null) {
1178 w.resumeTimers();
1179 }
1180 return true;
1181 } else {
1182 return false;
1183 }
1184 }
1185
Mike Reed7bfa63b2009-05-28 11:08:32 -04001186 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001187 if (mActivityInPause && !mPageStarted) {
1188 CookieSyncManager.getInstance().stopSync();
1189 WebView w = mTabControl.getCurrentWebView();
1190 if (w != null) {
1191 w.pauseTimers();
1192 }
1193 return true;
1194 } else {
1195 return false;
1196 }
1197 }
1198
Leon Scroggins1f005d32009-08-10 17:36:42 -04001199 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001200 /*
1201 * This function is called when we are launching for the first time. We
1202 * are waiting for the login credentials before loading Google home
1203 * pages. This way the user will be logged in straight away.
1204 */
1205 private void waitForCredentials() {
1206 // Show a toast
1207 mCredsDlg = new ProgressDialog(this);
1208 mCredsDlg.setIndeterminate(true);
1209 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1210 // If the user cancels the operation, then cancel the Google
1211 // Credentials request.
1212 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1213 mCredsDlg.show();
1214
1215 // We set a timeout for the retrieval of credentials in onResume()
1216 // as that is when we have freed up some CPU time to get
1217 // the login credentials.
1218 }
1219
1220 /*
1221 * If we have received the credentials or we have timed out and we are
1222 * showing the credentials dialog, then it is time to move on.
1223 */
1224 private void resumeAfterCredentials() {
1225 if (mCredsDlg == null) {
1226 return;
1227 }
1228
1229 // Clear the toast
1230 if (mCredsDlg.isShowing()) {
1231 mCredsDlg.dismiss();
1232 }
1233 mCredsDlg = null;
1234
1235 // Clear any pending timeout
1236 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1237
1238 // Load the page
1239 WebView w = mTabControl.getCurrentWebView();
1240 if (w != null) {
1241 w.loadUrl(mSettings.getHomePage());
1242 }
1243
1244 // Update the settings, need to do this last as it can take a moment
1245 // to persist the settings. In the mean time we could be loading
1246 // content.
1247 mSettings.setLoginInitialized(this);
1248 }
1249
1250 // Open the icon database and retain all the icons for visited sites.
1251 private void retainIconsOnStartup() {
1252 final WebIconDatabase db = WebIconDatabase.getInstance();
1253 db.open(getDir("icons", 0).getPath());
1254 try {
1255 Cursor c = Browser.getAllBookmarks(mResolver);
1256 if (!c.moveToFirst()) {
1257 c.deactivate();
1258 return;
1259 }
1260 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1261 do {
1262 String url = c.getString(urlIndex);
1263 db.retainIconForPageUrl(url);
1264 } while (c.moveToNext());
1265 c.deactivate();
1266 } catch (IllegalStateException e) {
1267 Log.e(LOGTAG, "retainIconsOnStartup", e);
1268 }
1269 }
1270
1271 // Helper method for getting the top window.
1272 WebView getTopWindow() {
1273 return mTabControl.getCurrentTopWebView();
1274 }
1275
1276 @Override
1277 public boolean onCreateOptionsMenu(Menu menu) {
1278 super.onCreateOptionsMenu(menu);
1279
1280 MenuInflater inflater = getMenuInflater();
1281 inflater.inflate(R.menu.browser, menu);
1282 mMenu = menu;
1283 updateInLoadMenuItems();
1284 return true;
1285 }
1286
1287 /**
1288 * As the menu can be open when loading state changes
1289 * we must manually update the state of the stop/reload menu
1290 * item
1291 */
1292 private void updateInLoadMenuItems() {
1293 if (mMenu == null) {
1294 return;
1295 }
1296 MenuItem src = mInLoad ?
1297 mMenu.findItem(R.id.stop_menu_id):
1298 mMenu.findItem(R.id.reload_menu_id);
1299 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1300 dest.setIcon(src.getIcon());
1301 dest.setTitle(src.getTitle());
1302 }
1303
1304 @Override
1305 public boolean onContextItemSelected(MenuItem item) {
1306 // chording is not an issue with context menus, but we use the same
1307 // options selector, so set mCanChord to true so we can access them.
1308 mCanChord = true;
1309 int id = item.getItemId();
1310 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001311 if (null == webView) {
1312 return false;
1313 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001314 final HashMap hrefMap = new HashMap();
1315 hrefMap.put("webview", webView);
1316 final Message msg = mHandler.obtainMessage(
1317 FOCUS_NODE_HREF, id, 0, hrefMap);
1318 switch (id) {
1319 // -- Browser context menu
1320 case R.id.open_context_menu_id:
1321 case R.id.open_newtab_context_menu_id:
1322 case R.id.bookmark_context_menu_id:
1323 case R.id.save_link_context_menu_id:
1324 case R.id.share_link_context_menu_id:
1325 case R.id.copy_link_context_menu_id:
1326 webView.requestFocusNodeHref(msg);
1327 break;
1328
1329 default:
1330 // For other context menus
1331 return onOptionsItemSelected(item);
1332 }
1333 mCanChord = false;
1334 return true;
1335 }
1336
1337 private Bundle createGoogleSearchSourceBundle(String source) {
1338 Bundle bundle = new Bundle();
1339 bundle.putString(SearchManager.SOURCE, source);
1340 return bundle;
1341 }
1342
1343 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001344 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001345 */
1346 @Override
1347 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001348 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001349 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001350 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001351 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001352 return true;
1353 }
1354
1355 @Override
1356 public void startSearch(String initialQuery, boolean selectInitialQuery,
1357 Bundle appSearchData, boolean globalSearch) {
1358 if (appSearchData == null) {
1359 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1360 }
1361 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1362 }
1363
Leon Scroggins1f005d32009-08-10 17:36:42 -04001364 /**
1365 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1366 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001367 * @param index Index of the tab to change to, as defined by
1368 * mTabControl.getTabIndex(Tab t).
1369 * @return boolean True if we successfully switched to a different tab. If
1370 * the indexth tab is null, or if that tab is the same as
1371 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001372 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001373 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001374 TabControl.Tab tab = mTabControl.getTab(index);
1375 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1376 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001377 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001378 }
1379 if (currentTab != null) {
1380 // currentTab may be null if it was just removed. In that case,
1381 // we do not need to remove it
1382 removeTabFromContentView(currentTab);
1383 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001384 mTabControl.setCurrentTab(tab);
1385 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001386 resetTitleIconAndProgress();
1387 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001388 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001389 }
1390
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001391 /* package */ TabControl.Tab openTabToHomePage() {
1392 return openTabAndShow(mSettings.getHomePage(), false, null);
1393 }
1394
Leon Scroggins1f005d32009-08-10 17:36:42 -04001395 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001396 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001397 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001398 // This is the last tab. Open a new one, with the home
1399 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001400 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001401 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001402 return;
1403 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001404 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001405 int indexToShow = -1;
1406 if (parent != null) {
1407 indexToShow = mTabControl.getTabIndex(parent);
1408 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001409 final int currentIndex = mTabControl.getCurrentIndex();
1410 // Try to move to the tab to the right
1411 indexToShow = currentIndex + 1;
1412 if (indexToShow > mTabControl.getTabCount() - 1) {
1413 // Try to move to the tab to the left
1414 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001415 }
1416 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001417 if (switchToTab(indexToShow)) {
1418 // Close window
1419 closeTab(current);
1420 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001421 }
1422
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001423 private ActiveTabsPage mActiveTabsPage;
1424
1425 /**
1426 * Remove the active tabs page.
1427 * @param needToAttach If true, the active tabs page did not attach a tab
1428 * to the content view, so we need to do that here.
1429 */
1430 /* package */ void removeActiveTabPage(boolean needToAttach) {
1431 mContentView.removeView(mActiveTabsPage);
1432 mActiveTabsPage = null;
1433 mMenuState = R.id.MAIN_MENU;
1434 if (needToAttach) {
1435 attachTabToContentView(mTabControl.getCurrentTab());
1436 }
1437 getTopWindow().requestFocus();
1438 }
1439
The Android Open Source Project0c908882009-03-03 19:32:16 -08001440 @Override
1441 public boolean onOptionsItemSelected(MenuItem item) {
1442 if (!mCanChord) {
1443 // The user has already fired a shortcut with this hold down of the
1444 // menu key.
1445 return false;
1446 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001447 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001448 return false;
1449 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001450 if (mMenuIsDown) {
1451 // The shortcut action consumes the MENU. Even if it is still down,
1452 // it won't trigger the next shortcut action. In the case of the
1453 // shortcut action triggering a new activity, like Bookmarks, we
1454 // won't get onKeyUp for MENU. So it is important to reset it here.
1455 mMenuIsDown = false;
1456 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001457 switch (item.getItemId()) {
1458 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001459 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001460 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001461 break;
1462
Leon Scroggins64b80f32009-08-07 12:03:34 -04001463 case R.id.goto_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001464 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001465 break;
1466
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001467 case R.id.active_tabs_menu_id:
1468 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1469 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001470 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001471 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1472 mActiveTabsPage.requestFocus();
1473 mMenuState = EMPTY_MENU;
1474 break;
1475
Leon Scroggins1f005d32009-08-10 17:36:42 -04001476 case R.id.add_bookmark_menu_id:
1477 Intent i = new Intent(BrowserActivity.this,
1478 AddBookmarkPage.class);
1479 WebView w = getTopWindow();
1480 i.putExtra("url", w.getUrl());
1481 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001482 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001483 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001484 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001485 break;
1486
1487 case R.id.stop_reload_menu_id:
1488 if (mInLoad) {
1489 stopLoading();
1490 } else {
1491 getTopWindow().reload();
1492 }
1493 break;
1494
1495 case R.id.back_menu_id:
1496 getTopWindow().goBack();
1497 break;
1498
1499 case R.id.forward_menu_id:
1500 getTopWindow().goForward();
1501 break;
1502
1503 case R.id.close_menu_id:
1504 // Close the subwindow if it exists.
1505 if (mTabControl.getCurrentSubWindow() != null) {
1506 dismissSubWindow(mTabControl.getCurrentTab());
1507 break;
1508 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001509 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001510 break;
1511
1512 case R.id.homepage_menu_id:
1513 TabControl.Tab current = mTabControl.getCurrentTab();
1514 if (current != null) {
1515 dismissSubWindow(current);
1516 current.getWebView().loadUrl(mSettings.getHomePage());
1517 }
1518 break;
1519
1520 case R.id.preferences_menu_id:
1521 Intent intent = new Intent(this,
1522 BrowserPreferencesPage.class);
1523 startActivityForResult(intent, PREFERENCES_PAGE);
1524 break;
1525
1526 case R.id.find_menu_id:
1527 if (null == mFindDialog) {
1528 mFindDialog = new FindDialog(this);
1529 }
1530 mFindDialog.setWebView(getTopWindow());
1531 mFindDialog.show();
1532 mMenuState = EMPTY_MENU;
1533 break;
1534
1535 case R.id.select_text_id:
1536 getTopWindow().emulateShiftHeld();
1537 break;
1538 case R.id.page_info_menu_id:
1539 showPageInfo(mTabControl.getCurrentTab(), false);
1540 break;
1541
1542 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001543 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001544 break;
1545
1546 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001547 Browser.sendString(this, getTopWindow().getUrl(),
1548 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001549 break;
1550
1551 case R.id.dump_nav_menu_id:
1552 getTopWindow().debugDump();
1553 break;
1554
1555 case R.id.zoom_in_menu_id:
1556 getTopWindow().zoomIn();
1557 break;
1558
1559 case R.id.zoom_out_menu_id:
1560 getTopWindow().zoomOut();
1561 break;
1562
1563 case R.id.view_downloads_menu_id:
1564 viewDownloads(null);
1565 break;
1566
The Android Open Source Project0c908882009-03-03 19:32:16 -08001567 case R.id.window_one_menu_id:
1568 case R.id.window_two_menu_id:
1569 case R.id.window_three_menu_id:
1570 case R.id.window_four_menu_id:
1571 case R.id.window_five_menu_id:
1572 case R.id.window_six_menu_id:
1573 case R.id.window_seven_menu_id:
1574 case R.id.window_eight_menu_id:
1575 {
1576 int menuid = item.getItemId();
1577 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1578 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1579 TabControl.Tab desiredTab = mTabControl.getTab(id);
1580 if (desiredTab != null &&
1581 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001582 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001583 }
1584 break;
1585 }
1586 }
1587 }
1588 break;
1589
1590 default:
1591 if (!super.onOptionsItemSelected(item)) {
1592 return false;
1593 }
1594 // Otherwise fall through.
1595 }
1596 mCanChord = false;
1597 return true;
1598 }
1599
1600 public void closeFind() {
1601 mMenuState = R.id.MAIN_MENU;
1602 }
1603
1604 @Override public boolean onPrepareOptionsMenu(Menu menu)
1605 {
1606 // This happens when the user begins to hold down the menu key, so
1607 // allow them to chord to get a shortcut.
1608 mCanChord = true;
1609 // Note: setVisible will decide whether an item is visible; while
1610 // setEnabled() will decide whether an item is enabled, which also means
1611 // whether the matching shortcut key will function.
1612 super.onPrepareOptionsMenu(menu);
1613 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001614 case EMPTY_MENU:
1615 if (mCurrentMenuState != mMenuState) {
1616 menu.setGroupVisible(R.id.MAIN_MENU, false);
1617 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1618 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001619 }
1620 break;
1621 default:
1622 if (mCurrentMenuState != mMenuState) {
1623 menu.setGroupVisible(R.id.MAIN_MENU, true);
1624 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1625 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001626 }
1627 final WebView w = getTopWindow();
1628 boolean canGoBack = false;
1629 boolean canGoForward = false;
1630 boolean isHome = false;
1631 if (w != null) {
1632 canGoBack = w.canGoBack();
1633 canGoForward = w.canGoForward();
1634 isHome = mSettings.getHomePage().equals(w.getUrl());
1635 }
1636 final MenuItem back = menu.findItem(R.id.back_menu_id);
1637 back.setEnabled(canGoBack);
1638
1639 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1640 home.setEnabled(!isHome);
1641
1642 menu.findItem(R.id.forward_menu_id)
1643 .setEnabled(canGoForward);
1644
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001645 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1646 mTabControl.getTabCount() < TabControl.MAX_TABS);
1647
The Android Open Source Project0c908882009-03-03 19:32:16 -08001648 // decide whether to show the share link option
1649 PackageManager pm = getPackageManager();
1650 Intent send = new Intent(Intent.ACTION_SEND);
1651 send.setType("text/plain");
1652 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1653 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1654
The Android Open Source Project0c908882009-03-03 19:32:16 -08001655 boolean isNavDump = mSettings.isNavDump();
1656 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1657 nav.setVisible(isNavDump);
1658 nav.setEnabled(isNavDump);
1659 break;
1660 }
1661 mCurrentMenuState = mMenuState;
1662 return true;
1663 }
1664
1665 @Override
1666 public void onCreateContextMenu(ContextMenu menu, View v,
1667 ContextMenuInfo menuInfo) {
1668 WebView webview = (WebView) v;
1669 WebView.HitTestResult result = webview.getHitTestResult();
1670 if (result == null) {
1671 return;
1672 }
1673
1674 int type = result.getType();
1675 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1676 Log.w(LOGTAG,
1677 "We should not show context menu when nothing is touched");
1678 return;
1679 }
1680 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1681 // let TextView handles context menu
1682 return;
1683 }
1684
1685 // Note, http://b/issue?id=1106666 is requesting that
1686 // an inflated menu can be used again. This is not available
1687 // yet, so inflate each time (yuk!)
1688 MenuInflater inflater = getMenuInflater();
1689 inflater.inflate(R.menu.browsercontext, menu);
1690
1691 // Show the correct menu group
1692 String extra = result.getExtra();
1693 menu.setGroupVisible(R.id.PHONE_MENU,
1694 type == WebView.HitTestResult.PHONE_TYPE);
1695 menu.setGroupVisible(R.id.EMAIL_MENU,
1696 type == WebView.HitTestResult.EMAIL_TYPE);
1697 menu.setGroupVisible(R.id.GEO_MENU,
1698 type == WebView.HitTestResult.GEO_TYPE);
1699 menu.setGroupVisible(R.id.IMAGE_MENU,
1700 type == WebView.HitTestResult.IMAGE_TYPE
1701 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1702 menu.setGroupVisible(R.id.ANCHOR_MENU,
1703 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1704 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1705
1706 // Setup custom handling depending on the type
1707 switch (type) {
1708 case WebView.HitTestResult.PHONE_TYPE:
1709 menu.setHeaderTitle(Uri.decode(extra));
1710 menu.findItem(R.id.dial_context_menu_id).setIntent(
1711 new Intent(Intent.ACTION_VIEW, Uri
1712 .parse(WebView.SCHEME_TEL + extra)));
1713 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1714 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001715 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001716 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1717 addIntent);
1718 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1719 new Copy(extra));
1720 break;
1721
1722 case WebView.HitTestResult.EMAIL_TYPE:
1723 menu.setHeaderTitle(extra);
1724 menu.findItem(R.id.email_context_menu_id).setIntent(
1725 new Intent(Intent.ACTION_VIEW, Uri
1726 .parse(WebView.SCHEME_MAILTO + extra)));
1727 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1728 new Copy(extra));
1729 break;
1730
1731 case WebView.HitTestResult.GEO_TYPE:
1732 menu.setHeaderTitle(extra);
1733 menu.findItem(R.id.map_context_menu_id).setIntent(
1734 new Intent(Intent.ACTION_VIEW, Uri
1735 .parse(WebView.SCHEME_GEO
1736 + URLEncoder.encode(extra))));
1737 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1738 new Copy(extra));
1739 break;
1740
1741 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1742 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1743 TextView titleView = (TextView) LayoutInflater.from(this)
1744 .inflate(android.R.layout.browser_link_context_header,
1745 null);
1746 titleView.setText(extra);
1747 menu.setHeaderView(titleView);
1748 // decide whether to show the open link in new tab option
1749 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1750 mTabControl.getTabCount() < TabControl.MAX_TABS);
1751 PackageManager pm = getPackageManager();
1752 Intent send = new Intent(Intent.ACTION_SEND);
1753 send.setType("text/plain");
1754 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1755 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1756 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1757 break;
1758 }
1759 // otherwise fall through to handle image part
1760 case WebView.HitTestResult.IMAGE_TYPE:
1761 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1762 menu.setHeaderTitle(extra);
1763 }
1764 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1765 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1766 menu.findItem(R.id.download_context_menu_id).
1767 setOnMenuItemClickListener(new Download(extra));
1768 break;
1769
1770 default:
1771 Log.w(LOGTAG, "We should not get here.");
1772 break;
1773 }
1774 }
1775
The Android Open Source Project0c908882009-03-03 19:32:16 -08001776 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001777 // this should only be called for the current tab.
The Android Open Source Project0c908882009-03-03 19:32:16 -08001778 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001779 // Attach the container that contains the main WebView and any other UI
1780 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001781 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001782
1783 if (mShouldShowErrorConsole) {
1784 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1785 if (errorConsole.numberOfErrors() == 0) {
1786 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1787 } else {
1788 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1789 }
1790
1791 mErrorConsoleContainer.addView(errorConsole,
1792 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1793 ViewGroup.LayoutParams.WRAP_CONTENT));
1794 }
1795
Grace Klobac928c302009-09-17 11:51:21 -07001796 setLockIconType(t.getLockIconType());
1797 setPrevLockType(t.getPrevLockIconType());
1798
1799 // this is to match the code in removeTabFromContentView()
1800 if (!mPageStarted && t.getTopWindow().getProgress() < 100) {
1801 mPageStarted = true;
Grace Klobaeb6eef42009-09-15 17:56:32 -07001802 }
1803
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001804 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001805 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001806 // Request focus on the top window.
1807 t.getTopWindow().requestFocus();
1808 }
1809
1810 // Attach a sub window to the main WebView of the given tab.
1811 private void attachSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001812 t.attachSubWindow(mContentView);
1813 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001814 }
1815
1816 // Remove the given tab from the content view.
1817 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001818 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001819 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001820
1821 if (mTabControl.getCurrentErrorConsole(false) != null) {
1822 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1823 }
1824
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001825 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001826 if (view != null) {
1827 view.setEmbeddedTitleBar(null);
1828 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001829
Grace Klobac928c302009-09-17 11:51:21 -07001830 // unlike attachTabToContentView(), removeTabFromContentView() can be
1831 // called for the non-current tab. Need to add the check.
Grace Klobaeb6eef42009-09-15 17:56:32 -07001832 if (t == mTabControl.getCurrentTab()) {
1833 t.setLockIconType(getLockIconType());
1834 t.setPrevLockIconType(getPrevLockType());
Grace Klobac928c302009-09-17 11:51:21 -07001835
1836 // this is not a perfect solution. But currently there is one
1837 // WebViewClient for all the WebView. if user switches from an
1838 // in-load window to an already loaded window, mPageStarted will not
1839 // be set to false. If user leaves the Browser, pauseWebViewTimers()
1840 // won't do anything and leaves the timer running even Browser is in
1841 // the background.
1842 if (mPageStarted) {
1843 mPageStarted = false;
1844 }
Grace Klobaeb6eef42009-09-15 17:56:32 -07001845 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001846 }
1847
1848 // Remove the sub window if it exists. Also called by TabControl when the
1849 // user clicks the 'X' to dismiss a sub window.
1850 /* package */ void dismissSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001851 t.removeSubWindow(mContentView);
1852 // Tell the TabControl to dismiss the subwindow. This will destroy
1853 // the WebView.
1854 mTabControl.dismissSubWindow(t);
1855 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001856 }
1857
Leon Scroggins1f005d32009-08-10 17:36:42 -04001858 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001859 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001860 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1861 String appId) {
1862 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001863 }
1864
1865 // This method does a ton of stuff. It will attempt to create a new tab
1866 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001867 // url isn't null, it will load the given url.
1868 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001869 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001870 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1871 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1872 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001873 final TabControl.Tab tab = mTabControl.createNewTab(
1874 closeOnExit, appId, urlData.mUrl);
1875 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001876 // If the last tab was removed from the active tabs page, currentTab
1877 // will be null.
1878 if (currentTab != null) {
1879 removeTabFromContentView(currentTab);
1880 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001881 // We must set the new tab as the current tab to reflect the old
1882 // animation behavior.
1883 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001884 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001885 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001886 urlData.loadIn(webview);
1887 }
1888 return tab;
1889 } else {
1890 // Get rid of the subwindow if it exists
1891 dismissSubWindow(currentTab);
1892 if (!urlData.isEmpty()) {
1893 // Load the given url.
1894 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001895 }
1896 }
Grace Klobac9181842009-04-14 08:53:22 -07001897 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001898 }
1899
Grace Klobac9181842009-04-14 08:53:22 -07001900 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001901 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001902 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001903 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001904 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001905 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001906 }
Grace Klobac9181842009-04-14 08:53:22 -07001907 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001908 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001909 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001910 }
1911 }
1912
1913 private class Copy implements OnMenuItemClickListener {
1914 private CharSequence mText;
1915
1916 public boolean onMenuItemClick(MenuItem item) {
1917 copy(mText);
1918 return true;
1919 }
1920
1921 public Copy(CharSequence toCopy) {
1922 mText = toCopy;
1923 }
1924 }
1925
1926 private class Download implements OnMenuItemClickListener {
1927 private String mText;
1928
1929 public boolean onMenuItemClick(MenuItem item) {
1930 onDownloadStartNoStream(mText, null, null, null, -1);
1931 return true;
1932 }
1933
1934 public Download(String toDownload) {
1935 mText = toDownload;
1936 }
1937 }
1938
1939 private void copy(CharSequence text) {
1940 try {
1941 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1942 if (clip != null) {
1943 clip.setClipboardText(text);
1944 }
1945 } catch (android.os.RemoteException e) {
1946 Log.e(LOGTAG, "Copy failed", e);
1947 }
1948 }
1949
1950 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001951 * Resets the browser title-view to whatever it must be
1952 * (for example, if we had a loading error)
1953 * When we have a new page, we call resetTitle, when we
1954 * have to reset the titlebar to whatever it used to be
1955 * (for example, if the user chose to stop loading), we
1956 * call resetTitleAndRevertLockIcon.
1957 */
1958 /* package */ void resetTitleAndRevertLockIcon() {
1959 revertLockIcon();
1960 resetTitleIconAndProgress();
1961 }
1962
1963 /**
1964 * Reset the title, favicon, and progress.
1965 */
1966 private void resetTitleIconAndProgress() {
1967 WebView current = mTabControl.getCurrentWebView();
1968 if (current == null) {
1969 return;
1970 }
1971 resetTitleAndIcon(current);
1972 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001973 mWebChromeClient.onProgressChanged(current, progress);
1974 }
1975
1976 // Reset the title and the icon based on the given item.
1977 private void resetTitleAndIcon(WebView view) {
1978 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1979 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001980 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001981 setFavicon(item.getFavicon());
1982 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001983 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001984 setFavicon(null);
1985 }
1986 }
1987
1988 /**
1989 * Sets a title composed of the URL and the title string.
1990 * @param url The URL of the site being loaded.
1991 * @param title The title of the site being loaded.
1992 */
Leon Scroggins68579392009-09-15 15:31:54 -04001993 private void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001994 mUrl = url;
1995 mTitle = title;
1996
Leon Scroggins68579392009-09-15 15:31:54 -04001997 mTitleBar.setTitleAndUrl(title, url);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001998 if (mFakeTitleBar != null) {
1999 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002000 }
2001 }
2002
2003 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002004 * @param url The URL to build a title version of the URL from.
2005 * @return The title version of the URL or null if fails.
2006 * The title version of the URL can be either the URL hostname,
2007 * or the hostname with an "https://" prefix (for secure URLs),
2008 * or an empty string if, for example, the URL in question is a
2009 * file:// URL with no hostname.
2010 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002011 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002012 String titleUrl = null;
2013
2014 if (url != null) {
2015 try {
2016 // parse the url string
2017 URL urlObj = new URL(url);
2018 if (urlObj != null) {
2019 titleUrl = "";
2020
2021 String protocol = urlObj.getProtocol();
2022 String host = urlObj.getHost();
2023
2024 if (host != null && 0 < host.length()) {
2025 titleUrl = host;
2026 if (protocol != null) {
2027 // if a secure site, add an "https://" prefix!
2028 if (protocol.equalsIgnoreCase("https")) {
2029 titleUrl = protocol + "://" + host;
2030 }
2031 }
2032 }
2033 }
2034 } catch (MalformedURLException e) {}
2035 }
2036
2037 return titleUrl;
2038 }
2039
2040 // Set the favicon in the title bar.
2041 private void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002042 mTitleBar.setFavicon(icon);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002043 if (mFakeTitleBar != null) {
2044 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002045 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002046 }
2047
2048 /**
2049 * Saves the current lock-icon state before resetting
2050 * the lock icon. If we have an error, we may need to
2051 * roll back to the previous state.
2052 */
2053 private void saveLockIcon() {
2054 mPrevLockType = mLockIconType;
2055 }
2056
2057 /**
2058 * Reverts the lock-icon state to the last saved state,
2059 * for example, if we had an error, and need to cancel
2060 * the load.
2061 */
2062 private void revertLockIcon() {
2063 mLockIconType = mPrevLockType;
2064
Dave Bort31a6d1c2009-04-13 15:56:49 -07002065 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002066 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2067 " revert lock icon to " + mLockIconType);
2068 }
2069
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002070 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002071 }
2072
Leon Scroggins1f005d32009-08-10 17:36:42 -04002073 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002074 * Close the tab, remove its associated title bar, and adjust mTabControl's
2075 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002076 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002077 /* package */ void closeTab(TabControl.Tab t) {
2078 int currentIndex = mTabControl.getCurrentIndex();
2079 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002080 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002081 if (currentIndex >= removeIndex && currentIndex != 0) {
2082 currentIndex--;
2083 }
2084 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002085 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002086 }
2087
2088 private void goBackOnePageOrQuit() {
2089 TabControl.Tab current = mTabControl.getCurrentTab();
2090 if (current == null) {
2091 /*
2092 * Instead of finishing the activity, simply push this to the back
2093 * of the stack and let ActivityManager to choose the foreground
2094 * activity. As BrowserActivity is singleTask, it will be always the
2095 * root of the task. So we can use either true or false for
2096 * moveTaskToBack().
2097 */
2098 moveTaskToBack(true);
2099 }
2100 WebView w = current.getWebView();
2101 if (w.canGoBack()) {
2102 w.goBack();
2103 } else {
2104 // Check to see if we are closing a window that was created by
2105 // another window. If so, we switch back to that window.
2106 TabControl.Tab parent = current.getParentTab();
2107 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002108 switchToTab(mTabControl.getTabIndex(parent));
2109 // Now we close the other tab
2110 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002111 } else {
2112 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002113 // force mPageStarted to be false as we are going to either
2114 // finish the activity or remove the tab. This will ensure
2115 // pauseWebView() taking action.
2116 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002117 if (mTabControl.getTabCount() == 1) {
2118 finish();
2119 return;
2120 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002121 // call pauseWebViewTimers() now, we won't be able to call
2122 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002123 // Temporarily change mActivityInPause to be true as
2124 // pauseWebViewTimers() will do nothing if mActivityInPause
2125 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002126 boolean savedState = mActivityInPause;
2127 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002128 Log.e(LOGTAG, "BrowserActivity is already paused "
2129 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002130 }
2131 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002132 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002133 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002134 removeTabFromContentView(current);
2135 mTabControl.removeTab(current);
2136 }
2137 /*
2138 * Instead of finishing the activity, simply push this to the back
2139 * of the stack and let ActivityManager to choose the foreground
2140 * activity. As BrowserActivity is singleTask, it will be always the
2141 * root of the task. So we can use either true or false for
2142 * moveTaskToBack().
2143 */
2144 moveTaskToBack(true);
2145 }
2146 }
2147 }
2148
Grace Kloba5942df02009-09-18 11:48:29 -07002149 @Override
2150 public boolean onKeyDown(int keyCode, KeyEvent event) {
2151 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2152 // still down, we don't want to trigger the search. Pretend to consume
2153 // the key and do nothing.
2154 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002155
Grace Kloba5942df02009-09-18 11:48:29 -07002156 switch(keyCode) {
2157 case KeyEvent.KEYCODE_MENU:
2158 mMenuIsDown = true;
2159 break;
2160 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002161 // WebView/WebTextView handle the keys in the KeyDown. As
2162 // the Activity's shortcut keys are only handled when WebView
2163 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2164 if (event.isShiftPressed()) {
2165 getTopWindow().pageUp(false);
2166 } else {
2167 getTopWindow().pageDown(false);
2168 }
Grace Kloba5942df02009-09-18 11:48:29 -07002169 return true;
2170 case KeyEvent.KEYCODE_BACK:
2171 if (event.getRepeatCount() == 0) {
2172 event.startTracking();
2173 return true;
2174 } else if (mCustomView == null && mActiveTabsPage == null
2175 && event.isLongPress()) {
2176 bookmarksOrHistoryPicker(true);
2177 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002178 }
Grace Kloba5942df02009-09-18 11:48:29 -07002179 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002180 }
Grace Kloba5942df02009-09-18 11:48:29 -07002181 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002182 }
2183
Grace Kloba5942df02009-09-18 11:48:29 -07002184 @Override
2185 public boolean onKeyUp(int keyCode, KeyEvent event) {
2186 switch(keyCode) {
2187 case KeyEvent.KEYCODE_MENU:
2188 mMenuIsDown = false;
2189 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002190 case KeyEvent.KEYCODE_BACK:
2191 if (event.isTracking() && !event.isCanceled()) {
2192 if (mCustomView != null) {
2193 // if a custom view is showing, hide it
2194 mWebChromeClient.onHideCustomView();
2195 } else if (mActiveTabsPage != null) {
2196 // if tab page is showing, hide it
2197 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002198 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002199 WebView subwindow = mTabControl.getCurrentSubWindow();
2200 if (subwindow != null) {
2201 if (subwindow.canGoBack()) {
2202 subwindow.goBack();
2203 } else {
2204 dismissSubWindow(mTabControl.getCurrentTab());
2205 }
2206 } else {
2207 goBackOnePageOrQuit();
2208 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002209 }
Grace Kloba5942df02009-09-18 11:48:29 -07002210 return true;
2211 }
2212 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002213 }
Grace Kloba5942df02009-09-18 11:48:29 -07002214 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002215 }
2216
Leon Scroggins68579392009-09-15 15:31:54 -04002217 /* package */ void stopLoading() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002218 resetTitleAndRevertLockIcon();
2219 WebView w = getTopWindow();
2220 w.stopLoading();
2221 mWebViewClient.onPageFinished(w, w.getUrl());
2222
2223 cancelStopToast();
2224 mStopToast = Toast
2225 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2226 mStopToast.show();
2227 }
2228
2229 private void cancelStopToast() {
2230 if (mStopToast != null) {
2231 mStopToast.cancel();
2232 mStopToast = null;
2233 }
2234 }
2235
2236 // called by a non-UI thread to post the message
2237 public void postMessage(int what, int arg1, int arg2, Object obj) {
2238 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2239 }
2240
2241 // public message ids
2242 public final static int LOAD_URL = 1001;
2243 public final static int STOP_LOAD = 1002;
2244
2245 // Message Ids
2246 private static final int FOCUS_NODE_HREF = 102;
2247 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002248 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002249
2250 // Private handler for handling javascript and saving passwords
2251 private Handler mHandler = new Handler() {
2252
2253 public void handleMessage(Message msg) {
2254 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002255 case FOCUS_NODE_HREF:
2256 String url = (String) msg.getData().get("url");
2257 if (url == null || url.length() == 0) {
2258 break;
2259 }
2260 HashMap focusNodeMap = (HashMap) msg.obj;
2261 WebView view = (WebView) focusNodeMap.get("webview");
2262 // Only apply the action if the top window did not change.
2263 if (getTopWindow() != view) {
2264 break;
2265 }
2266 switch (msg.arg1) {
2267 case R.id.open_context_menu_id:
2268 case R.id.view_image_context_menu_id:
2269 loadURL(getTopWindow(), url);
2270 break;
2271 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002272 final TabControl.Tab parent = mTabControl
2273 .getCurrentTab();
2274 final TabControl.Tab newTab = openTab(url);
2275 if (newTab != parent) {
2276 parent.addChildTab(newTab);
2277 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002278 break;
2279 case R.id.bookmark_context_menu_id:
2280 Intent intent = new Intent(BrowserActivity.this,
2281 AddBookmarkPage.class);
2282 intent.putExtra("url", url);
2283 startActivity(intent);
2284 break;
2285 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002286 Browser.sendString(BrowserActivity.this, url,
2287 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002288 break;
2289 case R.id.copy_link_context_menu_id:
2290 copy(url);
2291 break;
2292 case R.id.save_link_context_menu_id:
2293 case R.id.download_context_menu_id:
2294 onDownloadStartNoStream(url, null, null, null, -1);
2295 break;
2296 }
2297 break;
2298
2299 case LOAD_URL:
2300 loadURL(getTopWindow(), (String) msg.obj);
2301 break;
2302
2303 case STOP_LOAD:
2304 stopLoading();
2305 break;
2306
2307 case CANCEL_CREDS_REQUEST:
2308 resumeAfterCredentials();
2309 break;
2310
The Android Open Source Project0c908882009-03-03 19:32:16 -08002311 case RELEASE_WAKELOCK:
2312 if (mWakeLock.isHeld()) {
2313 mWakeLock.release();
2314 }
2315 break;
2316 }
2317 }
2318 };
2319
Leon Scroggins89c6d362009-07-15 16:54:37 -04002320 private void updateScreenshot(WebView view) {
2321 // If this is a bookmarked site, add a screenshot to the database.
2322 // FIXME: When should we update? Every time?
2323 // FIXME: Would like to make sure there is actually something to
2324 // draw, but the API for that (WebViewCore.pictureReady()) is not
2325 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002326 ContentResolver cr = getContentResolver();
2327 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002328 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002329 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002330 boolean succeed = c.moveToFirst();
2331 ContentValues values = null;
2332 while (succeed) {
2333 if (values == null) {
2334 final ByteArrayOutputStream os
2335 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002336 Bitmap bm = createScreenshot(view);
Leon Scroggins89c6d362009-07-15 16:54:37 -04002337 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2338 values = new ContentValues();
2339 values.put(Browser.BookmarkColumns.THUMBNAIL,
2340 os.toByteArray());
2341 }
2342 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2343 c.getInt(0)), values, null, null);
2344 succeed = c.moveToNext();
2345 }
2346 c.close();
2347 }
2348 }
2349
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002350 /**
2351 * Constants for the size of the thumbnail created when taking a screenshot
2352 */
2353 /* package */ static final int THUMBNAIL_WIDTH = 130;
2354 /* package */ static final int THUMBNAIL_HEIGHT = 104;
2355
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002356 private Bitmap createScreenshot(WebView view) {
2357 Picture thumbnail = view.capturePicture();
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002358 Bitmap bm = Bitmap.createBitmap(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT,
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002359 Bitmap.Config.ARGB_4444);
2360 Canvas canvas = new Canvas(bm);
2361 // May need to tweak these values to determine what is the
2362 // best scale factor
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002363 int contentWidth = view.getContentWidth();
2364 if (contentWidth > 0) {
2365 float scaleFactor = (float) THUMBNAIL_WIDTH / (float) contentWidth;
2366 canvas.scale(scaleFactor, scaleFactor);
2367 }
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002368 thumbnail.draw(canvas);
2369 return bm;
2370 }
2371
The Android Open Source Project0c908882009-03-03 19:32:16 -08002372 // -------------------------------------------------------------------------
2373 // WebViewClient implementation.
2374 //-------------------------------------------------------------------------
2375
2376 // Use in overrideUrlLoading
2377 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2378 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2379 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2380 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2381
2382 /* package */ WebViewClient getWebViewClient() {
2383 return mWebViewClient;
2384 }
2385
Patrick Scott3918d442009-08-04 13:22:29 -04002386 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002387 if (icon != null) {
2388 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott15525d42009-09-21 13:39:37 -04002389 view.getOriginalUrl(), view.getUrl(), icon);
2390 }
2391 setFavicon(icon);
2392 }
2393
2394 private void updateIcon(String url, Bitmap icon) {
2395 if (icon != null) {
2396 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2397 null, url, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002398 }
2399 setFavicon(icon);
2400 }
2401
2402 private final WebViewClient mWebViewClient = new WebViewClient() {
2403 @Override
2404 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2405 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002406 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002407
Patrick Scott59ce8302009-09-18 16:29:38 -04002408 // If we start a touch icon load and then load a new page, we don't
2409 // want to cancel the current touch icon loader. But, we do want to
2410 // create a new one when the touch icon url is known.
2411 if (mTouchIconLoader != null) {
2412 mTouchIconLoader.mActivity = null;
2413 mTouchIconLoader = null;
2414 }
2415
Ben Murdochbff2d602009-07-01 20:19:05 +01002416 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2417 if (errorConsole != null) {
2418 errorConsole.clearErrorMessages();
2419 if (mShouldShowErrorConsole) {
2420 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2421 }
2422 }
2423
The Android Open Source Project0c908882009-03-03 19:32:16 -08002424 // Call updateIcon instead of setFavicon so the bookmark
2425 // database can be updated.
Patrick Scott15525d42009-09-21 13:39:37 -04002426 updateIcon(url, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002427
Grace Kloba4d7880f2009-08-12 09:35:42 -07002428 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002429 String host;
2430 try {
2431 WebAddress uri = new WebAddress(url);
2432 host = uri.mHost;
2433 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002434 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002435 }
2436 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002437 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002438 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002439 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002440 }
2441
2442 // Performance probe
2443 if (false) {
2444 mStart = SystemClock.uptimeMillis();
2445 mProcessStart = Process.getElapsedCpuTime();
2446 long[] sysCpu = new long[7];
2447 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2448 sysCpu, null)) {
2449 mUserStart = sysCpu[0] + sysCpu[1];
2450 mSystemStart = sysCpu[2];
2451 mIdleStart = sysCpu[3];
2452 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2453 }
2454 mUiStart = SystemClock.currentThreadTimeMillis();
2455 }
2456
2457 if (!mPageStarted) {
2458 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002459 // if onResume() has been called, resumeWebViewTimers() does
2460 // nothing.
2461 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002462 }
2463
2464 // reset sync timer to avoid sync starts during loading a page
2465 CookieSyncManager.getInstance().resetSync();
2466
2467 mInLoad = true;
Leon Scroggins184f5e32009-09-21 10:38:24 -04002468 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002469 updateInLoadMenuItems();
2470 if (!mIsNetworkUp) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04002471 createAndShowNetworkDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002472 if (view != null) {
2473 view.setNetworkAvailable(false);
2474 }
2475 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002476 }
2477
2478 @Override
2479 public void onPageFinished(WebView view, String url) {
2480 // Reset the title and icon in case we stopped a provisional
2481 // load.
2482 resetTitleAndIcon(view);
2483
2484 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002485 updateLockIconToLatest();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002486 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002487
The Android Open Source Project0c908882009-03-03 19:32:16 -08002488 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002489 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002490 long[] sysCpu = new long[7];
2491 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2492 sysCpu, null)) {
2493 String uiInfo = "UI thread used "
2494 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2495 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002496 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002497 Log.d(LOGTAG, uiInfo);
2498 }
2499 //The string that gets written to the log
2500 String performanceString = "It took total "
2501 + (SystemClock.uptimeMillis() - mStart)
2502 + " ms clock time to load the page."
2503 + "\nbrowser process used "
2504 + (Process.getElapsedCpuTime() - mProcessStart)
2505 + " ms, user processes used "
2506 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2507 + " ms, kernel used "
2508 + (sysCpu[2] - mSystemStart) * 10
2509 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2510 + " ms and irq took "
2511 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2512 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002513 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002514 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2515 }
2516 if (url != null) {
2517 // strip the url to maintain consistency
2518 String newUrl = new String(url);
2519 if (newUrl.startsWith("http://www.")) {
2520 newUrl = newUrl.substring(11);
2521 } else if (newUrl.startsWith("http://")) {
2522 newUrl = newUrl.substring(7);
2523 } else if (newUrl.startsWith("https://www.")) {
2524 newUrl = newUrl.substring(12);
2525 } else if (newUrl.startsWith("https://")) {
2526 newUrl = newUrl.substring(8);
2527 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002528 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002529 Log.d(LOGTAG, newUrl + " loaded");
2530 }
2531 /*
2532 if (sWhiteList.contains(newUrl)) {
2533 // The string that gets pushed to the statistcs
2534 // service
2535 performanceString = performanceString
2536 + "\nWebpage: "
2537 + newUrl
2538 + "\nCarrier: "
2539 + android.os.SystemProperties
2540 .get("gsm.sim.operator.alpha");
2541 if (mWebView != null
2542 && mWebView.getContext() != null
2543 && mWebView.getContext().getSystemService(
2544 Context.CONNECTIVITY_SERVICE) != null) {
2545 ConnectivityManager cManager =
2546 (ConnectivityManager) mWebView
2547 .getContext().getSystemService(
2548 Context.CONNECTIVITY_SERVICE);
2549 NetworkInfo nInfo = cManager
2550 .getActiveNetworkInfo();
2551 if (nInfo != null) {
2552 performanceString = performanceString
2553 + "\nNetwork Type: "
2554 + nInfo.getType().toString();
2555 }
2556 }
2557 Checkin.logEvent(mResolver,
2558 Checkin.Events.Tag.WEBPAGE_LOAD,
2559 performanceString);
2560 Log.w(LOGTAG, "pushed to the statistics service");
2561 }
2562 */
2563 }
2564 }
2565 }
2566
2567 if (mInTrace) {
2568 mInTrace = false;
2569 Debug.stopMethodTracing();
2570 }
2571
2572 if (mPageStarted) {
2573 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002574 // pauseWebViewTimers() will do nothing and return false if
2575 // onPause() is not called yet.
2576 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002577 if (mWakeLock.isHeld()) {
2578 mHandler.removeMessages(RELEASE_WAKELOCK);
2579 mWakeLock.release();
2580 }
2581 }
2582 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002583 }
2584
2585 // return true if want to hijack the url to let another app to handle it
2586 @Override
2587 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2588 if (url.startsWith(SCHEME_WTAI)) {
2589 // wtai://wp/mc;number
2590 // number=string(phone-number)
2591 if (url.startsWith(SCHEME_WTAI_MC)) {
2592 Intent intent = new Intent(Intent.ACTION_VIEW,
2593 Uri.parse(WebView.SCHEME_TEL +
2594 url.substring(SCHEME_WTAI_MC.length())));
2595 startActivity(intent);
2596 return true;
2597 }
2598 // wtai://wp/sd;dtmf
2599 // dtmf=string(dialstring)
2600 if (url.startsWith(SCHEME_WTAI_SD)) {
2601 // TODO
2602 // only send when there is active voice connection
2603 return false;
2604 }
2605 // wtai://wp/ap;number;name
2606 // number=string(phone-number)
2607 // name=string
2608 if (url.startsWith(SCHEME_WTAI_AP)) {
2609 // TODO
2610 return false;
2611 }
2612 }
2613
Dianne Hackborn99189432009-06-17 18:06:18 -07002614 // The "about:" schemes are internal to the browser; don't
2615 // want these to be dispatched to other apps.
2616 if (url.startsWith("about:")) {
2617 return false;
2618 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002619
Dianne Hackborn99189432009-06-17 18:06:18 -07002620 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002621
Dianne Hackborn99189432009-06-17 18:06:18 -07002622 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002623 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002624 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2625 } catch (URISyntaxException ex) {
2626 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002627 return false;
2628 }
2629
Grace Kloba5b078b52009-06-24 20:23:41 -07002630 // check whether the intent can be resolved. If not, we will see
2631 // whether we can download it from the Market.
2632 if (getPackageManager().resolveActivity(intent, 0) == null) {
2633 String packagename = intent.getPackage();
2634 if (packagename != null) {
2635 intent = new Intent(Intent.ACTION_VIEW, Uri
2636 .parse("market://search?q=pname:" + packagename));
2637 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2638 startActivity(intent);
2639 return true;
2640 } else {
2641 return false;
2642 }
2643 }
2644
Dianne Hackborn99189432009-06-17 18:06:18 -07002645 // sanitize the Intent, ensuring web pages can not bypass browser
2646 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002647 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002648 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002649 try {
2650 if (startActivityIfNeeded(intent, -1)) {
2651 return true;
2652 }
2653 } catch (ActivityNotFoundException ex) {
2654 // ignore the error. If no application can handle the URL,
2655 // eg about:blank, assume the browser can handle it.
2656 }
2657
2658 if (mMenuIsDown) {
2659 openTab(url);
2660 closeOptionsMenu();
2661 return true;
2662 }
2663
2664 return false;
2665 }
2666
2667 /**
2668 * Updates the lock icon. This method is called when we discover another
2669 * resource to be loaded for this page (for example, javascript). While
2670 * we update the icon type, we do not update the lock icon itself until
2671 * we are done loading, it is slightly more secure this way.
2672 */
2673 @Override
2674 public void onLoadResource(WebView view, String url) {
2675 if (url != null && url.length() > 0) {
2676 // It is only if the page claims to be secure
2677 // that we may have to update the lock:
2678 if (mLockIconType == LOCK_ICON_SECURE) {
2679 // If NOT a 'safe' url, change the lock to mixed content!
2680 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2681 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002682 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002683 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2684 " updated lock icon to " + mLockIconType + " due to " + url);
2685 }
2686 }
2687 }
2688 }
2689 }
2690
2691 /**
2692 * Show the dialog, asking the user if they would like to continue after
2693 * an excessive number of HTTP redirects.
2694 */
2695 @Override
2696 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2697 final Message continueMsg) {
2698 new AlertDialog.Builder(BrowserActivity.this)
2699 .setTitle(R.string.browserFrameRedirect)
2700 .setMessage(R.string.browserFrame307Post)
2701 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2702 public void onClick(DialogInterface dialog, int which) {
2703 continueMsg.sendToTarget();
2704 }})
2705 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2706 public void onClick(DialogInterface dialog, int which) {
2707 cancelMsg.sendToTarget();
2708 }})
2709 .setOnCancelListener(new OnCancelListener() {
2710 public void onCancel(DialogInterface dialog) {
2711 cancelMsg.sendToTarget();
2712 }})
2713 .show();
2714 }
2715
Patrick Scott37911c72009-03-24 18:02:58 -07002716 // Container class for the next error dialog that needs to be
2717 // displayed.
2718 class ErrorDialog {
2719 public final int mTitle;
2720 public final String mDescription;
2721 public final int mError;
2722 ErrorDialog(int title, String desc, int error) {
2723 mTitle = title;
2724 mDescription = desc;
2725 mError = error;
2726 }
2727 };
2728
2729 private void processNextError() {
2730 if (mQueuedErrors == null) {
2731 return;
2732 }
2733 // The first one is currently displayed so just remove it.
2734 mQueuedErrors.removeFirst();
2735 if (mQueuedErrors.size() == 0) {
2736 mQueuedErrors = null;
2737 return;
2738 }
2739 showError(mQueuedErrors.getFirst());
2740 }
2741
2742 private DialogInterface.OnDismissListener mDialogListener =
2743 new DialogInterface.OnDismissListener() {
2744 public void onDismiss(DialogInterface d) {
2745 processNextError();
2746 }
2747 };
2748 private LinkedList<ErrorDialog> mQueuedErrors;
2749
2750 private void queueError(int err, String desc) {
2751 if (mQueuedErrors == null) {
2752 mQueuedErrors = new LinkedList<ErrorDialog>();
2753 }
2754 for (ErrorDialog d : mQueuedErrors) {
2755 if (d.mError == err) {
2756 // Already saw a similar error, ignore the new one.
2757 return;
2758 }
2759 }
2760 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002761 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002762 R.string.browserFrameFileErrorLabel :
2763 R.string.browserFrameNetworkErrorLabel,
2764 desc, err);
2765 mQueuedErrors.addLast(errDialog);
2766
2767 // Show the dialog now if the queue was empty.
2768 if (mQueuedErrors.size() == 1) {
2769 showError(errDialog);
2770 }
2771 }
2772
2773 private void showError(ErrorDialog errDialog) {
2774 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2775 .setTitle(errDialog.mTitle)
2776 .setMessage(errDialog.mDescription)
2777 .setPositiveButton(R.string.ok, null)
2778 .create();
2779 d.setOnDismissListener(mDialogListener);
2780 d.show();
2781 }
2782
The Android Open Source Project0c908882009-03-03 19:32:16 -08002783 /**
2784 * Show a dialog informing the user of the network error reported by
2785 * WebCore.
2786 */
2787 @Override
2788 public void onReceivedError(WebView view, int errorCode,
2789 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002790 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2791 errorCode != WebViewClient.ERROR_CONNECT &&
2792 errorCode != WebViewClient.ERROR_BAD_URL &&
2793 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2794 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002795 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002796 }
Patrick Scott37911c72009-03-24 18:02:58 -07002797 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2798 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002799
2800 // We need to reset the title after an error.
2801 resetTitleAndRevertLockIcon();
2802 }
2803
2804 /**
2805 * Check with the user if it is ok to resend POST data as the page they
2806 * are trying to navigate to is the result of a POST.
2807 */
2808 @Override
2809 public void onFormResubmission(WebView view, final Message dontResend,
2810 final Message resend) {
2811 new AlertDialog.Builder(BrowserActivity.this)
2812 .setTitle(R.string.browserFrameFormResubmitLabel)
2813 .setMessage(R.string.browserFrameFormResubmitMessage)
2814 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2815 public void onClick(DialogInterface dialog, int which) {
2816 resend.sendToTarget();
2817 }})
2818 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2819 public void onClick(DialogInterface dialog, int which) {
2820 dontResend.sendToTarget();
2821 }})
2822 .setOnCancelListener(new OnCancelListener() {
2823 public void onCancel(DialogInterface dialog) {
2824 dontResend.sendToTarget();
2825 }})
2826 .show();
2827 }
2828
2829 /**
2830 * Insert the url into the visited history database.
2831 * @param url The url to be inserted.
2832 * @param isReload True if this url is being reloaded.
2833 * FIXME: Not sure what to do when reloading the page.
2834 */
2835 @Override
2836 public void doUpdateVisitedHistory(WebView view, String url,
2837 boolean isReload) {
2838 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2839 return;
2840 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002841 // remove "client" before updating it to the history so that it wont
2842 // show up in the auto-complete list.
2843 int index = url.indexOf("client=ms-");
2844 if (index > 0 && url.contains(".google.")) {
2845 int end = url.indexOf('&', index);
2846 if (end > 0) {
2847 url = url.substring(0, index-1).concat(url.substring(end));
2848 } else {
2849 url = url.substring(0, index-1);
2850 }
2851 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002852 Browser.updateVisitedHistory(mResolver, url, true);
2853 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2854 }
2855
2856 /**
2857 * Displays SSL error(s) dialog to the user.
2858 */
2859 @Override
2860 public void onReceivedSslError(
2861 final WebView view, final SslErrorHandler handler, final SslError error) {
2862
2863 if (mSettings.showSecurityWarnings()) {
2864 final LayoutInflater factory =
2865 LayoutInflater.from(BrowserActivity.this);
2866 final View warningsView =
2867 factory.inflate(R.layout.ssl_warnings, null);
2868 final LinearLayout placeholder =
2869 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2870
2871 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2872 LinearLayout ll = (LinearLayout)factory
2873 .inflate(R.layout.ssl_warning, null);
2874 ((TextView)ll.findViewById(R.id.warning))
2875 .setText(R.string.ssl_untrusted);
2876 placeholder.addView(ll);
2877 }
2878
2879 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2880 LinearLayout ll = (LinearLayout)factory
2881 .inflate(R.layout.ssl_warning, null);
2882 ((TextView)ll.findViewById(R.id.warning))
2883 .setText(R.string.ssl_mismatch);
2884 placeholder.addView(ll);
2885 }
2886
2887 if (error.hasError(SslError.SSL_EXPIRED)) {
2888 LinearLayout ll = (LinearLayout)factory
2889 .inflate(R.layout.ssl_warning, null);
2890 ((TextView)ll.findViewById(R.id.warning))
2891 .setText(R.string.ssl_expired);
2892 placeholder.addView(ll);
2893 }
2894
2895 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2896 LinearLayout ll = (LinearLayout)factory
2897 .inflate(R.layout.ssl_warning, null);
2898 ((TextView)ll.findViewById(R.id.warning))
2899 .setText(R.string.ssl_not_yet_valid);
2900 placeholder.addView(ll);
2901 }
2902
2903 new AlertDialog.Builder(BrowserActivity.this)
2904 .setTitle(R.string.security_warning)
2905 .setIcon(android.R.drawable.ic_dialog_alert)
2906 .setView(warningsView)
2907 .setPositiveButton(R.string.ssl_continue,
2908 new DialogInterface.OnClickListener() {
2909 public void onClick(DialogInterface dialog, int whichButton) {
2910 handler.proceed();
2911 }
2912 })
2913 .setNeutralButton(R.string.view_certificate,
2914 new DialogInterface.OnClickListener() {
2915 public void onClick(DialogInterface dialog, int whichButton) {
2916 showSSLCertificateOnError(view, handler, error);
2917 }
2918 })
2919 .setNegativeButton(R.string.cancel,
2920 new DialogInterface.OnClickListener() {
2921 public void onClick(DialogInterface dialog, int whichButton) {
2922 handler.cancel();
2923 BrowserActivity.this.resetTitleAndRevertLockIcon();
2924 }
2925 })
2926 .setOnCancelListener(
2927 new DialogInterface.OnCancelListener() {
2928 public void onCancel(DialogInterface dialog) {
2929 handler.cancel();
2930 BrowserActivity.this.resetTitleAndRevertLockIcon();
2931 }
2932 })
2933 .show();
2934 } else {
2935 handler.proceed();
2936 }
2937 }
2938
2939 /**
2940 * Handles an HTTP authentication request.
2941 *
2942 * @param handler The authentication handler
2943 * @param host The host
2944 * @param realm The realm
2945 */
2946 @Override
2947 public void onReceivedHttpAuthRequest(WebView view,
2948 final HttpAuthHandler handler, final String host, final String realm) {
2949 String username = null;
2950 String password = null;
2951
2952 boolean reuseHttpAuthUsernamePassword =
2953 handler.useHttpAuthUsernamePassword();
2954
2955 if (reuseHttpAuthUsernamePassword &&
2956 (mTabControl.getCurrentWebView() != null)) {
2957 String[] credentials =
2958 mTabControl.getCurrentWebView()
2959 .getHttpAuthUsernamePassword(host, realm);
2960 if (credentials != null && credentials.length == 2) {
2961 username = credentials[0];
2962 password = credentials[1];
2963 }
2964 }
2965
2966 if (username != null && password != null) {
2967 handler.proceed(username, password);
2968 } else {
2969 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2970 }
2971 }
2972
2973 @Override
2974 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2975 if (mMenuIsDown) {
2976 // only check shortcut key when MENU is held
2977 return getWindow().isShortcutKey(event.getKeyCode(), event);
2978 } else {
2979 return false;
2980 }
2981 }
2982
2983 @Override
2984 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2985 if (view != mTabControl.getCurrentTopWebView()) {
2986 return;
2987 }
2988 if (event.isDown()) {
2989 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2990 } else {
2991 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2992 }
2993 }
2994 };
2995
2996 //--------------------------------------------------------------------------
2997 // WebChromeClient implementation
2998 //--------------------------------------------------------------------------
2999
3000 /* package */ WebChromeClient getWebChromeClient() {
3001 return mWebChromeClient;
3002 }
3003
3004 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3005 // Helper method to create a new tab or sub window.
3006 private void createWindow(final boolean dialog, final Message msg) {
3007 if (dialog) {
3008 mTabControl.createSubWindow();
3009 final TabControl.Tab t = mTabControl.getCurrentTab();
3010 attachSubWindow(t);
3011 WebView.WebViewTransport transport =
3012 (WebView.WebViewTransport) msg.obj;
3013 transport.setWebView(t.getSubWebView());
3014 msg.sendToTarget();
3015 } else {
3016 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003017 final TabControl.Tab newTab
3018 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07003019 if (newTab != parent) {
3020 parent.addChildTab(newTab);
3021 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003022 WebView.WebViewTransport transport =
3023 (WebView.WebViewTransport) msg.obj;
3024 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04003025 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003026 }
3027 }
3028
3029 @Override
3030 public boolean onCreateWindow(WebView view, final boolean dialog,
3031 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003032 // Short-circuit if we can't create any more tabs or sub windows.
3033 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3034 new AlertDialog.Builder(BrowserActivity.this)
3035 .setTitle(R.string.too_many_subwindows_dialog_title)
3036 .setIcon(android.R.drawable.ic_dialog_alert)
3037 .setMessage(R.string.too_many_subwindows_dialog_message)
3038 .setPositiveButton(R.string.ok, null)
3039 .show();
3040 return false;
3041 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3042 new AlertDialog.Builder(BrowserActivity.this)
3043 .setTitle(R.string.too_many_windows_dialog_title)
3044 .setIcon(android.R.drawable.ic_dialog_alert)
3045 .setMessage(R.string.too_many_windows_dialog_message)
3046 .setPositiveButton(R.string.ok, null)
3047 .show();
3048 return false;
3049 }
3050
3051 // Short-circuit if this was a user gesture.
3052 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003053 createWindow(dialog, resultMsg);
3054 return true;
3055 }
3056
3057 // Allow the popup and create the appropriate window.
3058 final AlertDialog.OnClickListener allowListener =
3059 new AlertDialog.OnClickListener() {
3060 public void onClick(DialogInterface d,
3061 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003062 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003063 }
3064 };
3065
3066 // Block the popup by returning a null WebView.
3067 final AlertDialog.OnClickListener blockListener =
3068 new AlertDialog.OnClickListener() {
3069 public void onClick(DialogInterface d, int which) {
3070 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003071 }
3072 };
3073
3074 // Build a confirmation dialog to display to the user.
3075 final AlertDialog d =
3076 new AlertDialog.Builder(BrowserActivity.this)
3077 .setTitle(R.string.attention)
3078 .setIcon(android.R.drawable.ic_dialog_alert)
3079 .setMessage(R.string.popup_window_attempt)
3080 .setPositiveButton(R.string.allow, allowListener)
3081 .setNegativeButton(R.string.block, blockListener)
3082 .setCancelable(false)
3083 .create();
3084
3085 // Show the confirmation dialog.
3086 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003087 return true;
3088 }
3089
3090 @Override
3091 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003092 final TabControl.Tab current = mTabControl.getCurrentTab();
3093 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003094 if (parent != null) {
3095 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003096 switchToTab(mTabControl.getTabIndex(parent));
3097 // Now we need to close the window
3098 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003099 }
3100 }
3101
3102 @Override
3103 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003104 mTitleBar.setProgress(newProgress);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003105 if (mFakeTitleBar != null) {
3106 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003107 }
3108
3109 if (newProgress == 100) {
3110 // onProgressChanged() is called for sub-frame too while
3111 // onPageFinished() is only called for the main frame. sync
3112 // cookie and cache promptly here.
3113 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003114 if (mInLoad) {
3115 mInLoad = false;
3116 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003117 // If the options menu is open, leave the title bar
3118 if (!mOptionsMenuOpen || !mIconView) {
3119 hideFakeTitleBar();
3120 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003121 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003122 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003123 // onPageFinished may have already been called but a subframe
3124 // is still loading and updating the progress. Reset mInLoad
3125 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003126 mInLoad = true;
3127 updateInLoadMenuItems();
Leon Scroggins184f5e32009-09-21 10:38:24 -04003128 if (!mOptionsMenuOpen || mIconView) {
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003129 // This page has begun to load, so show the title bar
3130 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003131 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003132 }
3133 }
3134
3135 @Override
3136 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003137 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003138
3139 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003140 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003141
3142 if (url == null ||
3143 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3144 return;
3145 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003146 // See if we can find the current url in our history database and
3147 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003148 if (url.startsWith("http://www.")) {
3149 url = url.substring(11);
3150 } else if (url.startsWith("http://")) {
3151 url = url.substring(4);
3152 }
3153 try {
3154 url = "%" + url;
3155 String [] selArgs = new String[] { url };
3156
3157 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3158 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3159 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3160 Browser.HISTORY_PROJECTION, where, selArgs, null);
3161 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003162 // Current implementation of database only has one entry per
3163 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003164 ContentValues map = new ContentValues();
3165 map.put(Browser.BookmarkColumns.TITLE, title);
3166 mResolver.update(Browser.BOOKMARKS_URI, map,
3167 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003168 }
3169 c.close();
3170 } catch (IllegalStateException e) {
3171 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3172 } catch (SQLiteException ex) {
3173 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3174 }
3175 }
3176
3177 @Override
3178 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003179 updateIcon(view, icon);
3180 }
3181
3182 @Override
Patrick Scott59ce8302009-09-18 16:29:38 -04003183 public void onReceivedTouchIconUrl(WebView view, String url,
3184 boolean precomposed) {
Patrick Scott3918d442009-08-04 13:22:29 -04003185 final ContentResolver cr = getContentResolver();
3186 final Cursor c =
3187 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003188 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003189 if (c != null) {
3190 if (c.getCount() > 0) {
Patrick Scott59ce8302009-09-18 16:29:38 -04003191 // Let precomposed icons take precedence over non-composed
3192 // icons.
3193 if (precomposed && mTouchIconLoader != null) {
3194 mTouchIconLoader.cancel(false);
3195 mTouchIconLoader = null;
3196 }
3197 // Have only one async task at a time.
3198 if (mTouchIconLoader == null) {
3199 mTouchIconLoader = new DownloadTouchIcon(
3200 BrowserActivity.this, cr, c, view);
3201 mTouchIconLoader.execute(url);
3202 }
Patrick Scott3918d442009-08-04 13:22:29 -04003203 } else {
3204 c.close();
3205 }
3206 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003207 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003208
Andrei Popescuadc008d2009-06-26 14:11:30 +01003209 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003210 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003211 if (mCustomView != null)
3212 return;
3213
3214 // Add the custom view to its container.
3215 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3216 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003217 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003218 // Save the menu state and set it to empty while the custom
3219 // view is showing.
3220 mOldMenuState = mMenuState;
3221 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003222 // Hide the content view.
3223 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003224 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003225 mCustomViewContainer.setVisibility(View.VISIBLE);
3226 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003227 }
3228
3229 @Override
3230 public void onHideCustomView() {
3231 if (mCustomView == null)
3232 return;
3233
Andrei Popescuc9b55562009-07-07 10:51:15 +01003234 // Hide the custom view.
3235 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003236 // Remove the custom view from its container.
3237 mCustomViewContainer.removeView(mCustomView);
3238 mCustomView = null;
3239 // Reset the old menu state.
3240 mMenuState = mOldMenuState;
3241 mOldMenuState = EMPTY_MENU;
3242 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003243 mCustomViewCallback.onCustomViewHidden();
3244 // Show the content view.
3245 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003246 }
3247
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003248 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003249 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003250 * @param url the URL that exceeded the quota
3251 * @param databaseIdentifier the identifier of the database on
3252 * which the transaction that caused the quota overflow was run
3253 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003254 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003255 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003256 * @param quotaUpdater The callback to run when a decision to allow or
3257 * deny quota has been made. Don't forget to call this!
3258 */
3259 @Override
3260 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003261 String databaseIdentifier, long currentQuota, long estimatedSize,
3262 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003263 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003264 url, databaseIdentifier, currentQuota, estimatedSize,
3265 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003266 }
3267
3268 /**
3269 * The Application Cache has exceeded its max size.
3270 * @param spaceNeeded is the amount of disk space that would be needed
3271 * in order for the last appcache operation to succeed.
3272 * @param totalUsedQuota is the sum of all origins' quota.
3273 * @param quotaUpdater A callback to inform the WebCore thread that a new
3274 * app cache size is available. This callback must always be executed at
3275 * some point to ensure that the sleeping WebCore thread is woken up.
3276 */
3277 @Override
3278 public void onReachedMaxAppCacheSize(long spaceNeeded,
3279 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3280 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3281 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003282 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003283
Steve Block2bc69912009-07-30 14:45:13 +01003284 /**
3285 * Instructs the browser to show a prompt to ask the user to set the
3286 * Geolocation permission state for the specified origin.
3287 * @param origin The origin for which Geolocation permissions are
3288 * requested.
3289 * @param callback The callback to call once the user has set the
3290 * Geolocation permission state.
3291 */
3292 @Override
3293 public void onGeolocationPermissionsShowPrompt(String origin,
3294 GeolocationPermissions.Callback callback) {
3295 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3296 origin, callback);
3297 }
3298
3299 /**
3300 * Instructs the browser to hide the Geolocation permissions prompt.
3301 */
3302 @Override
3303 public void onGeolocationPermissionsHidePrompt() {
3304 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3305 }
3306
Ben Murdoch7db26342009-06-03 18:21:19 +01003307 /* Adds a JavaScript error message to the system log.
3308 * @param message The error message to report.
3309 * @param lineNumber The line number of the error.
3310 * @param sourceID The name of the source file that caused the error.
3311 */
3312 @Override
3313 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003314 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3315 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3316 if (mShouldShowErrorConsole &&
3317 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3318 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3319 }
3320 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003321 }
Andrei Popescu540035d2009-09-18 18:59:20 +01003322
3323 /**
3324 * Ask the browser for an icon to represent a <video> element.
3325 * This icon will be used if the Web page did not specify a poster attribute.
3326 *
3327 * @return Bitmap The icon or null if no such icon is available.
3328 * @hide pending API Council approval
3329 */
3330 @Override
3331 public Bitmap getDefaultVideoPoster() {
3332 if (mDefaultVideoPoster == null) {
3333 mDefaultVideoPoster = BitmapFactory.decodeResource(
3334 getResources(), R.drawable.default_video_poster);
3335 }
3336 return mDefaultVideoPoster;
3337 }
3338
3339 /**
3340 * Ask the host application for a custom progress view to show while
3341 * a <video> is loading.
3342 *
3343 * @return View The progress view.
3344 * @hide pending API Council approval
3345 */
3346 @Override
3347 public View getVideoLoadingProgressView() {
3348 if (mVideoProgressView == null) {
3349 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
3350 mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
3351 }
3352 return mVideoProgressView;
3353 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003354 };
3355
3356 /**
3357 * Notify the host application a download should be done, or that
3358 * the data should be streamed if a streaming viewer is available.
3359 * @param url The full url to the content that should be downloaded
3360 * @param contentDisposition Content-disposition http header, if
3361 * present.
3362 * @param mimetype The mimetype of the content reported by the server
3363 * @param contentLength The file size reported by the server
3364 */
3365 public void onDownloadStart(String url, String userAgent,
3366 String contentDisposition, String mimetype, long contentLength) {
3367 // if we're dealing wih A/V content that's not explicitly marked
3368 // for download, check if it's streamable.
3369 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003370 || !contentDisposition.regionMatches(
3371 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003372 // query the package manager to see if there's a registered handler
3373 // that matches.
3374 Intent intent = new Intent(Intent.ACTION_VIEW);
3375 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003376 ResolveInfo info = getPackageManager().resolveActivity(intent,
3377 PackageManager.MATCH_DEFAULT_ONLY);
3378 if (info != null) {
3379 ComponentName myName = getComponentName();
3380 // If we resolved to ourselves, we don't want to attempt to
3381 // load the url only to try and download it again.
3382 if (!myName.getPackageName().equals(
3383 info.activityInfo.packageName)
3384 || !myName.getClassName().equals(
3385 info.activityInfo.name)) {
3386 // someone (other than us) knows how to handle this mime
3387 // type with this scheme, don't download.
3388 try {
3389 startActivity(intent);
3390 return;
3391 } catch (ActivityNotFoundException ex) {
3392 if (LOGD_ENABLED) {
3393 Log.d(LOGTAG, "activity not found for " + mimetype
3394 + " over " + Uri.parse(url).getScheme(),
3395 ex);
3396 }
3397 // Best behavior is to fall back to a download in this
3398 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003399 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003400 }
3401 }
3402 }
3403 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3404 }
3405
3406 /**
3407 * Notify the host application a download should be done, even if there
3408 * is a streaming viewer available for thise type.
3409 * @param url The full url to the content that should be downloaded
3410 * @param contentDisposition Content-disposition http header, if
3411 * present.
3412 * @param mimetype The mimetype of the content reported by the server
3413 * @param contentLength The file size reported by the server
3414 */
3415 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3416 String contentDisposition, String mimetype, long contentLength) {
3417
3418 String filename = URLUtil.guessFileName(url,
3419 contentDisposition, mimetype);
3420
3421 // Check to see if we have an SDCard
3422 String status = Environment.getExternalStorageState();
3423 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3424 int title;
3425 String msg;
3426
3427 // Check to see if the SDCard is busy, same as the music app
3428 if (status.equals(Environment.MEDIA_SHARED)) {
3429 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3430 title = R.string.download_sdcard_busy_dlg_title;
3431 } else {
3432 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3433 title = R.string.download_no_sdcard_dlg_title;
3434 }
3435
3436 new AlertDialog.Builder(this)
3437 .setTitle(title)
3438 .setIcon(android.R.drawable.ic_dialog_alert)
3439 .setMessage(msg)
3440 .setPositiveButton(R.string.ok, null)
3441 .show();
3442 return;
3443 }
3444
3445 // java.net.URI is a lot stricter than KURL so we have to undo
3446 // KURL's percent-encoding and redo the encoding using java.net.URI.
3447 URI uri = null;
3448 try {
3449 // Undo the percent-encoding that KURL may have done.
3450 String newUrl = new String(URLUtil.decode(url.getBytes()));
3451 // Parse the url into pieces
3452 WebAddress w = new WebAddress(newUrl);
3453 String frag = null;
3454 String query = null;
3455 String path = w.mPath;
3456 // Break the path into path, query, and fragment
3457 if (path.length() > 0) {
3458 // Strip the fragment
3459 int idx = path.lastIndexOf('#');
3460 if (idx != -1) {
3461 frag = path.substring(idx + 1);
3462 path = path.substring(0, idx);
3463 }
3464 idx = path.lastIndexOf('?');
3465 if (idx != -1) {
3466 query = path.substring(idx + 1);
3467 path = path.substring(0, idx);
3468 }
3469 }
3470 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3471 query, frag);
3472 } catch (Exception e) {
3473 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3474 return;
3475 }
3476
3477 // XXX: Have to use the old url since the cookies were stored using the
3478 // old percent-encoded url.
3479 String cookies = CookieManager.getInstance().getCookie(url);
3480
3481 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003482 values.put(Downloads.COLUMN_URI, uri.toString());
3483 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3484 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3485 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003486 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003487 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003488 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003489 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3490 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3491 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3492 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003493 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003494 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003495 }
3496 if (mimetype == null) {
3497 // We must have long pressed on a link or image to download it. We
3498 // are not sure of the mimetype in this case, so do a head request
3499 new FetchUrlMimeType(this).execute(values);
3500 } else {
3501 final Uri contentUri =
3502 getContentResolver().insert(Downloads.CONTENT_URI, values);
3503 viewDownloads(contentUri);
3504 }
3505
3506 }
3507
3508 /**
3509 * Resets the lock icon. This method is called when we start a new load and
3510 * know the url to be loaded.
3511 */
3512 private void resetLockIcon(String url) {
3513 // Save the lock-icon state (we revert to it if the load gets cancelled)
3514 saveLockIcon();
3515
3516 mLockIconType = LOCK_ICON_UNSECURE;
3517 if (URLUtil.isHttpsUrl(url)) {
3518 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003519 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003520 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3521 " reset lock icon to " + mLockIconType);
3522 }
3523 }
3524
3525 updateLockIconImage(LOCK_ICON_UNSECURE);
3526 }
3527
Grace Klobaeb6eef42009-09-15 17:56:32 -07003528 /* package */ void setLockIconType(int type) {
3529 mLockIconType = type;
3530 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003531
Grace Klobaeb6eef42009-09-15 17:56:32 -07003532 /* package */ int getLockIconType() {
3533 return mLockIconType;
3534 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003535
Grace Klobaeb6eef42009-09-15 17:56:32 -07003536 /* package */ void setPrevLockType(int type) {
3537 mPrevLockType = type;
3538 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003539
Grace Klobaeb6eef42009-09-15 17:56:32 -07003540 /* package */ int getPrevLockType() {
3541 return mPrevLockType;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003542 }
3543
3544 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003545 * Update the lock icon to correspond to our latest state.
3546 */
3547 /* package */ void updateLockIconToLatest() {
3548 updateLockIconImage(mLockIconType);
3549 }
3550
3551 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003552 * Updates the lock-icon image in the title-bar.
3553 */
3554 private void updateLockIconImage(int lockIconType) {
3555 Drawable d = null;
3556 if (lockIconType == LOCK_ICON_SECURE) {
3557 d = mSecLockIcon;
3558 } else if (lockIconType == LOCK_ICON_MIXED) {
3559 d = mMixLockIcon;
3560 }
Leon Scroggins68579392009-09-15 15:31:54 -04003561 mTitleBar.setLock(d);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003562 if (mFakeTitleBar != null) {
3563 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003564 }
3565 }
3566
3567 /**
3568 * Displays a page-info dialog.
3569 * @param tab The tab to show info about
3570 * @param fromShowSSLCertificateOnError The flag that indicates whether
3571 * this dialog was opened from the SSL-certificate-on-error dialog or
3572 * not. This is important, since we need to know whether to return to
3573 * the parent dialog or simply dismiss.
3574 */
3575 private void showPageInfo(final TabControl.Tab tab,
3576 final boolean fromShowSSLCertificateOnError) {
3577 final LayoutInflater factory = LayoutInflater
3578 .from(this);
3579
3580 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3581
3582 final WebView view = tab.getWebView();
3583
3584 String url = null;
3585 String title = null;
3586
3587 if (view == null) {
3588 url = tab.getUrl();
3589 title = tab.getTitle();
3590 } else if (view == mTabControl.getCurrentWebView()) {
3591 // Use the cached title and url if this is the current WebView
3592 url = mUrl;
3593 title = mTitle;
3594 } else {
3595 url = view.getUrl();
3596 title = view.getTitle();
3597 }
3598
3599 if (url == null) {
3600 url = "";
3601 }
3602 if (title == null) {
3603 title = "";
3604 }
3605
3606 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3607 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3608
3609 mPageInfoView = tab;
3610 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3611
3612 AlertDialog.Builder alertDialogBuilder =
3613 new AlertDialog.Builder(this)
3614 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3615 .setView(pageInfoView)
3616 .setPositiveButton(
3617 R.string.ok,
3618 new DialogInterface.OnClickListener() {
3619 public void onClick(DialogInterface dialog,
3620 int whichButton) {
3621 mPageInfoDialog = null;
3622 mPageInfoView = null;
3623 mPageInfoFromShowSSLCertificateOnError = null;
3624
3625 // if we came here from the SSL error dialog
3626 if (fromShowSSLCertificateOnError) {
3627 // go back to the SSL error dialog
3628 showSSLCertificateOnError(
3629 mSSLCertificateOnErrorView,
3630 mSSLCertificateOnErrorHandler,
3631 mSSLCertificateOnErrorError);
3632 }
3633 }
3634 })
3635 .setOnCancelListener(
3636 new DialogInterface.OnCancelListener() {
3637 public void onCancel(DialogInterface dialog) {
3638 mPageInfoDialog = null;
3639 mPageInfoView = null;
3640 mPageInfoFromShowSSLCertificateOnError = null;
3641
3642 // if we came here from the SSL error dialog
3643 if (fromShowSSLCertificateOnError) {
3644 // go back to the SSL error dialog
3645 showSSLCertificateOnError(
3646 mSSLCertificateOnErrorView,
3647 mSSLCertificateOnErrorHandler,
3648 mSSLCertificateOnErrorError);
3649 }
3650 }
3651 });
3652
3653 // if we have a main top-level page SSL certificate set or a certificate
3654 // error
3655 if (fromShowSSLCertificateOnError ||
3656 (view != null && view.getCertificate() != null)) {
3657 // add a 'View Certificate' button
3658 alertDialogBuilder.setNeutralButton(
3659 R.string.view_certificate,
3660 new DialogInterface.OnClickListener() {
3661 public void onClick(DialogInterface dialog,
3662 int whichButton) {
3663 mPageInfoDialog = null;
3664 mPageInfoView = null;
3665 mPageInfoFromShowSSLCertificateOnError = null;
3666
3667 // if we came here from the SSL error dialog
3668 if (fromShowSSLCertificateOnError) {
3669 // go back to the SSL error dialog
3670 showSSLCertificateOnError(
3671 mSSLCertificateOnErrorView,
3672 mSSLCertificateOnErrorHandler,
3673 mSSLCertificateOnErrorError);
3674 } else {
3675 // otherwise, display the top-most certificate from
3676 // the chain
3677 if (view.getCertificate() != null) {
3678 showSSLCertificate(tab);
3679 }
3680 }
3681 }
3682 });
3683 }
3684
3685 mPageInfoDialog = alertDialogBuilder.show();
3686 }
3687
3688 /**
3689 * Displays the main top-level page SSL certificate dialog
3690 * (accessible from the Page-Info dialog).
3691 * @param tab The tab to show certificate for.
3692 */
3693 private void showSSLCertificate(final TabControl.Tab tab) {
3694 final View certificateView =
3695 inflateCertificateView(tab.getWebView().getCertificate());
3696 if (certificateView == null) {
3697 return;
3698 }
3699
3700 LayoutInflater factory = LayoutInflater.from(this);
3701
3702 final LinearLayout placeholder =
3703 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3704
3705 LinearLayout ll = (LinearLayout) factory.inflate(
3706 R.layout.ssl_success, placeholder);
3707 ((TextView)ll.findViewById(R.id.success))
3708 .setText(R.string.ssl_certificate_is_valid);
3709
3710 mSSLCertificateView = tab;
3711 mSSLCertificateDialog =
3712 new AlertDialog.Builder(this)
3713 .setTitle(R.string.ssl_certificate).setIcon(
3714 R.drawable.ic_dialog_browser_certificate_secure)
3715 .setView(certificateView)
3716 .setPositiveButton(R.string.ok,
3717 new DialogInterface.OnClickListener() {
3718 public void onClick(DialogInterface dialog,
3719 int whichButton) {
3720 mSSLCertificateDialog = null;
3721 mSSLCertificateView = null;
3722
3723 showPageInfo(tab, false);
3724 }
3725 })
3726 .setOnCancelListener(
3727 new DialogInterface.OnCancelListener() {
3728 public void onCancel(DialogInterface dialog) {
3729 mSSLCertificateDialog = null;
3730 mSSLCertificateView = null;
3731
3732 showPageInfo(tab, false);
3733 }
3734 })
3735 .show();
3736 }
3737
3738 /**
3739 * Displays the SSL error certificate dialog.
3740 * @param view The target web-view.
3741 * @param handler The SSL error handler responsible for cancelling the
3742 * connection that resulted in an SSL error or proceeding per user request.
3743 * @param error The SSL error object.
3744 */
3745 private void showSSLCertificateOnError(
3746 final WebView view, final SslErrorHandler handler, final SslError error) {
3747
3748 final View certificateView =
3749 inflateCertificateView(error.getCertificate());
3750 if (certificateView == null) {
3751 return;
3752 }
3753
3754 LayoutInflater factory = LayoutInflater.from(this);
3755
3756 final LinearLayout placeholder =
3757 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3758
3759 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3760 LinearLayout ll = (LinearLayout)factory
3761 .inflate(R.layout.ssl_warning, placeholder);
3762 ((TextView)ll.findViewById(R.id.warning))
3763 .setText(R.string.ssl_untrusted);
3764 }
3765
3766 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3767 LinearLayout ll = (LinearLayout)factory
3768 .inflate(R.layout.ssl_warning, placeholder);
3769 ((TextView)ll.findViewById(R.id.warning))
3770 .setText(R.string.ssl_mismatch);
3771 }
3772
3773 if (error.hasError(SslError.SSL_EXPIRED)) {
3774 LinearLayout ll = (LinearLayout)factory
3775 .inflate(R.layout.ssl_warning, placeholder);
3776 ((TextView)ll.findViewById(R.id.warning))
3777 .setText(R.string.ssl_expired);
3778 }
3779
3780 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3781 LinearLayout ll = (LinearLayout)factory
3782 .inflate(R.layout.ssl_warning, placeholder);
3783 ((TextView)ll.findViewById(R.id.warning))
3784 .setText(R.string.ssl_not_yet_valid);
3785 }
3786
3787 mSSLCertificateOnErrorHandler = handler;
3788 mSSLCertificateOnErrorView = view;
3789 mSSLCertificateOnErrorError = error;
3790 mSSLCertificateOnErrorDialog =
3791 new AlertDialog.Builder(this)
3792 .setTitle(R.string.ssl_certificate).setIcon(
3793 R.drawable.ic_dialog_browser_certificate_partially_secure)
3794 .setView(certificateView)
3795 .setPositiveButton(R.string.ok,
3796 new DialogInterface.OnClickListener() {
3797 public void onClick(DialogInterface dialog,
3798 int whichButton) {
3799 mSSLCertificateOnErrorDialog = null;
3800 mSSLCertificateOnErrorView = null;
3801 mSSLCertificateOnErrorHandler = null;
3802 mSSLCertificateOnErrorError = null;
3803
3804 mWebViewClient.onReceivedSslError(
3805 view, handler, error);
3806 }
3807 })
3808 .setNeutralButton(R.string.page_info_view,
3809 new DialogInterface.OnClickListener() {
3810 public void onClick(DialogInterface dialog,
3811 int whichButton) {
3812 mSSLCertificateOnErrorDialog = null;
3813
3814 // do not clear the dialog state: we will
3815 // need to show the dialog again once the
3816 // user is done exploring the page-info details
3817
3818 showPageInfo(mTabControl.getTabFromView(view),
3819 true);
3820 }
3821 })
3822 .setOnCancelListener(
3823 new DialogInterface.OnCancelListener() {
3824 public void onCancel(DialogInterface dialog) {
3825 mSSLCertificateOnErrorDialog = null;
3826 mSSLCertificateOnErrorView = null;
3827 mSSLCertificateOnErrorHandler = null;
3828 mSSLCertificateOnErrorError = null;
3829
3830 mWebViewClient.onReceivedSslError(
3831 view, handler, error);
3832 }
3833 })
3834 .show();
3835 }
3836
3837 /**
3838 * Inflates the SSL certificate view (helper method).
3839 * @param certificate The SSL certificate.
3840 * @return The resultant certificate view with issued-to, issued-by,
3841 * issued-on, expires-on, and possibly other fields set.
3842 * If the input certificate is null, returns null.
3843 */
3844 private View inflateCertificateView(SslCertificate certificate) {
3845 if (certificate == null) {
3846 return null;
3847 }
3848
3849 LayoutInflater factory = LayoutInflater.from(this);
3850
3851 View certificateView = factory.inflate(
3852 R.layout.ssl_certificate, null);
3853
3854 // issued to:
3855 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3856 if (issuedTo != null) {
3857 ((TextView) certificateView.findViewById(R.id.to_common))
3858 .setText(issuedTo.getCName());
3859 ((TextView) certificateView.findViewById(R.id.to_org))
3860 .setText(issuedTo.getOName());
3861 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3862 .setText(issuedTo.getUName());
3863 }
3864
3865 // issued by:
3866 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3867 if (issuedBy != null) {
3868 ((TextView) certificateView.findViewById(R.id.by_common))
3869 .setText(issuedBy.getCName());
3870 ((TextView) certificateView.findViewById(R.id.by_org))
3871 .setText(issuedBy.getOName());
3872 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3873 .setText(issuedBy.getUName());
3874 }
3875
3876 // issued on:
3877 String issuedOn = reformatCertificateDate(
3878 certificate.getValidNotBefore());
3879 ((TextView) certificateView.findViewById(R.id.issued_on))
3880 .setText(issuedOn);
3881
3882 // expires on:
3883 String expiresOn = reformatCertificateDate(
3884 certificate.getValidNotAfter());
3885 ((TextView) certificateView.findViewById(R.id.expires_on))
3886 .setText(expiresOn);
3887
3888 return certificateView;
3889 }
3890
3891 /**
3892 * Re-formats the certificate date (Date.toString()) string to
3893 * a properly localized date string.
3894 * @return Properly localized version of the certificate date string and
3895 * the original certificate date string if fails to localize.
3896 * If the original string is null, returns an empty string "".
3897 */
3898 private String reformatCertificateDate(String certificateDate) {
3899 String reformattedDate = null;
3900
3901 if (certificateDate != null) {
3902 Date date = null;
3903 try {
3904 date = java.text.DateFormat.getInstance().parse(certificateDate);
3905 } catch (ParseException e) {
3906 date = null;
3907 }
3908
3909 if (date != null) {
3910 reformattedDate =
3911 DateFormat.getDateFormat(this).format(date);
3912 }
3913 }
3914
3915 return reformattedDate != null ? reformattedDate :
3916 (certificateDate != null ? certificateDate : "");
3917 }
3918
3919 /**
3920 * Displays an http-authentication dialog.
3921 */
3922 private void showHttpAuthentication(final HttpAuthHandler handler,
3923 final String host, final String realm, final String title,
3924 final String name, final String password, int focusId) {
3925 LayoutInflater factory = LayoutInflater.from(this);
3926 final View v = factory
3927 .inflate(R.layout.http_authentication, null);
3928 if (name != null) {
3929 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3930 }
3931 if (password != null) {
3932 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3933 }
3934
3935 String titleText = title;
3936 if (titleText == null) {
3937 titleText = getText(R.string.sign_in_to).toString().replace(
3938 "%s1", host).replace("%s2", realm);
3939 }
3940
3941 mHttpAuthHandler = handler;
3942 AlertDialog dialog = new AlertDialog.Builder(this)
3943 .setTitle(titleText)
3944 .setIcon(android.R.drawable.ic_dialog_alert)
3945 .setView(v)
3946 .setPositiveButton(R.string.action,
3947 new DialogInterface.OnClickListener() {
3948 public void onClick(DialogInterface dialog,
3949 int whichButton) {
3950 String nm = ((EditText) v
3951 .findViewById(R.id.username_edit))
3952 .getText().toString();
3953 String pw = ((EditText) v
3954 .findViewById(R.id.password_edit))
3955 .getText().toString();
3956 BrowserActivity.this.setHttpAuthUsernamePassword
3957 (host, realm, nm, pw);
3958 handler.proceed(nm, pw);
3959 mHttpAuthenticationDialog = null;
3960 mHttpAuthHandler = null;
3961 }})
3962 .setNegativeButton(R.string.cancel,
3963 new DialogInterface.OnClickListener() {
3964 public void onClick(DialogInterface dialog,
3965 int whichButton) {
3966 handler.cancel();
3967 BrowserActivity.this.resetTitleAndRevertLockIcon();
3968 mHttpAuthenticationDialog = null;
3969 mHttpAuthHandler = null;
3970 }})
3971 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3972 public void onCancel(DialogInterface dialog) {
3973 handler.cancel();
3974 BrowserActivity.this.resetTitleAndRevertLockIcon();
3975 mHttpAuthenticationDialog = null;
3976 mHttpAuthHandler = null;
3977 }})
3978 .create();
3979 // Make the IME appear when the dialog is displayed if applicable.
3980 dialog.getWindow().setSoftInputMode(
3981 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3982 dialog.show();
3983 if (focusId != 0) {
3984 dialog.findViewById(focusId).requestFocus();
3985 } else {
3986 v.findViewById(R.id.username_edit).requestFocus();
3987 }
3988 mHttpAuthenticationDialog = dialog;
3989 }
3990
3991 public int getProgress() {
3992 WebView w = mTabControl.getCurrentWebView();
3993 if (w != null) {
3994 return w.getProgress();
3995 } else {
3996 return 100;
3997 }
3998 }
3999
4000 /**
4001 * Set HTTP authentication password.
4002 *
4003 * @param host The host for the password
4004 * @param realm The realm for the password
4005 * @param username The username for the password. If it is null, it means
4006 * password can't be saved.
4007 * @param password The password
4008 */
4009 public void setHttpAuthUsernamePassword(String host, String realm,
4010 String username,
4011 String password) {
4012 WebView w = mTabControl.getCurrentWebView();
4013 if (w != null) {
4014 w.setHttpAuthUsernamePassword(host, realm, username, password);
4015 }
4016 }
4017
4018 /**
4019 * connectivity manager says net has come or gone... inform the user
4020 * @param up true if net has come up, false if net has gone down
4021 */
4022 public void onNetworkToggle(boolean up) {
4023 if (up == mIsNetworkUp) {
4024 return;
4025 } else if (up) {
4026 mIsNetworkUp = true;
4027 if (mAlertDialog != null) {
4028 mAlertDialog.cancel();
4029 mAlertDialog = null;
4030 }
4031 } else {
4032 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004033 if (mInLoad) {
4034 createAndShowNetworkDialog();
4035 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004036 }
4037 WebView w = mTabControl.getCurrentWebView();
4038 if (w != null) {
4039 w.setNetworkAvailable(up);
4040 }
4041 }
4042
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004043 // This method shows the network dialog alerting the user that the net is
4044 // down. It will only show the dialog if mAlertDialog is null.
4045 private void createAndShowNetworkDialog() {
4046 if (mAlertDialog == null) {
4047 mAlertDialog = new AlertDialog.Builder(this)
4048 .setTitle(R.string.loadSuspendedTitle)
4049 .setMessage(R.string.loadSuspended)
4050 .setPositiveButton(R.string.ok, null)
4051 .show();
4052 }
4053 }
4054
The Android Open Source Project0c908882009-03-03 19:32:16 -08004055 @Override
4056 protected void onActivityResult(int requestCode, int resultCode,
4057 Intent intent) {
4058 switch (requestCode) {
4059 case COMBO_PAGE:
4060 if (resultCode == RESULT_OK && intent != null) {
4061 String data = intent.getAction();
4062 Bundle extras = intent.getExtras();
4063 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04004064 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004065 } else {
4066 final TabControl.Tab currentTab =
4067 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04004068 dismissSubWindow(currentTab);
4069 if (data != null && data.length() != 0) {
4070 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004071 }
4072 }
4073 }
4074 break;
4075 default:
4076 break;
4077 }
Leon Scroggins30444232009-09-04 18:36:20 -04004078 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004079 }
4080
4081 /*
4082 * This method is called as a result of the user selecting the options
4083 * menu to see the download window, or when a download changes state. It
4084 * shows the download window ontop of the current window.
4085 */
4086 /* package */ void viewDownloads(Uri downloadRecord) {
4087 Intent intent = new Intent(this,
4088 BrowserDownloadPage.class);
4089 intent.setData(downloadRecord);
4090 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4091
4092 }
4093
Leon Scroggins160a7e72009-08-14 18:28:01 -04004094 /**
4095 * Open the Go page.
4096 * @param startWithHistory If true, open starting on the history tab.
4097 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004098 */
Leon Scroggins30444232009-09-04 18:36:20 -04004099 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004100 WebView current = mTabControl.getCurrentWebView();
4101 if (current == null) {
4102 return;
4103 }
4104 Intent intent = new Intent(this,
4105 CombinedBookmarkHistoryActivity.class);
4106 String title = current.getTitle();
4107 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004108 Bitmap thumbnail = createScreenshot(current);
4109
The Android Open Source Project0c908882009-03-03 19:32:16 -08004110 // Just in case the user opens bookmarks before a page finishes loading
4111 // so the current history item, and therefore the page, is null.
4112 if (null == url) {
4113 url = mLastEnteredUrl;
4114 // This can happen.
4115 if (null == url) {
4116 url = mSettings.getHomePage();
4117 }
4118 }
4119 // In case the web page has not yet received its associated title.
4120 if (title == null) {
4121 title = url;
4122 }
4123 intent.putExtra("title", title);
4124 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004125 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04004126 // Disable opening in a new window if we have maxed out the windows
4127 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4128 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004129 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004130 if (startWithHistory) {
4131 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4132 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4133 }
4134 startActivityForResult(intent, COMBO_PAGE);
4135 }
4136
4137 // Called when loading from context menu or LOAD_URL message
4138 private void loadURL(WebView view, String url) {
4139 // In case the user enters nothing.
4140 if (url != null && url.length() != 0 && view != null) {
4141 url = smartUrlFilter(url);
4142 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4143 view.loadUrl(url);
4144 }
4145 }
4146 }
4147
The Android Open Source Project0c908882009-03-03 19:32:16 -08004148 private String smartUrlFilter(Uri inUri) {
4149 if (inUri != null) {
4150 return smartUrlFilter(inUri.toString());
4151 }
4152 return null;
4153 }
4154
4155
4156 // get window count
4157
4158 int getWindowCount(){
4159 if(mTabControl != null){
4160 return mTabControl.getTabCount();
4161 }
4162 return 0;
4163 }
4164
Feng Qianb34f87a2009-03-24 21:27:26 -07004165 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004166 "(?i)" + // switch on case insensitive matching
4167 "(" + // begin group for schema
4168 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004169 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004170 ")" +
4171 "(.*)" );
4172
4173 /**
4174 * Attempts to determine whether user input is a URL or search
4175 * terms. Anything with a space is passed to search.
4176 *
4177 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4178 * "Http://" converts to "http://"
4179 *
4180 * @return Original or modified URL
4181 *
4182 */
4183 String smartUrlFilter(String url) {
4184
4185 String inUrl = url.trim();
4186 boolean hasSpace = inUrl.indexOf(' ') != -1;
4187
4188 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4189 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004190 // force scheme to lowercase
4191 String scheme = matcher.group(1);
4192 String lcScheme = scheme.toLowerCase();
4193 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004194 inUrl = lcScheme + matcher.group(2);
4195 }
4196 if (hasSpace) {
4197 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004198 }
4199 return inUrl;
4200 }
4201 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004202 // FIXME: Is this the correct place to add to searches?
4203 // what if someone else calls this function?
4204 int shortcut = parseUrlShortcut(inUrl);
4205 if (shortcut != SHORTCUT_INVALID) {
4206 Browser.addSearchUrl(mResolver, inUrl);
4207 String query = inUrl.substring(2);
4208 switch (shortcut) {
4209 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004210 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004211 case SHORTCUT_WIKIPEDIA_SEARCH:
4212 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4213 case SHORTCUT_DICTIONARY_SEARCH:
4214 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4215 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004216 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004217 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004218 }
4219 }
4220 } else {
4221 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4222 return URLUtil.guessUrl(inUrl);
4223 }
4224 }
4225
4226 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004227 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004228 }
4229
Ben Murdochbff2d602009-07-01 20:19:05 +01004230 /* package */ void setShouldShowErrorConsole(boolean flag) {
4231 if (flag == mShouldShowErrorConsole) {
4232 // Nothing to do.
4233 return;
4234 }
4235
4236 mShouldShowErrorConsole = flag;
4237
4238 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4239
4240 if (flag) {
4241 // Setting the show state of the console will cause it's the layout to be inflated.
4242 if (errorConsole.numberOfErrors() > 0) {
4243 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4244 } else {
4245 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4246 }
4247
4248 // Now we can add it to the main view.
4249 mErrorConsoleContainer.addView(errorConsole,
4250 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4251 ViewGroup.LayoutParams.WRAP_CONTENT));
4252 } else {
4253 mErrorConsoleContainer.removeView(errorConsole);
4254 }
4255
4256 }
4257
Grace Klobaeb6eef42009-09-15 17:56:32 -07004258 final static int LOCK_ICON_UNSECURE = 0;
4259 final static int LOCK_ICON_SECURE = 1;
4260 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004261
4262 private int mLockIconType = LOCK_ICON_UNSECURE;
4263 private int mPrevLockType = LOCK_ICON_UNSECURE;
4264
4265 private BrowserSettings mSettings;
4266 private TabControl mTabControl;
4267 private ContentResolver mResolver;
4268 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004269 private View mCustomView;
4270 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004271 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004272
4273 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4274 // view, we should rewrite this.
4275 private int mCurrentMenuState = 0;
4276 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004277 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004278 private static final int EMPTY_MENU = -1;
4279 private Menu mMenu;
4280
4281 private FindDialog mFindDialog;
4282 // Used to prevent chording to result in firing two shortcuts immediately
4283 // one after another. Fixes bug 1211714.
4284 boolean mCanChord;
4285
4286 private boolean mInLoad;
4287 private boolean mIsNetworkUp;
4288
4289 private boolean mPageStarted;
4290 private boolean mActivityInPause = true;
4291
4292 private boolean mMenuIsDown;
4293
The Android Open Source Project0c908882009-03-03 19:32:16 -08004294 private static boolean mInTrace;
4295
4296 // Performance probe
4297 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4298 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4299 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4300 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4301 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4302 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4303 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4304 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4305 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4306 };
4307
4308 private long mStart;
4309 private long mProcessStart;
4310 private long mUserStart;
4311 private long mSystemStart;
4312 private long mIdleStart;
4313 private long mIrqStart;
4314
4315 private long mUiStart;
4316
4317 private Drawable mMixLockIcon;
4318 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004319
4320 /* hold a ref so we can auto-cancel if necessary */
4321 private AlertDialog mAlertDialog;
4322
4323 // Wait for credentials before loading google.com
4324 private ProgressDialog mCredsDlg;
4325
4326 // The up-to-date URL and title (these can be different from those stored
4327 // in WebView, since it takes some time for the information in WebView to
4328 // get updated)
4329 private String mUrl;
4330 private String mTitle;
4331
4332 // As PageInfo has different style for landscape / portrait, we have
4333 // to re-open it when configuration changed
4334 private AlertDialog mPageInfoDialog;
4335 private TabControl.Tab mPageInfoView;
4336 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4337 // dialog, we should not just dismiss it, but should get back to the
4338 // SSL-certificate-on-error dialog. This flag is used to store this state
4339 private Boolean mPageInfoFromShowSSLCertificateOnError;
4340
4341 // as SSLCertificateOnError has different style for landscape / portrait,
4342 // we have to re-open it when configuration changed
4343 private AlertDialog mSSLCertificateOnErrorDialog;
4344 private WebView mSSLCertificateOnErrorView;
4345 private SslErrorHandler mSSLCertificateOnErrorHandler;
4346 private SslError mSSLCertificateOnErrorError;
4347
4348 // as SSLCertificate has different style for landscape / portrait, we
4349 // have to re-open it when configuration changed
4350 private AlertDialog mSSLCertificateDialog;
4351 private TabControl.Tab mSSLCertificateView;
4352
4353 // as HttpAuthentication has different style for landscape / portrait, we
4354 // have to re-open it when configuration changed
4355 private AlertDialog mHttpAuthenticationDialog;
4356 private HttpAuthHandler mHttpAuthHandler;
4357
4358 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4359 new FrameLayout.LayoutParams(
4360 ViewGroup.LayoutParams.FILL_PARENT,
4361 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004362 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4363 new FrameLayout.LayoutParams(
4364 ViewGroup.LayoutParams.FILL_PARENT,
4365 ViewGroup.LayoutParams.FILL_PARENT,
4366 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004367 // Google search
4368 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004369 // Wikipedia search
4370 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4371 // Dictionary search
4372 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4373 // Google Mobile Local search
4374 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4375
4376 final static String QUERY_PLACE_HOLDER = "%s";
4377
4378 // "source" parameter for Google search through search key
4379 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4380 // "source" parameter for Google search through goto menu
4381 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4382 // "source" parameter for Google search through simplily type
4383 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4384 // "source" parameter for Google search suggested by the browser
4385 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4386 // "source" parameter for Google search from unknown source
4387 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4388
4389 private final static String LOGTAG = "browser";
4390
The Android Open Source Project0c908882009-03-03 19:32:16 -08004391 private String mLastEnteredUrl;
4392
4393 private PowerManager.WakeLock mWakeLock;
4394 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4395
4396 private Toast mStopToast;
4397
Leon Scroggins68579392009-09-15 15:31:54 -04004398 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004399
Ben Murdochbff2d602009-07-01 20:19:05 +01004400 private LinearLayout mErrorConsoleContainer = null;
4401 private boolean mShouldShowErrorConsole = false;
4402
The Android Open Source Project0c908882009-03-03 19:32:16 -08004403 // As the ids are dynamically created, we can't guarantee that they will
4404 // be in sequence, so this static array maps ids to a window number.
4405 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4406 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4407 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4408 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4409
4410 // monitor platform changes
4411 private IntentFilter mNetworkStateChangedFilter;
4412 private BroadcastReceiver mNetworkStateIntentReceiver;
4413
Grace Klobab4da0ad2009-05-14 14:45:40 -07004414 private BroadcastReceiver mPackageInstallationReceiver;
4415
Patrick Scott59ce8302009-09-18 16:29:38 -04004416 // AsyncTask for downloading touch icons
4417 /* package */ DownloadTouchIcon mTouchIconLoader;
4418
The Android Open Source Project0c908882009-03-03 19:32:16 -08004419 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004420 final static int COMBO_PAGE = 1;
4421 final static int DOWNLOAD_PAGE = 2;
4422 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004423
Andrei Popescu540035d2009-09-18 18:59:20 +01004424 // the default <video> poster
4425 private Bitmap mDefaultVideoPoster;
4426 // the video progress view
4427 private View mVideoProgressView;
4428
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004429 /**
4430 * A UrlData class to abstract how the content will be set to WebView.
4431 * This base class uses loadUrl to show the content.
4432 */
4433 private static class UrlData {
4434 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004435 byte[] mPostData;
4436
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004437 UrlData(String url) {
4438 this.mUrl = url;
4439 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004440
4441 void setPostData(byte[] postData) {
4442 mPostData = postData;
4443 }
4444
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004445 boolean isEmpty() {
4446 return mUrl == null || mUrl.length() == 0;
4447 }
4448
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004449 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004450 if (mPostData != null) {
4451 webView.postUrl(mUrl, mPostData);
4452 } else {
4453 webView.loadUrl(mUrl);
4454 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004455 }
4456 };
4457
4458 /**
4459 * A subclass of UrlData class that can display inlined content using
4460 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4461 */
4462 private static class InlinedUrlData extends UrlData {
4463 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4464 super(failUrl);
4465 mInlined = inlined;
4466 mMimeType = mimeType;
4467 mEncoding = encoding;
4468 }
4469 String mMimeType;
4470 String mInlined;
4471 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004472 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004473 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004474 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004475 }
4476
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004477 @Override
4478 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004479 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4480 }
4481 }
4482
Leon Scroggins1f005d32009-08-10 17:36:42 -04004483 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004484}