blob: 7f8c0c6e3ecd8804a7b28190e84144e2cef4270d [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;
79import android.provider.Contacts;
80import android.provider.Downloads;
81import android.provider.MediaStore;
82import android.provider.Contacts.Intents.Insert;
83import 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 }
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100620 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA));
Satish Sampath565505b2009-05-29 15:37:27 +0100621 }
622
623 /**
624 * Launches the default web search activity with the query parameters if the given url string
625 * was identified as plain search terms and not URL/shortcut.
626 * @return true if the request was handled and web search activity was launched, false if not.
627 */
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100628 private boolean handleWebSearchRequest(String inUrl, Bundle appData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100629 if (inUrl == null) return false;
630
631 // In general, we shouldn't modify URL from Intent.
632 // But currently, we get the user-typed URL from search box as well.
633 String url = fixUrl(inUrl).trim();
634
635 // URLs and site specific search shortcuts are handled by the regular flow of control, so
636 // return early.
637 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100638 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100639 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
640 return false;
641 }
642
643 Browser.updateVisitedHistory(mResolver, url, false);
644 Browser.addSearchUrl(mResolver, url);
645
646 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
647 intent.addCategory(Intent.CATEGORY_DEFAULT);
648 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100649 if (appData != null) {
650 intent.putExtra(SearchManager.APP_DATA, appData);
651 }
Grace Klobacc634032009-07-28 15:58:19 -0700652 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100653 startActivity(intent);
654
655 return true;
656 }
657
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700658 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800659 String url = null;
660 if (intent != null) {
661 final String action = intent.getAction();
662 if (Intent.ACTION_VIEW.equals(action)) {
663 url = smartUrlFilter(intent.getData());
664 if (url != null && url.startsWith("content:")) {
665 /* Append mimetype so webview knows how to display */
666 String mimeType = intent.resolveType(getContentResolver());
667 if (mimeType != null) {
668 url += "?" + mimeType;
669 }
670 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700671 if ("inline:".equals(url)) {
672 return new InlinedUrlData(
673 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
674 intent.getType(),
675 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
676 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
677 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800678 } else if (Intent.ACTION_SEARCH.equals(action)
679 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
680 || Intent.ACTION_WEB_SEARCH.equals(action)) {
681 url = intent.getStringExtra(SearchManager.QUERY);
682 if (url != null) {
683 mLastEnteredUrl = url;
684 // Don't add Urls, just search terms.
685 // Urls will get added when the page is loaded.
686 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
687 Browser.updateVisitedHistory(mResolver, url, false);
688 }
689 // In general, we shouldn't modify URL from Intent.
690 // But currently, we get the user-typed URL from search box as well.
691 url = fixUrl(url);
692 url = smartUrlFilter(url);
693 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
694 if (url.contains(searchSource)) {
695 String source = null;
696 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
697 if (appData != null) {
698 source = appData.getString(SearchManager.SOURCE);
699 }
700 if (TextUtils.isEmpty(source)) {
701 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
702 }
703 url = url.replace(searchSource, "&source=android-"+source+"&");
704 }
705 }
706 }
707 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700708 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800709 }
710
711 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400712 // FIXME: Converting the url to lower case
713 // duplicates functionality in smartUrlFilter().
714 // However, changing all current callers of fixUrl to
715 // call smartUrlFilter in addition may have unwanted
716 // consequences, and is deferred for now.
717 int colon = inUrl.indexOf(':');
718 boolean allLower = true;
719 for (int index = 0; index < colon; index++) {
720 char ch = inUrl.charAt(index);
721 if (!Character.isLetter(ch)) {
722 break;
723 }
724 allLower &= Character.isLowerCase(ch);
725 if (index == colon - 1 && !allLower) {
726 inUrl = inUrl.substring(0, colon).toLowerCase()
727 + inUrl.substring(colon);
728 }
729 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800730 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
731 return inUrl;
732 if (inUrl.startsWith("http:") ||
733 inUrl.startsWith("https:")) {
734 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
735 inUrl = inUrl.replaceFirst("/", "//");
736 } else inUrl = inUrl.replaceFirst(":", "://");
737 }
738 return inUrl;
739 }
740
741 /**
742 * Looking for the pattern like this
743 *
744 * *
745 * * *
746 * *** * *******
747 * * *
748 * * *
749 * *
750 */
751 private final SensorListener mSensorListener = new SensorListener() {
752 private long mLastGestureTime;
753 private float[] mPrev = new float[3];
754 private float[] mPrevDiff = new float[3];
755 private float[] mDiff = new float[3];
756 private float[] mRevertDiff = new float[3];
757
758 public void onSensorChanged(int sensor, float[] values) {
759 boolean show = false;
760 float[] diff = new float[3];
761
762 for (int i = 0; i < 3; i++) {
763 diff[i] = values[i] - mPrev[i];
764 if (Math.abs(diff[i]) > 1) {
765 show = true;
766 }
767 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
768 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
769 // start track when there is a big move, or revert
770 mRevertDiff[i] = mDiff[i];
771 mDiff[i] = 0;
772 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
773 // reset when it is flat
774 mDiff[i] = mRevertDiff[i] = 0;
775 }
776 mDiff[i] += diff[i];
777 mPrevDiff[i] = diff[i];
778 mPrev[i] = values[i];
779 }
780
781 if (false) {
782 // only shows if we think the delta is big enough, in an attempt
783 // to detect "serious" moves left/right or up/down
784 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
785 + values[0] + ", " + values[1] + ", " + values[2] + ")"
786 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
787 + ")");
788 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
789 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
790 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
791 + mRevertDiff[2] + ")");
792 }
793
794 long now = android.os.SystemClock.uptimeMillis();
795 if (now - mLastGestureTime > 1000) {
796 mLastGestureTime = 0;
797
798 float y = mDiff[1];
799 float z = mDiff[2];
800 float ay = Math.abs(y);
801 float az = Math.abs(z);
802 float ry = mRevertDiff[1];
803 float rz = mRevertDiff[2];
804 float ary = Math.abs(ry);
805 float arz = Math.abs(rz);
806 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
807 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
808
809 if ((gestY || gestZ) && !(gestY && gestZ)) {
810 WebView view = mTabControl.getCurrentWebView();
811
812 if (view != null) {
813 if (gestZ) {
814 if (z < 0) {
815 view.zoomOut();
816 } else {
817 view.zoomIn();
818 }
819 } else {
820 view.flingScroll(0, Math.round(y * 100));
821 }
822 }
823 mLastGestureTime = now;
824 }
825 }
826 }
827
828 public void onAccuracyChanged(int sensor, int accuracy) {
829 // TODO Auto-generated method stub
830
831 }
832 };
833
834 @Override protected void onResume() {
835 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700836 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800837 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
838 }
839
840 if (!mActivityInPause) {
841 Log.e(LOGTAG, "BrowserActivity is already resumed.");
842 return;
843 }
844
Mike Reed7bfa63b2009-05-28 11:08:32 -0400845 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800846 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400847 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800848
849 if (mWakeLock.isHeld()) {
850 mHandler.removeMessages(RELEASE_WAKELOCK);
851 mWakeLock.release();
852 }
853
854 if (mCredsDlg != null) {
855 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
856 // In case credential request never comes back
857 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
858 }
859 }
860
861 registerReceiver(mNetworkStateIntentReceiver,
862 mNetworkStateChangedFilter);
863 WebView.enablePlatformNotifications();
864
865 if (mSettings.doFlick()) {
866 if (mSensorManager == null) {
867 mSensorManager = (SensorManager) getSystemService(
868 Context.SENSOR_SERVICE);
869 }
870 mSensorManager.registerListener(mSensorListener,
871 SensorManager.SENSOR_ACCELEROMETER,
872 SensorManager.SENSOR_DELAY_FASTEST);
873 } else {
874 mSensorManager = null;
875 }
876 }
877
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400878 /**
879 * Since the actual title bar is embedded in the WebView, and removing it
880 * would change its appearance, create a temporary title bar to go at
881 * the top of the screen while the menu is open.
882 */
883 private TitleBar mFakeTitleBar;
884
885 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400886 * Holder for the fake title bar. It will have a foreground shadow, as well
887 * as a white background, so the fake title bar looks like the real one.
888 */
889 private ViewGroup mFakeTitleBarHolder;
890
891 /**
892 * Layout parameters for the fake title bar within mFakeTitleBarHolder
893 */
894 private FrameLayout.LayoutParams mFakeTitleBarParams
895 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400896 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400897 ViewGroup.LayoutParams.WRAP_CONTENT);
898 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400899 * Keeps track of whether the options menu is open. This is important in
900 * determining whether to show or hide the title bar overlay.
901 */
902 private boolean mOptionsMenuOpen;
903
904 /**
905 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
906 * of whether the configuration has changed. The first onMenuOpened call
907 * after a configuration change is simply a reopening of the same menu
908 * (i.e. mIconView did not change).
909 */
910 private boolean mConfigChanged;
911
912 /**
913 * Whether or not the options menu is in its smaller, icon menu form. When
914 * true, we want the title bar overlay to be up. When false, we do not.
915 * Only meaningful if mOptionsMenuOpen is true.
916 */
917 private boolean mIconView;
918
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400919 @Override
920 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400921 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
922 if (mOptionsMenuOpen) {
923 if (mConfigChanged) {
924 // We do not need to make any changes to the state of the
925 // title bar, since the only thing that happened was a
926 // change in orientation
927 mConfigChanged = false;
928 } else {
929 if (mIconView) {
930 // Switching the menu to expanded view, so hide the
931 // title bar.
932 hideFakeTitleBar();
933 mIconView = false;
934 } else {
935 // Switching the menu back to icon view, so show the
936 // title bar once again.
937 showFakeTitleBar();
938 mIconView = true;
939 }
940 }
941 } else {
942 // The options menu is closed, so open it, and show the title
943 showFakeTitleBar();
944 mOptionsMenuOpen = true;
945 mConfigChanged = false;
946 mIconView = true;
947 }
948 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400949 return true;
950 }
951
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400952 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400953 final View decor = getWindow().peekDecorView();
Leon Scroggins4d7e4062009-09-15 15:49:45 -0400954 if (mFakeTitleBar == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400955 && !mActivityInPause && decor != null
956 && decor.getWindowToken() != null) {
Leon Scrogginsf4bb18a2009-09-11 18:37:53 -0400957 final WebView webView = getTopWindow();
Leon Scroggins68579392009-09-15 15:31:54 -0400958 mFakeTitleBar = new TitleBar(this);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400959 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
960 mFakeTitleBar.setProgress(webView.getProgress());
961 mFakeTitleBar.setFavicon(webView.getFavicon());
962 updateLockIconToLatest();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400963
964 WindowManager manager
965 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
966
967 // Add the title bar to the window manager so it can receive touches
968 // while the menu is up
969 WindowManager.LayoutParams params
970 = new WindowManager.LayoutParams(
971 ViewGroup.LayoutParams.FILL_PARENT,
972 ViewGroup.LayoutParams.WRAP_CONTENT,
973 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
974 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
975 PixelFormat.OPAQUE);
976 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400977 WebView mainView = mTabControl.getCurrentWebView();
978 params.windowAnimations = mainView == null
979 || mainView.getScrollY() != 0
980 ? com.android.internal.R.style.Animation_DropDownDown : 0;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400981 // XXX : Without providing an offset, the fake title bar will be
982 // placed underneath the status bar. Use the global visible rect
983 // of mBrowserFrameLayout to determine the bottom of the status bar
984 Rect rectangle = new Rect();
985 mBrowserFrameLayout.getGlobalVisibleRect(rectangle);
986 params.y = rectangle.top;
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400987 // Add a holder for the title bar. It is a FrameLayout, which
988 // allows it to have an overlay shadow. It also has a white
989 // background, which is the same as the background when it is
990 // placed in a WebView.
991 if (mFakeTitleBarHolder == null) {
992 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
993 .inflate(R.layout.title_bar_bg, null);
994 }
995 mFakeTitleBarHolder.addView(mFakeTitleBar, mFakeTitleBarParams);
996 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400997 }
998 }
999
1000 @Override
1001 public void onOptionsMenuClosed(Menu menu) {
1002 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04001003 if (!mInLoad) {
1004 hideFakeTitleBar();
1005 } else if (!mIconView) {
1006 // The page is currently loading, and we are in expanded mode, so
1007 // we were not showing the menu. Show it once again. It will be
1008 // removed when the page finishes.
1009 showFakeTitleBar();
1010 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001011 }
1012 private void hideFakeTitleBar() {
1013 if (mFakeTitleBar == null) return;
1014 WindowManager manager
1015 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001016 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1017 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001018 mFakeTitleBar = null;
1019 }
1020
The Android Open Source Project0c908882009-03-03 19:32:16 -08001021 /**
1022 * onSaveInstanceState(Bundle map)
1023 * onSaveInstanceState is called right before onStop(). The map contains
1024 * the saved state.
1025 */
1026 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001027 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001028 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1029 }
1030 // the default implementation requires each view to have an id. As the
1031 // browser handles the state itself and it doesn't use id for the views,
1032 // don't call the default implementation. Otherwise it will trigger the
1033 // warning like this, "couldn't save which view has focus because the
1034 // focused view XXX has no id".
1035
1036 // Save all the tabs
1037 mTabControl.saveState(outState);
1038 }
1039
1040 @Override protected void onPause() {
1041 super.onPause();
1042
1043 if (mActivityInPause) {
1044 Log.e(LOGTAG, "BrowserActivity is already paused.");
1045 return;
1046 }
1047
Mike Reed7bfa63b2009-05-28 11:08:32 -04001048 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001049 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001050 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001051 mWakeLock.acquire();
1052 mHandler.sendMessageDelayed(mHandler
1053 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1054 }
1055
1056 // Clear the credentials toast if it is up
1057 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1058 mCredsDlg.dismiss();
1059 }
1060 mCredsDlg = null;
1061
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001062 // FIXME: This removes the active tabs page and resets the menu to
1063 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1064 // but then we would need to save it in onSaveInstanceState and restore
1065 // it in onCreate/onRestoreInstanceState
1066 if (mActiveTabsPage != null) {
1067 removeActiveTabPage(true);
1068 }
1069
The Android Open Source Project0c908882009-03-03 19:32:16 -08001070 cancelStopToast();
1071
1072 // unregister network state listener
1073 unregisterReceiver(mNetworkStateIntentReceiver);
1074 WebView.disablePlatformNotifications();
1075
1076 if (mSensorManager != null) {
1077 mSensorManager.unregisterListener(mSensorListener);
1078 }
1079 }
1080
1081 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001082 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001083 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1084 }
1085 super.onDestroy();
1086 // Remove the current tab and sub window
1087 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001088 if (t != null) {
1089 dismissSubWindow(t);
1090 removeTabFromContentView(t);
1091 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001092 // Destroy all the tabs
1093 mTabControl.destroy();
1094 WebIconDatabase.getInstance().close();
1095 if (mGlsConnection != null) {
1096 unbindService(mGlsConnection);
1097 mGlsConnection = null;
1098 }
1099
1100 //
1101 // stop MASF proxy service
1102 //
1103 //Intent proxyServiceIntent = new Intent();
1104 //proxyServiceIntent.setComponent
1105 // (new ComponentName(
1106 // "com.android.masfproxyservice",
1107 // "com.android.masfproxyservice.MasfProxyService"));
1108 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001109
1110 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001111 }
1112
1113 @Override
1114 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001115 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001116 super.onConfigurationChanged(newConfig);
1117
1118 if (mPageInfoDialog != null) {
1119 mPageInfoDialog.dismiss();
1120 showPageInfo(
1121 mPageInfoView,
1122 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1123 }
1124 if (mSSLCertificateDialog != null) {
1125 mSSLCertificateDialog.dismiss();
1126 showSSLCertificate(
1127 mSSLCertificateView);
1128 }
1129 if (mSSLCertificateOnErrorDialog != null) {
1130 mSSLCertificateOnErrorDialog.dismiss();
1131 showSSLCertificateOnError(
1132 mSSLCertificateOnErrorView,
1133 mSSLCertificateOnErrorHandler,
1134 mSSLCertificateOnErrorError);
1135 }
1136 if (mHttpAuthenticationDialog != null) {
1137 String title = ((TextView) mHttpAuthenticationDialog
1138 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1139 .toString();
1140 String name = ((TextView) mHttpAuthenticationDialog
1141 .findViewById(R.id.username_edit)).getText().toString();
1142 String password = ((TextView) mHttpAuthenticationDialog
1143 .findViewById(R.id.password_edit)).getText().toString();
1144 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1145 .getId();
1146 mHttpAuthenticationDialog.dismiss();
1147 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1148 name, password, focusId);
1149 }
1150 if (mFindDialog != null && mFindDialog.isShowing()) {
1151 mFindDialog.onConfigurationChanged(newConfig);
1152 }
1153 }
1154
1155 @Override public void onLowMemory() {
1156 super.onLowMemory();
1157 mTabControl.freeMemory();
1158 }
1159
Mike Reed7bfa63b2009-05-28 11:08:32 -04001160 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001161 if ((!mActivityInPause && !mPageStarted) ||
1162 (mActivityInPause && mPageStarted)) {
1163 CookieSyncManager.getInstance().startSync();
1164 WebView w = mTabControl.getCurrentWebView();
1165 if (w != null) {
1166 w.resumeTimers();
1167 }
1168 return true;
1169 } else {
1170 return false;
1171 }
1172 }
1173
Mike Reed7bfa63b2009-05-28 11:08:32 -04001174 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001175 if (mActivityInPause && !mPageStarted) {
1176 CookieSyncManager.getInstance().stopSync();
1177 WebView w = mTabControl.getCurrentWebView();
1178 if (w != null) {
1179 w.pauseTimers();
1180 }
1181 return true;
1182 } else {
1183 return false;
1184 }
1185 }
1186
Leon Scroggins1f005d32009-08-10 17:36:42 -04001187 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001188 /*
1189 * This function is called when we are launching for the first time. We
1190 * are waiting for the login credentials before loading Google home
1191 * pages. This way the user will be logged in straight away.
1192 */
1193 private void waitForCredentials() {
1194 // Show a toast
1195 mCredsDlg = new ProgressDialog(this);
1196 mCredsDlg.setIndeterminate(true);
1197 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1198 // If the user cancels the operation, then cancel the Google
1199 // Credentials request.
1200 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1201 mCredsDlg.show();
1202
1203 // We set a timeout for the retrieval of credentials in onResume()
1204 // as that is when we have freed up some CPU time to get
1205 // the login credentials.
1206 }
1207
1208 /*
1209 * If we have received the credentials or we have timed out and we are
1210 * showing the credentials dialog, then it is time to move on.
1211 */
1212 private void resumeAfterCredentials() {
1213 if (mCredsDlg == null) {
1214 return;
1215 }
1216
1217 // Clear the toast
1218 if (mCredsDlg.isShowing()) {
1219 mCredsDlg.dismiss();
1220 }
1221 mCredsDlg = null;
1222
1223 // Clear any pending timeout
1224 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1225
1226 // Load the page
1227 WebView w = mTabControl.getCurrentWebView();
1228 if (w != null) {
1229 w.loadUrl(mSettings.getHomePage());
1230 }
1231
1232 // Update the settings, need to do this last as it can take a moment
1233 // to persist the settings. In the mean time we could be loading
1234 // content.
1235 mSettings.setLoginInitialized(this);
1236 }
1237
1238 // Open the icon database and retain all the icons for visited sites.
1239 private void retainIconsOnStartup() {
1240 final WebIconDatabase db = WebIconDatabase.getInstance();
1241 db.open(getDir("icons", 0).getPath());
1242 try {
1243 Cursor c = Browser.getAllBookmarks(mResolver);
1244 if (!c.moveToFirst()) {
1245 c.deactivate();
1246 return;
1247 }
1248 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1249 do {
1250 String url = c.getString(urlIndex);
1251 db.retainIconForPageUrl(url);
1252 } while (c.moveToNext());
1253 c.deactivate();
1254 } catch (IllegalStateException e) {
1255 Log.e(LOGTAG, "retainIconsOnStartup", e);
1256 }
1257 }
1258
1259 // Helper method for getting the top window.
1260 WebView getTopWindow() {
1261 return mTabControl.getCurrentTopWebView();
1262 }
1263
1264 @Override
1265 public boolean onCreateOptionsMenu(Menu menu) {
1266 super.onCreateOptionsMenu(menu);
1267
1268 MenuInflater inflater = getMenuInflater();
1269 inflater.inflate(R.menu.browser, menu);
1270 mMenu = menu;
1271 updateInLoadMenuItems();
1272 return true;
1273 }
1274
1275 /**
1276 * As the menu can be open when loading state changes
1277 * we must manually update the state of the stop/reload menu
1278 * item
1279 */
1280 private void updateInLoadMenuItems() {
1281 if (mMenu == null) {
1282 return;
1283 }
1284 MenuItem src = mInLoad ?
1285 mMenu.findItem(R.id.stop_menu_id):
1286 mMenu.findItem(R.id.reload_menu_id);
1287 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1288 dest.setIcon(src.getIcon());
1289 dest.setTitle(src.getTitle());
1290 }
1291
1292 @Override
1293 public boolean onContextItemSelected(MenuItem item) {
1294 // chording is not an issue with context menus, but we use the same
1295 // options selector, so set mCanChord to true so we can access them.
1296 mCanChord = true;
1297 int id = item.getItemId();
1298 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001299 if (null == webView) {
1300 return false;
1301 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001302 final HashMap hrefMap = new HashMap();
1303 hrefMap.put("webview", webView);
1304 final Message msg = mHandler.obtainMessage(
1305 FOCUS_NODE_HREF, id, 0, hrefMap);
1306 switch (id) {
1307 // -- Browser context menu
1308 case R.id.open_context_menu_id:
1309 case R.id.open_newtab_context_menu_id:
1310 case R.id.bookmark_context_menu_id:
1311 case R.id.save_link_context_menu_id:
1312 case R.id.share_link_context_menu_id:
1313 case R.id.copy_link_context_menu_id:
1314 webView.requestFocusNodeHref(msg);
1315 break;
1316
1317 default:
1318 // For other context menus
1319 return onOptionsItemSelected(item);
1320 }
1321 mCanChord = false;
1322 return true;
1323 }
1324
1325 private Bundle createGoogleSearchSourceBundle(String source) {
1326 Bundle bundle = new Bundle();
1327 bundle.putString(SearchManager.SOURCE, source);
1328 return bundle;
1329 }
1330
1331 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001332 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001333 */
1334 @Override
1335 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001336 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001337 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001338 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001339 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001340 return true;
1341 }
1342
1343 @Override
1344 public void startSearch(String initialQuery, boolean selectInitialQuery,
1345 Bundle appSearchData, boolean globalSearch) {
1346 if (appSearchData == null) {
1347 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1348 }
1349 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1350 }
1351
Leon Scroggins1f005d32009-08-10 17:36:42 -04001352 /**
1353 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1354 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001355 * @param index Index of the tab to change to, as defined by
1356 * mTabControl.getTabIndex(Tab t).
1357 * @return boolean True if we successfully switched to a different tab. If
1358 * the indexth tab is null, or if that tab is the same as
1359 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001360 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001361 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001362 TabControl.Tab tab = mTabControl.getTab(index);
1363 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1364 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001365 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001366 }
1367 if (currentTab != null) {
1368 // currentTab may be null if it was just removed. In that case,
1369 // we do not need to remove it
1370 removeTabFromContentView(currentTab);
1371 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001372 mTabControl.setCurrentTab(tab);
1373 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001374 resetTitleIconAndProgress();
1375 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001376 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001377 }
1378
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001379 /* package */ TabControl.Tab openTabToHomePage() {
1380 return openTabAndShow(mSettings.getHomePage(), false, null);
1381 }
1382
Leon Scroggins1f005d32009-08-10 17:36:42 -04001383 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001384 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001385 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001386 // This is the last tab. Open a new one, with the home
1387 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001388 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001389 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001390 return;
1391 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001392 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001393 int indexToShow = -1;
1394 if (parent != null) {
1395 indexToShow = mTabControl.getTabIndex(parent);
1396 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001397 final int currentIndex = mTabControl.getCurrentIndex();
1398 // Try to move to the tab to the right
1399 indexToShow = currentIndex + 1;
1400 if (indexToShow > mTabControl.getTabCount() - 1) {
1401 // Try to move to the tab to the left
1402 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001403 }
1404 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001405 if (switchToTab(indexToShow)) {
1406 // Close window
1407 closeTab(current);
1408 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001409 }
1410
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001411 private ActiveTabsPage mActiveTabsPage;
1412
1413 /**
1414 * Remove the active tabs page.
1415 * @param needToAttach If true, the active tabs page did not attach a tab
1416 * to the content view, so we need to do that here.
1417 */
1418 /* package */ void removeActiveTabPage(boolean needToAttach) {
1419 mContentView.removeView(mActiveTabsPage);
1420 mActiveTabsPage = null;
1421 mMenuState = R.id.MAIN_MENU;
1422 if (needToAttach) {
1423 attachTabToContentView(mTabControl.getCurrentTab());
1424 }
1425 getTopWindow().requestFocus();
1426 }
1427
The Android Open Source Project0c908882009-03-03 19:32:16 -08001428 @Override
1429 public boolean onOptionsItemSelected(MenuItem item) {
1430 if (!mCanChord) {
1431 // The user has already fired a shortcut with this hold down of the
1432 // menu key.
1433 return false;
1434 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001435 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001436 return false;
1437 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001438 if (mMenuIsDown) {
1439 // The shortcut action consumes the MENU. Even if it is still down,
1440 // it won't trigger the next shortcut action. In the case of the
1441 // shortcut action triggering a new activity, like Bookmarks, we
1442 // won't get onKeyUp for MENU. So it is important to reset it here.
1443 mMenuIsDown = false;
1444 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001445 switch (item.getItemId()) {
1446 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001447 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001448 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001449 break;
1450
Leon Scroggins64b80f32009-08-07 12:03:34 -04001451 case R.id.goto_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001452 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001453 break;
1454
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001455 case R.id.active_tabs_menu_id:
1456 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1457 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001458 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001459 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1460 mActiveTabsPage.requestFocus();
1461 mMenuState = EMPTY_MENU;
1462 break;
1463
Leon Scroggins1f005d32009-08-10 17:36:42 -04001464 case R.id.add_bookmark_menu_id:
1465 Intent i = new Intent(BrowserActivity.this,
1466 AddBookmarkPage.class);
1467 WebView w = getTopWindow();
1468 i.putExtra("url", w.getUrl());
1469 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001470 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001471 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001472 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001473 break;
1474
1475 case R.id.stop_reload_menu_id:
1476 if (mInLoad) {
1477 stopLoading();
1478 } else {
1479 getTopWindow().reload();
1480 }
1481 break;
1482
1483 case R.id.back_menu_id:
1484 getTopWindow().goBack();
1485 break;
1486
1487 case R.id.forward_menu_id:
1488 getTopWindow().goForward();
1489 break;
1490
1491 case R.id.close_menu_id:
1492 // Close the subwindow if it exists.
1493 if (mTabControl.getCurrentSubWindow() != null) {
1494 dismissSubWindow(mTabControl.getCurrentTab());
1495 break;
1496 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001497 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001498 break;
1499
1500 case R.id.homepage_menu_id:
1501 TabControl.Tab current = mTabControl.getCurrentTab();
1502 if (current != null) {
1503 dismissSubWindow(current);
1504 current.getWebView().loadUrl(mSettings.getHomePage());
1505 }
1506 break;
1507
1508 case R.id.preferences_menu_id:
1509 Intent intent = new Intent(this,
1510 BrowserPreferencesPage.class);
1511 startActivityForResult(intent, PREFERENCES_PAGE);
1512 break;
1513
1514 case R.id.find_menu_id:
1515 if (null == mFindDialog) {
1516 mFindDialog = new FindDialog(this);
1517 }
1518 mFindDialog.setWebView(getTopWindow());
1519 mFindDialog.show();
1520 mMenuState = EMPTY_MENU;
1521 break;
1522
1523 case R.id.select_text_id:
1524 getTopWindow().emulateShiftHeld();
1525 break;
1526 case R.id.page_info_menu_id:
1527 showPageInfo(mTabControl.getCurrentTab(), false);
1528 break;
1529
1530 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001531 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001532 break;
1533
1534 case R.id.share_page_menu_id:
1535 Browser.sendString(this, getTopWindow().getUrl());
1536 break;
1537
1538 case R.id.dump_nav_menu_id:
1539 getTopWindow().debugDump();
1540 break;
1541
1542 case R.id.zoom_in_menu_id:
1543 getTopWindow().zoomIn();
1544 break;
1545
1546 case R.id.zoom_out_menu_id:
1547 getTopWindow().zoomOut();
1548 break;
1549
1550 case R.id.view_downloads_menu_id:
1551 viewDownloads(null);
1552 break;
1553
The Android Open Source Project0c908882009-03-03 19:32:16 -08001554 case R.id.window_one_menu_id:
1555 case R.id.window_two_menu_id:
1556 case R.id.window_three_menu_id:
1557 case R.id.window_four_menu_id:
1558 case R.id.window_five_menu_id:
1559 case R.id.window_six_menu_id:
1560 case R.id.window_seven_menu_id:
1561 case R.id.window_eight_menu_id:
1562 {
1563 int menuid = item.getItemId();
1564 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1565 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1566 TabControl.Tab desiredTab = mTabControl.getTab(id);
1567 if (desiredTab != null &&
1568 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001569 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001570 }
1571 break;
1572 }
1573 }
1574 }
1575 break;
1576
1577 default:
1578 if (!super.onOptionsItemSelected(item)) {
1579 return false;
1580 }
1581 // Otherwise fall through.
1582 }
1583 mCanChord = false;
1584 return true;
1585 }
1586
1587 public void closeFind() {
1588 mMenuState = R.id.MAIN_MENU;
1589 }
1590
1591 @Override public boolean onPrepareOptionsMenu(Menu menu)
1592 {
1593 // This happens when the user begins to hold down the menu key, so
1594 // allow them to chord to get a shortcut.
1595 mCanChord = true;
1596 // Note: setVisible will decide whether an item is visible; while
1597 // setEnabled() will decide whether an item is enabled, which also means
1598 // whether the matching shortcut key will function.
1599 super.onPrepareOptionsMenu(menu);
1600 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001601 case EMPTY_MENU:
1602 if (mCurrentMenuState != mMenuState) {
1603 menu.setGroupVisible(R.id.MAIN_MENU, false);
1604 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1605 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001606 }
1607 break;
1608 default:
1609 if (mCurrentMenuState != mMenuState) {
1610 menu.setGroupVisible(R.id.MAIN_MENU, true);
1611 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1612 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001613 }
1614 final WebView w = getTopWindow();
1615 boolean canGoBack = false;
1616 boolean canGoForward = false;
1617 boolean isHome = false;
1618 if (w != null) {
1619 canGoBack = w.canGoBack();
1620 canGoForward = w.canGoForward();
1621 isHome = mSettings.getHomePage().equals(w.getUrl());
1622 }
1623 final MenuItem back = menu.findItem(R.id.back_menu_id);
1624 back.setEnabled(canGoBack);
1625
1626 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1627 home.setEnabled(!isHome);
1628
1629 menu.findItem(R.id.forward_menu_id)
1630 .setEnabled(canGoForward);
1631
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001632 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1633 mTabControl.getTabCount() < TabControl.MAX_TABS);
1634
The Android Open Source Project0c908882009-03-03 19:32:16 -08001635 // decide whether to show the share link option
1636 PackageManager pm = getPackageManager();
1637 Intent send = new Intent(Intent.ACTION_SEND);
1638 send.setType("text/plain");
1639 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1640 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1641
The Android Open Source Project0c908882009-03-03 19:32:16 -08001642 boolean isNavDump = mSettings.isNavDump();
1643 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1644 nav.setVisible(isNavDump);
1645 nav.setEnabled(isNavDump);
1646 break;
1647 }
1648 mCurrentMenuState = mMenuState;
1649 return true;
1650 }
1651
1652 @Override
1653 public void onCreateContextMenu(ContextMenu menu, View v,
1654 ContextMenuInfo menuInfo) {
1655 WebView webview = (WebView) v;
1656 WebView.HitTestResult result = webview.getHitTestResult();
1657 if (result == null) {
1658 return;
1659 }
1660
1661 int type = result.getType();
1662 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1663 Log.w(LOGTAG,
1664 "We should not show context menu when nothing is touched");
1665 return;
1666 }
1667 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1668 // let TextView handles context menu
1669 return;
1670 }
1671
1672 // Note, http://b/issue?id=1106666 is requesting that
1673 // an inflated menu can be used again. This is not available
1674 // yet, so inflate each time (yuk!)
1675 MenuInflater inflater = getMenuInflater();
1676 inflater.inflate(R.menu.browsercontext, menu);
1677
1678 // Show the correct menu group
1679 String extra = result.getExtra();
1680 menu.setGroupVisible(R.id.PHONE_MENU,
1681 type == WebView.HitTestResult.PHONE_TYPE);
1682 menu.setGroupVisible(R.id.EMAIL_MENU,
1683 type == WebView.HitTestResult.EMAIL_TYPE);
1684 menu.setGroupVisible(R.id.GEO_MENU,
1685 type == WebView.HitTestResult.GEO_TYPE);
1686 menu.setGroupVisible(R.id.IMAGE_MENU,
1687 type == WebView.HitTestResult.IMAGE_TYPE
1688 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1689 menu.setGroupVisible(R.id.ANCHOR_MENU,
1690 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1691 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1692
1693 // Setup custom handling depending on the type
1694 switch (type) {
1695 case WebView.HitTestResult.PHONE_TYPE:
1696 menu.setHeaderTitle(Uri.decode(extra));
1697 menu.findItem(R.id.dial_context_menu_id).setIntent(
1698 new Intent(Intent.ACTION_VIEW, Uri
1699 .parse(WebView.SCHEME_TEL + extra)));
1700 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1701 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1702 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1703 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1704 addIntent);
1705 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1706 new Copy(extra));
1707 break;
1708
1709 case WebView.HitTestResult.EMAIL_TYPE:
1710 menu.setHeaderTitle(extra);
1711 menu.findItem(R.id.email_context_menu_id).setIntent(
1712 new Intent(Intent.ACTION_VIEW, Uri
1713 .parse(WebView.SCHEME_MAILTO + extra)));
1714 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1715 new Copy(extra));
1716 break;
1717
1718 case WebView.HitTestResult.GEO_TYPE:
1719 menu.setHeaderTitle(extra);
1720 menu.findItem(R.id.map_context_menu_id).setIntent(
1721 new Intent(Intent.ACTION_VIEW, Uri
1722 .parse(WebView.SCHEME_GEO
1723 + URLEncoder.encode(extra))));
1724 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1725 new Copy(extra));
1726 break;
1727
1728 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1729 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1730 TextView titleView = (TextView) LayoutInflater.from(this)
1731 .inflate(android.R.layout.browser_link_context_header,
1732 null);
1733 titleView.setText(extra);
1734 menu.setHeaderView(titleView);
1735 // decide whether to show the open link in new tab option
1736 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1737 mTabControl.getTabCount() < TabControl.MAX_TABS);
1738 PackageManager pm = getPackageManager();
1739 Intent send = new Intent(Intent.ACTION_SEND);
1740 send.setType("text/plain");
1741 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1742 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1743 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1744 break;
1745 }
1746 // otherwise fall through to handle image part
1747 case WebView.HitTestResult.IMAGE_TYPE:
1748 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1749 menu.setHeaderTitle(extra);
1750 }
1751 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1752 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1753 menu.findItem(R.id.download_context_menu_id).
1754 setOnMenuItemClickListener(new Download(extra));
1755 break;
1756
1757 default:
1758 Log.w(LOGTAG, "We should not get here.");
1759 break;
1760 }
1761 }
1762
The Android Open Source Project0c908882009-03-03 19:32:16 -08001763 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001764 // this should only be called for the current tab.
The Android Open Source Project0c908882009-03-03 19:32:16 -08001765 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001766 // Attach the container that contains the main WebView and any other UI
1767 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001768 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001769
1770 if (mShouldShowErrorConsole) {
1771 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1772 if (errorConsole.numberOfErrors() == 0) {
1773 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1774 } else {
1775 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1776 }
1777
1778 mErrorConsoleContainer.addView(errorConsole,
1779 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1780 ViewGroup.LayoutParams.WRAP_CONTENT));
1781 }
1782
Grace Klobac928c302009-09-17 11:51:21 -07001783 setLockIconType(t.getLockIconType());
1784 setPrevLockType(t.getPrevLockIconType());
1785
1786 // this is to match the code in removeTabFromContentView()
1787 if (!mPageStarted && t.getTopWindow().getProgress() < 100) {
1788 mPageStarted = true;
Grace Klobaeb6eef42009-09-15 17:56:32 -07001789 }
1790
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001791 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001792 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001793 // Request focus on the top window.
1794 t.getTopWindow().requestFocus();
1795 }
1796
1797 // Attach a sub window to the main WebView of the given tab.
1798 private void attachSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001799 t.attachSubWindow(mContentView);
1800 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001801 }
1802
1803 // Remove the given tab from the content view.
1804 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001805 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001806 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001807
1808 if (mTabControl.getCurrentErrorConsole(false) != null) {
1809 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1810 }
1811
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001812 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001813 if (view != null) {
1814 view.setEmbeddedTitleBar(null);
1815 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001816
Grace Klobac928c302009-09-17 11:51:21 -07001817 // unlike attachTabToContentView(), removeTabFromContentView() can be
1818 // called for the non-current tab. Need to add the check.
Grace Klobaeb6eef42009-09-15 17:56:32 -07001819 if (t == mTabControl.getCurrentTab()) {
1820 t.setLockIconType(getLockIconType());
1821 t.setPrevLockIconType(getPrevLockType());
Grace Klobac928c302009-09-17 11:51:21 -07001822
1823 // this is not a perfect solution. But currently there is one
1824 // WebViewClient for all the WebView. if user switches from an
1825 // in-load window to an already loaded window, mPageStarted will not
1826 // be set to false. If user leaves the Browser, pauseWebViewTimers()
1827 // won't do anything and leaves the timer running even Browser is in
1828 // the background.
1829 if (mPageStarted) {
1830 mPageStarted = false;
1831 }
Grace Klobaeb6eef42009-09-15 17:56:32 -07001832 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001833 }
1834
1835 // Remove the sub window if it exists. Also called by TabControl when the
1836 // user clicks the 'X' to dismiss a sub window.
1837 /* package */ void dismissSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001838 t.removeSubWindow(mContentView);
1839 // Tell the TabControl to dismiss the subwindow. This will destroy
1840 // the WebView.
1841 mTabControl.dismissSubWindow(t);
1842 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001843 }
1844
Leon Scroggins1f005d32009-08-10 17:36:42 -04001845 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001846 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001847 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1848 String appId) {
1849 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001850 }
1851
1852 // This method does a ton of stuff. It will attempt to create a new tab
1853 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001854 // url isn't null, it will load the given url.
1855 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001856 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001857 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1858 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1859 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001860 final TabControl.Tab tab = mTabControl.createNewTab(
1861 closeOnExit, appId, urlData.mUrl);
1862 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001863 // If the last tab was removed from the active tabs page, currentTab
1864 // will be null.
1865 if (currentTab != null) {
1866 removeTabFromContentView(currentTab);
1867 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001868 // We must set the new tab as the current tab to reflect the old
1869 // animation behavior.
1870 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001871 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001872 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001873 urlData.loadIn(webview);
1874 }
1875 return tab;
1876 } else {
1877 // Get rid of the subwindow if it exists
1878 dismissSubWindow(currentTab);
1879 if (!urlData.isEmpty()) {
1880 // Load the given url.
1881 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001882 }
1883 }
Grace Klobac9181842009-04-14 08:53:22 -07001884 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001885 }
1886
Grace Klobac9181842009-04-14 08:53:22 -07001887 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001888 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001889 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001890 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001891 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001892 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001893 }
Grace Klobac9181842009-04-14 08:53:22 -07001894 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001895 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001896 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001897 }
1898 }
1899
1900 private class Copy implements OnMenuItemClickListener {
1901 private CharSequence mText;
1902
1903 public boolean onMenuItemClick(MenuItem item) {
1904 copy(mText);
1905 return true;
1906 }
1907
1908 public Copy(CharSequence toCopy) {
1909 mText = toCopy;
1910 }
1911 }
1912
1913 private class Download implements OnMenuItemClickListener {
1914 private String mText;
1915
1916 public boolean onMenuItemClick(MenuItem item) {
1917 onDownloadStartNoStream(mText, null, null, null, -1);
1918 return true;
1919 }
1920
1921 public Download(String toDownload) {
1922 mText = toDownload;
1923 }
1924 }
1925
1926 private void copy(CharSequence text) {
1927 try {
1928 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1929 if (clip != null) {
1930 clip.setClipboardText(text);
1931 }
1932 } catch (android.os.RemoteException e) {
1933 Log.e(LOGTAG, "Copy failed", e);
1934 }
1935 }
1936
1937 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001938 * Resets the browser title-view to whatever it must be
1939 * (for example, if we had a loading error)
1940 * When we have a new page, we call resetTitle, when we
1941 * have to reset the titlebar to whatever it used to be
1942 * (for example, if the user chose to stop loading), we
1943 * call resetTitleAndRevertLockIcon.
1944 */
1945 /* package */ void resetTitleAndRevertLockIcon() {
1946 revertLockIcon();
1947 resetTitleIconAndProgress();
1948 }
1949
1950 /**
1951 * Reset the title, favicon, and progress.
1952 */
1953 private void resetTitleIconAndProgress() {
1954 WebView current = mTabControl.getCurrentWebView();
1955 if (current == null) {
1956 return;
1957 }
1958 resetTitleAndIcon(current);
1959 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001960 mWebChromeClient.onProgressChanged(current, progress);
1961 }
1962
1963 // Reset the title and the icon based on the given item.
1964 private void resetTitleAndIcon(WebView view) {
1965 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1966 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001967 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001968 setFavicon(item.getFavicon());
1969 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001970 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001971 setFavicon(null);
1972 }
1973 }
1974
1975 /**
1976 * Sets a title composed of the URL and the title string.
1977 * @param url The URL of the site being loaded.
1978 * @param title The title of the site being loaded.
1979 */
Leon Scroggins68579392009-09-15 15:31:54 -04001980 private void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001981 mUrl = url;
1982 mTitle = title;
1983
Leon Scroggins68579392009-09-15 15:31:54 -04001984 mTitleBar.setTitleAndUrl(title, url);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001985 if (mFakeTitleBar != null) {
1986 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001987 }
1988 }
1989
1990 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001991 * @param url The URL to build a title version of the URL from.
1992 * @return The title version of the URL or null if fails.
1993 * The title version of the URL can be either the URL hostname,
1994 * or the hostname with an "https://" prefix (for secure URLs),
1995 * or an empty string if, for example, the URL in question is a
1996 * file:// URL with no hostname.
1997 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001998 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001999 String titleUrl = null;
2000
2001 if (url != null) {
2002 try {
2003 // parse the url string
2004 URL urlObj = new URL(url);
2005 if (urlObj != null) {
2006 titleUrl = "";
2007
2008 String protocol = urlObj.getProtocol();
2009 String host = urlObj.getHost();
2010
2011 if (host != null && 0 < host.length()) {
2012 titleUrl = host;
2013 if (protocol != null) {
2014 // if a secure site, add an "https://" prefix!
2015 if (protocol.equalsIgnoreCase("https")) {
2016 titleUrl = protocol + "://" + host;
2017 }
2018 }
2019 }
2020 }
2021 } catch (MalformedURLException e) {}
2022 }
2023
2024 return titleUrl;
2025 }
2026
2027 // Set the favicon in the title bar.
2028 private void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002029 mTitleBar.setFavicon(icon);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002030 if (mFakeTitleBar != null) {
2031 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002032 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002033 }
2034
2035 /**
2036 * Saves the current lock-icon state before resetting
2037 * the lock icon. If we have an error, we may need to
2038 * roll back to the previous state.
2039 */
2040 private void saveLockIcon() {
2041 mPrevLockType = mLockIconType;
2042 }
2043
2044 /**
2045 * Reverts the lock-icon state to the last saved state,
2046 * for example, if we had an error, and need to cancel
2047 * the load.
2048 */
2049 private void revertLockIcon() {
2050 mLockIconType = mPrevLockType;
2051
Dave Bort31a6d1c2009-04-13 15:56:49 -07002052 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002053 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2054 " revert lock icon to " + mLockIconType);
2055 }
2056
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002057 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002058 }
2059
Leon Scroggins1f005d32009-08-10 17:36:42 -04002060 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002061 * Close the tab, remove its associated title bar, and adjust mTabControl's
2062 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002063 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002064 /* package */ void closeTab(TabControl.Tab t) {
2065 int currentIndex = mTabControl.getCurrentIndex();
2066 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002067 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002068 if (currentIndex >= removeIndex && currentIndex != 0) {
2069 currentIndex--;
2070 }
2071 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
The Android Open Source Project0c908882009-03-03 19:32:16 -08002072 }
2073
2074 private void goBackOnePageOrQuit() {
2075 TabControl.Tab current = mTabControl.getCurrentTab();
2076 if (current == null) {
2077 /*
2078 * Instead of finishing the activity, simply push this to the back
2079 * of the stack and let ActivityManager to choose the foreground
2080 * activity. As BrowserActivity is singleTask, it will be always the
2081 * root of the task. So we can use either true or false for
2082 * moveTaskToBack().
2083 */
2084 moveTaskToBack(true);
2085 }
2086 WebView w = current.getWebView();
2087 if (w.canGoBack()) {
2088 w.goBack();
2089 } else {
2090 // Check to see if we are closing a window that was created by
2091 // another window. If so, we switch back to that window.
2092 TabControl.Tab parent = current.getParentTab();
2093 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002094 switchToTab(mTabControl.getTabIndex(parent));
2095 // Now we close the other tab
2096 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002097 } else {
2098 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002099 // force mPageStarted to be false as we are going to either
2100 // finish the activity or remove the tab. This will ensure
2101 // pauseWebView() taking action.
2102 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002103 if (mTabControl.getTabCount() == 1) {
2104 finish();
2105 return;
2106 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002107 // call pauseWebViewTimers() now, we won't be able to call
2108 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002109 // Temporarily change mActivityInPause to be true as
2110 // pauseWebViewTimers() will do nothing if mActivityInPause
2111 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002112 boolean savedState = mActivityInPause;
2113 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002114 Log.e(LOGTAG, "BrowserActivity is already paused "
2115 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002116 }
2117 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002118 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002119 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002120 removeTabFromContentView(current);
2121 mTabControl.removeTab(current);
2122 }
2123 /*
2124 * Instead of finishing the activity, simply push this to the back
2125 * of the stack and let ActivityManager to choose the foreground
2126 * activity. As BrowserActivity is singleTask, it will be always the
2127 * root of the task. So we can use either true or false for
2128 * moveTaskToBack().
2129 */
2130 moveTaskToBack(true);
2131 }
2132 }
2133 }
2134
Grace Kloba5942df02009-09-18 11:48:29 -07002135 @Override
2136 public boolean onKeyDown(int keyCode, KeyEvent event) {
2137 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2138 // still down, we don't want to trigger the search. Pretend to consume
2139 // the key and do nothing.
2140 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002141
Grace Kloba5942df02009-09-18 11:48:29 -07002142 switch(keyCode) {
2143 case KeyEvent.KEYCODE_MENU:
2144 mMenuIsDown = true;
2145 break;
2146 case KeyEvent.KEYCODE_SPACE:
2147 // Browser's hidden shortcut key. Don't call super so that
2148 // search won't be triggered.
2149 return true;
2150 case KeyEvent.KEYCODE_BACK:
2151 if (event.getRepeatCount() == 0) {
2152 event.startTracking();
2153 return true;
2154 } else if (mCustomView == null && mActiveTabsPage == null
2155 && event.isLongPress()) {
2156 bookmarksOrHistoryPicker(true);
2157 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002158 }
Grace Kloba5942df02009-09-18 11:48:29 -07002159 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002160 }
Grace Kloba5942df02009-09-18 11:48:29 -07002161 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002162 }
2163
Grace Kloba5942df02009-09-18 11:48:29 -07002164 @Override
2165 public boolean onKeyUp(int keyCode, KeyEvent event) {
2166 switch(keyCode) {
2167 case KeyEvent.KEYCODE_MENU:
2168 mMenuIsDown = false;
2169 break;
2170 case KeyEvent.KEYCODE_SPACE:
2171 if (event.isShiftPressed()) {
2172 getTopWindow().pageUp(false);
2173 } else {
2174 getTopWindow().pageDown(false);
2175 }
2176 return true;
2177 case KeyEvent.KEYCODE_BACK:
2178 if (event.isTracking() && !event.isCanceled()) {
2179 if (mCustomView != null) {
2180 // if a custom view is showing, hide it
2181 mWebChromeClient.onHideCustomView();
2182 } else if (mActiveTabsPage != null) {
2183 // if tab page is showing, hide it
2184 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002185 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002186 WebView subwindow = mTabControl.getCurrentSubWindow();
2187 if (subwindow != null) {
2188 if (subwindow.canGoBack()) {
2189 subwindow.goBack();
2190 } else {
2191 dismissSubWindow(mTabControl.getCurrentTab());
2192 }
2193 } else {
2194 goBackOnePageOrQuit();
2195 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002196 }
Grace Kloba5942df02009-09-18 11:48:29 -07002197 return true;
2198 }
2199 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002200 }
Grace Kloba5942df02009-09-18 11:48:29 -07002201 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002202 }
2203
Leon Scroggins68579392009-09-15 15:31:54 -04002204 /* package */ void stopLoading() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002205 resetTitleAndRevertLockIcon();
2206 WebView w = getTopWindow();
2207 w.stopLoading();
2208 mWebViewClient.onPageFinished(w, w.getUrl());
2209
2210 cancelStopToast();
2211 mStopToast = Toast
2212 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2213 mStopToast.show();
2214 }
2215
2216 private void cancelStopToast() {
2217 if (mStopToast != null) {
2218 mStopToast.cancel();
2219 mStopToast = null;
2220 }
2221 }
2222
2223 // called by a non-UI thread to post the message
2224 public void postMessage(int what, int arg1, int arg2, Object obj) {
2225 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2226 }
2227
2228 // public message ids
2229 public final static int LOAD_URL = 1001;
2230 public final static int STOP_LOAD = 1002;
2231
2232 // Message Ids
2233 private static final int FOCUS_NODE_HREF = 102;
2234 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002235 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002236
2237 // Private handler for handling javascript and saving passwords
2238 private Handler mHandler = new Handler() {
2239
2240 public void handleMessage(Message msg) {
2241 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002242 case FOCUS_NODE_HREF:
2243 String url = (String) msg.getData().get("url");
2244 if (url == null || url.length() == 0) {
2245 break;
2246 }
2247 HashMap focusNodeMap = (HashMap) msg.obj;
2248 WebView view = (WebView) focusNodeMap.get("webview");
2249 // Only apply the action if the top window did not change.
2250 if (getTopWindow() != view) {
2251 break;
2252 }
2253 switch (msg.arg1) {
2254 case R.id.open_context_menu_id:
2255 case R.id.view_image_context_menu_id:
2256 loadURL(getTopWindow(), url);
2257 break;
2258 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002259 final TabControl.Tab parent = mTabControl
2260 .getCurrentTab();
2261 final TabControl.Tab newTab = openTab(url);
2262 if (newTab != parent) {
2263 parent.addChildTab(newTab);
2264 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002265 break;
2266 case R.id.bookmark_context_menu_id:
2267 Intent intent = new Intent(BrowserActivity.this,
2268 AddBookmarkPage.class);
2269 intent.putExtra("url", url);
2270 startActivity(intent);
2271 break;
2272 case R.id.share_link_context_menu_id:
2273 Browser.sendString(BrowserActivity.this, url);
2274 break;
2275 case R.id.copy_link_context_menu_id:
2276 copy(url);
2277 break;
2278 case R.id.save_link_context_menu_id:
2279 case R.id.download_context_menu_id:
2280 onDownloadStartNoStream(url, null, null, null, -1);
2281 break;
2282 }
2283 break;
2284
2285 case LOAD_URL:
2286 loadURL(getTopWindow(), (String) msg.obj);
2287 break;
2288
2289 case STOP_LOAD:
2290 stopLoading();
2291 break;
2292
2293 case CANCEL_CREDS_REQUEST:
2294 resumeAfterCredentials();
2295 break;
2296
The Android Open Source Project0c908882009-03-03 19:32:16 -08002297 case RELEASE_WAKELOCK:
2298 if (mWakeLock.isHeld()) {
2299 mWakeLock.release();
2300 }
2301 break;
2302 }
2303 }
2304 };
2305
Leon Scroggins89c6d362009-07-15 16:54:37 -04002306 private void updateScreenshot(WebView view) {
2307 // If this is a bookmarked site, add a screenshot to the database.
2308 // FIXME: When should we update? Every time?
2309 // FIXME: Would like to make sure there is actually something to
2310 // draw, but the API for that (WebViewCore.pictureReady()) is not
2311 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002312 ContentResolver cr = getContentResolver();
2313 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002314 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002315 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002316 boolean succeed = c.moveToFirst();
2317 ContentValues values = null;
2318 while (succeed) {
2319 if (values == null) {
2320 final ByteArrayOutputStream os
2321 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002322 Bitmap bm = createScreenshot(view);
Leon Scroggins89c6d362009-07-15 16:54:37 -04002323 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2324 values = new ContentValues();
2325 values.put(Browser.BookmarkColumns.THUMBNAIL,
2326 os.toByteArray());
2327 }
2328 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2329 c.getInt(0)), values, null, null);
2330 succeed = c.moveToNext();
2331 }
2332 c.close();
2333 }
2334 }
2335
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002336 private Bitmap createScreenshot(WebView view) {
2337 Picture thumbnail = view.capturePicture();
2338 // Keep width and height in sync with BrowserBookmarksPage
2339 // and bookmark_thumb
2340 Bitmap bm = Bitmap.createBitmap(100, 80,
2341 Bitmap.Config.ARGB_4444);
2342 Canvas canvas = new Canvas(bm);
2343 // May need to tweak these values to determine what is the
2344 // best scale factor
2345 canvas.scale(.5f, .5f);
2346 thumbnail.draw(canvas);
2347 return bm;
2348 }
2349
The Android Open Source Project0c908882009-03-03 19:32:16 -08002350 // -------------------------------------------------------------------------
2351 // WebViewClient implementation.
2352 //-------------------------------------------------------------------------
2353
2354 // Use in overrideUrlLoading
2355 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2356 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2357 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2358 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2359
2360 /* package */ WebViewClient getWebViewClient() {
2361 return mWebViewClient;
2362 }
2363
Patrick Scott3918d442009-08-04 13:22:29 -04002364 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002365 if (icon != null) {
2366 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott15525d42009-09-21 13:39:37 -04002367 view.getOriginalUrl(), view.getUrl(), icon);
2368 }
2369 setFavicon(icon);
2370 }
2371
2372 private void updateIcon(String url, Bitmap icon) {
2373 if (icon != null) {
2374 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2375 null, url, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002376 }
2377 setFavicon(icon);
2378 }
2379
2380 private final WebViewClient mWebViewClient = new WebViewClient() {
2381 @Override
2382 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2383 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002384 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002385
2386 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2387 if (errorConsole != null) {
2388 errorConsole.clearErrorMessages();
2389 if (mShouldShowErrorConsole) {
2390 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2391 }
2392 }
2393
The Android Open Source Project0c908882009-03-03 19:32:16 -08002394 // Call updateIcon instead of setFavicon so the bookmark
2395 // database can be updated.
Patrick Scott15525d42009-09-21 13:39:37 -04002396 updateIcon(url, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002397
Grace Kloba4d7880f2009-08-12 09:35:42 -07002398 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002399 String host;
2400 try {
2401 WebAddress uri = new WebAddress(url);
2402 host = uri.mHost;
2403 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002404 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002405 }
2406 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002407 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002408 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002409 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002410 }
2411
2412 // Performance probe
2413 if (false) {
2414 mStart = SystemClock.uptimeMillis();
2415 mProcessStart = Process.getElapsedCpuTime();
2416 long[] sysCpu = new long[7];
2417 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2418 sysCpu, null)) {
2419 mUserStart = sysCpu[0] + sysCpu[1];
2420 mSystemStart = sysCpu[2];
2421 mIdleStart = sysCpu[3];
2422 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2423 }
2424 mUiStart = SystemClock.currentThreadTimeMillis();
2425 }
2426
2427 if (!mPageStarted) {
2428 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002429 // if onResume() has been called, resumeWebViewTimers() does
2430 // nothing.
2431 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002432 }
2433
2434 // reset sync timer to avoid sync starts during loading a page
2435 CookieSyncManager.getInstance().resetSync();
2436
2437 mInLoad = true;
Leon Scroggins184f5e32009-09-21 10:38:24 -04002438 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002439 updateInLoadMenuItems();
2440 if (!mIsNetworkUp) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04002441 createAndShowNetworkDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002442 if (view != null) {
2443 view.setNetworkAvailable(false);
2444 }
2445 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002446 }
2447
2448 @Override
2449 public void onPageFinished(WebView view, String url) {
2450 // Reset the title and icon in case we stopped a provisional
2451 // load.
2452 resetTitleAndIcon(view);
2453
2454 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002455 updateLockIconToLatest();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002456 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002457
The Android Open Source Project0c908882009-03-03 19:32:16 -08002458 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002459 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002460 long[] sysCpu = new long[7];
2461 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2462 sysCpu, null)) {
2463 String uiInfo = "UI thread used "
2464 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2465 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002466 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002467 Log.d(LOGTAG, uiInfo);
2468 }
2469 //The string that gets written to the log
2470 String performanceString = "It took total "
2471 + (SystemClock.uptimeMillis() - mStart)
2472 + " ms clock time to load the page."
2473 + "\nbrowser process used "
2474 + (Process.getElapsedCpuTime() - mProcessStart)
2475 + " ms, user processes used "
2476 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2477 + " ms, kernel used "
2478 + (sysCpu[2] - mSystemStart) * 10
2479 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2480 + " ms and irq took "
2481 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2482 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002483 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002484 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2485 }
2486 if (url != null) {
2487 // strip the url to maintain consistency
2488 String newUrl = new String(url);
2489 if (newUrl.startsWith("http://www.")) {
2490 newUrl = newUrl.substring(11);
2491 } else if (newUrl.startsWith("http://")) {
2492 newUrl = newUrl.substring(7);
2493 } else if (newUrl.startsWith("https://www.")) {
2494 newUrl = newUrl.substring(12);
2495 } else if (newUrl.startsWith("https://")) {
2496 newUrl = newUrl.substring(8);
2497 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002498 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002499 Log.d(LOGTAG, newUrl + " loaded");
2500 }
2501 /*
2502 if (sWhiteList.contains(newUrl)) {
2503 // The string that gets pushed to the statistcs
2504 // service
2505 performanceString = performanceString
2506 + "\nWebpage: "
2507 + newUrl
2508 + "\nCarrier: "
2509 + android.os.SystemProperties
2510 .get("gsm.sim.operator.alpha");
2511 if (mWebView != null
2512 && mWebView.getContext() != null
2513 && mWebView.getContext().getSystemService(
2514 Context.CONNECTIVITY_SERVICE) != null) {
2515 ConnectivityManager cManager =
2516 (ConnectivityManager) mWebView
2517 .getContext().getSystemService(
2518 Context.CONNECTIVITY_SERVICE);
2519 NetworkInfo nInfo = cManager
2520 .getActiveNetworkInfo();
2521 if (nInfo != null) {
2522 performanceString = performanceString
2523 + "\nNetwork Type: "
2524 + nInfo.getType().toString();
2525 }
2526 }
2527 Checkin.logEvent(mResolver,
2528 Checkin.Events.Tag.WEBPAGE_LOAD,
2529 performanceString);
2530 Log.w(LOGTAG, "pushed to the statistics service");
2531 }
2532 */
2533 }
2534 }
2535 }
2536
2537 if (mInTrace) {
2538 mInTrace = false;
2539 Debug.stopMethodTracing();
2540 }
2541
2542 if (mPageStarted) {
2543 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002544 // pauseWebViewTimers() will do nothing and return false if
2545 // onPause() is not called yet.
2546 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002547 if (mWakeLock.isHeld()) {
2548 mHandler.removeMessages(RELEASE_WAKELOCK);
2549 mWakeLock.release();
2550 }
2551 }
2552 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002553 }
2554
2555 // return true if want to hijack the url to let another app to handle it
2556 @Override
2557 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2558 if (url.startsWith(SCHEME_WTAI)) {
2559 // wtai://wp/mc;number
2560 // number=string(phone-number)
2561 if (url.startsWith(SCHEME_WTAI_MC)) {
2562 Intent intent = new Intent(Intent.ACTION_VIEW,
2563 Uri.parse(WebView.SCHEME_TEL +
2564 url.substring(SCHEME_WTAI_MC.length())));
2565 startActivity(intent);
2566 return true;
2567 }
2568 // wtai://wp/sd;dtmf
2569 // dtmf=string(dialstring)
2570 if (url.startsWith(SCHEME_WTAI_SD)) {
2571 // TODO
2572 // only send when there is active voice connection
2573 return false;
2574 }
2575 // wtai://wp/ap;number;name
2576 // number=string(phone-number)
2577 // name=string
2578 if (url.startsWith(SCHEME_WTAI_AP)) {
2579 // TODO
2580 return false;
2581 }
2582 }
2583
Dianne Hackborn99189432009-06-17 18:06:18 -07002584 // The "about:" schemes are internal to the browser; don't
2585 // want these to be dispatched to other apps.
2586 if (url.startsWith("about:")) {
2587 return false;
2588 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002589
Dianne Hackborn99189432009-06-17 18:06:18 -07002590 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002591
Dianne Hackborn99189432009-06-17 18:06:18 -07002592 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002593 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002594 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2595 } catch (URISyntaxException ex) {
2596 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002597 return false;
2598 }
2599
Grace Kloba5b078b52009-06-24 20:23:41 -07002600 // check whether the intent can be resolved. If not, we will see
2601 // whether we can download it from the Market.
2602 if (getPackageManager().resolveActivity(intent, 0) == null) {
2603 String packagename = intent.getPackage();
2604 if (packagename != null) {
2605 intent = new Intent(Intent.ACTION_VIEW, Uri
2606 .parse("market://search?q=pname:" + packagename));
2607 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2608 startActivity(intent);
2609 return true;
2610 } else {
2611 return false;
2612 }
2613 }
2614
Dianne Hackborn99189432009-06-17 18:06:18 -07002615 // sanitize the Intent, ensuring web pages can not bypass browser
2616 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002617 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002618 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002619 try {
2620 if (startActivityIfNeeded(intent, -1)) {
2621 return true;
2622 }
2623 } catch (ActivityNotFoundException ex) {
2624 // ignore the error. If no application can handle the URL,
2625 // eg about:blank, assume the browser can handle it.
2626 }
2627
2628 if (mMenuIsDown) {
2629 openTab(url);
2630 closeOptionsMenu();
2631 return true;
2632 }
2633
2634 return false;
2635 }
2636
2637 /**
2638 * Updates the lock icon. This method is called when we discover another
2639 * resource to be loaded for this page (for example, javascript). While
2640 * we update the icon type, we do not update the lock icon itself until
2641 * we are done loading, it is slightly more secure this way.
2642 */
2643 @Override
2644 public void onLoadResource(WebView view, String url) {
2645 if (url != null && url.length() > 0) {
2646 // It is only if the page claims to be secure
2647 // that we may have to update the lock:
2648 if (mLockIconType == LOCK_ICON_SECURE) {
2649 // If NOT a 'safe' url, change the lock to mixed content!
2650 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2651 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002652 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002653 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2654 " updated lock icon to " + mLockIconType + " due to " + url);
2655 }
2656 }
2657 }
2658 }
2659 }
2660
2661 /**
2662 * Show the dialog, asking the user if they would like to continue after
2663 * an excessive number of HTTP redirects.
2664 */
2665 @Override
2666 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2667 final Message continueMsg) {
2668 new AlertDialog.Builder(BrowserActivity.this)
2669 .setTitle(R.string.browserFrameRedirect)
2670 .setMessage(R.string.browserFrame307Post)
2671 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2672 public void onClick(DialogInterface dialog, int which) {
2673 continueMsg.sendToTarget();
2674 }})
2675 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2676 public void onClick(DialogInterface dialog, int which) {
2677 cancelMsg.sendToTarget();
2678 }})
2679 .setOnCancelListener(new OnCancelListener() {
2680 public void onCancel(DialogInterface dialog) {
2681 cancelMsg.sendToTarget();
2682 }})
2683 .show();
2684 }
2685
Patrick Scott37911c72009-03-24 18:02:58 -07002686 // Container class for the next error dialog that needs to be
2687 // displayed.
2688 class ErrorDialog {
2689 public final int mTitle;
2690 public final String mDescription;
2691 public final int mError;
2692 ErrorDialog(int title, String desc, int error) {
2693 mTitle = title;
2694 mDescription = desc;
2695 mError = error;
2696 }
2697 };
2698
2699 private void processNextError() {
2700 if (mQueuedErrors == null) {
2701 return;
2702 }
2703 // The first one is currently displayed so just remove it.
2704 mQueuedErrors.removeFirst();
2705 if (mQueuedErrors.size() == 0) {
2706 mQueuedErrors = null;
2707 return;
2708 }
2709 showError(mQueuedErrors.getFirst());
2710 }
2711
2712 private DialogInterface.OnDismissListener mDialogListener =
2713 new DialogInterface.OnDismissListener() {
2714 public void onDismiss(DialogInterface d) {
2715 processNextError();
2716 }
2717 };
2718 private LinkedList<ErrorDialog> mQueuedErrors;
2719
2720 private void queueError(int err, String desc) {
2721 if (mQueuedErrors == null) {
2722 mQueuedErrors = new LinkedList<ErrorDialog>();
2723 }
2724 for (ErrorDialog d : mQueuedErrors) {
2725 if (d.mError == err) {
2726 // Already saw a similar error, ignore the new one.
2727 return;
2728 }
2729 }
2730 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002731 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002732 R.string.browserFrameFileErrorLabel :
2733 R.string.browserFrameNetworkErrorLabel,
2734 desc, err);
2735 mQueuedErrors.addLast(errDialog);
2736
2737 // Show the dialog now if the queue was empty.
2738 if (mQueuedErrors.size() == 1) {
2739 showError(errDialog);
2740 }
2741 }
2742
2743 private void showError(ErrorDialog errDialog) {
2744 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2745 .setTitle(errDialog.mTitle)
2746 .setMessage(errDialog.mDescription)
2747 .setPositiveButton(R.string.ok, null)
2748 .create();
2749 d.setOnDismissListener(mDialogListener);
2750 d.show();
2751 }
2752
The Android Open Source Project0c908882009-03-03 19:32:16 -08002753 /**
2754 * Show a dialog informing the user of the network error reported by
2755 * WebCore.
2756 */
2757 @Override
2758 public void onReceivedError(WebView view, int errorCode,
2759 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002760 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2761 errorCode != WebViewClient.ERROR_CONNECT &&
2762 errorCode != WebViewClient.ERROR_BAD_URL &&
2763 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2764 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002765 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002766 }
Patrick Scott37911c72009-03-24 18:02:58 -07002767 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2768 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002769
2770 // We need to reset the title after an error.
2771 resetTitleAndRevertLockIcon();
2772 }
2773
2774 /**
2775 * Check with the user if it is ok to resend POST data as the page they
2776 * are trying to navigate to is the result of a POST.
2777 */
2778 @Override
2779 public void onFormResubmission(WebView view, final Message dontResend,
2780 final Message resend) {
2781 new AlertDialog.Builder(BrowserActivity.this)
2782 .setTitle(R.string.browserFrameFormResubmitLabel)
2783 .setMessage(R.string.browserFrameFormResubmitMessage)
2784 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2785 public void onClick(DialogInterface dialog, int which) {
2786 resend.sendToTarget();
2787 }})
2788 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2789 public void onClick(DialogInterface dialog, int which) {
2790 dontResend.sendToTarget();
2791 }})
2792 .setOnCancelListener(new OnCancelListener() {
2793 public void onCancel(DialogInterface dialog) {
2794 dontResend.sendToTarget();
2795 }})
2796 .show();
2797 }
2798
2799 /**
2800 * Insert the url into the visited history database.
2801 * @param url The url to be inserted.
2802 * @param isReload True if this url is being reloaded.
2803 * FIXME: Not sure what to do when reloading the page.
2804 */
2805 @Override
2806 public void doUpdateVisitedHistory(WebView view, String url,
2807 boolean isReload) {
2808 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2809 return;
2810 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002811 // remove "client" before updating it to the history so that it wont
2812 // show up in the auto-complete list.
2813 int index = url.indexOf("client=ms-");
2814 if (index > 0 && url.contains(".google.")) {
2815 int end = url.indexOf('&', index);
2816 if (end > 0) {
2817 url = url.substring(0, index-1).concat(url.substring(end));
2818 } else {
2819 url = url.substring(0, index-1);
2820 }
2821 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002822 Browser.updateVisitedHistory(mResolver, url, true);
2823 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2824 }
2825
2826 /**
2827 * Displays SSL error(s) dialog to the user.
2828 */
2829 @Override
2830 public void onReceivedSslError(
2831 final WebView view, final SslErrorHandler handler, final SslError error) {
2832
2833 if (mSettings.showSecurityWarnings()) {
2834 final LayoutInflater factory =
2835 LayoutInflater.from(BrowserActivity.this);
2836 final View warningsView =
2837 factory.inflate(R.layout.ssl_warnings, null);
2838 final LinearLayout placeholder =
2839 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2840
2841 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2842 LinearLayout ll = (LinearLayout)factory
2843 .inflate(R.layout.ssl_warning, null);
2844 ((TextView)ll.findViewById(R.id.warning))
2845 .setText(R.string.ssl_untrusted);
2846 placeholder.addView(ll);
2847 }
2848
2849 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2850 LinearLayout ll = (LinearLayout)factory
2851 .inflate(R.layout.ssl_warning, null);
2852 ((TextView)ll.findViewById(R.id.warning))
2853 .setText(R.string.ssl_mismatch);
2854 placeholder.addView(ll);
2855 }
2856
2857 if (error.hasError(SslError.SSL_EXPIRED)) {
2858 LinearLayout ll = (LinearLayout)factory
2859 .inflate(R.layout.ssl_warning, null);
2860 ((TextView)ll.findViewById(R.id.warning))
2861 .setText(R.string.ssl_expired);
2862 placeholder.addView(ll);
2863 }
2864
2865 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2866 LinearLayout ll = (LinearLayout)factory
2867 .inflate(R.layout.ssl_warning, null);
2868 ((TextView)ll.findViewById(R.id.warning))
2869 .setText(R.string.ssl_not_yet_valid);
2870 placeholder.addView(ll);
2871 }
2872
2873 new AlertDialog.Builder(BrowserActivity.this)
2874 .setTitle(R.string.security_warning)
2875 .setIcon(android.R.drawable.ic_dialog_alert)
2876 .setView(warningsView)
2877 .setPositiveButton(R.string.ssl_continue,
2878 new DialogInterface.OnClickListener() {
2879 public void onClick(DialogInterface dialog, int whichButton) {
2880 handler.proceed();
2881 }
2882 })
2883 .setNeutralButton(R.string.view_certificate,
2884 new DialogInterface.OnClickListener() {
2885 public void onClick(DialogInterface dialog, int whichButton) {
2886 showSSLCertificateOnError(view, handler, error);
2887 }
2888 })
2889 .setNegativeButton(R.string.cancel,
2890 new DialogInterface.OnClickListener() {
2891 public void onClick(DialogInterface dialog, int whichButton) {
2892 handler.cancel();
2893 BrowserActivity.this.resetTitleAndRevertLockIcon();
2894 }
2895 })
2896 .setOnCancelListener(
2897 new DialogInterface.OnCancelListener() {
2898 public void onCancel(DialogInterface dialog) {
2899 handler.cancel();
2900 BrowserActivity.this.resetTitleAndRevertLockIcon();
2901 }
2902 })
2903 .show();
2904 } else {
2905 handler.proceed();
2906 }
2907 }
2908
2909 /**
2910 * Handles an HTTP authentication request.
2911 *
2912 * @param handler The authentication handler
2913 * @param host The host
2914 * @param realm The realm
2915 */
2916 @Override
2917 public void onReceivedHttpAuthRequest(WebView view,
2918 final HttpAuthHandler handler, final String host, final String realm) {
2919 String username = null;
2920 String password = null;
2921
2922 boolean reuseHttpAuthUsernamePassword =
2923 handler.useHttpAuthUsernamePassword();
2924
2925 if (reuseHttpAuthUsernamePassword &&
2926 (mTabControl.getCurrentWebView() != null)) {
2927 String[] credentials =
2928 mTabControl.getCurrentWebView()
2929 .getHttpAuthUsernamePassword(host, realm);
2930 if (credentials != null && credentials.length == 2) {
2931 username = credentials[0];
2932 password = credentials[1];
2933 }
2934 }
2935
2936 if (username != null && password != null) {
2937 handler.proceed(username, password);
2938 } else {
2939 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2940 }
2941 }
2942
2943 @Override
2944 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2945 if (mMenuIsDown) {
2946 // only check shortcut key when MENU is held
2947 return getWindow().isShortcutKey(event.getKeyCode(), event);
2948 } else {
2949 return false;
2950 }
2951 }
2952
2953 @Override
2954 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2955 if (view != mTabControl.getCurrentTopWebView()) {
2956 return;
2957 }
2958 if (event.isDown()) {
2959 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2960 } else {
2961 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2962 }
2963 }
2964 };
2965
2966 //--------------------------------------------------------------------------
2967 // WebChromeClient implementation
2968 //--------------------------------------------------------------------------
2969
2970 /* package */ WebChromeClient getWebChromeClient() {
2971 return mWebChromeClient;
2972 }
2973
2974 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2975 // Helper method to create a new tab or sub window.
2976 private void createWindow(final boolean dialog, final Message msg) {
2977 if (dialog) {
2978 mTabControl.createSubWindow();
2979 final TabControl.Tab t = mTabControl.getCurrentTab();
2980 attachSubWindow(t);
2981 WebView.WebViewTransport transport =
2982 (WebView.WebViewTransport) msg.obj;
2983 transport.setWebView(t.getSubWebView());
2984 msg.sendToTarget();
2985 } else {
2986 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04002987 final TabControl.Tab newTab
2988 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07002989 if (newTab != parent) {
2990 parent.addChildTab(newTab);
2991 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002992 WebView.WebViewTransport transport =
2993 (WebView.WebViewTransport) msg.obj;
2994 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04002995 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002996 }
2997 }
2998
2999 @Override
3000 public boolean onCreateWindow(WebView view, final boolean dialog,
3001 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003002 // Short-circuit if we can't create any more tabs or sub windows.
3003 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3004 new AlertDialog.Builder(BrowserActivity.this)
3005 .setTitle(R.string.too_many_subwindows_dialog_title)
3006 .setIcon(android.R.drawable.ic_dialog_alert)
3007 .setMessage(R.string.too_many_subwindows_dialog_message)
3008 .setPositiveButton(R.string.ok, null)
3009 .show();
3010 return false;
3011 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3012 new AlertDialog.Builder(BrowserActivity.this)
3013 .setTitle(R.string.too_many_windows_dialog_title)
3014 .setIcon(android.R.drawable.ic_dialog_alert)
3015 .setMessage(R.string.too_many_windows_dialog_message)
3016 .setPositiveButton(R.string.ok, null)
3017 .show();
3018 return false;
3019 }
3020
3021 // Short-circuit if this was a user gesture.
3022 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003023 createWindow(dialog, resultMsg);
3024 return true;
3025 }
3026
3027 // Allow the popup and create the appropriate window.
3028 final AlertDialog.OnClickListener allowListener =
3029 new AlertDialog.OnClickListener() {
3030 public void onClick(DialogInterface d,
3031 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003032 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003033 }
3034 };
3035
3036 // Block the popup by returning a null WebView.
3037 final AlertDialog.OnClickListener blockListener =
3038 new AlertDialog.OnClickListener() {
3039 public void onClick(DialogInterface d, int which) {
3040 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003041 }
3042 };
3043
3044 // Build a confirmation dialog to display to the user.
3045 final AlertDialog d =
3046 new AlertDialog.Builder(BrowserActivity.this)
3047 .setTitle(R.string.attention)
3048 .setIcon(android.R.drawable.ic_dialog_alert)
3049 .setMessage(R.string.popup_window_attempt)
3050 .setPositiveButton(R.string.allow, allowListener)
3051 .setNegativeButton(R.string.block, blockListener)
3052 .setCancelable(false)
3053 .create();
3054
3055 // Show the confirmation dialog.
3056 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003057 return true;
3058 }
3059
3060 @Override
3061 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003062 final TabControl.Tab current = mTabControl.getCurrentTab();
3063 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003064 if (parent != null) {
3065 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003066 switchToTab(mTabControl.getTabIndex(parent));
3067 // Now we need to close the window
3068 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003069 }
3070 }
3071
3072 @Override
3073 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003074 mTitleBar.setProgress(newProgress);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003075 if (mFakeTitleBar != null) {
3076 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003077 }
3078
3079 if (newProgress == 100) {
3080 // onProgressChanged() is called for sub-frame too while
3081 // onPageFinished() is only called for the main frame. sync
3082 // cookie and cache promptly here.
3083 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003084 if (mInLoad) {
3085 mInLoad = false;
3086 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003087 // If the options menu is open, leave the title bar
3088 if (!mOptionsMenuOpen || !mIconView) {
3089 hideFakeTitleBar();
3090 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003091 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003092 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003093 // onPageFinished may have already been called but a subframe
3094 // is still loading and updating the progress. Reset mInLoad
3095 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003096 mInLoad = true;
3097 updateInLoadMenuItems();
Leon Scroggins184f5e32009-09-21 10:38:24 -04003098 if (!mOptionsMenuOpen || mIconView) {
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003099 // This page has begun to load, so show the title bar
3100 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003101 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003102 }
3103 }
3104
3105 @Override
3106 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003107 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003108
3109 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003110 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003111
3112 if (url == null ||
3113 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3114 return;
3115 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003116 // See if we can find the current url in our history database and
3117 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003118 if (url.startsWith("http://www.")) {
3119 url = url.substring(11);
3120 } else if (url.startsWith("http://")) {
3121 url = url.substring(4);
3122 }
3123 try {
3124 url = "%" + url;
3125 String [] selArgs = new String[] { url };
3126
3127 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3128 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3129 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3130 Browser.HISTORY_PROJECTION, where, selArgs, null);
3131 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003132 // Current implementation of database only has one entry per
3133 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003134 ContentValues map = new ContentValues();
3135 map.put(Browser.BookmarkColumns.TITLE, title);
3136 mResolver.update(Browser.BOOKMARKS_URI, map,
3137 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003138 }
3139 c.close();
3140 } catch (IllegalStateException e) {
3141 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3142 } catch (SQLiteException ex) {
3143 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3144 }
3145 }
3146
3147 @Override
3148 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003149 updateIcon(view, icon);
3150 }
3151
3152 @Override
3153 public void onReceivedTouchIconUrl(WebView view, String url) {
3154 final ContentResolver cr = getContentResolver();
3155 final Cursor c =
3156 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003157 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003158 if (c != null) {
3159 if (c.getCount() > 0) {
3160 new DownloadTouchIcon(cr, c, view).execute(url);
3161 } else {
3162 c.close();
3163 }
3164 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003165 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003166
Andrei Popescuadc008d2009-06-26 14:11:30 +01003167 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003168 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003169 if (mCustomView != null)
3170 return;
3171
3172 // Add the custom view to its container.
3173 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3174 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003175 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003176 // Save the menu state and set it to empty while the custom
3177 // view is showing.
3178 mOldMenuState = mMenuState;
3179 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003180 // Hide the content view.
3181 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003182 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003183 mCustomViewContainer.setVisibility(View.VISIBLE);
3184 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003185 }
3186
3187 @Override
3188 public void onHideCustomView() {
3189 if (mCustomView == null)
3190 return;
3191
Andrei Popescuc9b55562009-07-07 10:51:15 +01003192 // Hide the custom view.
3193 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003194 // Remove the custom view from its container.
3195 mCustomViewContainer.removeView(mCustomView);
3196 mCustomView = null;
3197 // Reset the old menu state.
3198 mMenuState = mOldMenuState;
3199 mOldMenuState = EMPTY_MENU;
3200 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003201 mCustomViewCallback.onCustomViewHidden();
3202 // Show the content view.
3203 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003204 }
3205
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003206 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003207 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003208 * @param url the URL that exceeded the quota
3209 * @param databaseIdentifier the identifier of the database on
3210 * which the transaction that caused the quota overflow was run
3211 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003212 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003213 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003214 * @param quotaUpdater The callback to run when a decision to allow or
3215 * deny quota has been made. Don't forget to call this!
3216 */
3217 @Override
3218 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003219 String databaseIdentifier, long currentQuota, long estimatedSize,
3220 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003221 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003222 url, databaseIdentifier, currentQuota, estimatedSize,
3223 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003224 }
3225
3226 /**
3227 * The Application Cache has exceeded its max size.
3228 * @param spaceNeeded is the amount of disk space that would be needed
3229 * in order for the last appcache operation to succeed.
3230 * @param totalUsedQuota is the sum of all origins' quota.
3231 * @param quotaUpdater A callback to inform the WebCore thread that a new
3232 * app cache size is available. This callback must always be executed at
3233 * some point to ensure that the sleeping WebCore thread is woken up.
3234 */
3235 @Override
3236 public void onReachedMaxAppCacheSize(long spaceNeeded,
3237 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3238 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3239 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003240 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003241
Steve Block2bc69912009-07-30 14:45:13 +01003242 /**
3243 * Instructs the browser to show a prompt to ask the user to set the
3244 * Geolocation permission state for the specified origin.
3245 * @param origin The origin for which Geolocation permissions are
3246 * requested.
3247 * @param callback The callback to call once the user has set the
3248 * Geolocation permission state.
3249 */
3250 @Override
3251 public void onGeolocationPermissionsShowPrompt(String origin,
3252 GeolocationPermissions.Callback callback) {
3253 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3254 origin, callback);
3255 }
3256
3257 /**
3258 * Instructs the browser to hide the Geolocation permissions prompt.
3259 */
3260 @Override
3261 public void onGeolocationPermissionsHidePrompt() {
3262 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3263 }
3264
Ben Murdoch7db26342009-06-03 18:21:19 +01003265 /* Adds a JavaScript error message to the system log.
3266 * @param message The error message to report.
3267 * @param lineNumber The line number of the error.
3268 * @param sourceID The name of the source file that caused the error.
3269 */
3270 @Override
3271 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003272 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3273 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3274 if (mShouldShowErrorConsole &&
3275 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3276 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3277 }
3278 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003279 }
Andrei Popescu540035d2009-09-18 18:59:20 +01003280
3281 /**
3282 * Ask the browser for an icon to represent a <video> element.
3283 * This icon will be used if the Web page did not specify a poster attribute.
3284 *
3285 * @return Bitmap The icon or null if no such icon is available.
3286 * @hide pending API Council approval
3287 */
3288 @Override
3289 public Bitmap getDefaultVideoPoster() {
3290 if (mDefaultVideoPoster == null) {
3291 mDefaultVideoPoster = BitmapFactory.decodeResource(
3292 getResources(), R.drawable.default_video_poster);
3293 }
3294 return mDefaultVideoPoster;
3295 }
3296
3297 /**
3298 * Ask the host application for a custom progress view to show while
3299 * a <video> is loading.
3300 *
3301 * @return View The progress view.
3302 * @hide pending API Council approval
3303 */
3304 @Override
3305 public View getVideoLoadingProgressView() {
3306 if (mVideoProgressView == null) {
3307 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
3308 mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
3309 }
3310 return mVideoProgressView;
3311 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003312 };
3313
3314 /**
3315 * Notify the host application a download should be done, or that
3316 * the data should be streamed if a streaming viewer is available.
3317 * @param url The full url to the content that should be downloaded
3318 * @param contentDisposition Content-disposition http header, if
3319 * present.
3320 * @param mimetype The mimetype of the content reported by the server
3321 * @param contentLength The file size reported by the server
3322 */
3323 public void onDownloadStart(String url, String userAgent,
3324 String contentDisposition, String mimetype, long contentLength) {
3325 // if we're dealing wih A/V content that's not explicitly marked
3326 // for download, check if it's streamable.
3327 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003328 || !contentDisposition.regionMatches(
3329 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003330 // query the package manager to see if there's a registered handler
3331 // that matches.
3332 Intent intent = new Intent(Intent.ACTION_VIEW);
3333 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003334 ResolveInfo info = getPackageManager().resolveActivity(intent,
3335 PackageManager.MATCH_DEFAULT_ONLY);
3336 if (info != null) {
3337 ComponentName myName = getComponentName();
3338 // If we resolved to ourselves, we don't want to attempt to
3339 // load the url only to try and download it again.
3340 if (!myName.getPackageName().equals(
3341 info.activityInfo.packageName)
3342 || !myName.getClassName().equals(
3343 info.activityInfo.name)) {
3344 // someone (other than us) knows how to handle this mime
3345 // type with this scheme, don't download.
3346 try {
3347 startActivity(intent);
3348 return;
3349 } catch (ActivityNotFoundException ex) {
3350 if (LOGD_ENABLED) {
3351 Log.d(LOGTAG, "activity not found for " + mimetype
3352 + " over " + Uri.parse(url).getScheme(),
3353 ex);
3354 }
3355 // Best behavior is to fall back to a download in this
3356 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003357 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003358 }
3359 }
3360 }
3361 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3362 }
3363
3364 /**
3365 * Notify the host application a download should be done, even if there
3366 * is a streaming viewer available for thise type.
3367 * @param url The full url to the content that should be downloaded
3368 * @param contentDisposition Content-disposition http header, if
3369 * present.
3370 * @param mimetype The mimetype of the content reported by the server
3371 * @param contentLength The file size reported by the server
3372 */
3373 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3374 String contentDisposition, String mimetype, long contentLength) {
3375
3376 String filename = URLUtil.guessFileName(url,
3377 contentDisposition, mimetype);
3378
3379 // Check to see if we have an SDCard
3380 String status = Environment.getExternalStorageState();
3381 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3382 int title;
3383 String msg;
3384
3385 // Check to see if the SDCard is busy, same as the music app
3386 if (status.equals(Environment.MEDIA_SHARED)) {
3387 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3388 title = R.string.download_sdcard_busy_dlg_title;
3389 } else {
3390 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3391 title = R.string.download_no_sdcard_dlg_title;
3392 }
3393
3394 new AlertDialog.Builder(this)
3395 .setTitle(title)
3396 .setIcon(android.R.drawable.ic_dialog_alert)
3397 .setMessage(msg)
3398 .setPositiveButton(R.string.ok, null)
3399 .show();
3400 return;
3401 }
3402
3403 // java.net.URI is a lot stricter than KURL so we have to undo
3404 // KURL's percent-encoding and redo the encoding using java.net.URI.
3405 URI uri = null;
3406 try {
3407 // Undo the percent-encoding that KURL may have done.
3408 String newUrl = new String(URLUtil.decode(url.getBytes()));
3409 // Parse the url into pieces
3410 WebAddress w = new WebAddress(newUrl);
3411 String frag = null;
3412 String query = null;
3413 String path = w.mPath;
3414 // Break the path into path, query, and fragment
3415 if (path.length() > 0) {
3416 // Strip the fragment
3417 int idx = path.lastIndexOf('#');
3418 if (idx != -1) {
3419 frag = path.substring(idx + 1);
3420 path = path.substring(0, idx);
3421 }
3422 idx = path.lastIndexOf('?');
3423 if (idx != -1) {
3424 query = path.substring(idx + 1);
3425 path = path.substring(0, idx);
3426 }
3427 }
3428 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3429 query, frag);
3430 } catch (Exception e) {
3431 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3432 return;
3433 }
3434
3435 // XXX: Have to use the old url since the cookies were stored using the
3436 // old percent-encoded url.
3437 String cookies = CookieManager.getInstance().getCookie(url);
3438
3439 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003440 values.put(Downloads.COLUMN_URI, uri.toString());
3441 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3442 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3443 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003444 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003445 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003446 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003447 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3448 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3449 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3450 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003451 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003452 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003453 }
3454 if (mimetype == null) {
3455 // We must have long pressed on a link or image to download it. We
3456 // are not sure of the mimetype in this case, so do a head request
3457 new FetchUrlMimeType(this).execute(values);
3458 } else {
3459 final Uri contentUri =
3460 getContentResolver().insert(Downloads.CONTENT_URI, values);
3461 viewDownloads(contentUri);
3462 }
3463
3464 }
3465
3466 /**
3467 * Resets the lock icon. This method is called when we start a new load and
3468 * know the url to be loaded.
3469 */
3470 private void resetLockIcon(String url) {
3471 // Save the lock-icon state (we revert to it if the load gets cancelled)
3472 saveLockIcon();
3473
3474 mLockIconType = LOCK_ICON_UNSECURE;
3475 if (URLUtil.isHttpsUrl(url)) {
3476 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003477 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003478 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3479 " reset lock icon to " + mLockIconType);
3480 }
3481 }
3482
3483 updateLockIconImage(LOCK_ICON_UNSECURE);
3484 }
3485
Grace Klobaeb6eef42009-09-15 17:56:32 -07003486 /* package */ void setLockIconType(int type) {
3487 mLockIconType = type;
3488 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003489
Grace Klobaeb6eef42009-09-15 17:56:32 -07003490 /* package */ int getLockIconType() {
3491 return mLockIconType;
3492 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003493
Grace Klobaeb6eef42009-09-15 17:56:32 -07003494 /* package */ void setPrevLockType(int type) {
3495 mPrevLockType = type;
3496 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003497
Grace Klobaeb6eef42009-09-15 17:56:32 -07003498 /* package */ int getPrevLockType() {
3499 return mPrevLockType;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003500 }
3501
3502 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003503 * Update the lock icon to correspond to our latest state.
3504 */
3505 /* package */ void updateLockIconToLatest() {
3506 updateLockIconImage(mLockIconType);
3507 }
3508
3509 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003510 * Updates the lock-icon image in the title-bar.
3511 */
3512 private void updateLockIconImage(int lockIconType) {
3513 Drawable d = null;
3514 if (lockIconType == LOCK_ICON_SECURE) {
3515 d = mSecLockIcon;
3516 } else if (lockIconType == LOCK_ICON_MIXED) {
3517 d = mMixLockIcon;
3518 }
Leon Scroggins68579392009-09-15 15:31:54 -04003519 mTitleBar.setLock(d);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003520 if (mFakeTitleBar != null) {
3521 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003522 }
3523 }
3524
3525 /**
3526 * Displays a page-info dialog.
3527 * @param tab The tab to show info about
3528 * @param fromShowSSLCertificateOnError The flag that indicates whether
3529 * this dialog was opened from the SSL-certificate-on-error dialog or
3530 * not. This is important, since we need to know whether to return to
3531 * the parent dialog or simply dismiss.
3532 */
3533 private void showPageInfo(final TabControl.Tab tab,
3534 final boolean fromShowSSLCertificateOnError) {
3535 final LayoutInflater factory = LayoutInflater
3536 .from(this);
3537
3538 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3539
3540 final WebView view = tab.getWebView();
3541
3542 String url = null;
3543 String title = null;
3544
3545 if (view == null) {
3546 url = tab.getUrl();
3547 title = tab.getTitle();
3548 } else if (view == mTabControl.getCurrentWebView()) {
3549 // Use the cached title and url if this is the current WebView
3550 url = mUrl;
3551 title = mTitle;
3552 } else {
3553 url = view.getUrl();
3554 title = view.getTitle();
3555 }
3556
3557 if (url == null) {
3558 url = "";
3559 }
3560 if (title == null) {
3561 title = "";
3562 }
3563
3564 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3565 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3566
3567 mPageInfoView = tab;
3568 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3569
3570 AlertDialog.Builder alertDialogBuilder =
3571 new AlertDialog.Builder(this)
3572 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3573 .setView(pageInfoView)
3574 .setPositiveButton(
3575 R.string.ok,
3576 new DialogInterface.OnClickListener() {
3577 public void onClick(DialogInterface dialog,
3578 int whichButton) {
3579 mPageInfoDialog = null;
3580 mPageInfoView = null;
3581 mPageInfoFromShowSSLCertificateOnError = null;
3582
3583 // if we came here from the SSL error dialog
3584 if (fromShowSSLCertificateOnError) {
3585 // go back to the SSL error dialog
3586 showSSLCertificateOnError(
3587 mSSLCertificateOnErrorView,
3588 mSSLCertificateOnErrorHandler,
3589 mSSLCertificateOnErrorError);
3590 }
3591 }
3592 })
3593 .setOnCancelListener(
3594 new DialogInterface.OnCancelListener() {
3595 public void onCancel(DialogInterface dialog) {
3596 mPageInfoDialog = null;
3597 mPageInfoView = null;
3598 mPageInfoFromShowSSLCertificateOnError = null;
3599
3600 // if we came here from the SSL error dialog
3601 if (fromShowSSLCertificateOnError) {
3602 // go back to the SSL error dialog
3603 showSSLCertificateOnError(
3604 mSSLCertificateOnErrorView,
3605 mSSLCertificateOnErrorHandler,
3606 mSSLCertificateOnErrorError);
3607 }
3608 }
3609 });
3610
3611 // if we have a main top-level page SSL certificate set or a certificate
3612 // error
3613 if (fromShowSSLCertificateOnError ||
3614 (view != null && view.getCertificate() != null)) {
3615 // add a 'View Certificate' button
3616 alertDialogBuilder.setNeutralButton(
3617 R.string.view_certificate,
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 } else {
3633 // otherwise, display the top-most certificate from
3634 // the chain
3635 if (view.getCertificate() != null) {
3636 showSSLCertificate(tab);
3637 }
3638 }
3639 }
3640 });
3641 }
3642
3643 mPageInfoDialog = alertDialogBuilder.show();
3644 }
3645
3646 /**
3647 * Displays the main top-level page SSL certificate dialog
3648 * (accessible from the Page-Info dialog).
3649 * @param tab The tab to show certificate for.
3650 */
3651 private void showSSLCertificate(final TabControl.Tab tab) {
3652 final View certificateView =
3653 inflateCertificateView(tab.getWebView().getCertificate());
3654 if (certificateView == null) {
3655 return;
3656 }
3657
3658 LayoutInflater factory = LayoutInflater.from(this);
3659
3660 final LinearLayout placeholder =
3661 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3662
3663 LinearLayout ll = (LinearLayout) factory.inflate(
3664 R.layout.ssl_success, placeholder);
3665 ((TextView)ll.findViewById(R.id.success))
3666 .setText(R.string.ssl_certificate_is_valid);
3667
3668 mSSLCertificateView = tab;
3669 mSSLCertificateDialog =
3670 new AlertDialog.Builder(this)
3671 .setTitle(R.string.ssl_certificate).setIcon(
3672 R.drawable.ic_dialog_browser_certificate_secure)
3673 .setView(certificateView)
3674 .setPositiveButton(R.string.ok,
3675 new DialogInterface.OnClickListener() {
3676 public void onClick(DialogInterface dialog,
3677 int whichButton) {
3678 mSSLCertificateDialog = null;
3679 mSSLCertificateView = null;
3680
3681 showPageInfo(tab, false);
3682 }
3683 })
3684 .setOnCancelListener(
3685 new DialogInterface.OnCancelListener() {
3686 public void onCancel(DialogInterface dialog) {
3687 mSSLCertificateDialog = null;
3688 mSSLCertificateView = null;
3689
3690 showPageInfo(tab, false);
3691 }
3692 })
3693 .show();
3694 }
3695
3696 /**
3697 * Displays the SSL error certificate dialog.
3698 * @param view The target web-view.
3699 * @param handler The SSL error handler responsible for cancelling the
3700 * connection that resulted in an SSL error or proceeding per user request.
3701 * @param error The SSL error object.
3702 */
3703 private void showSSLCertificateOnError(
3704 final WebView view, final SslErrorHandler handler, final SslError error) {
3705
3706 final View certificateView =
3707 inflateCertificateView(error.getCertificate());
3708 if (certificateView == null) {
3709 return;
3710 }
3711
3712 LayoutInflater factory = LayoutInflater.from(this);
3713
3714 final LinearLayout placeholder =
3715 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3716
3717 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3718 LinearLayout ll = (LinearLayout)factory
3719 .inflate(R.layout.ssl_warning, placeholder);
3720 ((TextView)ll.findViewById(R.id.warning))
3721 .setText(R.string.ssl_untrusted);
3722 }
3723
3724 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3725 LinearLayout ll = (LinearLayout)factory
3726 .inflate(R.layout.ssl_warning, placeholder);
3727 ((TextView)ll.findViewById(R.id.warning))
3728 .setText(R.string.ssl_mismatch);
3729 }
3730
3731 if (error.hasError(SslError.SSL_EXPIRED)) {
3732 LinearLayout ll = (LinearLayout)factory
3733 .inflate(R.layout.ssl_warning, placeholder);
3734 ((TextView)ll.findViewById(R.id.warning))
3735 .setText(R.string.ssl_expired);
3736 }
3737
3738 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3739 LinearLayout ll = (LinearLayout)factory
3740 .inflate(R.layout.ssl_warning, placeholder);
3741 ((TextView)ll.findViewById(R.id.warning))
3742 .setText(R.string.ssl_not_yet_valid);
3743 }
3744
3745 mSSLCertificateOnErrorHandler = handler;
3746 mSSLCertificateOnErrorView = view;
3747 mSSLCertificateOnErrorError = error;
3748 mSSLCertificateOnErrorDialog =
3749 new AlertDialog.Builder(this)
3750 .setTitle(R.string.ssl_certificate).setIcon(
3751 R.drawable.ic_dialog_browser_certificate_partially_secure)
3752 .setView(certificateView)
3753 .setPositiveButton(R.string.ok,
3754 new DialogInterface.OnClickListener() {
3755 public void onClick(DialogInterface dialog,
3756 int whichButton) {
3757 mSSLCertificateOnErrorDialog = null;
3758 mSSLCertificateOnErrorView = null;
3759 mSSLCertificateOnErrorHandler = null;
3760 mSSLCertificateOnErrorError = null;
3761
3762 mWebViewClient.onReceivedSslError(
3763 view, handler, error);
3764 }
3765 })
3766 .setNeutralButton(R.string.page_info_view,
3767 new DialogInterface.OnClickListener() {
3768 public void onClick(DialogInterface dialog,
3769 int whichButton) {
3770 mSSLCertificateOnErrorDialog = null;
3771
3772 // do not clear the dialog state: we will
3773 // need to show the dialog again once the
3774 // user is done exploring the page-info details
3775
3776 showPageInfo(mTabControl.getTabFromView(view),
3777 true);
3778 }
3779 })
3780 .setOnCancelListener(
3781 new DialogInterface.OnCancelListener() {
3782 public void onCancel(DialogInterface dialog) {
3783 mSSLCertificateOnErrorDialog = null;
3784 mSSLCertificateOnErrorView = null;
3785 mSSLCertificateOnErrorHandler = null;
3786 mSSLCertificateOnErrorError = null;
3787
3788 mWebViewClient.onReceivedSslError(
3789 view, handler, error);
3790 }
3791 })
3792 .show();
3793 }
3794
3795 /**
3796 * Inflates the SSL certificate view (helper method).
3797 * @param certificate The SSL certificate.
3798 * @return The resultant certificate view with issued-to, issued-by,
3799 * issued-on, expires-on, and possibly other fields set.
3800 * If the input certificate is null, returns null.
3801 */
3802 private View inflateCertificateView(SslCertificate certificate) {
3803 if (certificate == null) {
3804 return null;
3805 }
3806
3807 LayoutInflater factory = LayoutInflater.from(this);
3808
3809 View certificateView = factory.inflate(
3810 R.layout.ssl_certificate, null);
3811
3812 // issued to:
3813 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3814 if (issuedTo != null) {
3815 ((TextView) certificateView.findViewById(R.id.to_common))
3816 .setText(issuedTo.getCName());
3817 ((TextView) certificateView.findViewById(R.id.to_org))
3818 .setText(issuedTo.getOName());
3819 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3820 .setText(issuedTo.getUName());
3821 }
3822
3823 // issued by:
3824 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3825 if (issuedBy != null) {
3826 ((TextView) certificateView.findViewById(R.id.by_common))
3827 .setText(issuedBy.getCName());
3828 ((TextView) certificateView.findViewById(R.id.by_org))
3829 .setText(issuedBy.getOName());
3830 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3831 .setText(issuedBy.getUName());
3832 }
3833
3834 // issued on:
3835 String issuedOn = reformatCertificateDate(
3836 certificate.getValidNotBefore());
3837 ((TextView) certificateView.findViewById(R.id.issued_on))
3838 .setText(issuedOn);
3839
3840 // expires on:
3841 String expiresOn = reformatCertificateDate(
3842 certificate.getValidNotAfter());
3843 ((TextView) certificateView.findViewById(R.id.expires_on))
3844 .setText(expiresOn);
3845
3846 return certificateView;
3847 }
3848
3849 /**
3850 * Re-formats the certificate date (Date.toString()) string to
3851 * a properly localized date string.
3852 * @return Properly localized version of the certificate date string and
3853 * the original certificate date string if fails to localize.
3854 * If the original string is null, returns an empty string "".
3855 */
3856 private String reformatCertificateDate(String certificateDate) {
3857 String reformattedDate = null;
3858
3859 if (certificateDate != null) {
3860 Date date = null;
3861 try {
3862 date = java.text.DateFormat.getInstance().parse(certificateDate);
3863 } catch (ParseException e) {
3864 date = null;
3865 }
3866
3867 if (date != null) {
3868 reformattedDate =
3869 DateFormat.getDateFormat(this).format(date);
3870 }
3871 }
3872
3873 return reformattedDate != null ? reformattedDate :
3874 (certificateDate != null ? certificateDate : "");
3875 }
3876
3877 /**
3878 * Displays an http-authentication dialog.
3879 */
3880 private void showHttpAuthentication(final HttpAuthHandler handler,
3881 final String host, final String realm, final String title,
3882 final String name, final String password, int focusId) {
3883 LayoutInflater factory = LayoutInflater.from(this);
3884 final View v = factory
3885 .inflate(R.layout.http_authentication, null);
3886 if (name != null) {
3887 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3888 }
3889 if (password != null) {
3890 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3891 }
3892
3893 String titleText = title;
3894 if (titleText == null) {
3895 titleText = getText(R.string.sign_in_to).toString().replace(
3896 "%s1", host).replace("%s2", realm);
3897 }
3898
3899 mHttpAuthHandler = handler;
3900 AlertDialog dialog = new AlertDialog.Builder(this)
3901 .setTitle(titleText)
3902 .setIcon(android.R.drawable.ic_dialog_alert)
3903 .setView(v)
3904 .setPositiveButton(R.string.action,
3905 new DialogInterface.OnClickListener() {
3906 public void onClick(DialogInterface dialog,
3907 int whichButton) {
3908 String nm = ((EditText) v
3909 .findViewById(R.id.username_edit))
3910 .getText().toString();
3911 String pw = ((EditText) v
3912 .findViewById(R.id.password_edit))
3913 .getText().toString();
3914 BrowserActivity.this.setHttpAuthUsernamePassword
3915 (host, realm, nm, pw);
3916 handler.proceed(nm, pw);
3917 mHttpAuthenticationDialog = null;
3918 mHttpAuthHandler = null;
3919 }})
3920 .setNegativeButton(R.string.cancel,
3921 new DialogInterface.OnClickListener() {
3922 public void onClick(DialogInterface dialog,
3923 int whichButton) {
3924 handler.cancel();
3925 BrowserActivity.this.resetTitleAndRevertLockIcon();
3926 mHttpAuthenticationDialog = null;
3927 mHttpAuthHandler = null;
3928 }})
3929 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3930 public void onCancel(DialogInterface dialog) {
3931 handler.cancel();
3932 BrowserActivity.this.resetTitleAndRevertLockIcon();
3933 mHttpAuthenticationDialog = null;
3934 mHttpAuthHandler = null;
3935 }})
3936 .create();
3937 // Make the IME appear when the dialog is displayed if applicable.
3938 dialog.getWindow().setSoftInputMode(
3939 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3940 dialog.show();
3941 if (focusId != 0) {
3942 dialog.findViewById(focusId).requestFocus();
3943 } else {
3944 v.findViewById(R.id.username_edit).requestFocus();
3945 }
3946 mHttpAuthenticationDialog = dialog;
3947 }
3948
3949 public int getProgress() {
3950 WebView w = mTabControl.getCurrentWebView();
3951 if (w != null) {
3952 return w.getProgress();
3953 } else {
3954 return 100;
3955 }
3956 }
3957
3958 /**
3959 * Set HTTP authentication password.
3960 *
3961 * @param host The host for the password
3962 * @param realm The realm for the password
3963 * @param username The username for the password. If it is null, it means
3964 * password can't be saved.
3965 * @param password The password
3966 */
3967 public void setHttpAuthUsernamePassword(String host, String realm,
3968 String username,
3969 String password) {
3970 WebView w = mTabControl.getCurrentWebView();
3971 if (w != null) {
3972 w.setHttpAuthUsernamePassword(host, realm, username, password);
3973 }
3974 }
3975
3976 /**
3977 * connectivity manager says net has come or gone... inform the user
3978 * @param up true if net has come up, false if net has gone down
3979 */
3980 public void onNetworkToggle(boolean up) {
3981 if (up == mIsNetworkUp) {
3982 return;
3983 } else if (up) {
3984 mIsNetworkUp = true;
3985 if (mAlertDialog != null) {
3986 mAlertDialog.cancel();
3987 mAlertDialog = null;
3988 }
3989 } else {
3990 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003991 if (mInLoad) {
3992 createAndShowNetworkDialog();
3993 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003994 }
3995 WebView w = mTabControl.getCurrentWebView();
3996 if (w != null) {
3997 w.setNetworkAvailable(up);
3998 }
3999 }
4000
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004001 // This method shows the network dialog alerting the user that the net is
4002 // down. It will only show the dialog if mAlertDialog is null.
4003 private void createAndShowNetworkDialog() {
4004 if (mAlertDialog == null) {
4005 mAlertDialog = new AlertDialog.Builder(this)
4006 .setTitle(R.string.loadSuspendedTitle)
4007 .setMessage(R.string.loadSuspended)
4008 .setPositiveButton(R.string.ok, null)
4009 .show();
4010 }
4011 }
4012
The Android Open Source Project0c908882009-03-03 19:32:16 -08004013 @Override
4014 protected void onActivityResult(int requestCode, int resultCode,
4015 Intent intent) {
4016 switch (requestCode) {
4017 case COMBO_PAGE:
4018 if (resultCode == RESULT_OK && intent != null) {
4019 String data = intent.getAction();
4020 Bundle extras = intent.getExtras();
4021 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04004022 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004023 } else {
4024 final TabControl.Tab currentTab =
4025 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04004026 dismissSubWindow(currentTab);
4027 if (data != null && data.length() != 0) {
4028 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004029 }
4030 }
4031 }
4032 break;
4033 default:
4034 break;
4035 }
Leon Scroggins30444232009-09-04 18:36:20 -04004036 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004037 }
4038
4039 /*
4040 * This method is called as a result of the user selecting the options
4041 * menu to see the download window, or when a download changes state. It
4042 * shows the download window ontop of the current window.
4043 */
4044 /* package */ void viewDownloads(Uri downloadRecord) {
4045 Intent intent = new Intent(this,
4046 BrowserDownloadPage.class);
4047 intent.setData(downloadRecord);
4048 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4049
4050 }
4051
Leon Scroggins160a7e72009-08-14 18:28:01 -04004052 /**
4053 * Open the Go page.
4054 * @param startWithHistory If true, open starting on the history tab.
4055 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004056 */
Leon Scroggins30444232009-09-04 18:36:20 -04004057 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004058 WebView current = mTabControl.getCurrentWebView();
4059 if (current == null) {
4060 return;
4061 }
4062 Intent intent = new Intent(this,
4063 CombinedBookmarkHistoryActivity.class);
4064 String title = current.getTitle();
4065 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004066 Bitmap thumbnail = createScreenshot(current);
4067
The Android Open Source Project0c908882009-03-03 19:32:16 -08004068 // Just in case the user opens bookmarks before a page finishes loading
4069 // so the current history item, and therefore the page, is null.
4070 if (null == url) {
4071 url = mLastEnteredUrl;
4072 // This can happen.
4073 if (null == url) {
4074 url = mSettings.getHomePage();
4075 }
4076 }
4077 // In case the web page has not yet received its associated title.
4078 if (title == null) {
4079 title = url;
4080 }
4081 intent.putExtra("title", title);
4082 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004083 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04004084 // Disable opening in a new window if we have maxed out the windows
4085 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4086 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004087 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004088 if (startWithHistory) {
4089 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4090 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4091 }
4092 startActivityForResult(intent, COMBO_PAGE);
4093 }
4094
4095 // Called when loading from context menu or LOAD_URL message
4096 private void loadURL(WebView view, String url) {
4097 // In case the user enters nothing.
4098 if (url != null && url.length() != 0 && view != null) {
4099 url = smartUrlFilter(url);
4100 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4101 view.loadUrl(url);
4102 }
4103 }
4104 }
4105
The Android Open Source Project0c908882009-03-03 19:32:16 -08004106 private String smartUrlFilter(Uri inUri) {
4107 if (inUri != null) {
4108 return smartUrlFilter(inUri.toString());
4109 }
4110 return null;
4111 }
4112
4113
4114 // get window count
4115
4116 int getWindowCount(){
4117 if(mTabControl != null){
4118 return mTabControl.getTabCount();
4119 }
4120 return 0;
4121 }
4122
Feng Qianb34f87a2009-03-24 21:27:26 -07004123 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004124 "(?i)" + // switch on case insensitive matching
4125 "(" + // begin group for schema
4126 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004127 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004128 ")" +
4129 "(.*)" );
4130
4131 /**
4132 * Attempts to determine whether user input is a URL or search
4133 * terms. Anything with a space is passed to search.
4134 *
4135 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4136 * "Http://" converts to "http://"
4137 *
4138 * @return Original or modified URL
4139 *
4140 */
4141 String smartUrlFilter(String url) {
4142
4143 String inUrl = url.trim();
4144 boolean hasSpace = inUrl.indexOf(' ') != -1;
4145
4146 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4147 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004148 // force scheme to lowercase
4149 String scheme = matcher.group(1);
4150 String lcScheme = scheme.toLowerCase();
4151 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004152 inUrl = lcScheme + matcher.group(2);
4153 }
4154 if (hasSpace) {
4155 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004156 }
4157 return inUrl;
4158 }
4159 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004160 // FIXME: Is this the correct place to add to searches?
4161 // what if someone else calls this function?
4162 int shortcut = parseUrlShortcut(inUrl);
4163 if (shortcut != SHORTCUT_INVALID) {
4164 Browser.addSearchUrl(mResolver, inUrl);
4165 String query = inUrl.substring(2);
4166 switch (shortcut) {
4167 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004168 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004169 case SHORTCUT_WIKIPEDIA_SEARCH:
4170 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4171 case SHORTCUT_DICTIONARY_SEARCH:
4172 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4173 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004174 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004175 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004176 }
4177 }
4178 } else {
4179 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4180 return URLUtil.guessUrl(inUrl);
4181 }
4182 }
4183
4184 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004185 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004186 }
4187
Ben Murdochbff2d602009-07-01 20:19:05 +01004188 /* package */ void setShouldShowErrorConsole(boolean flag) {
4189 if (flag == mShouldShowErrorConsole) {
4190 // Nothing to do.
4191 return;
4192 }
4193
4194 mShouldShowErrorConsole = flag;
4195
4196 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4197
4198 if (flag) {
4199 // Setting the show state of the console will cause it's the layout to be inflated.
4200 if (errorConsole.numberOfErrors() > 0) {
4201 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4202 } else {
4203 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4204 }
4205
4206 // Now we can add it to the main view.
4207 mErrorConsoleContainer.addView(errorConsole,
4208 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4209 ViewGroup.LayoutParams.WRAP_CONTENT));
4210 } else {
4211 mErrorConsoleContainer.removeView(errorConsole);
4212 }
4213
4214 }
4215
Grace Klobaeb6eef42009-09-15 17:56:32 -07004216 final static int LOCK_ICON_UNSECURE = 0;
4217 final static int LOCK_ICON_SECURE = 1;
4218 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004219
4220 private int mLockIconType = LOCK_ICON_UNSECURE;
4221 private int mPrevLockType = LOCK_ICON_UNSECURE;
4222
4223 private BrowserSettings mSettings;
4224 private TabControl mTabControl;
4225 private ContentResolver mResolver;
4226 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004227 private View mCustomView;
4228 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004229 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004230
4231 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4232 // view, we should rewrite this.
4233 private int mCurrentMenuState = 0;
4234 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004235 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004236 private static final int EMPTY_MENU = -1;
4237 private Menu mMenu;
4238
4239 private FindDialog mFindDialog;
4240 // Used to prevent chording to result in firing two shortcuts immediately
4241 // one after another. Fixes bug 1211714.
4242 boolean mCanChord;
4243
4244 private boolean mInLoad;
4245 private boolean mIsNetworkUp;
4246
4247 private boolean mPageStarted;
4248 private boolean mActivityInPause = true;
4249
4250 private boolean mMenuIsDown;
4251
The Android Open Source Project0c908882009-03-03 19:32:16 -08004252 private static boolean mInTrace;
4253
4254 // Performance probe
4255 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4256 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4257 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4258 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4259 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4260 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4261 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4262 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4263 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4264 };
4265
4266 private long mStart;
4267 private long mProcessStart;
4268 private long mUserStart;
4269 private long mSystemStart;
4270 private long mIdleStart;
4271 private long mIrqStart;
4272
4273 private long mUiStart;
4274
4275 private Drawable mMixLockIcon;
4276 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004277
4278 /* hold a ref so we can auto-cancel if necessary */
4279 private AlertDialog mAlertDialog;
4280
4281 // Wait for credentials before loading google.com
4282 private ProgressDialog mCredsDlg;
4283
4284 // The up-to-date URL and title (these can be different from those stored
4285 // in WebView, since it takes some time for the information in WebView to
4286 // get updated)
4287 private String mUrl;
4288 private String mTitle;
4289
4290 // As PageInfo has different style for landscape / portrait, we have
4291 // to re-open it when configuration changed
4292 private AlertDialog mPageInfoDialog;
4293 private TabControl.Tab mPageInfoView;
4294 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4295 // dialog, we should not just dismiss it, but should get back to the
4296 // SSL-certificate-on-error dialog. This flag is used to store this state
4297 private Boolean mPageInfoFromShowSSLCertificateOnError;
4298
4299 // as SSLCertificateOnError has different style for landscape / portrait,
4300 // we have to re-open it when configuration changed
4301 private AlertDialog mSSLCertificateOnErrorDialog;
4302 private WebView mSSLCertificateOnErrorView;
4303 private SslErrorHandler mSSLCertificateOnErrorHandler;
4304 private SslError mSSLCertificateOnErrorError;
4305
4306 // as SSLCertificate has different style for landscape / portrait, we
4307 // have to re-open it when configuration changed
4308 private AlertDialog mSSLCertificateDialog;
4309 private TabControl.Tab mSSLCertificateView;
4310
4311 // as HttpAuthentication has different style for landscape / portrait, we
4312 // have to re-open it when configuration changed
4313 private AlertDialog mHttpAuthenticationDialog;
4314 private HttpAuthHandler mHttpAuthHandler;
4315
4316 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4317 new FrameLayout.LayoutParams(
4318 ViewGroup.LayoutParams.FILL_PARENT,
4319 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004320 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4321 new FrameLayout.LayoutParams(
4322 ViewGroup.LayoutParams.FILL_PARENT,
4323 ViewGroup.LayoutParams.FILL_PARENT,
4324 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004325 // Google search
4326 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004327 // Wikipedia search
4328 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4329 // Dictionary search
4330 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4331 // Google Mobile Local search
4332 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4333
4334 final static String QUERY_PLACE_HOLDER = "%s";
4335
4336 // "source" parameter for Google search through search key
4337 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4338 // "source" parameter for Google search through goto menu
4339 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4340 // "source" parameter for Google search through simplily type
4341 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4342 // "source" parameter for Google search suggested by the browser
4343 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4344 // "source" parameter for Google search from unknown source
4345 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4346
4347 private final static String LOGTAG = "browser";
4348
The Android Open Source Project0c908882009-03-03 19:32:16 -08004349 private String mLastEnteredUrl;
4350
4351 private PowerManager.WakeLock mWakeLock;
4352 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4353
4354 private Toast mStopToast;
4355
Leon Scroggins68579392009-09-15 15:31:54 -04004356 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004357
Ben Murdochbff2d602009-07-01 20:19:05 +01004358 private LinearLayout mErrorConsoleContainer = null;
4359 private boolean mShouldShowErrorConsole = false;
4360
The Android Open Source Project0c908882009-03-03 19:32:16 -08004361 // As the ids are dynamically created, we can't guarantee that they will
4362 // be in sequence, so this static array maps ids to a window number.
4363 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4364 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4365 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4366 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4367
4368 // monitor platform changes
4369 private IntentFilter mNetworkStateChangedFilter;
4370 private BroadcastReceiver mNetworkStateIntentReceiver;
4371
Grace Klobab4da0ad2009-05-14 14:45:40 -07004372 private BroadcastReceiver mPackageInstallationReceiver;
4373
The Android Open Source Project0c908882009-03-03 19:32:16 -08004374 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004375 final static int COMBO_PAGE = 1;
4376 final static int DOWNLOAD_PAGE = 2;
4377 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004378
Andrei Popescu540035d2009-09-18 18:59:20 +01004379 // the default <video> poster
4380 private Bitmap mDefaultVideoPoster;
4381 // the video progress view
4382 private View mVideoProgressView;
4383
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004384 /**
4385 * A UrlData class to abstract how the content will be set to WebView.
4386 * This base class uses loadUrl to show the content.
4387 */
4388 private static class UrlData {
4389 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004390 byte[] mPostData;
4391
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004392 UrlData(String url) {
4393 this.mUrl = url;
4394 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004395
4396 void setPostData(byte[] postData) {
4397 mPostData = postData;
4398 }
4399
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004400 boolean isEmpty() {
4401 return mUrl == null || mUrl.length() == 0;
4402 }
4403
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004404 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004405 if (mPostData != null) {
4406 webView.postUrl(mUrl, mPostData);
4407 } else {
4408 webView.loadUrl(mUrl);
4409 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004410 }
4411 };
4412
4413 /**
4414 * A subclass of UrlData class that can display inlined content using
4415 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4416 */
4417 private static class InlinedUrlData extends UrlData {
4418 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4419 super(failUrl);
4420 mInlined = inlined;
4421 mMimeType = mimeType;
4422 mEncoding = encoding;
4423 }
4424 String mMimeType;
4425 String mInlined;
4426 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004427 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004428 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004429 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004430 }
4431
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004432 @Override
4433 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004434 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4435 }
4436 }
4437
Leon Scroggins1f005d32009-08-10 17:36:42 -04004438 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004439}