blob: adb9b7da641a838884c912190a1c0eb01ead61f7 [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;
48import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.DrawFilter;
50import android.graphics.Paint;
51import android.graphics.PaintFlagsDrawFilter;
52import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040053import android.graphics.PixelFormat;
54import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080055import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080056import android.hardware.SensorListener;
57import android.hardware.SensorManager;
58import android.net.ConnectivityManager;
59import android.net.Uri;
60import android.net.WebAddress;
61import android.net.http.EventHandler;
62import android.net.http.SslCertificate;
63import android.net.http.SslError;
64import android.os.AsyncTask;
65import android.os.Bundle;
66import android.os.Debug;
67import android.os.Environment;
68import android.os.Handler;
69import android.os.IBinder;
70import android.os.Message;
71import android.os.PowerManager;
72import android.os.Process;
73import android.os.RemoteException;
74import android.os.ServiceManager;
75import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080076import android.provider.Browser;
77import android.provider.Contacts;
78import android.provider.Downloads;
79import android.provider.MediaStore;
80import android.provider.Contacts.Intents.Insert;
81import android.text.IClipboard;
82import android.text.TextUtils;
83import android.text.format.DateFormat;
84import android.text.util.Regex;
The Android Open Source Project0c908882009-03-03 19:32:16 -080085import android.util.Log;
86import android.view.ContextMenu;
87import android.view.Gravity;
88import android.view.KeyEvent;
89import android.view.LayoutInflater;
90import android.view.Menu;
91import android.view.MenuInflater;
92import android.view.MenuItem;
93import android.view.View;
94import android.view.ViewGroup;
95import android.view.Window;
96import android.view.WindowManager;
97import android.view.ContextMenu.ContextMenuInfo;
98import android.view.MenuItem.OnMenuItemClickListener;
99import android.view.animation.AlphaAnimation;
100import android.view.animation.Animation;
101import android.view.animation.AnimationSet;
102import android.view.animation.DecelerateInterpolator;
103import android.view.animation.ScaleAnimation;
104import android.view.animation.TranslateAnimation;
105import android.webkit.CookieManager;
106import android.webkit.CookieSyncManager;
107import android.webkit.DownloadListener;
Steve Block2bc69912009-07-30 14:45:13 +0100108import android.webkit.GeolocationPermissions;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800109import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -0700110import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800111import android.webkit.SslErrorHandler;
112import android.webkit.URLUtil;
113import android.webkit.WebChromeClient;
Andrei Popescuc9b55562009-07-07 10:51:15 +0100114import android.webkit.WebChromeClient.CustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800115import android.webkit.WebHistoryItem;
116import android.webkit.WebIconDatabase;
Ben Murdoch092dd5d2009-04-22 12:34:12 +0100117import android.webkit.WebStorage;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import android.webkit.WebView;
119import android.webkit.WebViewClient;
120import android.widget.EditText;
121import android.widget.FrameLayout;
122import android.widget.LinearLayout;
123import android.widget.TextView;
124import android.widget.Toast;
125
126import java.io.BufferedOutputStream;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400127import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128import java.io.File;
129import java.io.FileInputStream;
130import java.io.FileOutputStream;
131import java.io.IOException;
132import java.io.InputStream;
133import java.net.MalformedURLException;
134import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700135import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800136import java.net.URL;
137import java.net.URLEncoder;
138import java.text.ParseException;
139import java.util.Date;
140import java.util.Enumeration;
141import java.util.HashMap;
Patrick Scott37911c72009-03-24 18:02:58 -0700142import java.util.LinkedList;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800143import java.util.Vector;
144import java.util.regex.Matcher;
145import java.util.regex.Pattern;
146import java.util.zip.ZipEntry;
147import java.util.zip.ZipFile;
148
149public class BrowserActivity extends Activity
150 implements KeyTracker.OnKeyTracker,
151 View.OnCreateContextMenuListener,
152 DownloadListener {
153
Dave Bort31a6d1c2009-04-13 15:56:49 -0700154 /* Define some aliases to make these debugging flags easier to refer to.
155 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
156 */
157 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
158 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
159 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
160
The Android Open Source Project0c908882009-03-03 19:32:16 -0800161 private IGoogleLoginService mGls = null;
162 private ServiceConnection mGlsConnection = null;
163
164 private SensorManager mSensorManager = null;
165
Satish Sampath565505b2009-05-29 15:37:27 +0100166 // These are single-character shortcuts for searching popular sources.
167 private static final int SHORTCUT_INVALID = 0;
168 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
169 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
170 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
171 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
172
The Android Open Source Project0c908882009-03-03 19:32:16 -0800173 /* Whitelisted webpages
174 private static HashSet<String> sWhiteList;
175
176 static {
177 sWhiteList = new HashSet<String>();
178 sWhiteList.add("cnn.com/");
179 sWhiteList.add("espn.go.com/");
180 sWhiteList.add("nytimes.com/");
181 sWhiteList.add("engadget.com/");
182 sWhiteList.add("yahoo.com/");
183 sWhiteList.add("msn.com/");
184 sWhiteList.add("amazon.com/");
185 sWhiteList.add("consumerist.com/");
186 sWhiteList.add("google.com/m/news");
187 }
188 */
189
190 private void setupHomePage() {
191 final Runnable getAccount = new Runnable() {
192 public void run() {
193 // Lower priority
194 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
195 // get the default home page
196 String homepage = mSettings.getHomePage();
197
198 try {
199 if (mGls == null) return;
200
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700201 if (!homepage.startsWith("http://www.google.")) return;
202 if (homepage.indexOf('?') == -1) return;
203
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
205 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
206
207 // three cases:
208 //
209 // hostedUser == googleUser
210 // The device has only a google account
211 //
212 // hostedUser != googleUser
213 // The device has a hosted account and a google account
214 //
215 // hostedUser != null, googleUser == null
216 // The device has only a hosted account (so far)
217
218 // developers might have no accounts at all
219 if (hostedUser == null) return;
220
221 if (googleUser == null || !hostedUser.equals(googleUser)) {
222 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700223 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800224 }
225 } catch (RemoteException ignore) {
226 // Login service died; carry on
227 } catch (RuntimeException ignore) {
228 // Login service died; carry on
229 } finally {
230 finish(homepage);
231 }
232 }
233
234 private void finish(final String homepage) {
235 mHandler.post(new Runnable() {
236 public void run() {
237 mSettings.setHomePage(BrowserActivity.this, homepage);
238 resumeAfterCredentials();
239
240 // as this is running in a separate thread,
241 // BrowserActivity's onDestroy() may have been called,
242 // which also calls unbindService().
243 if (mGlsConnection != null) {
244 // we no longer need to keep GLS open
245 unbindService(mGlsConnection);
246 mGlsConnection = null;
247 }
248 } });
249 } };
250
251 final boolean[] done = { false };
252
253 // Open a connection to the Google Login Service. The first
254 // time the connection is established, set up the homepage depending on
255 // the account in a background thread.
256 mGlsConnection = new ServiceConnection() {
257 public void onServiceConnected(ComponentName className, IBinder service) {
258 mGls = IGoogleLoginService.Stub.asInterface(service);
259 if (done[0] == false) {
260 done[0] = true;
261 Thread account = new Thread(getAccount);
262 account.setName("GLSAccount");
263 account.start();
264 }
265 }
266 public void onServiceDisconnected(ComponentName className) {
267 mGls = null;
268 }
269 };
270
271 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
272 mGlsConnection, Context.BIND_AUTO_CREATE);
273 }
274
Cary Clarka9771242009-08-11 16:42:26 -0400275 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800276 @Override
277 public Void doInBackground(File... files) {
278 if (files != null) {
279 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400280 if (!f.delete()) {
281 Log.e(LOGTAG, f.getPath() + " was not deleted");
282 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800283 }
284 }
285 return null;
286 }
287 }
288
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400289 /**
290 * This layout holds everything you see below the status bar, including the
291 * error console, the custom view container, and the webviews.
292 */
293 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400294
The Android Open Source Project0c908882009-03-03 19:32:16 -0800295 @Override public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700296 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800297 Log.v(LOGTAG, this + " onStart");
298 }
299 super.onCreate(icicle);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400300 this.requestWindowFeature(Window.FEATURE_NO_TITLE);
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);
334 mTitleBar = new TitleBarSet(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)) {
360 boolean down = intent.getBooleanExtra(
361 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
362 onNetworkToggle(!down);
363 }
364 }
365 };
366
Grace Kloba615c6c92009-08-03 10:22:44 -0700367 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
368 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
369 filter.addDataScheme("package");
370 mPackageInstallationReceiver = new BroadcastReceiver() {
371 @Override
372 public void onReceive(Context context, Intent intent) {
373 final String action = intent.getAction();
374 final String packageName = intent.getData()
375 .getSchemeSpecificPart();
376 final boolean replacing = intent.getBooleanExtra(
377 Intent.EXTRA_REPLACING, false);
378 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
379 // if it is replacing, refreshPlugins() when adding
380 return;
381 }
382 PackageManager pm = BrowserActivity.this.getPackageManager();
383 PackageInfo pkgInfo = null;
384 try {
385 pkgInfo = pm.getPackageInfo(packageName,
386 PackageManager.GET_PERMISSIONS);
387 } catch (PackageManager.NameNotFoundException e) {
388 return;
389 }
390 if (pkgInfo != null) {
391 String permissions[] = pkgInfo.requestedPermissions;
392 if (permissions == null) {
393 return;
394 }
395 boolean permissionOk = false;
396 for (String permit : permissions) {
397 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
398 permissionOk = true;
399 break;
400 }
401 }
402 if (permissionOk) {
403 PluginManager.getInstance(BrowserActivity.this)
404 .refreshPlugins(
405 Intent.ACTION_PACKAGE_ADDED
406 .equals(action));
407 }
408 }
409 }
410 };
411 registerReceiver(mPackageInstallationReceiver, filter);
412
Satish Sampath565505b2009-05-29 15:37:27 +0100413 // If this was a web search request, pass it on to the default web search provider.
414 if (handleWebSearchIntent(getIntent())) {
415 moveTaskToBack(true);
416 return;
417 }
418
The Android Open Source Project0c908882009-03-03 19:32:16 -0800419 if (!mTabControl.restoreState(icicle)) {
420 // clear up the thumbnail directory if we can't restore the state as
421 // none of the files in the directory are referenced any more.
422 new ClearThumbnails().execute(
423 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700424 // there is no quit on Android. But if we can't restore the state,
425 // we can treat it as a new Browser, remove the old session cookies.
426 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800427 final Intent intent = getIntent();
428 final Bundle extra = intent.getExtras();
429 // Create an initial tab.
430 // If the intent is ACTION_VIEW and data is not null, the Browser is
431 // invoked to view the content by another application. In this case,
432 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700433 UrlData urlData = getUrlDataFromIntent(intent);
434
The Android Open Source Project0c908882009-03-03 19:32:16 -0800435 final TabControl.Tab t = mTabControl.createNewTab(
436 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700437 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700438 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800439 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800440 attachTabToContentView(t);
441 WebView webView = t.getWebView();
442 if (extra != null) {
443 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
444 if (scale > 0 && scale <= 1000) {
445 webView.setInitialScale(scale);
446 }
447 }
448 // If we are not restoring from an icicle, then there is a high
449 // likely hood this is the first run. So, check to see if the
450 // homepage needs to be configured and copy any plugins from our
451 // asset directory to the data partition.
452 if ((extra == null || !extra.getBoolean("testing"))
453 && !mSettings.isLoginInitialized()) {
454 setupHomePage();
455 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800456
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700457 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400458 if (mSettings.isLoginInitialized()) {
459 webView.loadUrl(mSettings.getHomePage());
460 } else {
461 waitForCredentials();
462 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800463 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700464 if (extra != null) {
465 urlData.setPostData(extra
466 .getByteArray(Browser.EXTRA_POST_DATA));
467 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700468 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800469 }
470 } else {
471 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400472 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800473 attachTabToContentView(mTabControl.getCurrentTab());
474 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700475
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400476 mTitleBar.init(this);
477 // Create title bars for all of the tabs that have been created
478 for (int i = 0; i < mTabControl.getTabCount(); i ++) {
479 WebView view = mTabControl.getTab(i).getWebView();
480 mTitleBar.addTab(view, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400481 }
482
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400483 mTitleBar.setCurrentTab(mTabControl.getCurrentIndex());
484
Feng Qianb3c02da2009-06-29 15:58:08 -0700485 // Read JavaScript flags if it exists.
486 String jsFlags = mSettings.getJsFlags();
487 if (jsFlags.trim().length() != 0) {
488 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
489 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800490 }
491
492 @Override
493 protected void onNewIntent(Intent intent) {
494 TabControl.Tab current = mTabControl.getCurrentTab();
495 // When a tab is closed on exit, the current tab index is set to -1.
496 // Reset before proceed as Browser requires the current tab to be set.
497 if (current == null) {
498 // Try to reset the tab in case the index was incorrect.
499 current = mTabControl.getTab(0);
500 if (current == null) {
501 // No tabs at all so just ignore this intent.
502 return;
503 }
504 mTabControl.setCurrentTab(current);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400505 mTitleBar.setCurrentTab(mTabControl.getTabIndex(current));
The Android Open Source Project0c908882009-03-03 19:32:16 -0800506 attachTabToContentView(current);
507 resetTitleAndIcon(current.getWebView());
508 }
509 final String action = intent.getAction();
510 final int flags = intent.getFlags();
511 if (Intent.ACTION_MAIN.equals(action) ||
512 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
513 // just resume the browser
514 return;
515 }
516 if (Intent.ACTION_VIEW.equals(action)
517 || Intent.ACTION_SEARCH.equals(action)
518 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
519 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100520 // If this was a search request (e.g. search query directly typed into the address bar),
521 // pass it on to the default web search provider.
522 if (handleWebSearchIntent(intent)) {
523 return;
524 }
525
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700526 UrlData urlData = getUrlDataFromIntent(intent);
527 if (urlData.isEmpty()) {
528 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800529 }
Grace Kloba81678d92009-06-30 07:09:56 -0700530 urlData.setPostData(intent
531 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700532
Grace Klobacc634032009-07-28 15:58:19 -0700533 final String appId = intent
534 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
535 if (Intent.ACTION_VIEW.equals(action)
536 && !getPackageName().equals(appId)
537 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Patrick Scottcd115892009-07-16 09:42:58 -0400538 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700539 if (appTab != null) {
540 Log.i(LOGTAG, "Reusing tab for " + appId);
541 // Dismiss the subwindow if applicable.
542 dismissSubWindow(appTab);
543 // Since we might kill the WebView, remove it from the
544 // content view first.
545 removeTabFromContentView(appTab);
546 // Recreate the main WebView after destroying the old one.
547 // If the WebView has the same original url and is on that
548 // page, it can be reused.
549 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700550 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100551
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700552 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400553 switchToTab(mTabControl.getTabIndex(appTab));
554 if (needsLoad) {
555 urlData.loadIn(appTab.getWebView());
556 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700557 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400558 // If the tab was the current tab, we have to attach
559 // it to the view system again.
560 attachTabToContentView(appTab);
561 if (needsLoad) {
562 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700563 }
564 }
565 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400566 } else {
567 // No matching application tab, try to find a regular tab
568 // with a matching url.
569 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400570 if (appTab != null) {
571 if (current != appTab) {
572 switchToTab(mTabControl.getTabIndex(appTab));
573 }
574 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400575 } else {
576 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
577 // will be opened in a new tab unless we have reached
578 // MAX_TABS. Then the url will be opened in the current
579 // tab. If a new tab is created, it will have "true" for
580 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400581 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400582 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700583 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800584 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700585 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800586 mSettings.toggleDebugSettings();
587 return;
588 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400589 // Get rid of the subwindow if it exists
590 dismissSubWindow(current);
591 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800592 }
593 }
594 }
595
Satish Sampath565505b2009-05-29 15:37:27 +0100596 private int parseUrlShortcut(String url) {
597 if (url == null) return SHORTCUT_INVALID;
598
599 // FIXME: quick search, need to be customized by setting
600 if (url.length() > 2 && url.charAt(1) == ' ') {
601 switch (url.charAt(0)) {
602 case 'g': return SHORTCUT_GOOGLE_SEARCH;
603 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
604 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
605 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
606 }
607 }
608 return SHORTCUT_INVALID;
609 }
610
611 /**
612 * Launches the default web search activity with the query parameters if the given intent's data
613 * are identified as plain search terms and not URLs/shortcuts.
614 * @return true if the intent was handled and web search activity was launched, false if not.
615 */
616 private boolean handleWebSearchIntent(Intent intent) {
617 if (intent == null) return false;
618
619 String url = null;
620 final String action = intent.getAction();
621 if (Intent.ACTION_VIEW.equals(action)) {
622 url = intent.getData().toString();
623 } else if (Intent.ACTION_SEARCH.equals(action)
624 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
625 || Intent.ACTION_WEB_SEARCH.equals(action)) {
626 url = intent.getStringExtra(SearchManager.QUERY);
627 }
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100628 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA));
Satish Sampath565505b2009-05-29 15:37:27 +0100629 }
630
631 /**
632 * Launches the default web search activity with the query parameters if the given url string
633 * was identified as plain search terms and not URL/shortcut.
634 * @return true if the request was handled and web search activity was launched, false if not.
635 */
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100636 private boolean handleWebSearchRequest(String inUrl, Bundle appData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100637 if (inUrl == null) return false;
638
639 // In general, we shouldn't modify URL from Intent.
640 // But currently, we get the user-typed URL from search box as well.
641 String url = fixUrl(inUrl).trim();
642
643 // URLs and site specific search shortcuts are handled by the regular flow of control, so
644 // return early.
645 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100646 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100647 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
648 return false;
649 }
650
651 Browser.updateVisitedHistory(mResolver, url, false);
652 Browser.addSearchUrl(mResolver, url);
653
654 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
655 intent.addCategory(Intent.CATEGORY_DEFAULT);
656 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100657 if (appData != null) {
658 intent.putExtra(SearchManager.APP_DATA, appData);
659 }
Grace Klobacc634032009-07-28 15:58:19 -0700660 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100661 startActivity(intent);
662
663 return true;
664 }
665
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700666 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800667 String url = null;
668 if (intent != null) {
669 final String action = intent.getAction();
670 if (Intent.ACTION_VIEW.equals(action)) {
671 url = smartUrlFilter(intent.getData());
672 if (url != null && url.startsWith("content:")) {
673 /* Append mimetype so webview knows how to display */
674 String mimeType = intent.resolveType(getContentResolver());
675 if (mimeType != null) {
676 url += "?" + mimeType;
677 }
678 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700679 if ("inline:".equals(url)) {
680 return new InlinedUrlData(
681 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
682 intent.getType(),
683 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
684 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
685 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800686 } else if (Intent.ACTION_SEARCH.equals(action)
687 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
688 || Intent.ACTION_WEB_SEARCH.equals(action)) {
689 url = intent.getStringExtra(SearchManager.QUERY);
690 if (url != null) {
691 mLastEnteredUrl = url;
692 // Don't add Urls, just search terms.
693 // Urls will get added when the page is loaded.
694 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
695 Browser.updateVisitedHistory(mResolver, url, false);
696 }
697 // In general, we shouldn't modify URL from Intent.
698 // But currently, we get the user-typed URL from search box as well.
699 url = fixUrl(url);
700 url = smartUrlFilter(url);
701 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
702 if (url.contains(searchSource)) {
703 String source = null;
704 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
705 if (appData != null) {
706 source = appData.getString(SearchManager.SOURCE);
707 }
708 if (TextUtils.isEmpty(source)) {
709 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
710 }
711 url = url.replace(searchSource, "&source=android-"+source+"&");
712 }
713 }
714 }
715 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700716 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800717 }
718
719 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400720 // FIXME: Converting the url to lower case
721 // duplicates functionality in smartUrlFilter().
722 // However, changing all current callers of fixUrl to
723 // call smartUrlFilter in addition may have unwanted
724 // consequences, and is deferred for now.
725 int colon = inUrl.indexOf(':');
726 boolean allLower = true;
727 for (int index = 0; index < colon; index++) {
728 char ch = inUrl.charAt(index);
729 if (!Character.isLetter(ch)) {
730 break;
731 }
732 allLower &= Character.isLowerCase(ch);
733 if (index == colon - 1 && !allLower) {
734 inUrl = inUrl.substring(0, colon).toLowerCase()
735 + inUrl.substring(colon);
736 }
737 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800738 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
739 return inUrl;
740 if (inUrl.startsWith("http:") ||
741 inUrl.startsWith("https:")) {
742 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
743 inUrl = inUrl.replaceFirst("/", "//");
744 } else inUrl = inUrl.replaceFirst(":", "://");
745 }
746 return inUrl;
747 }
748
749 /**
750 * Looking for the pattern like this
751 *
752 * *
753 * * *
754 * *** * *******
755 * * *
756 * * *
757 * *
758 */
759 private final SensorListener mSensorListener = new SensorListener() {
760 private long mLastGestureTime;
761 private float[] mPrev = new float[3];
762 private float[] mPrevDiff = new float[3];
763 private float[] mDiff = new float[3];
764 private float[] mRevertDiff = new float[3];
765
766 public void onSensorChanged(int sensor, float[] values) {
767 boolean show = false;
768 float[] diff = new float[3];
769
770 for (int i = 0; i < 3; i++) {
771 diff[i] = values[i] - mPrev[i];
772 if (Math.abs(diff[i]) > 1) {
773 show = true;
774 }
775 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
776 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
777 // start track when there is a big move, or revert
778 mRevertDiff[i] = mDiff[i];
779 mDiff[i] = 0;
780 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
781 // reset when it is flat
782 mDiff[i] = mRevertDiff[i] = 0;
783 }
784 mDiff[i] += diff[i];
785 mPrevDiff[i] = diff[i];
786 mPrev[i] = values[i];
787 }
788
789 if (false) {
790 // only shows if we think the delta is big enough, in an attempt
791 // to detect "serious" moves left/right or up/down
792 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
793 + values[0] + ", " + values[1] + ", " + values[2] + ")"
794 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
795 + ")");
796 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
797 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
798 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
799 + mRevertDiff[2] + ")");
800 }
801
802 long now = android.os.SystemClock.uptimeMillis();
803 if (now - mLastGestureTime > 1000) {
804 mLastGestureTime = 0;
805
806 float y = mDiff[1];
807 float z = mDiff[2];
808 float ay = Math.abs(y);
809 float az = Math.abs(z);
810 float ry = mRevertDiff[1];
811 float rz = mRevertDiff[2];
812 float ary = Math.abs(ry);
813 float arz = Math.abs(rz);
814 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
815 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
816
817 if ((gestY || gestZ) && !(gestY && gestZ)) {
818 WebView view = mTabControl.getCurrentWebView();
819
820 if (view != null) {
821 if (gestZ) {
822 if (z < 0) {
823 view.zoomOut();
824 } else {
825 view.zoomIn();
826 }
827 } else {
828 view.flingScroll(0, Math.round(y * 100));
829 }
830 }
831 mLastGestureTime = now;
832 }
833 }
834 }
835
836 public void onAccuracyChanged(int sensor, int accuracy) {
837 // TODO Auto-generated method stub
838
839 }
840 };
841
842 @Override protected void onResume() {
843 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700844 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800845 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
846 }
847
848 if (!mActivityInPause) {
849 Log.e(LOGTAG, "BrowserActivity is already resumed.");
850 return;
851 }
852
Mike Reed7bfa63b2009-05-28 11:08:32 -0400853 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800854 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400855 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800856
857 if (mWakeLock.isHeld()) {
858 mHandler.removeMessages(RELEASE_WAKELOCK);
859 mWakeLock.release();
860 }
861
862 if (mCredsDlg != null) {
863 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
864 // In case credential request never comes back
865 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
866 }
867 }
868
869 registerReceiver(mNetworkStateIntentReceiver,
870 mNetworkStateChangedFilter);
871 WebView.enablePlatformNotifications();
872
873 if (mSettings.doFlick()) {
874 if (mSensorManager == null) {
875 mSensorManager = (SensorManager) getSystemService(
876 Context.SENSOR_SERVICE);
877 }
878 mSensorManager.registerListener(mSensorListener,
879 SensorManager.SENSOR_ACCELEROMETER,
880 SensorManager.SENSOR_DELAY_FASTEST);
881 } else {
882 mSensorManager = null;
883 }
884 }
885
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400886 /**
887 * Since the actual title bar is embedded in the WebView, and removing it
888 * would change its appearance, create a temporary title bar to go at
889 * the top of the screen while the menu is open.
890 */
891 private TitleBar mFakeTitleBar;
892
893 /**
894 * Keeps track of whether the options menu is open. This is important in
895 * determining whether to show or hide the title bar overlay.
896 */
897 private boolean mOptionsMenuOpen;
898
899 /**
900 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
901 * of whether the configuration has changed. The first onMenuOpened call
902 * after a configuration change is simply a reopening of the same menu
903 * (i.e. mIconView did not change).
904 */
905 private boolean mConfigChanged;
906
907 /**
908 * Whether or not the options menu is in its smaller, icon menu form. When
909 * true, we want the title bar overlay to be up. When false, we do not.
910 * Only meaningful if mOptionsMenuOpen is true.
911 */
912 private boolean mIconView;
913
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400914 @Override
915 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400916 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
917 if (mOptionsMenuOpen) {
918 if (mConfigChanged) {
919 // We do not need to make any changes to the state of the
920 // title bar, since the only thing that happened was a
921 // change in orientation
922 mConfigChanged = false;
923 } else {
924 if (mIconView) {
925 // Switching the menu to expanded view, so hide the
926 // title bar.
927 hideFakeTitleBar();
928 mIconView = false;
929 } else {
930 // Switching the menu back to icon view, so show the
931 // title bar once again.
932 showFakeTitleBar();
933 mIconView = true;
934 }
935 }
936 } else {
937 // The options menu is closed, so open it, and show the title
938 showFakeTitleBar();
939 mOptionsMenuOpen = true;
940 mConfigChanged = false;
941 mIconView = true;
942 }
943 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400944 return true;
945 }
946
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400947 private void showFakeTitleBar() {
948 if (mFakeTitleBar == null) {
949 WebView webView = getTopWindow();
950 mFakeTitleBar = new TitleBar(this, webView);
951 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
952 mFakeTitleBar.setProgress(webView.getProgress());
953 mFakeTitleBar.setFavicon(webView.getFavicon());
954 updateLockIconToLatest();
955 View title = mFakeTitleBar.findViewById(R.id.title);
956 title.setOnClickListener(new View.OnClickListener() {
957 public void onClick(View v) {
958 onSearchRequested();
959 closeOptionsMenu();
960 }
961 });
962
963 WindowManager manager
964 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
965
966 // Add the title bar to the window manager so it can receive touches
967 // while the menu is up
968 WindowManager.LayoutParams params
969 = new WindowManager.LayoutParams(
970 ViewGroup.LayoutParams.FILL_PARENT,
971 ViewGroup.LayoutParams.WRAP_CONTENT,
972 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
973 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
974 PixelFormat.OPAQUE);
975 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400976 WebView mainView = mTabControl.getCurrentWebView();
977 params.windowAnimations = mainView == null
978 || mainView.getScrollY() != 0
979 ? com.android.internal.R.style.Animation_DropDownDown : 0;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400980 // XXX : Without providing an offset, the fake title bar will be
981 // placed underneath the status bar. Use the global visible rect
982 // of mBrowserFrameLayout to determine the bottom of the status bar
983 Rect rectangle = new Rect();
984 mBrowserFrameLayout.getGlobalVisibleRect(rectangle);
985 params.y = rectangle.top;
986 manager.addView(mFakeTitleBar, params);
987 }
988 }
989
990 @Override
991 public void onOptionsMenuClosed(Menu menu) {
992 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400993 if (!mInLoad) {
994 hideFakeTitleBar();
995 } else if (!mIconView) {
996 // The page is currently loading, and we are in expanded mode, so
997 // we were not showing the menu. Show it once again. It will be
998 // removed when the page finishes.
999 showFakeTitleBar();
1000 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001001 }
1002 private void hideFakeTitleBar() {
1003 if (mFakeTitleBar == null) return;
1004 WindowManager manager
1005 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
1006 manager.removeView(mFakeTitleBar);
1007 mFakeTitleBar = null;
1008 }
1009
The Android Open Source Project0c908882009-03-03 19:32:16 -08001010 /**
1011 * onSaveInstanceState(Bundle map)
1012 * onSaveInstanceState is called right before onStop(). The map contains
1013 * the saved state.
1014 */
1015 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001016 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001017 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1018 }
1019 // the default implementation requires each view to have an id. As the
1020 // browser handles the state itself and it doesn't use id for the views,
1021 // don't call the default implementation. Otherwise it will trigger the
1022 // warning like this, "couldn't save which view has focus because the
1023 // focused view XXX has no id".
1024
1025 // Save all the tabs
1026 mTabControl.saveState(outState);
1027 }
1028
1029 @Override protected void onPause() {
1030 super.onPause();
1031
1032 if (mActivityInPause) {
1033 Log.e(LOGTAG, "BrowserActivity is already paused.");
1034 return;
1035 }
1036
Mike Reed7bfa63b2009-05-28 11:08:32 -04001037 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001038 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001039 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001040 mWakeLock.acquire();
1041 mHandler.sendMessageDelayed(mHandler
1042 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1043 }
1044
1045 // Clear the credentials toast if it is up
1046 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1047 mCredsDlg.dismiss();
1048 }
1049 mCredsDlg = null;
1050
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001051 // FIXME: This removes the active tabs page and resets the menu to
1052 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1053 // but then we would need to save it in onSaveInstanceState and restore
1054 // it in onCreate/onRestoreInstanceState
1055 if (mActiveTabsPage != null) {
1056 removeActiveTabPage(true);
1057 }
1058
The Android Open Source Project0c908882009-03-03 19:32:16 -08001059 cancelStopToast();
1060
1061 // unregister network state listener
1062 unregisterReceiver(mNetworkStateIntentReceiver);
1063 WebView.disablePlatformNotifications();
1064
1065 if (mSensorManager != null) {
1066 mSensorManager.unregisterListener(mSensorListener);
1067 }
1068 }
1069
1070 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001071 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001072 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1073 }
1074 super.onDestroy();
1075 // Remove the current tab and sub window
1076 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001077 if (t != null) {
1078 dismissSubWindow(t);
1079 removeTabFromContentView(t);
1080 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001081 // Destroy all the tabs
1082 mTabControl.destroy();
1083 WebIconDatabase.getInstance().close();
1084 if (mGlsConnection != null) {
1085 unbindService(mGlsConnection);
1086 mGlsConnection = null;
1087 }
1088
1089 //
1090 // stop MASF proxy service
1091 //
1092 //Intent proxyServiceIntent = new Intent();
1093 //proxyServiceIntent.setComponent
1094 // (new ComponentName(
1095 // "com.android.masfproxyservice",
1096 // "com.android.masfproxyservice.MasfProxyService"));
1097 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001098
1099 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001100 }
1101
1102 @Override
1103 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001104 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001105 super.onConfigurationChanged(newConfig);
1106
1107 if (mPageInfoDialog != null) {
1108 mPageInfoDialog.dismiss();
1109 showPageInfo(
1110 mPageInfoView,
1111 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1112 }
1113 if (mSSLCertificateDialog != null) {
1114 mSSLCertificateDialog.dismiss();
1115 showSSLCertificate(
1116 mSSLCertificateView);
1117 }
1118 if (mSSLCertificateOnErrorDialog != null) {
1119 mSSLCertificateOnErrorDialog.dismiss();
1120 showSSLCertificateOnError(
1121 mSSLCertificateOnErrorView,
1122 mSSLCertificateOnErrorHandler,
1123 mSSLCertificateOnErrorError);
1124 }
1125 if (mHttpAuthenticationDialog != null) {
1126 String title = ((TextView) mHttpAuthenticationDialog
1127 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1128 .toString();
1129 String name = ((TextView) mHttpAuthenticationDialog
1130 .findViewById(R.id.username_edit)).getText().toString();
1131 String password = ((TextView) mHttpAuthenticationDialog
1132 .findViewById(R.id.password_edit)).getText().toString();
1133 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1134 .getId();
1135 mHttpAuthenticationDialog.dismiss();
1136 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1137 name, password, focusId);
1138 }
1139 if (mFindDialog != null && mFindDialog.isShowing()) {
1140 mFindDialog.onConfigurationChanged(newConfig);
1141 }
1142 }
1143
1144 @Override public void onLowMemory() {
1145 super.onLowMemory();
1146 mTabControl.freeMemory();
1147 }
1148
Mike Reed7bfa63b2009-05-28 11:08:32 -04001149 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001150 if ((!mActivityInPause && !mPageStarted) ||
1151 (mActivityInPause && mPageStarted)) {
1152 CookieSyncManager.getInstance().startSync();
1153 WebView w = mTabControl.getCurrentWebView();
1154 if (w != null) {
1155 w.resumeTimers();
1156 }
1157 return true;
1158 } else {
1159 return false;
1160 }
1161 }
1162
Mike Reed7bfa63b2009-05-28 11:08:32 -04001163 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001164 if (mActivityInPause && !mPageStarted) {
1165 CookieSyncManager.getInstance().stopSync();
1166 WebView w = mTabControl.getCurrentWebView();
1167 if (w != null) {
1168 w.pauseTimers();
1169 }
1170 return true;
1171 } else {
1172 return false;
1173 }
1174 }
1175
Leon Scroggins1f005d32009-08-10 17:36:42 -04001176 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001177 /*
1178 * This function is called when we are launching for the first time. We
1179 * are waiting for the login credentials before loading Google home
1180 * pages. This way the user will be logged in straight away.
1181 */
1182 private void waitForCredentials() {
1183 // Show a toast
1184 mCredsDlg = new ProgressDialog(this);
1185 mCredsDlg.setIndeterminate(true);
1186 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1187 // If the user cancels the operation, then cancel the Google
1188 // Credentials request.
1189 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1190 mCredsDlg.show();
1191
1192 // We set a timeout for the retrieval of credentials in onResume()
1193 // as that is when we have freed up some CPU time to get
1194 // the login credentials.
1195 }
1196
1197 /*
1198 * If we have received the credentials or we have timed out and we are
1199 * showing the credentials dialog, then it is time to move on.
1200 */
1201 private void resumeAfterCredentials() {
1202 if (mCredsDlg == null) {
1203 return;
1204 }
1205
1206 // Clear the toast
1207 if (mCredsDlg.isShowing()) {
1208 mCredsDlg.dismiss();
1209 }
1210 mCredsDlg = null;
1211
1212 // Clear any pending timeout
1213 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1214
1215 // Load the page
1216 WebView w = mTabControl.getCurrentWebView();
1217 if (w != null) {
1218 w.loadUrl(mSettings.getHomePage());
1219 }
1220
1221 // Update the settings, need to do this last as it can take a moment
1222 // to persist the settings. In the mean time we could be loading
1223 // content.
1224 mSettings.setLoginInitialized(this);
1225 }
1226
1227 // Open the icon database and retain all the icons for visited sites.
1228 private void retainIconsOnStartup() {
1229 final WebIconDatabase db = WebIconDatabase.getInstance();
1230 db.open(getDir("icons", 0).getPath());
1231 try {
1232 Cursor c = Browser.getAllBookmarks(mResolver);
1233 if (!c.moveToFirst()) {
1234 c.deactivate();
1235 return;
1236 }
1237 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1238 do {
1239 String url = c.getString(urlIndex);
1240 db.retainIconForPageUrl(url);
1241 } while (c.moveToNext());
1242 c.deactivate();
1243 } catch (IllegalStateException e) {
1244 Log.e(LOGTAG, "retainIconsOnStartup", e);
1245 }
1246 }
1247
1248 // Helper method for getting the top window.
1249 WebView getTopWindow() {
1250 return mTabControl.getCurrentTopWebView();
1251 }
1252
1253 @Override
1254 public boolean onCreateOptionsMenu(Menu menu) {
1255 super.onCreateOptionsMenu(menu);
1256
1257 MenuInflater inflater = getMenuInflater();
1258 inflater.inflate(R.menu.browser, menu);
1259 mMenu = menu;
1260 updateInLoadMenuItems();
1261 return true;
1262 }
1263
1264 /**
1265 * As the menu can be open when loading state changes
1266 * we must manually update the state of the stop/reload menu
1267 * item
1268 */
1269 private void updateInLoadMenuItems() {
1270 if (mMenu == null) {
1271 return;
1272 }
1273 MenuItem src = mInLoad ?
1274 mMenu.findItem(R.id.stop_menu_id):
1275 mMenu.findItem(R.id.reload_menu_id);
1276 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1277 dest.setIcon(src.getIcon());
1278 dest.setTitle(src.getTitle());
1279 }
1280
1281 @Override
1282 public boolean onContextItemSelected(MenuItem item) {
1283 // chording is not an issue with context menus, but we use the same
1284 // options selector, so set mCanChord to true so we can access them.
1285 mCanChord = true;
1286 int id = item.getItemId();
1287 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001288 if (null == webView) {
1289 return false;
1290 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001291 final HashMap hrefMap = new HashMap();
1292 hrefMap.put("webview", webView);
1293 final Message msg = mHandler.obtainMessage(
1294 FOCUS_NODE_HREF, id, 0, hrefMap);
1295 switch (id) {
1296 // -- Browser context menu
1297 case R.id.open_context_menu_id:
1298 case R.id.open_newtab_context_menu_id:
1299 case R.id.bookmark_context_menu_id:
1300 case R.id.save_link_context_menu_id:
1301 case R.id.share_link_context_menu_id:
1302 case R.id.copy_link_context_menu_id:
1303 webView.requestFocusNodeHref(msg);
1304 break;
1305
1306 default:
1307 // For other context menus
1308 return onOptionsItemSelected(item);
1309 }
1310 mCanChord = false;
1311 return true;
1312 }
1313
1314 private Bundle createGoogleSearchSourceBundle(String source) {
1315 Bundle bundle = new Bundle();
1316 bundle.putString(SearchManager.SOURCE, source);
1317 return bundle;
1318 }
1319
1320 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001321 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001322 */
1323 @Override
1324 public boolean onSearchRequested() {
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001325 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001326 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001327 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001328 return true;
1329 }
1330
1331 @Override
1332 public void startSearch(String initialQuery, boolean selectInitialQuery,
1333 Bundle appSearchData, boolean globalSearch) {
1334 if (appSearchData == null) {
1335 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1336 }
1337 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1338 }
1339
Leon Scroggins1f005d32009-08-10 17:36:42 -04001340 /**
1341 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1342 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001343 * @param index Index of the tab to change to, as defined by
1344 * mTabControl.getTabIndex(Tab t).
1345 * @return boolean True if we successfully switched to a different tab. If
1346 * the indexth tab is null, or if that tab is the same as
1347 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001348 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001349 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001350 TabControl.Tab tab = mTabControl.getTab(index);
1351 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1352 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001353 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001354 }
1355 if (currentTab != null) {
1356 // currentTab may be null if it was just removed. In that case,
1357 // we do not need to remove it
1358 removeTabFromContentView(currentTab);
1359 }
1360 removeTabFromContentView(tab);
1361 mTabControl.setCurrentTab(tab);
1362 attachTabToContentView(tab);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001363 mTitleBar.setCurrentTab(index);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001364 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001365 }
1366
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001367 /* package */ TabControl.Tab openTabToHomePage() {
1368 return openTabAndShow(mSettings.getHomePage(), false, null);
1369 }
1370
Leon Scroggins1f005d32009-08-10 17:36:42 -04001371 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001372 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001373 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001374 // This is the last tab. Open a new one, with the home
1375 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001376 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001377 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001378 return;
1379 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001380 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001381 int indexToShow = -1;
1382 if (parent != null) {
1383 indexToShow = mTabControl.getTabIndex(parent);
1384 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001385 final int currentIndex = mTabControl.getCurrentIndex();
1386 // Try to move to the tab to the right
1387 indexToShow = currentIndex + 1;
1388 if (indexToShow > mTabControl.getTabCount() - 1) {
1389 // Try to move to the tab to the left
1390 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001391 }
1392 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001393 if (switchToTab(indexToShow)) {
1394 // Close window
1395 closeTab(current);
1396 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001397 }
1398
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001399 private ActiveTabsPage mActiveTabsPage;
1400
1401 /**
1402 * Remove the active tabs page.
1403 * @param needToAttach If true, the active tabs page did not attach a tab
1404 * to the content view, so we need to do that here.
1405 */
1406 /* package */ void removeActiveTabPage(boolean needToAttach) {
1407 mContentView.removeView(mActiveTabsPage);
1408 mActiveTabsPage = null;
1409 mMenuState = R.id.MAIN_MENU;
1410 if (needToAttach) {
1411 attachTabToContentView(mTabControl.getCurrentTab());
1412 }
1413 getTopWindow().requestFocus();
1414 }
1415
The Android Open Source Project0c908882009-03-03 19:32:16 -08001416 @Override
1417 public boolean onOptionsItemSelected(MenuItem item) {
1418 if (!mCanChord) {
1419 // The user has already fired a shortcut with this hold down of the
1420 // menu key.
1421 return false;
1422 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001423 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001424 return false;
1425 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001426 if (mMenuIsDown) {
1427 // The shortcut action consumes the MENU. Even if it is still down,
1428 // it won't trigger the next shortcut action. In the case of the
1429 // shortcut action triggering a new activity, like Bookmarks, we
1430 // won't get onKeyUp for MENU. So it is important to reset it here.
1431 mMenuIsDown = false;
1432 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001433 switch (item.getItemId()) {
1434 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001435 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001436 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001437 break;
1438
Leon Scroggins64b80f32009-08-07 12:03:34 -04001439 case R.id.goto_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001440 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001441 break;
1442
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001443 case R.id.active_tabs_menu_id:
1444 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1445 removeTabFromContentView(mTabControl.getCurrentTab());
1446 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1447 mActiveTabsPage.requestFocus();
1448 mMenuState = EMPTY_MENU;
1449 break;
1450
Leon Scroggins1f005d32009-08-10 17:36:42 -04001451 case R.id.add_bookmark_menu_id:
1452 Intent i = new Intent(BrowserActivity.this,
1453 AddBookmarkPage.class);
1454 WebView w = getTopWindow();
1455 i.putExtra("url", w.getUrl());
1456 i.putExtra("title", w.getTitle());
1457 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001458 break;
1459
1460 case R.id.stop_reload_menu_id:
1461 if (mInLoad) {
1462 stopLoading();
1463 } else {
1464 getTopWindow().reload();
1465 }
1466 break;
1467
1468 case R.id.back_menu_id:
1469 getTopWindow().goBack();
1470 break;
1471
1472 case R.id.forward_menu_id:
1473 getTopWindow().goForward();
1474 break;
1475
1476 case R.id.close_menu_id:
1477 // Close the subwindow if it exists.
1478 if (mTabControl.getCurrentSubWindow() != null) {
1479 dismissSubWindow(mTabControl.getCurrentTab());
1480 break;
1481 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001482 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001483 break;
1484
1485 case R.id.homepage_menu_id:
1486 TabControl.Tab current = mTabControl.getCurrentTab();
1487 if (current != null) {
1488 dismissSubWindow(current);
1489 current.getWebView().loadUrl(mSettings.getHomePage());
1490 }
1491 break;
1492
1493 case R.id.preferences_menu_id:
1494 Intent intent = new Intent(this,
1495 BrowserPreferencesPage.class);
1496 startActivityForResult(intent, PREFERENCES_PAGE);
1497 break;
1498
1499 case R.id.find_menu_id:
1500 if (null == mFindDialog) {
1501 mFindDialog = new FindDialog(this);
1502 }
1503 mFindDialog.setWebView(getTopWindow());
1504 mFindDialog.show();
1505 mMenuState = EMPTY_MENU;
1506 break;
1507
1508 case R.id.select_text_id:
1509 getTopWindow().emulateShiftHeld();
1510 break;
1511 case R.id.page_info_menu_id:
1512 showPageInfo(mTabControl.getCurrentTab(), false);
1513 break;
1514
1515 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001516 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001517 break;
1518
1519 case R.id.share_page_menu_id:
1520 Browser.sendString(this, getTopWindow().getUrl());
1521 break;
1522
1523 case R.id.dump_nav_menu_id:
1524 getTopWindow().debugDump();
1525 break;
1526
1527 case R.id.zoom_in_menu_id:
1528 getTopWindow().zoomIn();
1529 break;
1530
1531 case R.id.zoom_out_menu_id:
1532 getTopWindow().zoomOut();
1533 break;
1534
1535 case R.id.view_downloads_menu_id:
1536 viewDownloads(null);
1537 break;
1538
The Android Open Source Project0c908882009-03-03 19:32:16 -08001539 case R.id.window_one_menu_id:
1540 case R.id.window_two_menu_id:
1541 case R.id.window_three_menu_id:
1542 case R.id.window_four_menu_id:
1543 case R.id.window_five_menu_id:
1544 case R.id.window_six_menu_id:
1545 case R.id.window_seven_menu_id:
1546 case R.id.window_eight_menu_id:
1547 {
1548 int menuid = item.getItemId();
1549 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1550 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1551 TabControl.Tab desiredTab = mTabControl.getTab(id);
1552 if (desiredTab != null &&
1553 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001554 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001555 }
1556 break;
1557 }
1558 }
1559 }
1560 break;
1561
1562 default:
1563 if (!super.onOptionsItemSelected(item)) {
1564 return false;
1565 }
1566 // Otherwise fall through.
1567 }
1568 mCanChord = false;
1569 return true;
1570 }
1571
1572 public void closeFind() {
1573 mMenuState = R.id.MAIN_MENU;
1574 }
1575
1576 @Override public boolean onPrepareOptionsMenu(Menu menu)
1577 {
1578 // This happens when the user begins to hold down the menu key, so
1579 // allow them to chord to get a shortcut.
1580 mCanChord = true;
1581 // Note: setVisible will decide whether an item is visible; while
1582 // setEnabled() will decide whether an item is enabled, which also means
1583 // whether the matching shortcut key will function.
1584 super.onPrepareOptionsMenu(menu);
1585 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001586 case EMPTY_MENU:
1587 if (mCurrentMenuState != mMenuState) {
1588 menu.setGroupVisible(R.id.MAIN_MENU, false);
1589 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1590 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001591 }
1592 break;
1593 default:
1594 if (mCurrentMenuState != mMenuState) {
1595 menu.setGroupVisible(R.id.MAIN_MENU, true);
1596 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1597 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001598 }
1599 final WebView w = getTopWindow();
1600 boolean canGoBack = false;
1601 boolean canGoForward = false;
1602 boolean isHome = false;
1603 if (w != null) {
1604 canGoBack = w.canGoBack();
1605 canGoForward = w.canGoForward();
1606 isHome = mSettings.getHomePage().equals(w.getUrl());
1607 }
1608 final MenuItem back = menu.findItem(R.id.back_menu_id);
1609 back.setEnabled(canGoBack);
1610
1611 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1612 home.setEnabled(!isHome);
1613
1614 menu.findItem(R.id.forward_menu_id)
1615 .setEnabled(canGoForward);
1616
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001617 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1618 mTabControl.getTabCount() < TabControl.MAX_TABS);
1619
The Android Open Source Project0c908882009-03-03 19:32:16 -08001620 // decide whether to show the share link option
1621 PackageManager pm = getPackageManager();
1622 Intent send = new Intent(Intent.ACTION_SEND);
1623 send.setType("text/plain");
1624 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1625 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1626
The Android Open Source Project0c908882009-03-03 19:32:16 -08001627 boolean isNavDump = mSettings.isNavDump();
1628 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1629 nav.setVisible(isNavDump);
1630 nav.setEnabled(isNavDump);
1631 break;
1632 }
1633 mCurrentMenuState = mMenuState;
1634 return true;
1635 }
1636
1637 @Override
1638 public void onCreateContextMenu(ContextMenu menu, View v,
1639 ContextMenuInfo menuInfo) {
1640 WebView webview = (WebView) v;
1641 WebView.HitTestResult result = webview.getHitTestResult();
1642 if (result == null) {
1643 return;
1644 }
1645
1646 int type = result.getType();
1647 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1648 Log.w(LOGTAG,
1649 "We should not show context menu when nothing is touched");
1650 return;
1651 }
1652 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1653 // let TextView handles context menu
1654 return;
1655 }
1656
1657 // Note, http://b/issue?id=1106666 is requesting that
1658 // an inflated menu can be used again. This is not available
1659 // yet, so inflate each time (yuk!)
1660 MenuInflater inflater = getMenuInflater();
1661 inflater.inflate(R.menu.browsercontext, menu);
1662
1663 // Show the correct menu group
1664 String extra = result.getExtra();
1665 menu.setGroupVisible(R.id.PHONE_MENU,
1666 type == WebView.HitTestResult.PHONE_TYPE);
1667 menu.setGroupVisible(R.id.EMAIL_MENU,
1668 type == WebView.HitTestResult.EMAIL_TYPE);
1669 menu.setGroupVisible(R.id.GEO_MENU,
1670 type == WebView.HitTestResult.GEO_TYPE);
1671 menu.setGroupVisible(R.id.IMAGE_MENU,
1672 type == WebView.HitTestResult.IMAGE_TYPE
1673 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1674 menu.setGroupVisible(R.id.ANCHOR_MENU,
1675 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1676 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1677
1678 // Setup custom handling depending on the type
1679 switch (type) {
1680 case WebView.HitTestResult.PHONE_TYPE:
1681 menu.setHeaderTitle(Uri.decode(extra));
1682 menu.findItem(R.id.dial_context_menu_id).setIntent(
1683 new Intent(Intent.ACTION_VIEW, Uri
1684 .parse(WebView.SCHEME_TEL + extra)));
1685 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1686 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1687 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1688 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1689 addIntent);
1690 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1691 new Copy(extra));
1692 break;
1693
1694 case WebView.HitTestResult.EMAIL_TYPE:
1695 menu.setHeaderTitle(extra);
1696 menu.findItem(R.id.email_context_menu_id).setIntent(
1697 new Intent(Intent.ACTION_VIEW, Uri
1698 .parse(WebView.SCHEME_MAILTO + extra)));
1699 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1700 new Copy(extra));
1701 break;
1702
1703 case WebView.HitTestResult.GEO_TYPE:
1704 menu.setHeaderTitle(extra);
1705 menu.findItem(R.id.map_context_menu_id).setIntent(
1706 new Intent(Intent.ACTION_VIEW, Uri
1707 .parse(WebView.SCHEME_GEO
1708 + URLEncoder.encode(extra))));
1709 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1710 new Copy(extra));
1711 break;
1712
1713 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1714 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1715 TextView titleView = (TextView) LayoutInflater.from(this)
1716 .inflate(android.R.layout.browser_link_context_header,
1717 null);
1718 titleView.setText(extra);
1719 menu.setHeaderView(titleView);
1720 // decide whether to show the open link in new tab option
1721 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1722 mTabControl.getTabCount() < TabControl.MAX_TABS);
1723 PackageManager pm = getPackageManager();
1724 Intent send = new Intent(Intent.ACTION_SEND);
1725 send.setType("text/plain");
1726 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1727 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1728 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1729 break;
1730 }
1731 // otherwise fall through to handle image part
1732 case WebView.HitTestResult.IMAGE_TYPE:
1733 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1734 menu.setHeaderTitle(extra);
1735 }
1736 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1737 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1738 menu.findItem(R.id.download_context_menu_id).
1739 setOnMenuItemClickListener(new Download(extra));
1740 break;
1741
1742 default:
1743 Log.w(LOGTAG, "We should not get here.");
1744 break;
1745 }
1746 }
1747
The Android Open Source Project0c908882009-03-03 19:32:16 -08001748 // Attach the given tab to the content view.
1749 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001750 // Attach the container that contains the main WebView and any other UI
1751 // associated with the tab.
1752 mContentView.addView(t.getContainer(), COVER_SCREEN_PARAMS);
Ben Murdochbff2d602009-07-01 20:19:05 +01001753
1754 if (mShouldShowErrorConsole) {
1755 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1756 if (errorConsole.numberOfErrors() == 0) {
1757 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1758 } else {
1759 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1760 }
1761
1762 mErrorConsoleContainer.addView(errorConsole,
1763 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1764 ViewGroup.LayoutParams.WRAP_CONTENT));
1765 }
1766
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001767 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001768 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001769 // Attach the sub window if necessary
1770 attachSubWindow(t);
1771 // Request focus on the top window.
1772 t.getTopWindow().requestFocus();
1773 }
1774
1775 // Attach a sub window to the main WebView of the given tab.
1776 private void attachSubWindow(TabControl.Tab t) {
1777 // If a sub window exists, attach it to the content view.
1778 final WebView subView = t.getSubWebView();
1779 if (subView != null) {
1780 final View container = t.getSubWebViewContainer();
1781 mContentView.addView(container, COVER_SCREEN_PARAMS);
1782 subView.requestFocus();
1783 }
1784 }
1785
1786 // Remove the given tab from the content view.
1787 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001788 // Remove the container that contains the main WebView.
1789 mContentView.removeView(t.getContainer());
Ben Murdochbff2d602009-07-01 20:19:05 +01001790
1791 if (mTabControl.getCurrentErrorConsole(false) != null) {
1792 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1793 }
1794
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001795 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001796 view.setEmbeddedTitleBar(null);
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001797
The Android Open Source Project0c908882009-03-03 19:32:16 -08001798 // Remove the sub window if it exists.
1799 if (t.getSubWebView() != null) {
1800 mContentView.removeView(t.getSubWebViewContainer());
1801 }
1802 }
1803
1804 // Remove the sub window if it exists. Also called by TabControl when the
1805 // user clicks the 'X' to dismiss a sub window.
1806 /* package */ void dismissSubWindow(TabControl.Tab t) {
1807 final WebView mainView = t.getWebView();
1808 if (t.getSubWebView() != null) {
1809 // Remove the container view and request focus on the main WebView.
1810 mContentView.removeView(t.getSubWebViewContainer());
1811 mainView.requestFocus();
1812 // Tell the TabControl to dismiss the subwindow. This will destroy
1813 // the WebView.
1814 mTabControl.dismissSubWindow(t);
1815 }
1816 }
1817
Leon Scroggins1f005d32009-08-10 17:36:42 -04001818 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001819 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001820 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1821 String appId) {
1822 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001823 }
1824
1825 // This method does a ton of stuff. It will attempt to create a new tab
1826 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001827 // url isn't null, it will load the given url.
1828 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001829 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001830 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1831 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1832 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001833 final TabControl.Tab tab = mTabControl.createNewTab(
1834 closeOnExit, appId, urlData.mUrl);
1835 WebView webview = tab.getWebView();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001836 mTitleBar.addTab(webview, true);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001837 // If the last tab was removed from the active tabs page, currentTab
1838 // will be null.
1839 if (currentTab != null) {
1840 removeTabFromContentView(currentTab);
1841 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001842 attachTabToContentView(tab);
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001843 // We must set the new tab as the current tab to reflect the old
1844 // animation behavior.
1845 mTabControl.setCurrentTab(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001846 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001847 urlData.loadIn(webview);
1848 }
1849 return tab;
1850 } else {
1851 // Get rid of the subwindow if it exists
1852 dismissSubWindow(currentTab);
1853 if (!urlData.isEmpty()) {
1854 // Load the given url.
1855 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001856 }
1857 }
Grace Klobac9181842009-04-14 08:53:22 -07001858 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001859 }
1860
Grace Klobac9181842009-04-14 08:53:22 -07001861 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001862 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001863 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001864 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001865 WebView view = t.getWebView();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001866 mTitleBar.addTab(view, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001867 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001868 }
Grace Klobac9181842009-04-14 08:53:22 -07001869 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001870 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001871 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001872 }
1873 }
1874
1875 private class Copy implements OnMenuItemClickListener {
1876 private CharSequence mText;
1877
1878 public boolean onMenuItemClick(MenuItem item) {
1879 copy(mText);
1880 return true;
1881 }
1882
1883 public Copy(CharSequence toCopy) {
1884 mText = toCopy;
1885 }
1886 }
1887
1888 private class Download implements OnMenuItemClickListener {
1889 private String mText;
1890
1891 public boolean onMenuItemClick(MenuItem item) {
1892 onDownloadStartNoStream(mText, null, null, null, -1);
1893 return true;
1894 }
1895
1896 public Download(String toDownload) {
1897 mText = toDownload;
1898 }
1899 }
1900
1901 private void copy(CharSequence text) {
1902 try {
1903 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1904 if (clip != null) {
1905 clip.setClipboardText(text);
1906 }
1907 } catch (android.os.RemoteException e) {
1908 Log.e(LOGTAG, "Copy failed", e);
1909 }
1910 }
1911
1912 /**
1913 * Resets the browser title-view to whatever it must be (for example, if we
1914 * load a page from history).
1915 */
1916 private void resetTitle() {
1917 resetLockIcon();
1918 resetTitleIconAndProgress();
1919 }
1920
1921 /**
1922 * Resets the browser title-view to whatever it must be
1923 * (for example, if we had a loading error)
1924 * When we have a new page, we call resetTitle, when we
1925 * have to reset the titlebar to whatever it used to be
1926 * (for example, if the user chose to stop loading), we
1927 * call resetTitleAndRevertLockIcon.
1928 */
1929 /* package */ void resetTitleAndRevertLockIcon() {
1930 revertLockIcon();
1931 resetTitleIconAndProgress();
1932 }
1933
1934 /**
1935 * Reset the title, favicon, and progress.
1936 */
1937 private void resetTitleIconAndProgress() {
1938 WebView current = mTabControl.getCurrentWebView();
1939 if (current == null) {
1940 return;
1941 }
1942 resetTitleAndIcon(current);
1943 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001944 mWebChromeClient.onProgressChanged(current, progress);
1945 }
1946
1947 // Reset the title and the icon based on the given item.
1948 private void resetTitleAndIcon(WebView view) {
1949 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1950 if (item != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001951 setUrlTitle(item.getUrl(), item.getTitle(), view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001952 setFavicon(item.getFavicon());
1953 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001954 setUrlTitle(null, null, view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001955 setFavicon(null);
1956 }
1957 }
1958
1959 /**
1960 * Sets a title composed of the URL and the title string.
1961 * @param url The URL of the site being loaded.
1962 * @param title The title of the site being loaded.
1963 */
Leon Scroggins1f005d32009-08-10 17:36:42 -04001964 private void setUrlTitle(String url, String title, WebView view) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001965 mUrl = url;
1966 mTitle = title;
1967
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001968 mTitleBar.setTitleAndUrl(title, url, view);
1969 if (mFakeTitleBar != null) {
1970 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001971 }
1972 }
1973
1974 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001975 * @param url The URL to build a title version of the URL from.
1976 * @return The title version of the URL or null if fails.
1977 * The title version of the URL can be either the URL hostname,
1978 * or the hostname with an "https://" prefix (for secure URLs),
1979 * or an empty string if, for example, the URL in question is a
1980 * file:// URL with no hostname.
1981 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001982 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001983 String titleUrl = null;
1984
1985 if (url != null) {
1986 try {
1987 // parse the url string
1988 URL urlObj = new URL(url);
1989 if (urlObj != null) {
1990 titleUrl = "";
1991
1992 String protocol = urlObj.getProtocol();
1993 String host = urlObj.getHost();
1994
1995 if (host != null && 0 < host.length()) {
1996 titleUrl = host;
1997 if (protocol != null) {
1998 // if a secure site, add an "https://" prefix!
1999 if (protocol.equalsIgnoreCase("https")) {
2000 titleUrl = protocol + "://" + host;
2001 }
2002 }
2003 }
2004 }
2005 } catch (MalformedURLException e) {}
2006 }
2007
2008 return titleUrl;
2009 }
2010
2011 // Set the favicon in the title bar.
2012 private void setFavicon(Bitmap icon) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002013 mTitleBar.setFavicon(icon, getTopWindow());
2014 if (mFakeTitleBar != null) {
2015 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002016 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002017 }
2018
2019 /**
2020 * Saves the current lock-icon state before resetting
2021 * the lock icon. If we have an error, we may need to
2022 * roll back to the previous state.
2023 */
2024 private void saveLockIcon() {
2025 mPrevLockType = mLockIconType;
2026 }
2027
2028 /**
2029 * Reverts the lock-icon state to the last saved state,
2030 * for example, if we had an error, and need to cancel
2031 * the load.
2032 */
2033 private void revertLockIcon() {
2034 mLockIconType = mPrevLockType;
2035
Dave Bort31a6d1c2009-04-13 15:56:49 -07002036 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002037 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2038 " revert lock icon to " + mLockIconType);
2039 }
2040
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002041 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002042 }
2043
Leon Scroggins1f005d32009-08-10 17:36:42 -04002044 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002045 * Close the tab, remove its associated title bar, and adjust mTabControl's
2046 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002047 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002048 /* package */ void closeTab(TabControl.Tab t) {
2049 int currentIndex = mTabControl.getCurrentIndex();
2050 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002051 mTitleBar.removeTab(removeIndex);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002052 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002053 if (currentIndex >= removeIndex && currentIndex != 0) {
2054 currentIndex--;
2055 }
2056 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
The Android Open Source Project0c908882009-03-03 19:32:16 -08002057 }
2058
2059 private void goBackOnePageOrQuit() {
2060 TabControl.Tab current = mTabControl.getCurrentTab();
2061 if (current == null) {
2062 /*
2063 * Instead of finishing the activity, simply push this to the back
2064 * of the stack and let ActivityManager to choose the foreground
2065 * activity. As BrowserActivity is singleTask, it will be always the
2066 * root of the task. So we can use either true or false for
2067 * moveTaskToBack().
2068 */
2069 moveTaskToBack(true);
2070 }
2071 WebView w = current.getWebView();
2072 if (w.canGoBack()) {
2073 w.goBack();
2074 } else {
2075 // Check to see if we are closing a window that was created by
2076 // another window. If so, we switch back to that window.
2077 TabControl.Tab parent = current.getParentTab();
2078 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002079 switchToTab(mTabControl.getTabIndex(parent));
2080 // Now we close the other tab
2081 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002082 } else {
2083 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002084 // force mPageStarted to be false as we are going to either
2085 // finish the activity or remove the tab. This will ensure
2086 // pauseWebView() taking action.
2087 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002088 if (mTabControl.getTabCount() == 1) {
2089 finish();
2090 return;
2091 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002092 // call pauseWebViewTimers() now, we won't be able to call
2093 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002094 // Temporarily change mActivityInPause to be true as
2095 // pauseWebViewTimers() will do nothing if mActivityInPause
2096 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002097 boolean savedState = mActivityInPause;
2098 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002099 Log.e(LOGTAG, "BrowserActivity is already paused "
2100 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002101 }
2102 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002103 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002104 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002105 removeTabFromContentView(current);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002106 mTitleBar.removeTab(mTabControl.getTabIndex(current));
The Android Open Source Project0c908882009-03-03 19:32:16 -08002107 mTabControl.removeTab(current);
2108 }
2109 /*
2110 * Instead of finishing the activity, simply push this to the back
2111 * of the stack and let ActivityManager to choose the foreground
2112 * activity. As BrowserActivity is singleTask, it will be always the
2113 * root of the task. So we can use either true or false for
2114 * moveTaskToBack().
2115 */
2116 moveTaskToBack(true);
2117 }
2118 }
2119 }
2120
2121 public KeyTracker.State onKeyTracker(int keyCode,
2122 KeyEvent event,
2123 KeyTracker.Stage stage,
2124 int duration) {
2125 // if onKeyTracker() is called after activity onStop()
2126 // because of accumulated key events,
2127 // we should ignore it as browser is not active any more.
2128 WebView topWindow = getTopWindow();
Andrei Popescuadc008d2009-06-26 14:11:30 +01002129 if (topWindow == null && mCustomView == null)
The Android Open Source Project0c908882009-03-03 19:32:16 -08002130 return KeyTracker.State.NOT_TRACKING;
2131
2132 if (keyCode == KeyEvent.KEYCODE_BACK) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01002133 // Check if a custom view is currently showing and, if it is, hide it.
2134 if (mCustomView != null) {
2135 mWebChromeClient.onHideCustomView();
2136 return KeyTracker.State.DONE_TRACKING;
2137 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002138 if (stage == KeyTracker.Stage.LONG_REPEAT) {
Leon Scroggins30444232009-09-04 18:36:20 -04002139 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002140 return KeyTracker.State.DONE_TRACKING;
2141 } else if (stage == KeyTracker.Stage.UP) {
2142 // FIXME: Currently, we do not have a notion of the
2143 // history picker for the subwindow, but maybe we
2144 // should?
2145 WebView subwindow = mTabControl.getCurrentSubWindow();
2146 if (subwindow != null) {
2147 if (subwindow.canGoBack()) {
2148 subwindow.goBack();
2149 } else {
2150 dismissSubWindow(mTabControl.getCurrentTab());
2151 }
2152 } else {
2153 goBackOnePageOrQuit();
2154 }
2155 return KeyTracker.State.DONE_TRACKING;
2156 }
2157 return KeyTracker.State.KEEP_TRACKING;
2158 }
2159 return KeyTracker.State.NOT_TRACKING;
2160 }
2161
2162 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2163 if (keyCode == KeyEvent.KEYCODE_MENU) {
2164 mMenuIsDown = true;
Grace Kloba6ee9c492009-07-13 10:04:34 -07002165 } else if (mMenuIsDown) {
2166 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2167 // still down, we don't want to trigger the search. Pretend to
2168 // consume the key and do nothing.
2169 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002170 }
2171 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2172 if (!handled) {
2173 switch (keyCode) {
2174 case KeyEvent.KEYCODE_SPACE:
2175 if (event.isShiftPressed()) {
2176 getTopWindow().pageUp(false);
2177 } else {
2178 getTopWindow().pageDown(false);
2179 }
2180 handled = true;
2181 break;
2182
2183 default:
2184 break;
2185 }
2186 }
2187 return handled || super.onKeyDown(keyCode, event);
2188 }
2189
2190 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2191 if (keyCode == KeyEvent.KEYCODE_MENU) {
2192 mMenuIsDown = false;
2193 }
2194 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2195 }
2196
2197 private void stopLoading() {
2198 resetTitleAndRevertLockIcon();
2199 WebView w = getTopWindow();
2200 w.stopLoading();
2201 mWebViewClient.onPageFinished(w, w.getUrl());
2202
2203 cancelStopToast();
2204 mStopToast = Toast
2205 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2206 mStopToast.show();
2207 }
2208
2209 private void cancelStopToast() {
2210 if (mStopToast != null) {
2211 mStopToast.cancel();
2212 mStopToast = null;
2213 }
2214 }
2215
2216 // called by a non-UI thread to post the message
2217 public void postMessage(int what, int arg1, int arg2, Object obj) {
2218 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2219 }
2220
2221 // public message ids
2222 public final static int LOAD_URL = 1001;
2223 public final static int STOP_LOAD = 1002;
2224
2225 // Message Ids
2226 private static final int FOCUS_NODE_HREF = 102;
2227 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002228 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002229
2230 // Private handler for handling javascript and saving passwords
2231 private Handler mHandler = new Handler() {
2232
2233 public void handleMessage(Message msg) {
2234 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002235 case FOCUS_NODE_HREF:
2236 String url = (String) msg.getData().get("url");
2237 if (url == null || url.length() == 0) {
2238 break;
2239 }
2240 HashMap focusNodeMap = (HashMap) msg.obj;
2241 WebView view = (WebView) focusNodeMap.get("webview");
2242 // Only apply the action if the top window did not change.
2243 if (getTopWindow() != view) {
2244 break;
2245 }
2246 switch (msg.arg1) {
2247 case R.id.open_context_menu_id:
2248 case R.id.view_image_context_menu_id:
2249 loadURL(getTopWindow(), url);
2250 break;
2251 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002252 final TabControl.Tab parent = mTabControl
2253 .getCurrentTab();
2254 final TabControl.Tab newTab = openTab(url);
2255 if (newTab != parent) {
2256 parent.addChildTab(newTab);
2257 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002258 break;
2259 case R.id.bookmark_context_menu_id:
2260 Intent intent = new Intent(BrowserActivity.this,
2261 AddBookmarkPage.class);
2262 intent.putExtra("url", url);
2263 startActivity(intent);
2264 break;
2265 case R.id.share_link_context_menu_id:
2266 Browser.sendString(BrowserActivity.this, url);
2267 break;
2268 case R.id.copy_link_context_menu_id:
2269 copy(url);
2270 break;
2271 case R.id.save_link_context_menu_id:
2272 case R.id.download_context_menu_id:
2273 onDownloadStartNoStream(url, null, null, null, -1);
2274 break;
2275 }
2276 break;
2277
2278 case LOAD_URL:
2279 loadURL(getTopWindow(), (String) msg.obj);
2280 break;
2281
2282 case STOP_LOAD:
2283 stopLoading();
2284 break;
2285
2286 case CANCEL_CREDS_REQUEST:
2287 resumeAfterCredentials();
2288 break;
2289
The Android Open Source Project0c908882009-03-03 19:32:16 -08002290 case RELEASE_WAKELOCK:
2291 if (mWakeLock.isHeld()) {
2292 mWakeLock.release();
2293 }
2294 break;
2295 }
2296 }
2297 };
2298
Leon Scroggins89c6d362009-07-15 16:54:37 -04002299 private void updateScreenshot(WebView view) {
2300 // If this is a bookmarked site, add a screenshot to the database.
2301 // FIXME: When should we update? Every time?
2302 // FIXME: Would like to make sure there is actually something to
2303 // draw, but the API for that (WebViewCore.pictureReady()) is not
2304 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002305 ContentResolver cr = getContentResolver();
2306 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002307 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002308 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002309 boolean succeed = c.moveToFirst();
2310 ContentValues values = null;
2311 while (succeed) {
2312 if (values == null) {
2313 final ByteArrayOutputStream os
2314 = new ByteArrayOutputStream();
2315 Picture thumbnail = view.capturePicture();
2316 // Keep width and height in sync with BrowserBookmarksPage
2317 // and bookmark_thumb
2318 Bitmap bm = Bitmap.createBitmap(100, 80,
2319 Bitmap.Config.ARGB_4444);
2320 Canvas canvas = new Canvas(bm);
2321 // May need to tweak these values to determine what is the
2322 // best scale factor
2323 canvas.scale(.5f, .5f);
2324 thumbnail.draw(canvas);
2325 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2326 values = new ContentValues();
2327 values.put(Browser.BookmarkColumns.THUMBNAIL,
2328 os.toByteArray());
2329 }
2330 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2331 c.getInt(0)), values, null, null);
2332 succeed = c.moveToNext();
2333 }
2334 c.close();
2335 }
2336 }
2337
The Android Open Source Project0c908882009-03-03 19:32:16 -08002338 // -------------------------------------------------------------------------
2339 // WebViewClient implementation.
2340 //-------------------------------------------------------------------------
2341
2342 // Use in overrideUrlLoading
2343 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2344 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2345 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2346 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2347
2348 /* package */ WebViewClient getWebViewClient() {
2349 return mWebViewClient;
2350 }
2351
Patrick Scott3918d442009-08-04 13:22:29 -04002352 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002353 if (icon != null) {
2354 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott3918d442009-08-04 13:22:29 -04002355 view, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002356 }
2357 setFavicon(icon);
2358 }
2359
2360 private final WebViewClient mWebViewClient = new WebViewClient() {
2361 @Override
2362 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2363 resetLockIcon(url);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002364 setUrlTitle(url, null, view);
Ben Murdochbff2d602009-07-01 20:19:05 +01002365
2366 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2367 if (errorConsole != null) {
2368 errorConsole.clearErrorMessages();
2369 if (mShouldShowErrorConsole) {
2370 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2371 }
2372 }
2373
The Android Open Source Project0c908882009-03-03 19:32:16 -08002374 // Call updateIcon instead of setFavicon so the bookmark
2375 // database can be updated.
Patrick Scott3918d442009-08-04 13:22:29 -04002376 updateIcon(view, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002377
Grace Kloba4d7880f2009-08-12 09:35:42 -07002378 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002379 String host;
2380 try {
2381 WebAddress uri = new WebAddress(url);
2382 host = uri.mHost;
2383 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002384 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002385 }
2386 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002387 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002388 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002389 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002390 }
2391
2392 // Performance probe
2393 if (false) {
2394 mStart = SystemClock.uptimeMillis();
2395 mProcessStart = Process.getElapsedCpuTime();
2396 long[] sysCpu = new long[7];
2397 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2398 sysCpu, null)) {
2399 mUserStart = sysCpu[0] + sysCpu[1];
2400 mSystemStart = sysCpu[2];
2401 mIdleStart = sysCpu[3];
2402 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2403 }
2404 mUiStart = SystemClock.currentThreadTimeMillis();
2405 }
2406
2407 if (!mPageStarted) {
2408 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002409 // if onResume() has been called, resumeWebViewTimers() does
2410 // nothing.
2411 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002412 }
2413
2414 // reset sync timer to avoid sync starts during loading a page
2415 CookieSyncManager.getInstance().resetSync();
2416
2417 mInLoad = true;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002418 WebView currentWebView = mTabControl.getCurrentWebView();
2419 if (currentWebView == null || currentWebView.getScrollY() != 0) {
2420 // This page has begun to load, so show the title bar
2421 showFakeTitleBar();
2422 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002423 updateInLoadMenuItems();
2424 if (!mIsNetworkUp) {
2425 if ( mAlertDialog == null) {
2426 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2427 .setTitle(R.string.loadSuspendedTitle)
2428 .setMessage(R.string.loadSuspended)
2429 .setPositiveButton(R.string.ok, null)
2430 .show();
2431 }
2432 if (view != null) {
2433 view.setNetworkAvailable(false);
2434 }
2435 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002436 }
2437
2438 @Override
2439 public void onPageFinished(WebView view, String url) {
2440 // Reset the title and icon in case we stopped a provisional
2441 // load.
2442 resetTitleAndIcon(view);
2443
2444 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002445 updateLockIconToLatest();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002446 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002447
The Android Open Source Project0c908882009-03-03 19:32:16 -08002448 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002449 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002450 long[] sysCpu = new long[7];
2451 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2452 sysCpu, null)) {
2453 String uiInfo = "UI thread used "
2454 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2455 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002456 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002457 Log.d(LOGTAG, uiInfo);
2458 }
2459 //The string that gets written to the log
2460 String performanceString = "It took total "
2461 + (SystemClock.uptimeMillis() - mStart)
2462 + " ms clock time to load the page."
2463 + "\nbrowser process used "
2464 + (Process.getElapsedCpuTime() - mProcessStart)
2465 + " ms, user processes used "
2466 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2467 + " ms, kernel used "
2468 + (sysCpu[2] - mSystemStart) * 10
2469 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2470 + " ms and irq took "
2471 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2472 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002473 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002474 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2475 }
2476 if (url != null) {
2477 // strip the url to maintain consistency
2478 String newUrl = new String(url);
2479 if (newUrl.startsWith("http://www.")) {
2480 newUrl = newUrl.substring(11);
2481 } else if (newUrl.startsWith("http://")) {
2482 newUrl = newUrl.substring(7);
2483 } else if (newUrl.startsWith("https://www.")) {
2484 newUrl = newUrl.substring(12);
2485 } else if (newUrl.startsWith("https://")) {
2486 newUrl = newUrl.substring(8);
2487 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002488 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002489 Log.d(LOGTAG, newUrl + " loaded");
2490 }
2491 /*
2492 if (sWhiteList.contains(newUrl)) {
2493 // The string that gets pushed to the statistcs
2494 // service
2495 performanceString = performanceString
2496 + "\nWebpage: "
2497 + newUrl
2498 + "\nCarrier: "
2499 + android.os.SystemProperties
2500 .get("gsm.sim.operator.alpha");
2501 if (mWebView != null
2502 && mWebView.getContext() != null
2503 && mWebView.getContext().getSystemService(
2504 Context.CONNECTIVITY_SERVICE) != null) {
2505 ConnectivityManager cManager =
2506 (ConnectivityManager) mWebView
2507 .getContext().getSystemService(
2508 Context.CONNECTIVITY_SERVICE);
2509 NetworkInfo nInfo = cManager
2510 .getActiveNetworkInfo();
2511 if (nInfo != null) {
2512 performanceString = performanceString
2513 + "\nNetwork Type: "
2514 + nInfo.getType().toString();
2515 }
2516 }
2517 Checkin.logEvent(mResolver,
2518 Checkin.Events.Tag.WEBPAGE_LOAD,
2519 performanceString);
2520 Log.w(LOGTAG, "pushed to the statistics service");
2521 }
2522 */
2523 }
2524 }
2525 }
2526
2527 if (mInTrace) {
2528 mInTrace = false;
2529 Debug.stopMethodTracing();
2530 }
2531
2532 if (mPageStarted) {
2533 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002534 // pauseWebViewTimers() will do nothing and return false if
2535 // onPause() is not called yet.
2536 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002537 if (mWakeLock.isHeld()) {
2538 mHandler.removeMessages(RELEASE_WAKELOCK);
2539 mWakeLock.release();
2540 }
2541 }
2542 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002543 }
2544
2545 // return true if want to hijack the url to let another app to handle it
2546 @Override
2547 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2548 if (url.startsWith(SCHEME_WTAI)) {
2549 // wtai://wp/mc;number
2550 // number=string(phone-number)
2551 if (url.startsWith(SCHEME_WTAI_MC)) {
2552 Intent intent = new Intent(Intent.ACTION_VIEW,
2553 Uri.parse(WebView.SCHEME_TEL +
2554 url.substring(SCHEME_WTAI_MC.length())));
2555 startActivity(intent);
2556 return true;
2557 }
2558 // wtai://wp/sd;dtmf
2559 // dtmf=string(dialstring)
2560 if (url.startsWith(SCHEME_WTAI_SD)) {
2561 // TODO
2562 // only send when there is active voice connection
2563 return false;
2564 }
2565 // wtai://wp/ap;number;name
2566 // number=string(phone-number)
2567 // name=string
2568 if (url.startsWith(SCHEME_WTAI_AP)) {
2569 // TODO
2570 return false;
2571 }
2572 }
2573
Dianne Hackborn99189432009-06-17 18:06:18 -07002574 // The "about:" schemes are internal to the browser; don't
2575 // want these to be dispatched to other apps.
2576 if (url.startsWith("about:")) {
2577 return false;
2578 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002579
Dianne Hackborn99189432009-06-17 18:06:18 -07002580 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002581
Dianne Hackborn99189432009-06-17 18:06:18 -07002582 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002583 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002584 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2585 } catch (URISyntaxException ex) {
2586 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002587 return false;
2588 }
2589
Grace Kloba5b078b52009-06-24 20:23:41 -07002590 // check whether the intent can be resolved. If not, we will see
2591 // whether we can download it from the Market.
2592 if (getPackageManager().resolveActivity(intent, 0) == null) {
2593 String packagename = intent.getPackage();
2594 if (packagename != null) {
2595 intent = new Intent(Intent.ACTION_VIEW, Uri
2596 .parse("market://search?q=pname:" + packagename));
2597 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2598 startActivity(intent);
2599 return true;
2600 } else {
2601 return false;
2602 }
2603 }
2604
Dianne Hackborn99189432009-06-17 18:06:18 -07002605 // sanitize the Intent, ensuring web pages can not bypass browser
2606 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002607 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002608 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002609 try {
2610 if (startActivityIfNeeded(intent, -1)) {
2611 return true;
2612 }
2613 } catch (ActivityNotFoundException ex) {
2614 // ignore the error. If no application can handle the URL,
2615 // eg about:blank, assume the browser can handle it.
2616 }
2617
2618 if (mMenuIsDown) {
2619 openTab(url);
2620 closeOptionsMenu();
2621 return true;
2622 }
2623
2624 return false;
2625 }
2626
2627 /**
2628 * Updates the lock icon. This method is called when we discover another
2629 * resource to be loaded for this page (for example, javascript). While
2630 * we update the icon type, we do not update the lock icon itself until
2631 * we are done loading, it is slightly more secure this way.
2632 */
2633 @Override
2634 public void onLoadResource(WebView view, String url) {
2635 if (url != null && url.length() > 0) {
2636 // It is only if the page claims to be secure
2637 // that we may have to update the lock:
2638 if (mLockIconType == LOCK_ICON_SECURE) {
2639 // If NOT a 'safe' url, change the lock to mixed content!
2640 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2641 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002642 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002643 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2644 " updated lock icon to " + mLockIconType + " due to " + url);
2645 }
2646 }
2647 }
2648 }
2649 }
2650
2651 /**
2652 * Show the dialog, asking the user if they would like to continue after
2653 * an excessive number of HTTP redirects.
2654 */
2655 @Override
2656 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2657 final Message continueMsg) {
2658 new AlertDialog.Builder(BrowserActivity.this)
2659 .setTitle(R.string.browserFrameRedirect)
2660 .setMessage(R.string.browserFrame307Post)
2661 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2662 public void onClick(DialogInterface dialog, int which) {
2663 continueMsg.sendToTarget();
2664 }})
2665 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2666 public void onClick(DialogInterface dialog, int which) {
2667 cancelMsg.sendToTarget();
2668 }})
2669 .setOnCancelListener(new OnCancelListener() {
2670 public void onCancel(DialogInterface dialog) {
2671 cancelMsg.sendToTarget();
2672 }})
2673 .show();
2674 }
2675
Patrick Scott37911c72009-03-24 18:02:58 -07002676 // Container class for the next error dialog that needs to be
2677 // displayed.
2678 class ErrorDialog {
2679 public final int mTitle;
2680 public final String mDescription;
2681 public final int mError;
2682 ErrorDialog(int title, String desc, int error) {
2683 mTitle = title;
2684 mDescription = desc;
2685 mError = error;
2686 }
2687 };
2688
2689 private void processNextError() {
2690 if (mQueuedErrors == null) {
2691 return;
2692 }
2693 // The first one is currently displayed so just remove it.
2694 mQueuedErrors.removeFirst();
2695 if (mQueuedErrors.size() == 0) {
2696 mQueuedErrors = null;
2697 return;
2698 }
2699 showError(mQueuedErrors.getFirst());
2700 }
2701
2702 private DialogInterface.OnDismissListener mDialogListener =
2703 new DialogInterface.OnDismissListener() {
2704 public void onDismiss(DialogInterface d) {
2705 processNextError();
2706 }
2707 };
2708 private LinkedList<ErrorDialog> mQueuedErrors;
2709
2710 private void queueError(int err, String desc) {
2711 if (mQueuedErrors == null) {
2712 mQueuedErrors = new LinkedList<ErrorDialog>();
2713 }
2714 for (ErrorDialog d : mQueuedErrors) {
2715 if (d.mError == err) {
2716 // Already saw a similar error, ignore the new one.
2717 return;
2718 }
2719 }
2720 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002721 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002722 R.string.browserFrameFileErrorLabel :
2723 R.string.browserFrameNetworkErrorLabel,
2724 desc, err);
2725 mQueuedErrors.addLast(errDialog);
2726
2727 // Show the dialog now if the queue was empty.
2728 if (mQueuedErrors.size() == 1) {
2729 showError(errDialog);
2730 }
2731 }
2732
2733 private void showError(ErrorDialog errDialog) {
2734 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2735 .setTitle(errDialog.mTitle)
2736 .setMessage(errDialog.mDescription)
2737 .setPositiveButton(R.string.ok, null)
2738 .create();
2739 d.setOnDismissListener(mDialogListener);
2740 d.show();
2741 }
2742
The Android Open Source Project0c908882009-03-03 19:32:16 -08002743 /**
2744 * Show a dialog informing the user of the network error reported by
2745 * WebCore.
2746 */
2747 @Override
2748 public void onReceivedError(WebView view, int errorCode,
2749 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002750 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2751 errorCode != WebViewClient.ERROR_CONNECT &&
2752 errorCode != WebViewClient.ERROR_BAD_URL &&
2753 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2754 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002755 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002756 }
Patrick Scott37911c72009-03-24 18:02:58 -07002757 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2758 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002759
2760 // We need to reset the title after an error.
2761 resetTitleAndRevertLockIcon();
2762 }
2763
2764 /**
2765 * Check with the user if it is ok to resend POST data as the page they
2766 * are trying to navigate to is the result of a POST.
2767 */
2768 @Override
2769 public void onFormResubmission(WebView view, final Message dontResend,
2770 final Message resend) {
2771 new AlertDialog.Builder(BrowserActivity.this)
2772 .setTitle(R.string.browserFrameFormResubmitLabel)
2773 .setMessage(R.string.browserFrameFormResubmitMessage)
2774 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2775 public void onClick(DialogInterface dialog, int which) {
2776 resend.sendToTarget();
2777 }})
2778 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2779 public void onClick(DialogInterface dialog, int which) {
2780 dontResend.sendToTarget();
2781 }})
2782 .setOnCancelListener(new OnCancelListener() {
2783 public void onCancel(DialogInterface dialog) {
2784 dontResend.sendToTarget();
2785 }})
2786 .show();
2787 }
2788
2789 /**
2790 * Insert the url into the visited history database.
2791 * @param url The url to be inserted.
2792 * @param isReload True if this url is being reloaded.
2793 * FIXME: Not sure what to do when reloading the page.
2794 */
2795 @Override
2796 public void doUpdateVisitedHistory(WebView view, String url,
2797 boolean isReload) {
2798 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2799 return;
2800 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002801 // remove "client" before updating it to the history so that it wont
2802 // show up in the auto-complete list.
2803 int index = url.indexOf("client=ms-");
2804 if (index > 0 && url.contains(".google.")) {
2805 int end = url.indexOf('&', index);
2806 if (end > 0) {
2807 url = url.substring(0, index-1).concat(url.substring(end));
2808 } else {
2809 url = url.substring(0, index-1);
2810 }
2811 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002812 Browser.updateVisitedHistory(mResolver, url, true);
2813 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2814 }
2815
2816 /**
2817 * Displays SSL error(s) dialog to the user.
2818 */
2819 @Override
2820 public void onReceivedSslError(
2821 final WebView view, final SslErrorHandler handler, final SslError error) {
2822
2823 if (mSettings.showSecurityWarnings()) {
2824 final LayoutInflater factory =
2825 LayoutInflater.from(BrowserActivity.this);
2826 final View warningsView =
2827 factory.inflate(R.layout.ssl_warnings, null);
2828 final LinearLayout placeholder =
2829 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2830
2831 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2832 LinearLayout ll = (LinearLayout)factory
2833 .inflate(R.layout.ssl_warning, null);
2834 ((TextView)ll.findViewById(R.id.warning))
2835 .setText(R.string.ssl_untrusted);
2836 placeholder.addView(ll);
2837 }
2838
2839 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2840 LinearLayout ll = (LinearLayout)factory
2841 .inflate(R.layout.ssl_warning, null);
2842 ((TextView)ll.findViewById(R.id.warning))
2843 .setText(R.string.ssl_mismatch);
2844 placeholder.addView(ll);
2845 }
2846
2847 if (error.hasError(SslError.SSL_EXPIRED)) {
2848 LinearLayout ll = (LinearLayout)factory
2849 .inflate(R.layout.ssl_warning, null);
2850 ((TextView)ll.findViewById(R.id.warning))
2851 .setText(R.string.ssl_expired);
2852 placeholder.addView(ll);
2853 }
2854
2855 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2856 LinearLayout ll = (LinearLayout)factory
2857 .inflate(R.layout.ssl_warning, null);
2858 ((TextView)ll.findViewById(R.id.warning))
2859 .setText(R.string.ssl_not_yet_valid);
2860 placeholder.addView(ll);
2861 }
2862
2863 new AlertDialog.Builder(BrowserActivity.this)
2864 .setTitle(R.string.security_warning)
2865 .setIcon(android.R.drawable.ic_dialog_alert)
2866 .setView(warningsView)
2867 .setPositiveButton(R.string.ssl_continue,
2868 new DialogInterface.OnClickListener() {
2869 public void onClick(DialogInterface dialog, int whichButton) {
2870 handler.proceed();
2871 }
2872 })
2873 .setNeutralButton(R.string.view_certificate,
2874 new DialogInterface.OnClickListener() {
2875 public void onClick(DialogInterface dialog, int whichButton) {
2876 showSSLCertificateOnError(view, handler, error);
2877 }
2878 })
2879 .setNegativeButton(R.string.cancel,
2880 new DialogInterface.OnClickListener() {
2881 public void onClick(DialogInterface dialog, int whichButton) {
2882 handler.cancel();
2883 BrowserActivity.this.resetTitleAndRevertLockIcon();
2884 }
2885 })
2886 .setOnCancelListener(
2887 new DialogInterface.OnCancelListener() {
2888 public void onCancel(DialogInterface dialog) {
2889 handler.cancel();
2890 BrowserActivity.this.resetTitleAndRevertLockIcon();
2891 }
2892 })
2893 .show();
2894 } else {
2895 handler.proceed();
2896 }
2897 }
2898
2899 /**
2900 * Handles an HTTP authentication request.
2901 *
2902 * @param handler The authentication handler
2903 * @param host The host
2904 * @param realm The realm
2905 */
2906 @Override
2907 public void onReceivedHttpAuthRequest(WebView view,
2908 final HttpAuthHandler handler, final String host, final String realm) {
2909 String username = null;
2910 String password = null;
2911
2912 boolean reuseHttpAuthUsernamePassword =
2913 handler.useHttpAuthUsernamePassword();
2914
2915 if (reuseHttpAuthUsernamePassword &&
2916 (mTabControl.getCurrentWebView() != null)) {
2917 String[] credentials =
2918 mTabControl.getCurrentWebView()
2919 .getHttpAuthUsernamePassword(host, realm);
2920 if (credentials != null && credentials.length == 2) {
2921 username = credentials[0];
2922 password = credentials[1];
2923 }
2924 }
2925
2926 if (username != null && password != null) {
2927 handler.proceed(username, password);
2928 } else {
2929 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2930 }
2931 }
2932
2933 @Override
2934 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2935 if (mMenuIsDown) {
2936 // only check shortcut key when MENU is held
2937 return getWindow().isShortcutKey(event.getKeyCode(), event);
2938 } else {
2939 return false;
2940 }
2941 }
2942
2943 @Override
2944 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2945 if (view != mTabControl.getCurrentTopWebView()) {
2946 return;
2947 }
2948 if (event.isDown()) {
2949 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2950 } else {
2951 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2952 }
2953 }
2954 };
2955
2956 //--------------------------------------------------------------------------
2957 // WebChromeClient implementation
2958 //--------------------------------------------------------------------------
2959
2960 /* package */ WebChromeClient getWebChromeClient() {
2961 return mWebChromeClient;
2962 }
2963
2964 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2965 // Helper method to create a new tab or sub window.
2966 private void createWindow(final boolean dialog, final Message msg) {
2967 if (dialog) {
2968 mTabControl.createSubWindow();
2969 final TabControl.Tab t = mTabControl.getCurrentTab();
2970 attachSubWindow(t);
2971 WebView.WebViewTransport transport =
2972 (WebView.WebViewTransport) msg.obj;
2973 transport.setWebView(t.getSubWebView());
2974 msg.sendToTarget();
2975 } else {
2976 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04002977 final TabControl.Tab newTab
2978 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07002979 if (newTab != parent) {
2980 parent.addChildTab(newTab);
2981 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002982 WebView.WebViewTransport transport =
2983 (WebView.WebViewTransport) msg.obj;
2984 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04002985 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002986 }
2987 }
2988
2989 @Override
2990 public boolean onCreateWindow(WebView view, final boolean dialog,
2991 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002992 // Short-circuit if we can't create any more tabs or sub windows.
2993 if (dialog && mTabControl.getCurrentSubWindow() != null) {
2994 new AlertDialog.Builder(BrowserActivity.this)
2995 .setTitle(R.string.too_many_subwindows_dialog_title)
2996 .setIcon(android.R.drawable.ic_dialog_alert)
2997 .setMessage(R.string.too_many_subwindows_dialog_message)
2998 .setPositiveButton(R.string.ok, null)
2999 .show();
3000 return false;
3001 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3002 new AlertDialog.Builder(BrowserActivity.this)
3003 .setTitle(R.string.too_many_windows_dialog_title)
3004 .setIcon(android.R.drawable.ic_dialog_alert)
3005 .setMessage(R.string.too_many_windows_dialog_message)
3006 .setPositiveButton(R.string.ok, null)
3007 .show();
3008 return false;
3009 }
3010
3011 // Short-circuit if this was a user gesture.
3012 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003013 createWindow(dialog, resultMsg);
3014 return true;
3015 }
3016
3017 // Allow the popup and create the appropriate window.
3018 final AlertDialog.OnClickListener allowListener =
3019 new AlertDialog.OnClickListener() {
3020 public void onClick(DialogInterface d,
3021 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003022 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003023 }
3024 };
3025
3026 // Block the popup by returning a null WebView.
3027 final AlertDialog.OnClickListener blockListener =
3028 new AlertDialog.OnClickListener() {
3029 public void onClick(DialogInterface d, int which) {
3030 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003031 }
3032 };
3033
3034 // Build a confirmation dialog to display to the user.
3035 final AlertDialog d =
3036 new AlertDialog.Builder(BrowserActivity.this)
3037 .setTitle(R.string.attention)
3038 .setIcon(android.R.drawable.ic_dialog_alert)
3039 .setMessage(R.string.popup_window_attempt)
3040 .setPositiveButton(R.string.allow, allowListener)
3041 .setNegativeButton(R.string.block, blockListener)
3042 .setCancelable(false)
3043 .create();
3044
3045 // Show the confirmation dialog.
3046 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003047 return true;
3048 }
3049
3050 @Override
3051 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003052 final TabControl.Tab current = mTabControl.getCurrentTab();
3053 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003054 if (parent != null) {
3055 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003056 switchToTab(mTabControl.getTabIndex(parent));
3057 // Now we need to close the window
3058 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003059 }
3060 }
3061
3062 @Override
3063 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003064 mTitleBar.setProgress(newProgress, view);
3065 if (mFakeTitleBar != null) {
3066 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003067 }
3068
3069 if (newProgress == 100) {
3070 // onProgressChanged() is called for sub-frame too while
3071 // onPageFinished() is only called for the main frame. sync
3072 // cookie and cache promptly here.
3073 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003074 if (mInLoad) {
3075 mInLoad = false;
3076 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003077 // If the options menu is open, leave the title bar
3078 if (!mOptionsMenuOpen || !mIconView) {
3079 hideFakeTitleBar();
3080 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003081 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003082 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003083 // onPageFinished may have already been called but a subframe
3084 // is still loading and updating the progress. Reset mInLoad
3085 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003086 mInLoad = true;
3087 updateInLoadMenuItems();
3088 WebView currentWebView = mTabControl.getCurrentWebView();
3089 if ((currentWebView == null || currentWebView.getScrollY() != 0)
3090 && (!mOptionsMenuOpen || mIconView)) {
3091 // This page has begun to load, so show the title bar
3092 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003093 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003094 }
3095 }
3096
3097 @Override
3098 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003099 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003100
3101 // here, if url is null, we want to reset the title
Leon Scroggins1f005d32009-08-10 17:36:42 -04003102 setUrlTitle(url, title, view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003103
3104 if (url == null ||
3105 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3106 return;
3107 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003108 // See if we can find the current url in our history database and
3109 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003110 if (url.startsWith("http://www.")) {
3111 url = url.substring(11);
3112 } else if (url.startsWith("http://")) {
3113 url = url.substring(4);
3114 }
3115 try {
3116 url = "%" + url;
3117 String [] selArgs = new String[] { url };
3118
3119 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3120 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3121 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3122 Browser.HISTORY_PROJECTION, where, selArgs, null);
3123 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003124 // Current implementation of database only has one entry per
3125 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003126 ContentValues map = new ContentValues();
3127 map.put(Browser.BookmarkColumns.TITLE, title);
3128 mResolver.update(Browser.BOOKMARKS_URI, map,
3129 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003130 }
3131 c.close();
3132 } catch (IllegalStateException e) {
3133 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3134 } catch (SQLiteException ex) {
3135 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3136 }
3137 }
3138
3139 @Override
3140 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003141 updateIcon(view, icon);
3142 }
3143
3144 @Override
3145 public void onReceivedTouchIconUrl(WebView view, String url) {
3146 final ContentResolver cr = getContentResolver();
3147 final Cursor c =
3148 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003149 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003150 if (c != null) {
3151 if (c.getCount() > 0) {
3152 new DownloadTouchIcon(cr, c, view).execute(url);
3153 } else {
3154 c.close();
3155 }
3156 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003157 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003158
Andrei Popescuadc008d2009-06-26 14:11:30 +01003159 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003160 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003161 if (mCustomView != null)
3162 return;
3163
3164 // Add the custom view to its container.
3165 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3166 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003167 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003168 // Save the menu state and set it to empty while the custom
3169 // view is showing.
3170 mOldMenuState = mMenuState;
3171 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003172 // Hide the content view.
3173 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003174 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003175 mCustomViewContainer.setVisibility(View.VISIBLE);
3176 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003177 }
3178
3179 @Override
3180 public void onHideCustomView() {
3181 if (mCustomView == null)
3182 return;
3183
Andrei Popescuc9b55562009-07-07 10:51:15 +01003184 // Hide the custom view.
3185 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003186 // Remove the custom view from its container.
3187 mCustomViewContainer.removeView(mCustomView);
3188 mCustomView = null;
3189 // Reset the old menu state.
3190 mMenuState = mOldMenuState;
3191 mOldMenuState = EMPTY_MENU;
3192 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003193 mCustomViewCallback.onCustomViewHidden();
3194 // Show the content view.
3195 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003196 }
3197
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003198 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003199 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003200 * @param url the URL that exceeded the quota
3201 * @param databaseIdentifier the identifier of the database on
3202 * which the transaction that caused the quota overflow was run
3203 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003204 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003205 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003206 * @param quotaUpdater The callback to run when a decision to allow or
3207 * deny quota has been made. Don't forget to call this!
3208 */
3209 @Override
3210 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003211 String databaseIdentifier, long currentQuota, long estimatedSize,
3212 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003213 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003214 url, databaseIdentifier, currentQuota, estimatedSize,
3215 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003216 }
3217
3218 /**
3219 * The Application Cache has exceeded its max size.
3220 * @param spaceNeeded is the amount of disk space that would be needed
3221 * in order for the last appcache operation to succeed.
3222 * @param totalUsedQuota is the sum of all origins' quota.
3223 * @param quotaUpdater A callback to inform the WebCore thread that a new
3224 * app cache size is available. This callback must always be executed at
3225 * some point to ensure that the sleeping WebCore thread is woken up.
3226 */
3227 @Override
3228 public void onReachedMaxAppCacheSize(long spaceNeeded,
3229 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3230 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3231 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003232 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003233
Steve Block2bc69912009-07-30 14:45:13 +01003234 /**
3235 * Instructs the browser to show a prompt to ask the user to set the
3236 * Geolocation permission state for the specified origin.
3237 * @param origin The origin for which Geolocation permissions are
3238 * requested.
3239 * @param callback The callback to call once the user has set the
3240 * Geolocation permission state.
3241 */
3242 @Override
3243 public void onGeolocationPermissionsShowPrompt(String origin,
3244 GeolocationPermissions.Callback callback) {
3245 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3246 origin, callback);
3247 }
3248
3249 /**
3250 * Instructs the browser to hide the Geolocation permissions prompt.
3251 */
3252 @Override
3253 public void onGeolocationPermissionsHidePrompt() {
3254 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3255 }
3256
Ben Murdoch7db26342009-06-03 18:21:19 +01003257 /* Adds a JavaScript error message to the system log.
3258 * @param message The error message to report.
3259 * @param lineNumber The line number of the error.
3260 * @param sourceID The name of the source file that caused the error.
3261 */
3262 @Override
3263 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003264 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3265 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3266 if (mShouldShowErrorConsole &&
3267 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3268 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3269 }
3270 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003271 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003272 };
3273
3274 /**
3275 * Notify the host application a download should be done, or that
3276 * the data should be streamed if a streaming viewer is available.
3277 * @param url The full url to the content that should be downloaded
3278 * @param contentDisposition Content-disposition http header, if
3279 * present.
3280 * @param mimetype The mimetype of the content reported by the server
3281 * @param contentLength The file size reported by the server
3282 */
3283 public void onDownloadStart(String url, String userAgent,
3284 String contentDisposition, String mimetype, long contentLength) {
3285 // if we're dealing wih A/V content that's not explicitly marked
3286 // for download, check if it's streamable.
3287 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003288 || !contentDisposition.regionMatches(
3289 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003290 // query the package manager to see if there's a registered handler
3291 // that matches.
3292 Intent intent = new Intent(Intent.ACTION_VIEW);
3293 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003294 ResolveInfo info = getPackageManager().resolveActivity(intent,
3295 PackageManager.MATCH_DEFAULT_ONLY);
3296 if (info != null) {
3297 ComponentName myName = getComponentName();
3298 // If we resolved to ourselves, we don't want to attempt to
3299 // load the url only to try and download it again.
3300 if (!myName.getPackageName().equals(
3301 info.activityInfo.packageName)
3302 || !myName.getClassName().equals(
3303 info.activityInfo.name)) {
3304 // someone (other than us) knows how to handle this mime
3305 // type with this scheme, don't download.
3306 try {
3307 startActivity(intent);
3308 return;
3309 } catch (ActivityNotFoundException ex) {
3310 if (LOGD_ENABLED) {
3311 Log.d(LOGTAG, "activity not found for " + mimetype
3312 + " over " + Uri.parse(url).getScheme(),
3313 ex);
3314 }
3315 // Best behavior is to fall back to a download in this
3316 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003317 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003318 }
3319 }
3320 }
3321 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3322 }
3323
3324 /**
3325 * Notify the host application a download should be done, even if there
3326 * is a streaming viewer available for thise type.
3327 * @param url The full url to the content that should be downloaded
3328 * @param contentDisposition Content-disposition http header, if
3329 * present.
3330 * @param mimetype The mimetype of the content reported by the server
3331 * @param contentLength The file size reported by the server
3332 */
3333 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3334 String contentDisposition, String mimetype, long contentLength) {
3335
3336 String filename = URLUtil.guessFileName(url,
3337 contentDisposition, mimetype);
3338
3339 // Check to see if we have an SDCard
3340 String status = Environment.getExternalStorageState();
3341 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3342 int title;
3343 String msg;
3344
3345 // Check to see if the SDCard is busy, same as the music app
3346 if (status.equals(Environment.MEDIA_SHARED)) {
3347 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3348 title = R.string.download_sdcard_busy_dlg_title;
3349 } else {
3350 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3351 title = R.string.download_no_sdcard_dlg_title;
3352 }
3353
3354 new AlertDialog.Builder(this)
3355 .setTitle(title)
3356 .setIcon(android.R.drawable.ic_dialog_alert)
3357 .setMessage(msg)
3358 .setPositiveButton(R.string.ok, null)
3359 .show();
3360 return;
3361 }
3362
3363 // java.net.URI is a lot stricter than KURL so we have to undo
3364 // KURL's percent-encoding and redo the encoding using java.net.URI.
3365 URI uri = null;
3366 try {
3367 // Undo the percent-encoding that KURL may have done.
3368 String newUrl = new String(URLUtil.decode(url.getBytes()));
3369 // Parse the url into pieces
3370 WebAddress w = new WebAddress(newUrl);
3371 String frag = null;
3372 String query = null;
3373 String path = w.mPath;
3374 // Break the path into path, query, and fragment
3375 if (path.length() > 0) {
3376 // Strip the fragment
3377 int idx = path.lastIndexOf('#');
3378 if (idx != -1) {
3379 frag = path.substring(idx + 1);
3380 path = path.substring(0, idx);
3381 }
3382 idx = path.lastIndexOf('?');
3383 if (idx != -1) {
3384 query = path.substring(idx + 1);
3385 path = path.substring(0, idx);
3386 }
3387 }
3388 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3389 query, frag);
3390 } catch (Exception e) {
3391 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3392 return;
3393 }
3394
3395 // XXX: Have to use the old url since the cookies were stored using the
3396 // old percent-encoded url.
3397 String cookies = CookieManager.getInstance().getCookie(url);
3398
3399 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003400 values.put(Downloads.COLUMN_URI, uri.toString());
3401 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3402 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3403 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003404 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003405 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003406 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003407 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3408 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3409 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3410 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003411 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003412 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003413 }
3414 if (mimetype == null) {
3415 // We must have long pressed on a link or image to download it. We
3416 // are not sure of the mimetype in this case, so do a head request
3417 new FetchUrlMimeType(this).execute(values);
3418 } else {
3419 final Uri contentUri =
3420 getContentResolver().insert(Downloads.CONTENT_URI, values);
3421 viewDownloads(contentUri);
3422 }
3423
3424 }
3425
3426 /**
3427 * Resets the lock icon. This method is called when we start a new load and
3428 * know the url to be loaded.
3429 */
3430 private void resetLockIcon(String url) {
3431 // Save the lock-icon state (we revert to it if the load gets cancelled)
3432 saveLockIcon();
3433
3434 mLockIconType = LOCK_ICON_UNSECURE;
3435 if (URLUtil.isHttpsUrl(url)) {
3436 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003437 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003438 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3439 " reset lock icon to " + mLockIconType);
3440 }
3441 }
3442
3443 updateLockIconImage(LOCK_ICON_UNSECURE);
3444 }
3445
3446 /**
3447 * Resets the lock icon. This method is called when the icon needs to be
3448 * reset but we do not know whether we are loading a secure or not secure
3449 * page.
3450 */
3451 private void resetLockIcon() {
3452 // Save the lock-icon state (we revert to it if the load gets cancelled)
3453 saveLockIcon();
3454
3455 mLockIconType = LOCK_ICON_UNSECURE;
3456
Dave Bort31a6d1c2009-04-13 15:56:49 -07003457 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003458 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3459 " reset lock icon to " + mLockIconType);
3460 }
3461
3462 updateLockIconImage(LOCK_ICON_UNSECURE);
3463 }
3464
3465 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003466 * Update the lock icon to correspond to our latest state.
3467 */
3468 /* package */ void updateLockIconToLatest() {
3469 updateLockIconImage(mLockIconType);
3470 }
3471
3472 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003473 * Updates the lock-icon image in the title-bar.
3474 */
3475 private void updateLockIconImage(int lockIconType) {
3476 Drawable d = null;
3477 if (lockIconType == LOCK_ICON_SECURE) {
3478 d = mSecLockIcon;
3479 } else if (lockIconType == LOCK_ICON_MIXED) {
3480 d = mMixLockIcon;
3481 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003482 mTitleBar.setLock(d, getTopWindow());
3483 if (mFakeTitleBar != null) {
3484 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003485 }
3486 }
3487
3488 /**
3489 * Displays a page-info dialog.
3490 * @param tab The tab to show info about
3491 * @param fromShowSSLCertificateOnError The flag that indicates whether
3492 * this dialog was opened from the SSL-certificate-on-error dialog or
3493 * not. This is important, since we need to know whether to return to
3494 * the parent dialog or simply dismiss.
3495 */
3496 private void showPageInfo(final TabControl.Tab tab,
3497 final boolean fromShowSSLCertificateOnError) {
3498 final LayoutInflater factory = LayoutInflater
3499 .from(this);
3500
3501 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3502
3503 final WebView view = tab.getWebView();
3504
3505 String url = null;
3506 String title = null;
3507
3508 if (view == null) {
3509 url = tab.getUrl();
3510 title = tab.getTitle();
3511 } else if (view == mTabControl.getCurrentWebView()) {
3512 // Use the cached title and url if this is the current WebView
3513 url = mUrl;
3514 title = mTitle;
3515 } else {
3516 url = view.getUrl();
3517 title = view.getTitle();
3518 }
3519
3520 if (url == null) {
3521 url = "";
3522 }
3523 if (title == null) {
3524 title = "";
3525 }
3526
3527 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3528 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3529
3530 mPageInfoView = tab;
3531 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3532
3533 AlertDialog.Builder alertDialogBuilder =
3534 new AlertDialog.Builder(this)
3535 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3536 .setView(pageInfoView)
3537 .setPositiveButton(
3538 R.string.ok,
3539 new DialogInterface.OnClickListener() {
3540 public void onClick(DialogInterface dialog,
3541 int whichButton) {
3542 mPageInfoDialog = null;
3543 mPageInfoView = null;
3544 mPageInfoFromShowSSLCertificateOnError = null;
3545
3546 // if we came here from the SSL error dialog
3547 if (fromShowSSLCertificateOnError) {
3548 // go back to the SSL error dialog
3549 showSSLCertificateOnError(
3550 mSSLCertificateOnErrorView,
3551 mSSLCertificateOnErrorHandler,
3552 mSSLCertificateOnErrorError);
3553 }
3554 }
3555 })
3556 .setOnCancelListener(
3557 new DialogInterface.OnCancelListener() {
3558 public void onCancel(DialogInterface dialog) {
3559 mPageInfoDialog = null;
3560 mPageInfoView = null;
3561 mPageInfoFromShowSSLCertificateOnError = null;
3562
3563 // if we came here from the SSL error dialog
3564 if (fromShowSSLCertificateOnError) {
3565 // go back to the SSL error dialog
3566 showSSLCertificateOnError(
3567 mSSLCertificateOnErrorView,
3568 mSSLCertificateOnErrorHandler,
3569 mSSLCertificateOnErrorError);
3570 }
3571 }
3572 });
3573
3574 // if we have a main top-level page SSL certificate set or a certificate
3575 // error
3576 if (fromShowSSLCertificateOnError ||
3577 (view != null && view.getCertificate() != null)) {
3578 // add a 'View Certificate' button
3579 alertDialogBuilder.setNeutralButton(
3580 R.string.view_certificate,
3581 new DialogInterface.OnClickListener() {
3582 public void onClick(DialogInterface dialog,
3583 int whichButton) {
3584 mPageInfoDialog = null;
3585 mPageInfoView = null;
3586 mPageInfoFromShowSSLCertificateOnError = null;
3587
3588 // if we came here from the SSL error dialog
3589 if (fromShowSSLCertificateOnError) {
3590 // go back to the SSL error dialog
3591 showSSLCertificateOnError(
3592 mSSLCertificateOnErrorView,
3593 mSSLCertificateOnErrorHandler,
3594 mSSLCertificateOnErrorError);
3595 } else {
3596 // otherwise, display the top-most certificate from
3597 // the chain
3598 if (view.getCertificate() != null) {
3599 showSSLCertificate(tab);
3600 }
3601 }
3602 }
3603 });
3604 }
3605
3606 mPageInfoDialog = alertDialogBuilder.show();
3607 }
3608
3609 /**
3610 * Displays the main top-level page SSL certificate dialog
3611 * (accessible from the Page-Info dialog).
3612 * @param tab The tab to show certificate for.
3613 */
3614 private void showSSLCertificate(final TabControl.Tab tab) {
3615 final View certificateView =
3616 inflateCertificateView(tab.getWebView().getCertificate());
3617 if (certificateView == null) {
3618 return;
3619 }
3620
3621 LayoutInflater factory = LayoutInflater.from(this);
3622
3623 final LinearLayout placeholder =
3624 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3625
3626 LinearLayout ll = (LinearLayout) factory.inflate(
3627 R.layout.ssl_success, placeholder);
3628 ((TextView)ll.findViewById(R.id.success))
3629 .setText(R.string.ssl_certificate_is_valid);
3630
3631 mSSLCertificateView = tab;
3632 mSSLCertificateDialog =
3633 new AlertDialog.Builder(this)
3634 .setTitle(R.string.ssl_certificate).setIcon(
3635 R.drawable.ic_dialog_browser_certificate_secure)
3636 .setView(certificateView)
3637 .setPositiveButton(R.string.ok,
3638 new DialogInterface.OnClickListener() {
3639 public void onClick(DialogInterface dialog,
3640 int whichButton) {
3641 mSSLCertificateDialog = null;
3642 mSSLCertificateView = null;
3643
3644 showPageInfo(tab, false);
3645 }
3646 })
3647 .setOnCancelListener(
3648 new DialogInterface.OnCancelListener() {
3649 public void onCancel(DialogInterface dialog) {
3650 mSSLCertificateDialog = null;
3651 mSSLCertificateView = null;
3652
3653 showPageInfo(tab, false);
3654 }
3655 })
3656 .show();
3657 }
3658
3659 /**
3660 * Displays the SSL error certificate dialog.
3661 * @param view The target web-view.
3662 * @param handler The SSL error handler responsible for cancelling the
3663 * connection that resulted in an SSL error or proceeding per user request.
3664 * @param error The SSL error object.
3665 */
3666 private void showSSLCertificateOnError(
3667 final WebView view, final SslErrorHandler handler, final SslError error) {
3668
3669 final View certificateView =
3670 inflateCertificateView(error.getCertificate());
3671 if (certificateView == null) {
3672 return;
3673 }
3674
3675 LayoutInflater factory = LayoutInflater.from(this);
3676
3677 final LinearLayout placeholder =
3678 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3679
3680 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3681 LinearLayout ll = (LinearLayout)factory
3682 .inflate(R.layout.ssl_warning, placeholder);
3683 ((TextView)ll.findViewById(R.id.warning))
3684 .setText(R.string.ssl_untrusted);
3685 }
3686
3687 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3688 LinearLayout ll = (LinearLayout)factory
3689 .inflate(R.layout.ssl_warning, placeholder);
3690 ((TextView)ll.findViewById(R.id.warning))
3691 .setText(R.string.ssl_mismatch);
3692 }
3693
3694 if (error.hasError(SslError.SSL_EXPIRED)) {
3695 LinearLayout ll = (LinearLayout)factory
3696 .inflate(R.layout.ssl_warning, placeholder);
3697 ((TextView)ll.findViewById(R.id.warning))
3698 .setText(R.string.ssl_expired);
3699 }
3700
3701 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3702 LinearLayout ll = (LinearLayout)factory
3703 .inflate(R.layout.ssl_warning, placeholder);
3704 ((TextView)ll.findViewById(R.id.warning))
3705 .setText(R.string.ssl_not_yet_valid);
3706 }
3707
3708 mSSLCertificateOnErrorHandler = handler;
3709 mSSLCertificateOnErrorView = view;
3710 mSSLCertificateOnErrorError = error;
3711 mSSLCertificateOnErrorDialog =
3712 new AlertDialog.Builder(this)
3713 .setTitle(R.string.ssl_certificate).setIcon(
3714 R.drawable.ic_dialog_browser_certificate_partially_secure)
3715 .setView(certificateView)
3716 .setPositiveButton(R.string.ok,
3717 new DialogInterface.OnClickListener() {
3718 public void onClick(DialogInterface dialog,
3719 int whichButton) {
3720 mSSLCertificateOnErrorDialog = null;
3721 mSSLCertificateOnErrorView = null;
3722 mSSLCertificateOnErrorHandler = null;
3723 mSSLCertificateOnErrorError = null;
3724
3725 mWebViewClient.onReceivedSslError(
3726 view, handler, error);
3727 }
3728 })
3729 .setNeutralButton(R.string.page_info_view,
3730 new DialogInterface.OnClickListener() {
3731 public void onClick(DialogInterface dialog,
3732 int whichButton) {
3733 mSSLCertificateOnErrorDialog = null;
3734
3735 // do not clear the dialog state: we will
3736 // need to show the dialog again once the
3737 // user is done exploring the page-info details
3738
3739 showPageInfo(mTabControl.getTabFromView(view),
3740 true);
3741 }
3742 })
3743 .setOnCancelListener(
3744 new DialogInterface.OnCancelListener() {
3745 public void onCancel(DialogInterface dialog) {
3746 mSSLCertificateOnErrorDialog = null;
3747 mSSLCertificateOnErrorView = null;
3748 mSSLCertificateOnErrorHandler = null;
3749 mSSLCertificateOnErrorError = null;
3750
3751 mWebViewClient.onReceivedSslError(
3752 view, handler, error);
3753 }
3754 })
3755 .show();
3756 }
3757
3758 /**
3759 * Inflates the SSL certificate view (helper method).
3760 * @param certificate The SSL certificate.
3761 * @return The resultant certificate view with issued-to, issued-by,
3762 * issued-on, expires-on, and possibly other fields set.
3763 * If the input certificate is null, returns null.
3764 */
3765 private View inflateCertificateView(SslCertificate certificate) {
3766 if (certificate == null) {
3767 return null;
3768 }
3769
3770 LayoutInflater factory = LayoutInflater.from(this);
3771
3772 View certificateView = factory.inflate(
3773 R.layout.ssl_certificate, null);
3774
3775 // issued to:
3776 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3777 if (issuedTo != null) {
3778 ((TextView) certificateView.findViewById(R.id.to_common))
3779 .setText(issuedTo.getCName());
3780 ((TextView) certificateView.findViewById(R.id.to_org))
3781 .setText(issuedTo.getOName());
3782 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3783 .setText(issuedTo.getUName());
3784 }
3785
3786 // issued by:
3787 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3788 if (issuedBy != null) {
3789 ((TextView) certificateView.findViewById(R.id.by_common))
3790 .setText(issuedBy.getCName());
3791 ((TextView) certificateView.findViewById(R.id.by_org))
3792 .setText(issuedBy.getOName());
3793 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3794 .setText(issuedBy.getUName());
3795 }
3796
3797 // issued on:
3798 String issuedOn = reformatCertificateDate(
3799 certificate.getValidNotBefore());
3800 ((TextView) certificateView.findViewById(R.id.issued_on))
3801 .setText(issuedOn);
3802
3803 // expires on:
3804 String expiresOn = reformatCertificateDate(
3805 certificate.getValidNotAfter());
3806 ((TextView) certificateView.findViewById(R.id.expires_on))
3807 .setText(expiresOn);
3808
3809 return certificateView;
3810 }
3811
3812 /**
3813 * Re-formats the certificate date (Date.toString()) string to
3814 * a properly localized date string.
3815 * @return Properly localized version of the certificate date string and
3816 * the original certificate date string if fails to localize.
3817 * If the original string is null, returns an empty string "".
3818 */
3819 private String reformatCertificateDate(String certificateDate) {
3820 String reformattedDate = null;
3821
3822 if (certificateDate != null) {
3823 Date date = null;
3824 try {
3825 date = java.text.DateFormat.getInstance().parse(certificateDate);
3826 } catch (ParseException e) {
3827 date = null;
3828 }
3829
3830 if (date != null) {
3831 reformattedDate =
3832 DateFormat.getDateFormat(this).format(date);
3833 }
3834 }
3835
3836 return reformattedDate != null ? reformattedDate :
3837 (certificateDate != null ? certificateDate : "");
3838 }
3839
3840 /**
3841 * Displays an http-authentication dialog.
3842 */
3843 private void showHttpAuthentication(final HttpAuthHandler handler,
3844 final String host, final String realm, final String title,
3845 final String name, final String password, int focusId) {
3846 LayoutInflater factory = LayoutInflater.from(this);
3847 final View v = factory
3848 .inflate(R.layout.http_authentication, null);
3849 if (name != null) {
3850 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3851 }
3852 if (password != null) {
3853 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3854 }
3855
3856 String titleText = title;
3857 if (titleText == null) {
3858 titleText = getText(R.string.sign_in_to).toString().replace(
3859 "%s1", host).replace("%s2", realm);
3860 }
3861
3862 mHttpAuthHandler = handler;
3863 AlertDialog dialog = new AlertDialog.Builder(this)
3864 .setTitle(titleText)
3865 .setIcon(android.R.drawable.ic_dialog_alert)
3866 .setView(v)
3867 .setPositiveButton(R.string.action,
3868 new DialogInterface.OnClickListener() {
3869 public void onClick(DialogInterface dialog,
3870 int whichButton) {
3871 String nm = ((EditText) v
3872 .findViewById(R.id.username_edit))
3873 .getText().toString();
3874 String pw = ((EditText) v
3875 .findViewById(R.id.password_edit))
3876 .getText().toString();
3877 BrowserActivity.this.setHttpAuthUsernamePassword
3878 (host, realm, nm, pw);
3879 handler.proceed(nm, pw);
3880 mHttpAuthenticationDialog = null;
3881 mHttpAuthHandler = null;
3882 }})
3883 .setNegativeButton(R.string.cancel,
3884 new DialogInterface.OnClickListener() {
3885 public void onClick(DialogInterface dialog,
3886 int whichButton) {
3887 handler.cancel();
3888 BrowserActivity.this.resetTitleAndRevertLockIcon();
3889 mHttpAuthenticationDialog = null;
3890 mHttpAuthHandler = null;
3891 }})
3892 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3893 public void onCancel(DialogInterface dialog) {
3894 handler.cancel();
3895 BrowserActivity.this.resetTitleAndRevertLockIcon();
3896 mHttpAuthenticationDialog = null;
3897 mHttpAuthHandler = null;
3898 }})
3899 .create();
3900 // Make the IME appear when the dialog is displayed if applicable.
3901 dialog.getWindow().setSoftInputMode(
3902 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3903 dialog.show();
3904 if (focusId != 0) {
3905 dialog.findViewById(focusId).requestFocus();
3906 } else {
3907 v.findViewById(R.id.username_edit).requestFocus();
3908 }
3909 mHttpAuthenticationDialog = dialog;
3910 }
3911
3912 public int getProgress() {
3913 WebView w = mTabControl.getCurrentWebView();
3914 if (w != null) {
3915 return w.getProgress();
3916 } else {
3917 return 100;
3918 }
3919 }
3920
3921 /**
3922 * Set HTTP authentication password.
3923 *
3924 * @param host The host for the password
3925 * @param realm The realm for the password
3926 * @param username The username for the password. If it is null, it means
3927 * password can't be saved.
3928 * @param password The password
3929 */
3930 public void setHttpAuthUsernamePassword(String host, String realm,
3931 String username,
3932 String password) {
3933 WebView w = mTabControl.getCurrentWebView();
3934 if (w != null) {
3935 w.setHttpAuthUsernamePassword(host, realm, username, password);
3936 }
3937 }
3938
3939 /**
3940 * connectivity manager says net has come or gone... inform the user
3941 * @param up true if net has come up, false if net has gone down
3942 */
3943 public void onNetworkToggle(boolean up) {
3944 if (up == mIsNetworkUp) {
3945 return;
3946 } else if (up) {
3947 mIsNetworkUp = true;
3948 if (mAlertDialog != null) {
3949 mAlertDialog.cancel();
3950 mAlertDialog = null;
3951 }
3952 } else {
3953 mIsNetworkUp = false;
3954 if (mInLoad && mAlertDialog == null) {
3955 mAlertDialog = new AlertDialog.Builder(this)
3956 .setTitle(R.string.loadSuspendedTitle)
3957 .setMessage(R.string.loadSuspended)
3958 .setPositiveButton(R.string.ok, null)
3959 .show();
3960 }
3961 }
3962 WebView w = mTabControl.getCurrentWebView();
3963 if (w != null) {
3964 w.setNetworkAvailable(up);
3965 }
3966 }
3967
3968 @Override
3969 protected void onActivityResult(int requestCode, int resultCode,
3970 Intent intent) {
3971 switch (requestCode) {
3972 case COMBO_PAGE:
3973 if (resultCode == RESULT_OK && intent != null) {
3974 String data = intent.getAction();
3975 Bundle extras = intent.getExtras();
3976 if (extras != null && extras.getBoolean("new_window", false)) {
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003977 final TabControl.Tab newTab = openTab(data);
3978 if (mSettings.openInBackground() &&
Leon Scroggins1f005d32009-08-10 17:36:42 -04003979 newTab != null) {
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003980 mTabControl.populatePickerData(newTab);
3981 mTabControl.setCurrentTab(newTab);
Leon Scroggins1f005d32009-08-10 17:36:42 -04003982 int newIndex = mTabControl.getCurrentIndex();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003983 mTitleBar.setCurrentTab(newIndex);
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003984 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003985 } else {
3986 final TabControl.Tab currentTab =
3987 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003988 dismissSubWindow(currentTab);
3989 if (data != null && data.length() != 0) {
3990 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003991 }
3992 }
3993 }
3994 break;
3995 default:
3996 break;
3997 }
Leon Scroggins30444232009-09-04 18:36:20 -04003998 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003999 }
4000
4001 /*
4002 * This method is called as a result of the user selecting the options
4003 * menu to see the download window, or when a download changes state. It
4004 * shows the download window ontop of the current window.
4005 */
4006 /* package */ void viewDownloads(Uri downloadRecord) {
4007 Intent intent = new Intent(this,
4008 BrowserDownloadPage.class);
4009 intent.setData(downloadRecord);
4010 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4011
4012 }
4013
Leon Scroggins160a7e72009-08-14 18:28:01 -04004014 /**
4015 * Open the Go page.
4016 * @param startWithHistory If true, open starting on the history tab.
4017 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004018 */
Leon Scroggins30444232009-09-04 18:36:20 -04004019 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004020 WebView current = mTabControl.getCurrentWebView();
4021 if (current == null) {
4022 return;
4023 }
4024 Intent intent = new Intent(this,
4025 CombinedBookmarkHistoryActivity.class);
4026 String title = current.getTitle();
4027 String url = current.getUrl();
4028 // Just in case the user opens bookmarks before a page finishes loading
4029 // so the current history item, and therefore the page, is null.
4030 if (null == url) {
4031 url = mLastEnteredUrl;
4032 // This can happen.
4033 if (null == url) {
4034 url = mSettings.getHomePage();
4035 }
4036 }
4037 // In case the web page has not yet received its associated title.
4038 if (title == null) {
4039 title = url;
4040 }
4041 intent.putExtra("title", title);
4042 intent.putExtra("url", url);
Leon Scroggins30444232009-09-04 18:36:20 -04004043 // Disable opening in a new window if we have maxed out the windows
4044 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4045 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004046 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004047 if (startWithHistory) {
4048 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4049 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4050 }
4051 startActivityForResult(intent, COMBO_PAGE);
4052 }
4053
4054 // Called when loading from context menu or LOAD_URL message
4055 private void loadURL(WebView view, String url) {
4056 // In case the user enters nothing.
4057 if (url != null && url.length() != 0 && view != null) {
4058 url = smartUrlFilter(url);
4059 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4060 view.loadUrl(url);
4061 }
4062 }
4063 }
4064
The Android Open Source Project0c908882009-03-03 19:32:16 -08004065 private String smartUrlFilter(Uri inUri) {
4066 if (inUri != null) {
4067 return smartUrlFilter(inUri.toString());
4068 }
4069 return null;
4070 }
4071
4072
4073 // get window count
4074
4075 int getWindowCount(){
4076 if(mTabControl != null){
4077 return mTabControl.getTabCount();
4078 }
4079 return 0;
4080 }
4081
Feng Qianb34f87a2009-03-24 21:27:26 -07004082 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004083 "(?i)" + // switch on case insensitive matching
4084 "(" + // begin group for schema
4085 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004086 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004087 ")" +
4088 "(.*)" );
4089
4090 /**
4091 * Attempts to determine whether user input is a URL or search
4092 * terms. Anything with a space is passed to search.
4093 *
4094 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4095 * "Http://" converts to "http://"
4096 *
4097 * @return Original or modified URL
4098 *
4099 */
4100 String smartUrlFilter(String url) {
4101
4102 String inUrl = url.trim();
4103 boolean hasSpace = inUrl.indexOf(' ') != -1;
4104
4105 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4106 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004107 // force scheme to lowercase
4108 String scheme = matcher.group(1);
4109 String lcScheme = scheme.toLowerCase();
4110 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004111 inUrl = lcScheme + matcher.group(2);
4112 }
4113 if (hasSpace) {
4114 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004115 }
4116 return inUrl;
4117 }
4118 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004119 // FIXME: Is this the correct place to add to searches?
4120 // what if someone else calls this function?
4121 int shortcut = parseUrlShortcut(inUrl);
4122 if (shortcut != SHORTCUT_INVALID) {
4123 Browser.addSearchUrl(mResolver, inUrl);
4124 String query = inUrl.substring(2);
4125 switch (shortcut) {
4126 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004127 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004128 case SHORTCUT_WIKIPEDIA_SEARCH:
4129 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4130 case SHORTCUT_DICTIONARY_SEARCH:
4131 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4132 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004133 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004134 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004135 }
4136 }
4137 } else {
4138 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4139 return URLUtil.guessUrl(inUrl);
4140 }
4141 }
4142
4143 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004144 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004145 }
4146
Ben Murdochbff2d602009-07-01 20:19:05 +01004147 /* package */ void setShouldShowErrorConsole(boolean flag) {
4148 if (flag == mShouldShowErrorConsole) {
4149 // Nothing to do.
4150 return;
4151 }
4152
4153 mShouldShowErrorConsole = flag;
4154
4155 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4156
4157 if (flag) {
4158 // Setting the show state of the console will cause it's the layout to be inflated.
4159 if (errorConsole.numberOfErrors() > 0) {
4160 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4161 } else {
4162 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4163 }
4164
4165 // Now we can add it to the main view.
4166 mErrorConsoleContainer.addView(errorConsole,
4167 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4168 ViewGroup.LayoutParams.WRAP_CONTENT));
4169 } else {
4170 mErrorConsoleContainer.removeView(errorConsole);
4171 }
4172
4173 }
4174
The Android Open Source Project0c908882009-03-03 19:32:16 -08004175 private final static int LOCK_ICON_UNSECURE = 0;
4176 private final static int LOCK_ICON_SECURE = 1;
4177 private final static int LOCK_ICON_MIXED = 2;
4178
4179 private int mLockIconType = LOCK_ICON_UNSECURE;
4180 private int mPrevLockType = LOCK_ICON_UNSECURE;
4181
4182 private BrowserSettings mSettings;
4183 private TabControl mTabControl;
4184 private ContentResolver mResolver;
4185 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004186 private View mCustomView;
4187 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004188 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004189
4190 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4191 // view, we should rewrite this.
4192 private int mCurrentMenuState = 0;
4193 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004194 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004195 private static final int EMPTY_MENU = -1;
4196 private Menu mMenu;
4197
4198 private FindDialog mFindDialog;
4199 // Used to prevent chording to result in firing two shortcuts immediately
4200 // one after another. Fixes bug 1211714.
4201 boolean mCanChord;
4202
4203 private boolean mInLoad;
4204 private boolean mIsNetworkUp;
4205
4206 private boolean mPageStarted;
4207 private boolean mActivityInPause = true;
4208
4209 private boolean mMenuIsDown;
4210
4211 private final KeyTracker mKeyTracker = new KeyTracker(this);
4212
4213 // As trackball doesn't send repeat down, we have to track it ourselves
4214 private boolean mTrackTrackball;
4215
4216 private static boolean mInTrace;
4217
4218 // Performance probe
4219 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4220 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4221 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4222 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4223 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4224 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4225 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4226 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4227 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4228 };
4229
4230 private long mStart;
4231 private long mProcessStart;
4232 private long mUserStart;
4233 private long mSystemStart;
4234 private long mIdleStart;
4235 private long mIrqStart;
4236
4237 private long mUiStart;
4238
4239 private Drawable mMixLockIcon;
4240 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004241
4242 /* hold a ref so we can auto-cancel if necessary */
4243 private AlertDialog mAlertDialog;
4244
4245 // Wait for credentials before loading google.com
4246 private ProgressDialog mCredsDlg;
4247
4248 // The up-to-date URL and title (these can be different from those stored
4249 // in WebView, since it takes some time for the information in WebView to
4250 // get updated)
4251 private String mUrl;
4252 private String mTitle;
4253
4254 // As PageInfo has different style for landscape / portrait, we have
4255 // to re-open it when configuration changed
4256 private AlertDialog mPageInfoDialog;
4257 private TabControl.Tab mPageInfoView;
4258 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4259 // dialog, we should not just dismiss it, but should get back to the
4260 // SSL-certificate-on-error dialog. This flag is used to store this state
4261 private Boolean mPageInfoFromShowSSLCertificateOnError;
4262
4263 // as SSLCertificateOnError has different style for landscape / portrait,
4264 // we have to re-open it when configuration changed
4265 private AlertDialog mSSLCertificateOnErrorDialog;
4266 private WebView mSSLCertificateOnErrorView;
4267 private SslErrorHandler mSSLCertificateOnErrorHandler;
4268 private SslError mSSLCertificateOnErrorError;
4269
4270 // as SSLCertificate has different style for landscape / portrait, we
4271 // have to re-open it when configuration changed
4272 private AlertDialog mSSLCertificateDialog;
4273 private TabControl.Tab mSSLCertificateView;
4274
4275 // as HttpAuthentication has different style for landscape / portrait, we
4276 // have to re-open it when configuration changed
4277 private AlertDialog mHttpAuthenticationDialog;
4278 private HttpAuthHandler mHttpAuthHandler;
4279
4280 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4281 new FrameLayout.LayoutParams(
4282 ViewGroup.LayoutParams.FILL_PARENT,
4283 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004284 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4285 new FrameLayout.LayoutParams(
4286 ViewGroup.LayoutParams.FILL_PARENT,
4287 ViewGroup.LayoutParams.FILL_PARENT,
4288 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004289 // Google search
4290 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004291 // Wikipedia search
4292 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4293 // Dictionary search
4294 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4295 // Google Mobile Local search
4296 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4297
4298 final static String QUERY_PLACE_HOLDER = "%s";
4299
4300 // "source" parameter for Google search through search key
4301 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4302 // "source" parameter for Google search through goto menu
4303 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4304 // "source" parameter for Google search through simplily type
4305 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4306 // "source" parameter for Google search suggested by the browser
4307 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4308 // "source" parameter for Google search from unknown source
4309 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4310
4311 private final static String LOGTAG = "browser";
4312
The Android Open Source Project0c908882009-03-03 19:32:16 -08004313 private String mLastEnteredUrl;
4314
4315 private PowerManager.WakeLock mWakeLock;
4316 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4317
4318 private Toast mStopToast;
4319
Leon Scroggins1f005d32009-08-10 17:36:42 -04004320 private TitleBarSet mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004321
Ben Murdochbff2d602009-07-01 20:19:05 +01004322 private LinearLayout mErrorConsoleContainer = null;
4323 private boolean mShouldShowErrorConsole = false;
4324
The Android Open Source Project0c908882009-03-03 19:32:16 -08004325 // As the ids are dynamically created, we can't guarantee that they will
4326 // be in sequence, so this static array maps ids to a window number.
4327 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4328 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4329 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4330 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4331
4332 // monitor platform changes
4333 private IntentFilter mNetworkStateChangedFilter;
4334 private BroadcastReceiver mNetworkStateIntentReceiver;
4335
Grace Klobab4da0ad2009-05-14 14:45:40 -07004336 private BroadcastReceiver mPackageInstallationReceiver;
4337
The Android Open Source Project0c908882009-03-03 19:32:16 -08004338 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004339 final static int COMBO_PAGE = 1;
4340 final static int DOWNLOAD_PAGE = 2;
4341 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004342
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004343 /**
4344 * A UrlData class to abstract how the content will be set to WebView.
4345 * This base class uses loadUrl to show the content.
4346 */
4347 private static class UrlData {
4348 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004349 byte[] mPostData;
4350
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004351 UrlData(String url) {
4352 this.mUrl = url;
4353 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004354
4355 void setPostData(byte[] postData) {
4356 mPostData = postData;
4357 }
4358
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004359 boolean isEmpty() {
4360 return mUrl == null || mUrl.length() == 0;
4361 }
4362
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004363 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004364 if (mPostData != null) {
4365 webView.postUrl(mUrl, mPostData);
4366 } else {
4367 webView.loadUrl(mUrl);
4368 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004369 }
4370 };
4371
4372 /**
4373 * A subclass of UrlData class that can display inlined content using
4374 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4375 */
4376 private static class InlinedUrlData extends UrlData {
4377 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4378 super(failUrl);
4379 mInlined = inlined;
4380 mMimeType = mimeType;
4381 mEncoding = encoding;
4382 }
4383 String mMimeType;
4384 String mInlined;
4385 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004386 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004387 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004388 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004389 }
4390
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004391 @Override
4392 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004393 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4394 }
4395 }
4396
Leon Scroggins1f005d32009-08-10 17:36:42 -04004397 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004398}