blob: 74103f2ab54a05cbdd8fc49233e86439b4d6a531 [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);
Leon Scroggins68579392009-09-15 15:31:54 -0400334 mTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800335
336 // Create the tab control and our initial tab
337 mTabControl = new TabControl(this);
338
339 // Open the icon database and retain all the bookmark urls for favicons
340 retainIconsOnStartup();
341
342 // Keep a settings instance handy.
343 mSettings = BrowserSettings.getInstance();
344 mSettings.setTabControl(mTabControl);
345 mSettings.loadFromDb(this);
346
347 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
348 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
349
Grace Klobaa34f6862009-07-31 16:28:17 -0700350 /* enables registration for changes in network status from
351 http stack */
352 mNetworkStateChangedFilter = new IntentFilter();
353 mNetworkStateChangedFilter.addAction(
354 ConnectivityManager.CONNECTIVITY_ACTION);
355 mNetworkStateIntentReceiver = new BroadcastReceiver() {
356 @Override
357 public void onReceive(Context context, Intent intent) {
358 if (intent.getAction().equals(
359 ConnectivityManager.CONNECTIVITY_ACTION)) {
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
Feng Qianb3c02da2009-06-29 15:58:08 -0700476 // Read JavaScript flags if it exists.
477 String jsFlags = mSettings.getJsFlags();
478 if (jsFlags.trim().length() != 0) {
479 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
480 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800481 }
482
483 @Override
484 protected void onNewIntent(Intent intent) {
485 TabControl.Tab current = mTabControl.getCurrentTab();
486 // When a tab is closed on exit, the current tab index is set to -1.
487 // Reset before proceed as Browser requires the current tab to be set.
488 if (current == null) {
489 // Try to reset the tab in case the index was incorrect.
490 current = mTabControl.getTab(0);
491 if (current == null) {
492 // No tabs at all so just ignore this intent.
493 return;
494 }
495 mTabControl.setCurrentTab(current);
496 attachTabToContentView(current);
497 resetTitleAndIcon(current.getWebView());
498 }
499 final String action = intent.getAction();
500 final int flags = intent.getFlags();
501 if (Intent.ACTION_MAIN.equals(action) ||
502 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
503 // just resume the browser
504 return;
505 }
506 if (Intent.ACTION_VIEW.equals(action)
507 || Intent.ACTION_SEARCH.equals(action)
508 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
509 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100510 // If this was a search request (e.g. search query directly typed into the address bar),
511 // pass it on to the default web search provider.
512 if (handleWebSearchIntent(intent)) {
513 return;
514 }
515
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700516 UrlData urlData = getUrlDataFromIntent(intent);
517 if (urlData.isEmpty()) {
518 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800519 }
Grace Kloba81678d92009-06-30 07:09:56 -0700520 urlData.setPostData(intent
521 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700522
Grace Klobacc634032009-07-28 15:58:19 -0700523 final String appId = intent
524 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
525 if (Intent.ACTION_VIEW.equals(action)
526 && !getPackageName().equals(appId)
527 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Patrick Scottcd115892009-07-16 09:42:58 -0400528 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700529 if (appTab != null) {
530 Log.i(LOGTAG, "Reusing tab for " + appId);
531 // Dismiss the subwindow if applicable.
532 dismissSubWindow(appTab);
533 // Since we might kill the WebView, remove it from the
534 // content view first.
535 removeTabFromContentView(appTab);
536 // Recreate the main WebView after destroying the old one.
537 // If the WebView has the same original url and is on that
538 // page, it can be reused.
539 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700540 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100541
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700542 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400543 switchToTab(mTabControl.getTabIndex(appTab));
544 if (needsLoad) {
545 urlData.loadIn(appTab.getWebView());
546 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700547 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400548 // If the tab was the current tab, we have to attach
549 // it to the view system again.
550 attachTabToContentView(appTab);
551 if (needsLoad) {
552 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700553 }
554 }
555 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400556 } else {
557 // No matching application tab, try to find a regular tab
558 // with a matching url.
559 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400560 if (appTab != null) {
561 if (current != appTab) {
562 switchToTab(mTabControl.getTabIndex(appTab));
563 }
564 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400565 } else {
566 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
567 // will be opened in a new tab unless we have reached
568 // MAX_TABS. Then the url will be opened in the current
569 // tab. If a new tab is created, it will have "true" for
570 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400571 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400572 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700573 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800574 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700575 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800576 mSettings.toggleDebugSettings();
577 return;
578 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400579 // Get rid of the subwindow if it exists
580 dismissSubWindow(current);
581 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800582 }
583 }
584 }
585
Satish Sampath565505b2009-05-29 15:37:27 +0100586 private int parseUrlShortcut(String url) {
587 if (url == null) return SHORTCUT_INVALID;
588
589 // FIXME: quick search, need to be customized by setting
590 if (url.length() > 2 && url.charAt(1) == ' ') {
591 switch (url.charAt(0)) {
592 case 'g': return SHORTCUT_GOOGLE_SEARCH;
593 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
594 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
595 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
596 }
597 }
598 return SHORTCUT_INVALID;
599 }
600
601 /**
602 * Launches the default web search activity with the query parameters if the given intent's data
603 * are identified as plain search terms and not URLs/shortcuts.
604 * @return true if the intent was handled and web search activity was launched, false if not.
605 */
606 private boolean handleWebSearchIntent(Intent intent) {
607 if (intent == null) return false;
608
609 String url = null;
610 final String action = intent.getAction();
611 if (Intent.ACTION_VIEW.equals(action)) {
612 url = intent.getData().toString();
613 } else if (Intent.ACTION_SEARCH.equals(action)
614 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
615 || Intent.ACTION_WEB_SEARCH.equals(action)) {
616 url = intent.getStringExtra(SearchManager.QUERY);
617 }
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100618 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA));
Satish Sampath565505b2009-05-29 15:37:27 +0100619 }
620
621 /**
622 * Launches the default web search activity with the query parameters if the given url string
623 * was identified as plain search terms and not URL/shortcut.
624 * @return true if the request was handled and web search activity was launched, false if not.
625 */
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100626 private boolean handleWebSearchRequest(String inUrl, Bundle appData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100627 if (inUrl == null) return false;
628
629 // In general, we shouldn't modify URL from Intent.
630 // But currently, we get the user-typed URL from search box as well.
631 String url = fixUrl(inUrl).trim();
632
633 // URLs and site specific search shortcuts are handled by the regular flow of control, so
634 // return early.
635 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100636 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100637 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
638 return false;
639 }
640
641 Browser.updateVisitedHistory(mResolver, url, false);
642 Browser.addSearchUrl(mResolver, url);
643
644 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
645 intent.addCategory(Intent.CATEGORY_DEFAULT);
646 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100647 if (appData != null) {
648 intent.putExtra(SearchManager.APP_DATA, appData);
649 }
Grace Klobacc634032009-07-28 15:58:19 -0700650 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100651 startActivity(intent);
652
653 return true;
654 }
655
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700656 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800657 String url = null;
658 if (intent != null) {
659 final String action = intent.getAction();
660 if (Intent.ACTION_VIEW.equals(action)) {
661 url = smartUrlFilter(intent.getData());
662 if (url != null && url.startsWith("content:")) {
663 /* Append mimetype so webview knows how to display */
664 String mimeType = intent.resolveType(getContentResolver());
665 if (mimeType != null) {
666 url += "?" + mimeType;
667 }
668 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700669 if ("inline:".equals(url)) {
670 return new InlinedUrlData(
671 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
672 intent.getType(),
673 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
674 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
675 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800676 } else if (Intent.ACTION_SEARCH.equals(action)
677 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
678 || Intent.ACTION_WEB_SEARCH.equals(action)) {
679 url = intent.getStringExtra(SearchManager.QUERY);
680 if (url != null) {
681 mLastEnteredUrl = url;
682 // Don't add Urls, just search terms.
683 // Urls will get added when the page is loaded.
684 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
685 Browser.updateVisitedHistory(mResolver, url, false);
686 }
687 // In general, we shouldn't modify URL from Intent.
688 // But currently, we get the user-typed URL from search box as well.
689 url = fixUrl(url);
690 url = smartUrlFilter(url);
691 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
692 if (url.contains(searchSource)) {
693 String source = null;
694 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
695 if (appData != null) {
696 source = appData.getString(SearchManager.SOURCE);
697 }
698 if (TextUtils.isEmpty(source)) {
699 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
700 }
701 url = url.replace(searchSource, "&source=android-"+source+"&");
702 }
703 }
704 }
705 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700706 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800707 }
708
709 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400710 // FIXME: Converting the url to lower case
711 // duplicates functionality in smartUrlFilter().
712 // However, changing all current callers of fixUrl to
713 // call smartUrlFilter in addition may have unwanted
714 // consequences, and is deferred for now.
715 int colon = inUrl.indexOf(':');
716 boolean allLower = true;
717 for (int index = 0; index < colon; index++) {
718 char ch = inUrl.charAt(index);
719 if (!Character.isLetter(ch)) {
720 break;
721 }
722 allLower &= Character.isLowerCase(ch);
723 if (index == colon - 1 && !allLower) {
724 inUrl = inUrl.substring(0, colon).toLowerCase()
725 + inUrl.substring(colon);
726 }
727 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800728 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
729 return inUrl;
730 if (inUrl.startsWith("http:") ||
731 inUrl.startsWith("https:")) {
732 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
733 inUrl = inUrl.replaceFirst("/", "//");
734 } else inUrl = inUrl.replaceFirst(":", "://");
735 }
736 return inUrl;
737 }
738
739 /**
740 * Looking for the pattern like this
741 *
742 * *
743 * * *
744 * *** * *******
745 * * *
746 * * *
747 * *
748 */
749 private final SensorListener mSensorListener = new SensorListener() {
750 private long mLastGestureTime;
751 private float[] mPrev = new float[3];
752 private float[] mPrevDiff = new float[3];
753 private float[] mDiff = new float[3];
754 private float[] mRevertDiff = new float[3];
755
756 public void onSensorChanged(int sensor, float[] values) {
757 boolean show = false;
758 float[] diff = new float[3];
759
760 for (int i = 0; i < 3; i++) {
761 diff[i] = values[i] - mPrev[i];
762 if (Math.abs(diff[i]) > 1) {
763 show = true;
764 }
765 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
766 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
767 // start track when there is a big move, or revert
768 mRevertDiff[i] = mDiff[i];
769 mDiff[i] = 0;
770 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
771 // reset when it is flat
772 mDiff[i] = mRevertDiff[i] = 0;
773 }
774 mDiff[i] += diff[i];
775 mPrevDiff[i] = diff[i];
776 mPrev[i] = values[i];
777 }
778
779 if (false) {
780 // only shows if we think the delta is big enough, in an attempt
781 // to detect "serious" moves left/right or up/down
782 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
783 + values[0] + ", " + values[1] + ", " + values[2] + ")"
784 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
785 + ")");
786 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
787 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
788 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
789 + mRevertDiff[2] + ")");
790 }
791
792 long now = android.os.SystemClock.uptimeMillis();
793 if (now - mLastGestureTime > 1000) {
794 mLastGestureTime = 0;
795
796 float y = mDiff[1];
797 float z = mDiff[2];
798 float ay = Math.abs(y);
799 float az = Math.abs(z);
800 float ry = mRevertDiff[1];
801 float rz = mRevertDiff[2];
802 float ary = Math.abs(ry);
803 float arz = Math.abs(rz);
804 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
805 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
806
807 if ((gestY || gestZ) && !(gestY && gestZ)) {
808 WebView view = mTabControl.getCurrentWebView();
809
810 if (view != null) {
811 if (gestZ) {
812 if (z < 0) {
813 view.zoomOut();
814 } else {
815 view.zoomIn();
816 }
817 } else {
818 view.flingScroll(0, Math.round(y * 100));
819 }
820 }
821 mLastGestureTime = now;
822 }
823 }
824 }
825
826 public void onAccuracyChanged(int sensor, int accuracy) {
827 // TODO Auto-generated method stub
828
829 }
830 };
831
832 @Override protected void onResume() {
833 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700834 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800835 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
836 }
837
838 if (!mActivityInPause) {
839 Log.e(LOGTAG, "BrowserActivity is already resumed.");
840 return;
841 }
842
Mike Reed7bfa63b2009-05-28 11:08:32 -0400843 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800844 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400845 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800846
847 if (mWakeLock.isHeld()) {
848 mHandler.removeMessages(RELEASE_WAKELOCK);
849 mWakeLock.release();
850 }
851
852 if (mCredsDlg != null) {
853 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
854 // In case credential request never comes back
855 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
856 }
857 }
858
859 registerReceiver(mNetworkStateIntentReceiver,
860 mNetworkStateChangedFilter);
861 WebView.enablePlatformNotifications();
862
863 if (mSettings.doFlick()) {
864 if (mSensorManager == null) {
865 mSensorManager = (SensorManager) getSystemService(
866 Context.SENSOR_SERVICE);
867 }
868 mSensorManager.registerListener(mSensorListener,
869 SensorManager.SENSOR_ACCELEROMETER,
870 SensorManager.SENSOR_DELAY_FASTEST);
871 } else {
872 mSensorManager = null;
873 }
874 }
875
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400876 /**
877 * Since the actual title bar is embedded in the WebView, and removing it
878 * would change its appearance, create a temporary title bar to go at
879 * the top of the screen while the menu is open.
880 */
881 private TitleBar mFakeTitleBar;
882
883 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400884 * Holder for the fake title bar. It will have a foreground shadow, as well
885 * as a white background, so the fake title bar looks like the real one.
886 */
887 private ViewGroup mFakeTitleBarHolder;
888
889 /**
890 * Layout parameters for the fake title bar within mFakeTitleBarHolder
891 */
892 private FrameLayout.LayoutParams mFakeTitleBarParams
893 = new FrameLayout.LayoutParams(
894 ViewGroup.LayoutParams.WRAP_CONTENT,
895 ViewGroup.LayoutParams.WRAP_CONTENT);
896 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400897 * Keeps track of whether the options menu is open. This is important in
898 * determining whether to show or hide the title bar overlay.
899 */
900 private boolean mOptionsMenuOpen;
901
902 /**
903 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
904 * of whether the configuration has changed. The first onMenuOpened call
905 * after a configuration change is simply a reopening of the same menu
906 * (i.e. mIconView did not change).
907 */
908 private boolean mConfigChanged;
909
910 /**
911 * Whether or not the options menu is in its smaller, icon menu form. When
912 * true, we want the title bar overlay to be up. When false, we do not.
913 * Only meaningful if mOptionsMenuOpen is true.
914 */
915 private boolean mIconView;
916
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400917 @Override
918 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400919 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
920 if (mOptionsMenuOpen) {
921 if (mConfigChanged) {
922 // We do not need to make any changes to the state of the
923 // title bar, since the only thing that happened was a
924 // change in orientation
925 mConfigChanged = false;
926 } else {
927 if (mIconView) {
928 // Switching the menu to expanded view, so hide the
929 // title bar.
930 hideFakeTitleBar();
931 mIconView = false;
932 } else {
933 // Switching the menu back to icon view, so show the
934 // title bar once again.
935 showFakeTitleBar();
936 mIconView = true;
937 }
938 }
939 } else {
940 // The options menu is closed, so open it, and show the title
941 showFakeTitleBar();
942 mOptionsMenuOpen = true;
943 mConfigChanged = false;
944 mIconView = true;
945 }
946 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400947 return true;
948 }
949
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400950 private void showFakeTitleBar() {
Leon Scroggins4d7e4062009-09-15 15:49:45 -0400951 if (mFakeTitleBar == null && mActiveTabsPage == null
952 && !mActivityInPause) {
Leon Scrogginsf4bb18a2009-09-11 18:37:53 -0400953 final WebView webView = getTopWindow();
Leon Scroggins68579392009-09-15 15:31:54 -0400954 mFakeTitleBar = new TitleBar(this);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400955 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
956 mFakeTitleBar.setProgress(webView.getProgress());
957 mFakeTitleBar.setFavicon(webView.getFavicon());
958 updateLockIconToLatest();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400959
960 WindowManager manager
961 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
962
963 // Add the title bar to the window manager so it can receive touches
964 // while the menu is up
965 WindowManager.LayoutParams params
966 = new WindowManager.LayoutParams(
967 ViewGroup.LayoutParams.FILL_PARENT,
968 ViewGroup.LayoutParams.WRAP_CONTENT,
969 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
970 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
971 PixelFormat.OPAQUE);
972 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400973 WebView mainView = mTabControl.getCurrentWebView();
974 params.windowAnimations = mainView == null
975 || mainView.getScrollY() != 0
976 ? com.android.internal.R.style.Animation_DropDownDown : 0;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400977 // XXX : Without providing an offset, the fake title bar will be
978 // placed underneath the status bar. Use the global visible rect
979 // of mBrowserFrameLayout to determine the bottom of the status bar
980 Rect rectangle = new Rect();
981 mBrowserFrameLayout.getGlobalVisibleRect(rectangle);
982 params.y = rectangle.top;
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400983 // Add a holder for the title bar. It is a FrameLayout, which
984 // allows it to have an overlay shadow. It also has a white
985 // background, which is the same as the background when it is
986 // placed in a WebView.
987 if (mFakeTitleBarHolder == null) {
988 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
989 .inflate(R.layout.title_bar_bg, null);
990 }
991 mFakeTitleBarHolder.addView(mFakeTitleBar, mFakeTitleBarParams);
992 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400993 }
994 }
995
996 @Override
997 public void onOptionsMenuClosed(Menu menu) {
998 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400999 if (!mInLoad) {
1000 hideFakeTitleBar();
1001 } else if (!mIconView) {
1002 // The page is currently loading, and we are in expanded mode, so
1003 // we were not showing the menu. Show it once again. It will be
1004 // removed when the page finishes.
1005 showFakeTitleBar();
1006 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001007 }
1008 private void hideFakeTitleBar() {
1009 if (mFakeTitleBar == null) return;
1010 WindowManager manager
1011 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001012 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1013 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001014 mFakeTitleBar = null;
1015 }
1016
The Android Open Source Project0c908882009-03-03 19:32:16 -08001017 /**
1018 * onSaveInstanceState(Bundle map)
1019 * onSaveInstanceState is called right before onStop(). The map contains
1020 * the saved state.
1021 */
1022 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001023 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001024 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1025 }
1026 // the default implementation requires each view to have an id. As the
1027 // browser handles the state itself and it doesn't use id for the views,
1028 // don't call the default implementation. Otherwise it will trigger the
1029 // warning like this, "couldn't save which view has focus because the
1030 // focused view XXX has no id".
1031
1032 // Save all the tabs
1033 mTabControl.saveState(outState);
1034 }
1035
1036 @Override protected void onPause() {
1037 super.onPause();
1038
1039 if (mActivityInPause) {
1040 Log.e(LOGTAG, "BrowserActivity is already paused.");
1041 return;
1042 }
1043
Mike Reed7bfa63b2009-05-28 11:08:32 -04001044 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001045 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001046 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001047 mWakeLock.acquire();
1048 mHandler.sendMessageDelayed(mHandler
1049 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1050 }
1051
1052 // Clear the credentials toast if it is up
1053 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1054 mCredsDlg.dismiss();
1055 }
1056 mCredsDlg = null;
1057
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001058 // FIXME: This removes the active tabs page and resets the menu to
1059 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1060 // but then we would need to save it in onSaveInstanceState and restore
1061 // it in onCreate/onRestoreInstanceState
1062 if (mActiveTabsPage != null) {
1063 removeActiveTabPage(true);
1064 }
1065
The Android Open Source Project0c908882009-03-03 19:32:16 -08001066 cancelStopToast();
1067
1068 // unregister network state listener
1069 unregisterReceiver(mNetworkStateIntentReceiver);
1070 WebView.disablePlatformNotifications();
1071
1072 if (mSensorManager != null) {
1073 mSensorManager.unregisterListener(mSensorListener);
1074 }
1075 }
1076
1077 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001078 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001079 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1080 }
1081 super.onDestroy();
1082 // Remove the current tab and sub window
1083 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001084 if (t != null) {
1085 dismissSubWindow(t);
1086 removeTabFromContentView(t);
1087 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001088 // Destroy all the tabs
1089 mTabControl.destroy();
1090 WebIconDatabase.getInstance().close();
1091 if (mGlsConnection != null) {
1092 unbindService(mGlsConnection);
1093 mGlsConnection = null;
1094 }
1095
1096 //
1097 // stop MASF proxy service
1098 //
1099 //Intent proxyServiceIntent = new Intent();
1100 //proxyServiceIntent.setComponent
1101 // (new ComponentName(
1102 // "com.android.masfproxyservice",
1103 // "com.android.masfproxyservice.MasfProxyService"));
1104 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001105
1106 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001107 }
1108
1109 @Override
1110 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001111 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001112 super.onConfigurationChanged(newConfig);
1113
1114 if (mPageInfoDialog != null) {
1115 mPageInfoDialog.dismiss();
1116 showPageInfo(
1117 mPageInfoView,
1118 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1119 }
1120 if (mSSLCertificateDialog != null) {
1121 mSSLCertificateDialog.dismiss();
1122 showSSLCertificate(
1123 mSSLCertificateView);
1124 }
1125 if (mSSLCertificateOnErrorDialog != null) {
1126 mSSLCertificateOnErrorDialog.dismiss();
1127 showSSLCertificateOnError(
1128 mSSLCertificateOnErrorView,
1129 mSSLCertificateOnErrorHandler,
1130 mSSLCertificateOnErrorError);
1131 }
1132 if (mHttpAuthenticationDialog != null) {
1133 String title = ((TextView) mHttpAuthenticationDialog
1134 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1135 .toString();
1136 String name = ((TextView) mHttpAuthenticationDialog
1137 .findViewById(R.id.username_edit)).getText().toString();
1138 String password = ((TextView) mHttpAuthenticationDialog
1139 .findViewById(R.id.password_edit)).getText().toString();
1140 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1141 .getId();
1142 mHttpAuthenticationDialog.dismiss();
1143 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1144 name, password, focusId);
1145 }
1146 if (mFindDialog != null && mFindDialog.isShowing()) {
1147 mFindDialog.onConfigurationChanged(newConfig);
1148 }
1149 }
1150
1151 @Override public void onLowMemory() {
1152 super.onLowMemory();
1153 mTabControl.freeMemory();
1154 }
1155
Mike Reed7bfa63b2009-05-28 11:08:32 -04001156 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001157 if ((!mActivityInPause && !mPageStarted) ||
1158 (mActivityInPause && mPageStarted)) {
1159 CookieSyncManager.getInstance().startSync();
1160 WebView w = mTabControl.getCurrentWebView();
1161 if (w != null) {
1162 w.resumeTimers();
1163 }
1164 return true;
1165 } else {
1166 return false;
1167 }
1168 }
1169
Mike Reed7bfa63b2009-05-28 11:08:32 -04001170 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001171 if (mActivityInPause && !mPageStarted) {
1172 CookieSyncManager.getInstance().stopSync();
1173 WebView w = mTabControl.getCurrentWebView();
1174 if (w != null) {
1175 w.pauseTimers();
1176 }
1177 return true;
1178 } else {
1179 return false;
1180 }
1181 }
1182
Leon Scroggins1f005d32009-08-10 17:36:42 -04001183 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001184 /*
1185 * This function is called when we are launching for the first time. We
1186 * are waiting for the login credentials before loading Google home
1187 * pages. This way the user will be logged in straight away.
1188 */
1189 private void waitForCredentials() {
1190 // Show a toast
1191 mCredsDlg = new ProgressDialog(this);
1192 mCredsDlg.setIndeterminate(true);
1193 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1194 // If the user cancels the operation, then cancel the Google
1195 // Credentials request.
1196 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1197 mCredsDlg.show();
1198
1199 // We set a timeout for the retrieval of credentials in onResume()
1200 // as that is when we have freed up some CPU time to get
1201 // the login credentials.
1202 }
1203
1204 /*
1205 * If we have received the credentials or we have timed out and we are
1206 * showing the credentials dialog, then it is time to move on.
1207 */
1208 private void resumeAfterCredentials() {
1209 if (mCredsDlg == null) {
1210 return;
1211 }
1212
1213 // Clear the toast
1214 if (mCredsDlg.isShowing()) {
1215 mCredsDlg.dismiss();
1216 }
1217 mCredsDlg = null;
1218
1219 // Clear any pending timeout
1220 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1221
1222 // Load the page
1223 WebView w = mTabControl.getCurrentWebView();
1224 if (w != null) {
1225 w.loadUrl(mSettings.getHomePage());
1226 }
1227
1228 // Update the settings, need to do this last as it can take a moment
1229 // to persist the settings. In the mean time we could be loading
1230 // content.
1231 mSettings.setLoginInitialized(this);
1232 }
1233
1234 // Open the icon database and retain all the icons for visited sites.
1235 private void retainIconsOnStartup() {
1236 final WebIconDatabase db = WebIconDatabase.getInstance();
1237 db.open(getDir("icons", 0).getPath());
1238 try {
1239 Cursor c = Browser.getAllBookmarks(mResolver);
1240 if (!c.moveToFirst()) {
1241 c.deactivate();
1242 return;
1243 }
1244 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1245 do {
1246 String url = c.getString(urlIndex);
1247 db.retainIconForPageUrl(url);
1248 } while (c.moveToNext());
1249 c.deactivate();
1250 } catch (IllegalStateException e) {
1251 Log.e(LOGTAG, "retainIconsOnStartup", e);
1252 }
1253 }
1254
1255 // Helper method for getting the top window.
1256 WebView getTopWindow() {
1257 return mTabControl.getCurrentTopWebView();
1258 }
1259
1260 @Override
1261 public boolean onCreateOptionsMenu(Menu menu) {
1262 super.onCreateOptionsMenu(menu);
1263
1264 MenuInflater inflater = getMenuInflater();
1265 inflater.inflate(R.menu.browser, menu);
1266 mMenu = menu;
1267 updateInLoadMenuItems();
1268 return true;
1269 }
1270
1271 /**
1272 * As the menu can be open when loading state changes
1273 * we must manually update the state of the stop/reload menu
1274 * item
1275 */
1276 private void updateInLoadMenuItems() {
1277 if (mMenu == null) {
1278 return;
1279 }
1280 MenuItem src = mInLoad ?
1281 mMenu.findItem(R.id.stop_menu_id):
1282 mMenu.findItem(R.id.reload_menu_id);
1283 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1284 dest.setIcon(src.getIcon());
1285 dest.setTitle(src.getTitle());
1286 }
1287
1288 @Override
1289 public boolean onContextItemSelected(MenuItem item) {
1290 // chording is not an issue with context menus, but we use the same
1291 // options selector, so set mCanChord to true so we can access them.
1292 mCanChord = true;
1293 int id = item.getItemId();
1294 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001295 if (null == webView) {
1296 return false;
1297 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001298 final HashMap hrefMap = new HashMap();
1299 hrefMap.put("webview", webView);
1300 final Message msg = mHandler.obtainMessage(
1301 FOCUS_NODE_HREF, id, 0, hrefMap);
1302 switch (id) {
1303 // -- Browser context menu
1304 case R.id.open_context_menu_id:
1305 case R.id.open_newtab_context_menu_id:
1306 case R.id.bookmark_context_menu_id:
1307 case R.id.save_link_context_menu_id:
1308 case R.id.share_link_context_menu_id:
1309 case R.id.copy_link_context_menu_id:
1310 webView.requestFocusNodeHref(msg);
1311 break;
1312
1313 default:
1314 // For other context menus
1315 return onOptionsItemSelected(item);
1316 }
1317 mCanChord = false;
1318 return true;
1319 }
1320
1321 private Bundle createGoogleSearchSourceBundle(String source) {
1322 Bundle bundle = new Bundle();
1323 bundle.putString(SearchManager.SOURCE, source);
1324 return bundle;
1325 }
1326
1327 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001328 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001329 */
1330 @Override
1331 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001332 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001333 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001334 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001335 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001336 return true;
1337 }
1338
1339 @Override
1340 public void startSearch(String initialQuery, boolean selectInitialQuery,
1341 Bundle appSearchData, boolean globalSearch) {
1342 if (appSearchData == null) {
1343 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1344 }
1345 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1346 }
1347
Leon Scroggins1f005d32009-08-10 17:36:42 -04001348 /**
1349 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1350 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001351 * @param index Index of the tab to change to, as defined by
1352 * mTabControl.getTabIndex(Tab t).
1353 * @return boolean True if we successfully switched to a different tab. If
1354 * the indexth tab is null, or if that tab is the same as
1355 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001356 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001357 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001358 TabControl.Tab tab = mTabControl.getTab(index);
1359 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1360 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001361 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001362 }
1363 if (currentTab != null) {
1364 // currentTab may be null if it was just removed. In that case,
1365 // we do not need to remove it
1366 removeTabFromContentView(currentTab);
1367 }
1368 removeTabFromContentView(tab);
1369 mTabControl.setCurrentTab(tab);
1370 attachTabToContentView(tab);
Patrick Scottdb22ea72009-09-15 10:57:22 -04001371 resetTitle();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001372 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001373 }
1374
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001375 /* package */ TabControl.Tab openTabToHomePage() {
1376 return openTabAndShow(mSettings.getHomePage(), false, null);
1377 }
1378
Leon Scroggins1f005d32009-08-10 17:36:42 -04001379 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001380 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001381 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001382 // This is the last tab. Open a new one, with the home
1383 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001384 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001385 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001386 return;
1387 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001388 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001389 int indexToShow = -1;
1390 if (parent != null) {
1391 indexToShow = mTabControl.getTabIndex(parent);
1392 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001393 final int currentIndex = mTabControl.getCurrentIndex();
1394 // Try to move to the tab to the right
1395 indexToShow = currentIndex + 1;
1396 if (indexToShow > mTabControl.getTabCount() - 1) {
1397 // Try to move to the tab to the left
1398 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001399 }
1400 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001401 if (switchToTab(indexToShow)) {
1402 // Close window
1403 closeTab(current);
1404 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001405 }
1406
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001407 private ActiveTabsPage mActiveTabsPage;
1408
1409 /**
1410 * Remove the active tabs page.
1411 * @param needToAttach If true, the active tabs page did not attach a tab
1412 * to the content view, so we need to do that here.
1413 */
1414 /* package */ void removeActiveTabPage(boolean needToAttach) {
1415 mContentView.removeView(mActiveTabsPage);
1416 mActiveTabsPage = null;
1417 mMenuState = R.id.MAIN_MENU;
1418 if (needToAttach) {
1419 attachTabToContentView(mTabControl.getCurrentTab());
1420 }
1421 getTopWindow().requestFocus();
1422 }
1423
The Android Open Source Project0c908882009-03-03 19:32:16 -08001424 @Override
1425 public boolean onOptionsItemSelected(MenuItem item) {
1426 if (!mCanChord) {
1427 // The user has already fired a shortcut with this hold down of the
1428 // menu key.
1429 return false;
1430 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001431 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001432 return false;
1433 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001434 if (mMenuIsDown) {
1435 // The shortcut action consumes the MENU. Even if it is still down,
1436 // it won't trigger the next shortcut action. In the case of the
1437 // shortcut action triggering a new activity, like Bookmarks, we
1438 // won't get onKeyUp for MENU. So it is important to reset it here.
1439 mMenuIsDown = false;
1440 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001441 switch (item.getItemId()) {
1442 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001443 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001444 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001445 break;
1446
Leon Scroggins64b80f32009-08-07 12:03:34 -04001447 case R.id.goto_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001448 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001449 break;
1450
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001451 case R.id.active_tabs_menu_id:
1452 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1453 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001454 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001455 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1456 mActiveTabsPage.requestFocus();
1457 mMenuState = EMPTY_MENU;
1458 break;
1459
Leon Scroggins1f005d32009-08-10 17:36:42 -04001460 case R.id.add_bookmark_menu_id:
1461 Intent i = new Intent(BrowserActivity.this,
1462 AddBookmarkPage.class);
1463 WebView w = getTopWindow();
1464 i.putExtra("url", w.getUrl());
1465 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001466 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Leon Scroggins1f005d32009-08-10 17:36:42 -04001467 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001468 break;
1469
1470 case R.id.stop_reload_menu_id:
1471 if (mInLoad) {
1472 stopLoading();
1473 } else {
1474 getTopWindow().reload();
1475 }
1476 break;
1477
1478 case R.id.back_menu_id:
1479 getTopWindow().goBack();
1480 break;
1481
1482 case R.id.forward_menu_id:
1483 getTopWindow().goForward();
1484 break;
1485
1486 case R.id.close_menu_id:
1487 // Close the subwindow if it exists.
1488 if (mTabControl.getCurrentSubWindow() != null) {
1489 dismissSubWindow(mTabControl.getCurrentTab());
1490 break;
1491 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001492 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001493 break;
1494
1495 case R.id.homepage_menu_id:
1496 TabControl.Tab current = mTabControl.getCurrentTab();
1497 if (current != null) {
1498 dismissSubWindow(current);
1499 current.getWebView().loadUrl(mSettings.getHomePage());
1500 }
1501 break;
1502
1503 case R.id.preferences_menu_id:
1504 Intent intent = new Intent(this,
1505 BrowserPreferencesPage.class);
1506 startActivityForResult(intent, PREFERENCES_PAGE);
1507 break;
1508
1509 case R.id.find_menu_id:
1510 if (null == mFindDialog) {
1511 mFindDialog = new FindDialog(this);
1512 }
1513 mFindDialog.setWebView(getTopWindow());
1514 mFindDialog.show();
1515 mMenuState = EMPTY_MENU;
1516 break;
1517
1518 case R.id.select_text_id:
1519 getTopWindow().emulateShiftHeld();
1520 break;
1521 case R.id.page_info_menu_id:
1522 showPageInfo(mTabControl.getCurrentTab(), false);
1523 break;
1524
1525 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001526 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001527 break;
1528
1529 case R.id.share_page_menu_id:
1530 Browser.sendString(this, getTopWindow().getUrl());
1531 break;
1532
1533 case R.id.dump_nav_menu_id:
1534 getTopWindow().debugDump();
1535 break;
1536
1537 case R.id.zoom_in_menu_id:
1538 getTopWindow().zoomIn();
1539 break;
1540
1541 case R.id.zoom_out_menu_id:
1542 getTopWindow().zoomOut();
1543 break;
1544
1545 case R.id.view_downloads_menu_id:
1546 viewDownloads(null);
1547 break;
1548
The Android Open Source Project0c908882009-03-03 19:32:16 -08001549 case R.id.window_one_menu_id:
1550 case R.id.window_two_menu_id:
1551 case R.id.window_three_menu_id:
1552 case R.id.window_four_menu_id:
1553 case R.id.window_five_menu_id:
1554 case R.id.window_six_menu_id:
1555 case R.id.window_seven_menu_id:
1556 case R.id.window_eight_menu_id:
1557 {
1558 int menuid = item.getItemId();
1559 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1560 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1561 TabControl.Tab desiredTab = mTabControl.getTab(id);
1562 if (desiredTab != null &&
1563 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001564 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001565 }
1566 break;
1567 }
1568 }
1569 }
1570 break;
1571
1572 default:
1573 if (!super.onOptionsItemSelected(item)) {
1574 return false;
1575 }
1576 // Otherwise fall through.
1577 }
1578 mCanChord = false;
1579 return true;
1580 }
1581
1582 public void closeFind() {
1583 mMenuState = R.id.MAIN_MENU;
1584 }
1585
1586 @Override public boolean onPrepareOptionsMenu(Menu menu)
1587 {
1588 // This happens when the user begins to hold down the menu key, so
1589 // allow them to chord to get a shortcut.
1590 mCanChord = true;
1591 // Note: setVisible will decide whether an item is visible; while
1592 // setEnabled() will decide whether an item is enabled, which also means
1593 // whether the matching shortcut key will function.
1594 super.onPrepareOptionsMenu(menu);
1595 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001596 case EMPTY_MENU:
1597 if (mCurrentMenuState != mMenuState) {
1598 menu.setGroupVisible(R.id.MAIN_MENU, false);
1599 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1600 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001601 }
1602 break;
1603 default:
1604 if (mCurrentMenuState != mMenuState) {
1605 menu.setGroupVisible(R.id.MAIN_MENU, true);
1606 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1607 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001608 }
1609 final WebView w = getTopWindow();
1610 boolean canGoBack = false;
1611 boolean canGoForward = false;
1612 boolean isHome = false;
1613 if (w != null) {
1614 canGoBack = w.canGoBack();
1615 canGoForward = w.canGoForward();
1616 isHome = mSettings.getHomePage().equals(w.getUrl());
1617 }
1618 final MenuItem back = menu.findItem(R.id.back_menu_id);
1619 back.setEnabled(canGoBack);
1620
1621 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1622 home.setEnabled(!isHome);
1623
1624 menu.findItem(R.id.forward_menu_id)
1625 .setEnabled(canGoForward);
1626
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001627 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1628 mTabControl.getTabCount() < TabControl.MAX_TABS);
1629
The Android Open Source Project0c908882009-03-03 19:32:16 -08001630 // decide whether to show the share link option
1631 PackageManager pm = getPackageManager();
1632 Intent send = new Intent(Intent.ACTION_SEND);
1633 send.setType("text/plain");
1634 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1635 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1636
The Android Open Source Project0c908882009-03-03 19:32:16 -08001637 boolean isNavDump = mSettings.isNavDump();
1638 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1639 nav.setVisible(isNavDump);
1640 nav.setEnabled(isNavDump);
1641 break;
1642 }
1643 mCurrentMenuState = mMenuState;
1644 return true;
1645 }
1646
1647 @Override
1648 public void onCreateContextMenu(ContextMenu menu, View v,
1649 ContextMenuInfo menuInfo) {
1650 WebView webview = (WebView) v;
1651 WebView.HitTestResult result = webview.getHitTestResult();
1652 if (result == null) {
1653 return;
1654 }
1655
1656 int type = result.getType();
1657 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1658 Log.w(LOGTAG,
1659 "We should not show context menu when nothing is touched");
1660 return;
1661 }
1662 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1663 // let TextView handles context menu
1664 return;
1665 }
1666
1667 // Note, http://b/issue?id=1106666 is requesting that
1668 // an inflated menu can be used again. This is not available
1669 // yet, so inflate each time (yuk!)
1670 MenuInflater inflater = getMenuInflater();
1671 inflater.inflate(R.menu.browsercontext, menu);
1672
1673 // Show the correct menu group
1674 String extra = result.getExtra();
1675 menu.setGroupVisible(R.id.PHONE_MENU,
1676 type == WebView.HitTestResult.PHONE_TYPE);
1677 menu.setGroupVisible(R.id.EMAIL_MENU,
1678 type == WebView.HitTestResult.EMAIL_TYPE);
1679 menu.setGroupVisible(R.id.GEO_MENU,
1680 type == WebView.HitTestResult.GEO_TYPE);
1681 menu.setGroupVisible(R.id.IMAGE_MENU,
1682 type == WebView.HitTestResult.IMAGE_TYPE
1683 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1684 menu.setGroupVisible(R.id.ANCHOR_MENU,
1685 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1686 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1687
1688 // Setup custom handling depending on the type
1689 switch (type) {
1690 case WebView.HitTestResult.PHONE_TYPE:
1691 menu.setHeaderTitle(Uri.decode(extra));
1692 menu.findItem(R.id.dial_context_menu_id).setIntent(
1693 new Intent(Intent.ACTION_VIEW, Uri
1694 .parse(WebView.SCHEME_TEL + extra)));
1695 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1696 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1697 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1698 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1699 addIntent);
1700 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1701 new Copy(extra));
1702 break;
1703
1704 case WebView.HitTestResult.EMAIL_TYPE:
1705 menu.setHeaderTitle(extra);
1706 menu.findItem(R.id.email_context_menu_id).setIntent(
1707 new Intent(Intent.ACTION_VIEW, Uri
1708 .parse(WebView.SCHEME_MAILTO + extra)));
1709 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1710 new Copy(extra));
1711 break;
1712
1713 case WebView.HitTestResult.GEO_TYPE:
1714 menu.setHeaderTitle(extra);
1715 menu.findItem(R.id.map_context_menu_id).setIntent(
1716 new Intent(Intent.ACTION_VIEW, Uri
1717 .parse(WebView.SCHEME_GEO
1718 + URLEncoder.encode(extra))));
1719 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1720 new Copy(extra));
1721 break;
1722
1723 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1724 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1725 TextView titleView = (TextView) LayoutInflater.from(this)
1726 .inflate(android.R.layout.browser_link_context_header,
1727 null);
1728 titleView.setText(extra);
1729 menu.setHeaderView(titleView);
1730 // decide whether to show the open link in new tab option
1731 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1732 mTabControl.getTabCount() < TabControl.MAX_TABS);
1733 PackageManager pm = getPackageManager();
1734 Intent send = new Intent(Intent.ACTION_SEND);
1735 send.setType("text/plain");
1736 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1737 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1738 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1739 break;
1740 }
1741 // otherwise fall through to handle image part
1742 case WebView.HitTestResult.IMAGE_TYPE:
1743 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1744 menu.setHeaderTitle(extra);
1745 }
1746 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1747 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1748 menu.findItem(R.id.download_context_menu_id).
1749 setOnMenuItemClickListener(new Download(extra));
1750 break;
1751
1752 default:
1753 Log.w(LOGTAG, "We should not get here.");
1754 break;
1755 }
1756 }
1757
The Android Open Source Project0c908882009-03-03 19:32:16 -08001758 // Attach the given tab to the content view.
1759 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001760 // Attach the container that contains the main WebView and any other UI
1761 // associated with the tab.
1762 mContentView.addView(t.getContainer(), COVER_SCREEN_PARAMS);
Ben Murdochbff2d602009-07-01 20:19:05 +01001763
1764 if (mShouldShowErrorConsole) {
1765 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1766 if (errorConsole.numberOfErrors() == 0) {
1767 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1768 } else {
1769 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1770 }
1771
1772 mErrorConsoleContainer.addView(errorConsole,
1773 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1774 ViewGroup.LayoutParams.WRAP_CONTENT));
1775 }
1776
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001777 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001778 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001779 // Attach the sub window if necessary
1780 attachSubWindow(t);
1781 // Request focus on the top window.
1782 t.getTopWindow().requestFocus();
1783 }
1784
1785 // Attach a sub window to the main WebView of the given tab.
1786 private void attachSubWindow(TabControl.Tab t) {
1787 // If a sub window exists, attach it to the content view.
1788 final WebView subView = t.getSubWebView();
1789 if (subView != null) {
1790 final View container = t.getSubWebViewContainer();
1791 mContentView.addView(container, COVER_SCREEN_PARAMS);
1792 subView.requestFocus();
1793 }
1794 }
1795
1796 // Remove the given tab from the content view.
1797 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001798 // Remove the container that contains the main WebView.
1799 mContentView.removeView(t.getContainer());
Ben Murdochbff2d602009-07-01 20:19:05 +01001800
1801 if (mTabControl.getCurrentErrorConsole(false) != null) {
1802 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1803 }
1804
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001805 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001806 if (view != null) {
1807 view.setEmbeddedTitleBar(null);
1808 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001809
The Android Open Source Project0c908882009-03-03 19:32:16 -08001810 // Remove the sub window if it exists.
1811 if (t.getSubWebView() != null) {
1812 mContentView.removeView(t.getSubWebViewContainer());
1813 }
1814 }
1815
1816 // Remove the sub window if it exists. Also called by TabControl when the
1817 // user clicks the 'X' to dismiss a sub window.
1818 /* package */ void dismissSubWindow(TabControl.Tab t) {
1819 final WebView mainView = t.getWebView();
1820 if (t.getSubWebView() != null) {
1821 // Remove the container view and request focus on the main WebView.
1822 mContentView.removeView(t.getSubWebViewContainer());
1823 mainView.requestFocus();
1824 // Tell the TabControl to dismiss the subwindow. This will destroy
1825 // the WebView.
1826 mTabControl.dismissSubWindow(t);
1827 }
1828 }
1829
Leon Scroggins1f005d32009-08-10 17:36:42 -04001830 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001831 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001832 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1833 String appId) {
1834 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001835 }
1836
1837 // This method does a ton of stuff. It will attempt to create a new tab
1838 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001839 // url isn't null, it will load the given url.
1840 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001841 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001842 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1843 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1844 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001845 final TabControl.Tab tab = mTabControl.createNewTab(
1846 closeOnExit, appId, urlData.mUrl);
1847 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001848 // If the last tab was removed from the active tabs page, currentTab
1849 // will be null.
1850 if (currentTab != null) {
1851 removeTabFromContentView(currentTab);
1852 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001853 attachTabToContentView(tab);
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001854 // We must set the new tab as the current tab to reflect the old
1855 // animation behavior.
1856 mTabControl.setCurrentTab(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001857 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001858 urlData.loadIn(webview);
1859 }
1860 return tab;
1861 } else {
1862 // Get rid of the subwindow if it exists
1863 dismissSubWindow(currentTab);
1864 if (!urlData.isEmpty()) {
1865 // Load the given url.
1866 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001867 }
1868 }
Grace Klobac9181842009-04-14 08:53:22 -07001869 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001870 }
1871
Grace Klobac9181842009-04-14 08:53:22 -07001872 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001873 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001874 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001875 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001876 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001877 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001878 }
Grace Klobac9181842009-04-14 08:53:22 -07001879 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001880 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001881 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001882 }
1883 }
1884
1885 private class Copy implements OnMenuItemClickListener {
1886 private CharSequence mText;
1887
1888 public boolean onMenuItemClick(MenuItem item) {
1889 copy(mText);
1890 return true;
1891 }
1892
1893 public Copy(CharSequence toCopy) {
1894 mText = toCopy;
1895 }
1896 }
1897
1898 private class Download implements OnMenuItemClickListener {
1899 private String mText;
1900
1901 public boolean onMenuItemClick(MenuItem item) {
1902 onDownloadStartNoStream(mText, null, null, null, -1);
1903 return true;
1904 }
1905
1906 public Download(String toDownload) {
1907 mText = toDownload;
1908 }
1909 }
1910
1911 private void copy(CharSequence text) {
1912 try {
1913 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1914 if (clip != null) {
1915 clip.setClipboardText(text);
1916 }
1917 } catch (android.os.RemoteException e) {
1918 Log.e(LOGTAG, "Copy failed", e);
1919 }
1920 }
1921
1922 /**
1923 * Resets the browser title-view to whatever it must be (for example, if we
1924 * load a page from history).
1925 */
1926 private void resetTitle() {
1927 resetLockIcon();
1928 resetTitleIconAndProgress();
1929 }
1930
1931 /**
1932 * Resets the browser title-view to whatever it must be
1933 * (for example, if we had a loading error)
1934 * When we have a new page, we call resetTitle, when we
1935 * have to reset the titlebar to whatever it used to be
1936 * (for example, if the user chose to stop loading), we
1937 * call resetTitleAndRevertLockIcon.
1938 */
1939 /* package */ void resetTitleAndRevertLockIcon() {
1940 revertLockIcon();
1941 resetTitleIconAndProgress();
1942 }
1943
1944 /**
1945 * Reset the title, favicon, and progress.
1946 */
1947 private void resetTitleIconAndProgress() {
1948 WebView current = mTabControl.getCurrentWebView();
1949 if (current == null) {
1950 return;
1951 }
1952 resetTitleAndIcon(current);
1953 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001954 mWebChromeClient.onProgressChanged(current, progress);
1955 }
1956
1957 // Reset the title and the icon based on the given item.
1958 private void resetTitleAndIcon(WebView view) {
1959 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1960 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001961 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001962 setFavicon(item.getFavicon());
1963 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001964 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001965 setFavicon(null);
1966 }
1967 }
1968
1969 /**
1970 * Sets a title composed of the URL and the title string.
1971 * @param url The URL of the site being loaded.
1972 * @param title The title of the site being loaded.
1973 */
Leon Scroggins68579392009-09-15 15:31:54 -04001974 private void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001975 mUrl = url;
1976 mTitle = title;
1977
Leon Scroggins68579392009-09-15 15:31:54 -04001978 mTitleBar.setTitleAndUrl(title, url);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001979 if (mFakeTitleBar != null) {
1980 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001981 }
1982 }
1983
1984 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001985 * @param url The URL to build a title version of the URL from.
1986 * @return The title version of the URL or null if fails.
1987 * The title version of the URL can be either the URL hostname,
1988 * or the hostname with an "https://" prefix (for secure URLs),
1989 * or an empty string if, for example, the URL in question is a
1990 * file:// URL with no hostname.
1991 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001992 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001993 String titleUrl = null;
1994
1995 if (url != null) {
1996 try {
1997 // parse the url string
1998 URL urlObj = new URL(url);
1999 if (urlObj != null) {
2000 titleUrl = "";
2001
2002 String protocol = urlObj.getProtocol();
2003 String host = urlObj.getHost();
2004
2005 if (host != null && 0 < host.length()) {
2006 titleUrl = host;
2007 if (protocol != null) {
2008 // if a secure site, add an "https://" prefix!
2009 if (protocol.equalsIgnoreCase("https")) {
2010 titleUrl = protocol + "://" + host;
2011 }
2012 }
2013 }
2014 }
2015 } catch (MalformedURLException e) {}
2016 }
2017
2018 return titleUrl;
2019 }
2020
2021 // Set the favicon in the title bar.
2022 private void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002023 mTitleBar.setFavicon(icon);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002024 if (mFakeTitleBar != null) {
2025 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002026 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002027 }
2028
2029 /**
2030 * Saves the current lock-icon state before resetting
2031 * the lock icon. If we have an error, we may need to
2032 * roll back to the previous state.
2033 */
2034 private void saveLockIcon() {
2035 mPrevLockType = mLockIconType;
2036 }
2037
2038 /**
2039 * Reverts the lock-icon state to the last saved state,
2040 * for example, if we had an error, and need to cancel
2041 * the load.
2042 */
2043 private void revertLockIcon() {
2044 mLockIconType = mPrevLockType;
2045
Dave Bort31a6d1c2009-04-13 15:56:49 -07002046 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002047 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2048 " revert lock icon to " + mLockIconType);
2049 }
2050
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002051 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002052 }
2053
Leon Scroggins1f005d32009-08-10 17:36:42 -04002054 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002055 * Close the tab, remove its associated title bar, and adjust mTabControl's
2056 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002057 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002058 /* package */ void closeTab(TabControl.Tab t) {
2059 int currentIndex = mTabControl.getCurrentIndex();
2060 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002061 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002062 if (currentIndex >= removeIndex && currentIndex != 0) {
2063 currentIndex--;
2064 }
2065 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
The Android Open Source Project0c908882009-03-03 19:32:16 -08002066 }
2067
2068 private void goBackOnePageOrQuit() {
2069 TabControl.Tab current = mTabControl.getCurrentTab();
2070 if (current == null) {
2071 /*
2072 * Instead of finishing the activity, simply push this to the back
2073 * of the stack and let ActivityManager to choose the foreground
2074 * activity. As BrowserActivity is singleTask, it will be always the
2075 * root of the task. So we can use either true or false for
2076 * moveTaskToBack().
2077 */
2078 moveTaskToBack(true);
2079 }
2080 WebView w = current.getWebView();
2081 if (w.canGoBack()) {
2082 w.goBack();
2083 } else {
2084 // Check to see if we are closing a window that was created by
2085 // another window. If so, we switch back to that window.
2086 TabControl.Tab parent = current.getParentTab();
2087 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002088 switchToTab(mTabControl.getTabIndex(parent));
2089 // Now we close the other tab
2090 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002091 } else {
2092 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002093 // force mPageStarted to be false as we are going to either
2094 // finish the activity or remove the tab. This will ensure
2095 // pauseWebView() taking action.
2096 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002097 if (mTabControl.getTabCount() == 1) {
2098 finish();
2099 return;
2100 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002101 // call pauseWebViewTimers() now, we won't be able to call
2102 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002103 // Temporarily change mActivityInPause to be true as
2104 // pauseWebViewTimers() will do nothing if mActivityInPause
2105 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002106 boolean savedState = mActivityInPause;
2107 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002108 Log.e(LOGTAG, "BrowserActivity is already paused "
2109 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002110 }
2111 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002112 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002113 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002114 removeTabFromContentView(current);
2115 mTabControl.removeTab(current);
2116 }
2117 /*
2118 * Instead of finishing the activity, simply push this to the back
2119 * of the stack and let ActivityManager to choose the foreground
2120 * activity. As BrowserActivity is singleTask, it will be always the
2121 * root of the task. So we can use either true or false for
2122 * moveTaskToBack().
2123 */
2124 moveTaskToBack(true);
2125 }
2126 }
2127 }
2128
2129 public KeyTracker.State onKeyTracker(int keyCode,
2130 KeyEvent event,
2131 KeyTracker.Stage stage,
2132 int duration) {
2133 // if onKeyTracker() is called after activity onStop()
2134 // because of accumulated key events,
2135 // we should ignore it as browser is not active any more.
2136 WebView topWindow = getTopWindow();
Andrei Popescuadc008d2009-06-26 14:11:30 +01002137 if (topWindow == null && mCustomView == null)
The Android Open Source Project0c908882009-03-03 19:32:16 -08002138 return KeyTracker.State.NOT_TRACKING;
2139
2140 if (keyCode == KeyEvent.KEYCODE_BACK) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01002141 // Check if a custom view is currently showing and, if it is, hide it.
2142 if (mCustomView != null) {
2143 mWebChromeClient.onHideCustomView();
2144 return KeyTracker.State.DONE_TRACKING;
2145 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002146 if (stage == KeyTracker.Stage.LONG_REPEAT) {
Leon Scroggins30444232009-09-04 18:36:20 -04002147 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002148 return KeyTracker.State.DONE_TRACKING;
2149 } else if (stage == KeyTracker.Stage.UP) {
2150 // FIXME: Currently, we do not have a notion of the
2151 // history picker for the subwindow, but maybe we
2152 // should?
2153 WebView subwindow = mTabControl.getCurrentSubWindow();
2154 if (subwindow != null) {
2155 if (subwindow.canGoBack()) {
2156 subwindow.goBack();
2157 } else {
2158 dismissSubWindow(mTabControl.getCurrentTab());
2159 }
2160 } else {
2161 goBackOnePageOrQuit();
2162 }
2163 return KeyTracker.State.DONE_TRACKING;
2164 }
2165 return KeyTracker.State.KEEP_TRACKING;
2166 }
2167 return KeyTracker.State.NOT_TRACKING;
2168 }
2169
2170 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2171 if (keyCode == KeyEvent.KEYCODE_MENU) {
2172 mMenuIsDown = true;
Grace Kloba6ee9c492009-07-13 10:04:34 -07002173 } else if (mMenuIsDown) {
2174 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2175 // still down, we don't want to trigger the search. Pretend to
2176 // consume the key and do nothing.
2177 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002178 }
2179 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2180 if (!handled) {
2181 switch (keyCode) {
2182 case KeyEvent.KEYCODE_SPACE:
2183 if (event.isShiftPressed()) {
2184 getTopWindow().pageUp(false);
2185 } else {
2186 getTopWindow().pageDown(false);
2187 }
2188 handled = true;
2189 break;
2190
2191 default:
2192 break;
2193 }
2194 }
2195 return handled || super.onKeyDown(keyCode, event);
2196 }
2197
2198 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2199 if (keyCode == KeyEvent.KEYCODE_MENU) {
2200 mMenuIsDown = false;
2201 }
2202 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2203 }
2204
Leon Scroggins68579392009-09-15 15:31:54 -04002205 /* package */ void stopLoading() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002206 resetTitleAndRevertLockIcon();
2207 WebView w = getTopWindow();
2208 w.stopLoading();
2209 mWebViewClient.onPageFinished(w, w.getUrl());
2210
2211 cancelStopToast();
2212 mStopToast = Toast
2213 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2214 mStopToast.show();
2215 }
2216
2217 private void cancelStopToast() {
2218 if (mStopToast != null) {
2219 mStopToast.cancel();
2220 mStopToast = null;
2221 }
2222 }
2223
2224 // called by a non-UI thread to post the message
2225 public void postMessage(int what, int arg1, int arg2, Object obj) {
2226 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2227 }
2228
2229 // public message ids
2230 public final static int LOAD_URL = 1001;
2231 public final static int STOP_LOAD = 1002;
2232
2233 // Message Ids
2234 private static final int FOCUS_NODE_HREF = 102;
2235 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002236 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002237
2238 // Private handler for handling javascript and saving passwords
2239 private Handler mHandler = new Handler() {
2240
2241 public void handleMessage(Message msg) {
2242 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002243 case FOCUS_NODE_HREF:
2244 String url = (String) msg.getData().get("url");
2245 if (url == null || url.length() == 0) {
2246 break;
2247 }
2248 HashMap focusNodeMap = (HashMap) msg.obj;
2249 WebView view = (WebView) focusNodeMap.get("webview");
2250 // Only apply the action if the top window did not change.
2251 if (getTopWindow() != view) {
2252 break;
2253 }
2254 switch (msg.arg1) {
2255 case R.id.open_context_menu_id:
2256 case R.id.view_image_context_menu_id:
2257 loadURL(getTopWindow(), url);
2258 break;
2259 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002260 final TabControl.Tab parent = mTabControl
2261 .getCurrentTab();
2262 final TabControl.Tab newTab = openTab(url);
2263 if (newTab != parent) {
2264 parent.addChildTab(newTab);
2265 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002266 break;
2267 case R.id.bookmark_context_menu_id:
2268 Intent intent = new Intent(BrowserActivity.this,
2269 AddBookmarkPage.class);
2270 intent.putExtra("url", url);
2271 startActivity(intent);
2272 break;
2273 case R.id.share_link_context_menu_id:
2274 Browser.sendString(BrowserActivity.this, url);
2275 break;
2276 case R.id.copy_link_context_menu_id:
2277 copy(url);
2278 break;
2279 case R.id.save_link_context_menu_id:
2280 case R.id.download_context_menu_id:
2281 onDownloadStartNoStream(url, null, null, null, -1);
2282 break;
2283 }
2284 break;
2285
2286 case LOAD_URL:
2287 loadURL(getTopWindow(), (String) msg.obj);
2288 break;
2289
2290 case STOP_LOAD:
2291 stopLoading();
2292 break;
2293
2294 case CANCEL_CREDS_REQUEST:
2295 resumeAfterCredentials();
2296 break;
2297
The Android Open Source Project0c908882009-03-03 19:32:16 -08002298 case RELEASE_WAKELOCK:
2299 if (mWakeLock.isHeld()) {
2300 mWakeLock.release();
2301 }
2302 break;
2303 }
2304 }
2305 };
2306
Leon Scroggins89c6d362009-07-15 16:54:37 -04002307 private void updateScreenshot(WebView view) {
2308 // If this is a bookmarked site, add a screenshot to the database.
2309 // FIXME: When should we update? Every time?
2310 // FIXME: Would like to make sure there is actually something to
2311 // draw, but the API for that (WebViewCore.pictureReady()) is not
2312 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002313 ContentResolver cr = getContentResolver();
2314 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002315 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002316 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002317 boolean succeed = c.moveToFirst();
2318 ContentValues values = null;
2319 while (succeed) {
2320 if (values == null) {
2321 final ByteArrayOutputStream os
2322 = new ByteArrayOutputStream();
2323 Picture thumbnail = view.capturePicture();
2324 // Keep width and height in sync with BrowserBookmarksPage
2325 // and bookmark_thumb
2326 Bitmap bm = Bitmap.createBitmap(100, 80,
2327 Bitmap.Config.ARGB_4444);
2328 Canvas canvas = new Canvas(bm);
2329 // May need to tweak these values to determine what is the
2330 // best scale factor
2331 canvas.scale(.5f, .5f);
2332 thumbnail.draw(canvas);
2333 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2334 values = new ContentValues();
2335 values.put(Browser.BookmarkColumns.THUMBNAIL,
2336 os.toByteArray());
2337 }
2338 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2339 c.getInt(0)), values, null, null);
2340 succeed = c.moveToNext();
2341 }
2342 c.close();
2343 }
2344 }
2345
The Android Open Source Project0c908882009-03-03 19:32:16 -08002346 // -------------------------------------------------------------------------
2347 // WebViewClient implementation.
2348 //-------------------------------------------------------------------------
2349
2350 // Use in overrideUrlLoading
2351 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2352 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2353 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2354 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2355
2356 /* package */ WebViewClient getWebViewClient() {
2357 return mWebViewClient;
2358 }
2359
Patrick Scott3918d442009-08-04 13:22:29 -04002360 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002361 if (icon != null) {
2362 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott3918d442009-08-04 13:22:29 -04002363 view, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002364 }
2365 setFavicon(icon);
2366 }
2367
2368 private final WebViewClient mWebViewClient = new WebViewClient() {
2369 @Override
2370 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2371 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002372 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002373
2374 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2375 if (errorConsole != null) {
2376 errorConsole.clearErrorMessages();
2377 if (mShouldShowErrorConsole) {
2378 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2379 }
2380 }
2381
The Android Open Source Project0c908882009-03-03 19:32:16 -08002382 // Call updateIcon instead of setFavicon so the bookmark
2383 // database can be updated.
Patrick Scott3918d442009-08-04 13:22:29 -04002384 updateIcon(view, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002385
Grace Kloba4d7880f2009-08-12 09:35:42 -07002386 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002387 String host;
2388 try {
2389 WebAddress uri = new WebAddress(url);
2390 host = uri.mHost;
2391 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002392 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002393 }
2394 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002395 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002396 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002397 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002398 }
2399
2400 // Performance probe
2401 if (false) {
2402 mStart = SystemClock.uptimeMillis();
2403 mProcessStart = Process.getElapsedCpuTime();
2404 long[] sysCpu = new long[7];
2405 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2406 sysCpu, null)) {
2407 mUserStart = sysCpu[0] + sysCpu[1];
2408 mSystemStart = sysCpu[2];
2409 mIdleStart = sysCpu[3];
2410 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2411 }
2412 mUiStart = SystemClock.currentThreadTimeMillis();
2413 }
2414
2415 if (!mPageStarted) {
2416 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002417 // if onResume() has been called, resumeWebViewTimers() does
2418 // nothing.
2419 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002420 }
2421
2422 // reset sync timer to avoid sync starts during loading a page
2423 CookieSyncManager.getInstance().resetSync();
2424
2425 mInLoad = true;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002426 WebView currentWebView = mTabControl.getCurrentWebView();
2427 if (currentWebView == null || currentWebView.getScrollY() != 0) {
2428 // This page has begun to load, so show the title bar
2429 showFakeTitleBar();
2430 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002431 updateInLoadMenuItems();
2432 if (!mIsNetworkUp) {
2433 if ( mAlertDialog == null) {
2434 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2435 .setTitle(R.string.loadSuspendedTitle)
2436 .setMessage(R.string.loadSuspended)
2437 .setPositiveButton(R.string.ok, null)
2438 .show();
2439 }
2440 if (view != null) {
2441 view.setNetworkAvailable(false);
2442 }
2443 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002444 }
2445
2446 @Override
2447 public void onPageFinished(WebView view, String url) {
2448 // Reset the title and icon in case we stopped a provisional
2449 // load.
2450 resetTitleAndIcon(view);
2451
2452 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002453 updateLockIconToLatest();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002454 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002455
The Android Open Source Project0c908882009-03-03 19:32:16 -08002456 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002457 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002458 long[] sysCpu = new long[7];
2459 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2460 sysCpu, null)) {
2461 String uiInfo = "UI thread used "
2462 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2463 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002464 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002465 Log.d(LOGTAG, uiInfo);
2466 }
2467 //The string that gets written to the log
2468 String performanceString = "It took total "
2469 + (SystemClock.uptimeMillis() - mStart)
2470 + " ms clock time to load the page."
2471 + "\nbrowser process used "
2472 + (Process.getElapsedCpuTime() - mProcessStart)
2473 + " ms, user processes used "
2474 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2475 + " ms, kernel used "
2476 + (sysCpu[2] - mSystemStart) * 10
2477 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2478 + " ms and irq took "
2479 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2480 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002481 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002482 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2483 }
2484 if (url != null) {
2485 // strip the url to maintain consistency
2486 String newUrl = new String(url);
2487 if (newUrl.startsWith("http://www.")) {
2488 newUrl = newUrl.substring(11);
2489 } else if (newUrl.startsWith("http://")) {
2490 newUrl = newUrl.substring(7);
2491 } else if (newUrl.startsWith("https://www.")) {
2492 newUrl = newUrl.substring(12);
2493 } else if (newUrl.startsWith("https://")) {
2494 newUrl = newUrl.substring(8);
2495 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002496 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002497 Log.d(LOGTAG, newUrl + " loaded");
2498 }
2499 /*
2500 if (sWhiteList.contains(newUrl)) {
2501 // The string that gets pushed to the statistcs
2502 // service
2503 performanceString = performanceString
2504 + "\nWebpage: "
2505 + newUrl
2506 + "\nCarrier: "
2507 + android.os.SystemProperties
2508 .get("gsm.sim.operator.alpha");
2509 if (mWebView != null
2510 && mWebView.getContext() != null
2511 && mWebView.getContext().getSystemService(
2512 Context.CONNECTIVITY_SERVICE) != null) {
2513 ConnectivityManager cManager =
2514 (ConnectivityManager) mWebView
2515 .getContext().getSystemService(
2516 Context.CONNECTIVITY_SERVICE);
2517 NetworkInfo nInfo = cManager
2518 .getActiveNetworkInfo();
2519 if (nInfo != null) {
2520 performanceString = performanceString
2521 + "\nNetwork Type: "
2522 + nInfo.getType().toString();
2523 }
2524 }
2525 Checkin.logEvent(mResolver,
2526 Checkin.Events.Tag.WEBPAGE_LOAD,
2527 performanceString);
2528 Log.w(LOGTAG, "pushed to the statistics service");
2529 }
2530 */
2531 }
2532 }
2533 }
2534
2535 if (mInTrace) {
2536 mInTrace = false;
2537 Debug.stopMethodTracing();
2538 }
2539
2540 if (mPageStarted) {
2541 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002542 // pauseWebViewTimers() will do nothing and return false if
2543 // onPause() is not called yet.
2544 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002545 if (mWakeLock.isHeld()) {
2546 mHandler.removeMessages(RELEASE_WAKELOCK);
2547 mWakeLock.release();
2548 }
2549 }
2550 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002551 }
2552
2553 // return true if want to hijack the url to let another app to handle it
2554 @Override
2555 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2556 if (url.startsWith(SCHEME_WTAI)) {
2557 // wtai://wp/mc;number
2558 // number=string(phone-number)
2559 if (url.startsWith(SCHEME_WTAI_MC)) {
2560 Intent intent = new Intent(Intent.ACTION_VIEW,
2561 Uri.parse(WebView.SCHEME_TEL +
2562 url.substring(SCHEME_WTAI_MC.length())));
2563 startActivity(intent);
2564 return true;
2565 }
2566 // wtai://wp/sd;dtmf
2567 // dtmf=string(dialstring)
2568 if (url.startsWith(SCHEME_WTAI_SD)) {
2569 // TODO
2570 // only send when there is active voice connection
2571 return false;
2572 }
2573 // wtai://wp/ap;number;name
2574 // number=string(phone-number)
2575 // name=string
2576 if (url.startsWith(SCHEME_WTAI_AP)) {
2577 // TODO
2578 return false;
2579 }
2580 }
2581
Dianne Hackborn99189432009-06-17 18:06:18 -07002582 // The "about:" schemes are internal to the browser; don't
2583 // want these to be dispatched to other apps.
2584 if (url.startsWith("about:")) {
2585 return false;
2586 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002587
Dianne Hackborn99189432009-06-17 18:06:18 -07002588 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002589
Dianne Hackborn99189432009-06-17 18:06:18 -07002590 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002591 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002592 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2593 } catch (URISyntaxException ex) {
2594 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002595 return false;
2596 }
2597
Grace Kloba5b078b52009-06-24 20:23:41 -07002598 // check whether the intent can be resolved. If not, we will see
2599 // whether we can download it from the Market.
2600 if (getPackageManager().resolveActivity(intent, 0) == null) {
2601 String packagename = intent.getPackage();
2602 if (packagename != null) {
2603 intent = new Intent(Intent.ACTION_VIEW, Uri
2604 .parse("market://search?q=pname:" + packagename));
2605 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2606 startActivity(intent);
2607 return true;
2608 } else {
2609 return false;
2610 }
2611 }
2612
Dianne Hackborn99189432009-06-17 18:06:18 -07002613 // sanitize the Intent, ensuring web pages can not bypass browser
2614 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002615 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002616 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002617 try {
2618 if (startActivityIfNeeded(intent, -1)) {
2619 return true;
2620 }
2621 } catch (ActivityNotFoundException ex) {
2622 // ignore the error. If no application can handle the URL,
2623 // eg about:blank, assume the browser can handle it.
2624 }
2625
2626 if (mMenuIsDown) {
2627 openTab(url);
2628 closeOptionsMenu();
2629 return true;
2630 }
2631
2632 return false;
2633 }
2634
2635 /**
2636 * Updates the lock icon. This method is called when we discover another
2637 * resource to be loaded for this page (for example, javascript). While
2638 * we update the icon type, we do not update the lock icon itself until
2639 * we are done loading, it is slightly more secure this way.
2640 */
2641 @Override
2642 public void onLoadResource(WebView view, String url) {
2643 if (url != null && url.length() > 0) {
2644 // It is only if the page claims to be secure
2645 // that we may have to update the lock:
2646 if (mLockIconType == LOCK_ICON_SECURE) {
2647 // If NOT a 'safe' url, change the lock to mixed content!
2648 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2649 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002650 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002651 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2652 " updated lock icon to " + mLockIconType + " due to " + url);
2653 }
2654 }
2655 }
2656 }
2657 }
2658
2659 /**
2660 * Show the dialog, asking the user if they would like to continue after
2661 * an excessive number of HTTP redirects.
2662 */
2663 @Override
2664 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2665 final Message continueMsg) {
2666 new AlertDialog.Builder(BrowserActivity.this)
2667 .setTitle(R.string.browserFrameRedirect)
2668 .setMessage(R.string.browserFrame307Post)
2669 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2670 public void onClick(DialogInterface dialog, int which) {
2671 continueMsg.sendToTarget();
2672 }})
2673 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2674 public void onClick(DialogInterface dialog, int which) {
2675 cancelMsg.sendToTarget();
2676 }})
2677 .setOnCancelListener(new OnCancelListener() {
2678 public void onCancel(DialogInterface dialog) {
2679 cancelMsg.sendToTarget();
2680 }})
2681 .show();
2682 }
2683
Patrick Scott37911c72009-03-24 18:02:58 -07002684 // Container class for the next error dialog that needs to be
2685 // displayed.
2686 class ErrorDialog {
2687 public final int mTitle;
2688 public final String mDescription;
2689 public final int mError;
2690 ErrorDialog(int title, String desc, int error) {
2691 mTitle = title;
2692 mDescription = desc;
2693 mError = error;
2694 }
2695 };
2696
2697 private void processNextError() {
2698 if (mQueuedErrors == null) {
2699 return;
2700 }
2701 // The first one is currently displayed so just remove it.
2702 mQueuedErrors.removeFirst();
2703 if (mQueuedErrors.size() == 0) {
2704 mQueuedErrors = null;
2705 return;
2706 }
2707 showError(mQueuedErrors.getFirst());
2708 }
2709
2710 private DialogInterface.OnDismissListener mDialogListener =
2711 new DialogInterface.OnDismissListener() {
2712 public void onDismiss(DialogInterface d) {
2713 processNextError();
2714 }
2715 };
2716 private LinkedList<ErrorDialog> mQueuedErrors;
2717
2718 private void queueError(int err, String desc) {
2719 if (mQueuedErrors == null) {
2720 mQueuedErrors = new LinkedList<ErrorDialog>();
2721 }
2722 for (ErrorDialog d : mQueuedErrors) {
2723 if (d.mError == err) {
2724 // Already saw a similar error, ignore the new one.
2725 return;
2726 }
2727 }
2728 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002729 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002730 R.string.browserFrameFileErrorLabel :
2731 R.string.browserFrameNetworkErrorLabel,
2732 desc, err);
2733 mQueuedErrors.addLast(errDialog);
2734
2735 // Show the dialog now if the queue was empty.
2736 if (mQueuedErrors.size() == 1) {
2737 showError(errDialog);
2738 }
2739 }
2740
2741 private void showError(ErrorDialog errDialog) {
2742 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2743 .setTitle(errDialog.mTitle)
2744 .setMessage(errDialog.mDescription)
2745 .setPositiveButton(R.string.ok, null)
2746 .create();
2747 d.setOnDismissListener(mDialogListener);
2748 d.show();
2749 }
2750
The Android Open Source Project0c908882009-03-03 19:32:16 -08002751 /**
2752 * Show a dialog informing the user of the network error reported by
2753 * WebCore.
2754 */
2755 @Override
2756 public void onReceivedError(WebView view, int errorCode,
2757 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002758 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2759 errorCode != WebViewClient.ERROR_CONNECT &&
2760 errorCode != WebViewClient.ERROR_BAD_URL &&
2761 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2762 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002763 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002764 }
Patrick Scott37911c72009-03-24 18:02:58 -07002765 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2766 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002767
2768 // We need to reset the title after an error.
2769 resetTitleAndRevertLockIcon();
2770 }
2771
2772 /**
2773 * Check with the user if it is ok to resend POST data as the page they
2774 * are trying to navigate to is the result of a POST.
2775 */
2776 @Override
2777 public void onFormResubmission(WebView view, final Message dontResend,
2778 final Message resend) {
2779 new AlertDialog.Builder(BrowserActivity.this)
2780 .setTitle(R.string.browserFrameFormResubmitLabel)
2781 .setMessage(R.string.browserFrameFormResubmitMessage)
2782 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2783 public void onClick(DialogInterface dialog, int which) {
2784 resend.sendToTarget();
2785 }})
2786 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2787 public void onClick(DialogInterface dialog, int which) {
2788 dontResend.sendToTarget();
2789 }})
2790 .setOnCancelListener(new OnCancelListener() {
2791 public void onCancel(DialogInterface dialog) {
2792 dontResend.sendToTarget();
2793 }})
2794 .show();
2795 }
2796
2797 /**
2798 * Insert the url into the visited history database.
2799 * @param url The url to be inserted.
2800 * @param isReload True if this url is being reloaded.
2801 * FIXME: Not sure what to do when reloading the page.
2802 */
2803 @Override
2804 public void doUpdateVisitedHistory(WebView view, String url,
2805 boolean isReload) {
2806 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2807 return;
2808 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002809 // remove "client" before updating it to the history so that it wont
2810 // show up in the auto-complete list.
2811 int index = url.indexOf("client=ms-");
2812 if (index > 0 && url.contains(".google.")) {
2813 int end = url.indexOf('&', index);
2814 if (end > 0) {
2815 url = url.substring(0, index-1).concat(url.substring(end));
2816 } else {
2817 url = url.substring(0, index-1);
2818 }
2819 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002820 Browser.updateVisitedHistory(mResolver, url, true);
2821 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2822 }
2823
2824 /**
2825 * Displays SSL error(s) dialog to the user.
2826 */
2827 @Override
2828 public void onReceivedSslError(
2829 final WebView view, final SslErrorHandler handler, final SslError error) {
2830
2831 if (mSettings.showSecurityWarnings()) {
2832 final LayoutInflater factory =
2833 LayoutInflater.from(BrowserActivity.this);
2834 final View warningsView =
2835 factory.inflate(R.layout.ssl_warnings, null);
2836 final LinearLayout placeholder =
2837 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2838
2839 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2840 LinearLayout ll = (LinearLayout)factory
2841 .inflate(R.layout.ssl_warning, null);
2842 ((TextView)ll.findViewById(R.id.warning))
2843 .setText(R.string.ssl_untrusted);
2844 placeholder.addView(ll);
2845 }
2846
2847 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2848 LinearLayout ll = (LinearLayout)factory
2849 .inflate(R.layout.ssl_warning, null);
2850 ((TextView)ll.findViewById(R.id.warning))
2851 .setText(R.string.ssl_mismatch);
2852 placeholder.addView(ll);
2853 }
2854
2855 if (error.hasError(SslError.SSL_EXPIRED)) {
2856 LinearLayout ll = (LinearLayout)factory
2857 .inflate(R.layout.ssl_warning, null);
2858 ((TextView)ll.findViewById(R.id.warning))
2859 .setText(R.string.ssl_expired);
2860 placeholder.addView(ll);
2861 }
2862
2863 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2864 LinearLayout ll = (LinearLayout)factory
2865 .inflate(R.layout.ssl_warning, null);
2866 ((TextView)ll.findViewById(R.id.warning))
2867 .setText(R.string.ssl_not_yet_valid);
2868 placeholder.addView(ll);
2869 }
2870
2871 new AlertDialog.Builder(BrowserActivity.this)
2872 .setTitle(R.string.security_warning)
2873 .setIcon(android.R.drawable.ic_dialog_alert)
2874 .setView(warningsView)
2875 .setPositiveButton(R.string.ssl_continue,
2876 new DialogInterface.OnClickListener() {
2877 public void onClick(DialogInterface dialog, int whichButton) {
2878 handler.proceed();
2879 }
2880 })
2881 .setNeutralButton(R.string.view_certificate,
2882 new DialogInterface.OnClickListener() {
2883 public void onClick(DialogInterface dialog, int whichButton) {
2884 showSSLCertificateOnError(view, handler, error);
2885 }
2886 })
2887 .setNegativeButton(R.string.cancel,
2888 new DialogInterface.OnClickListener() {
2889 public void onClick(DialogInterface dialog, int whichButton) {
2890 handler.cancel();
2891 BrowserActivity.this.resetTitleAndRevertLockIcon();
2892 }
2893 })
2894 .setOnCancelListener(
2895 new DialogInterface.OnCancelListener() {
2896 public void onCancel(DialogInterface dialog) {
2897 handler.cancel();
2898 BrowserActivity.this.resetTitleAndRevertLockIcon();
2899 }
2900 })
2901 .show();
2902 } else {
2903 handler.proceed();
2904 }
2905 }
2906
2907 /**
2908 * Handles an HTTP authentication request.
2909 *
2910 * @param handler The authentication handler
2911 * @param host The host
2912 * @param realm The realm
2913 */
2914 @Override
2915 public void onReceivedHttpAuthRequest(WebView view,
2916 final HttpAuthHandler handler, final String host, final String realm) {
2917 String username = null;
2918 String password = null;
2919
2920 boolean reuseHttpAuthUsernamePassword =
2921 handler.useHttpAuthUsernamePassword();
2922
2923 if (reuseHttpAuthUsernamePassword &&
2924 (mTabControl.getCurrentWebView() != null)) {
2925 String[] credentials =
2926 mTabControl.getCurrentWebView()
2927 .getHttpAuthUsernamePassword(host, realm);
2928 if (credentials != null && credentials.length == 2) {
2929 username = credentials[0];
2930 password = credentials[1];
2931 }
2932 }
2933
2934 if (username != null && password != null) {
2935 handler.proceed(username, password);
2936 } else {
2937 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2938 }
2939 }
2940
2941 @Override
2942 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2943 if (mMenuIsDown) {
2944 // only check shortcut key when MENU is held
2945 return getWindow().isShortcutKey(event.getKeyCode(), event);
2946 } else {
2947 return false;
2948 }
2949 }
2950
2951 @Override
2952 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2953 if (view != mTabControl.getCurrentTopWebView()) {
2954 return;
2955 }
2956 if (event.isDown()) {
2957 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2958 } else {
2959 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2960 }
2961 }
2962 };
2963
2964 //--------------------------------------------------------------------------
2965 // WebChromeClient implementation
2966 //--------------------------------------------------------------------------
2967
2968 /* package */ WebChromeClient getWebChromeClient() {
2969 return mWebChromeClient;
2970 }
2971
2972 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2973 // Helper method to create a new tab or sub window.
2974 private void createWindow(final boolean dialog, final Message msg) {
2975 if (dialog) {
2976 mTabControl.createSubWindow();
2977 final TabControl.Tab t = mTabControl.getCurrentTab();
2978 attachSubWindow(t);
2979 WebView.WebViewTransport transport =
2980 (WebView.WebViewTransport) msg.obj;
2981 transport.setWebView(t.getSubWebView());
2982 msg.sendToTarget();
2983 } else {
2984 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04002985 final TabControl.Tab newTab
2986 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07002987 if (newTab != parent) {
2988 parent.addChildTab(newTab);
2989 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002990 WebView.WebViewTransport transport =
2991 (WebView.WebViewTransport) msg.obj;
2992 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04002993 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002994 }
2995 }
2996
2997 @Override
2998 public boolean onCreateWindow(WebView view, final boolean dialog,
2999 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003000 // Short-circuit if we can't create any more tabs or sub windows.
3001 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3002 new AlertDialog.Builder(BrowserActivity.this)
3003 .setTitle(R.string.too_many_subwindows_dialog_title)
3004 .setIcon(android.R.drawable.ic_dialog_alert)
3005 .setMessage(R.string.too_many_subwindows_dialog_message)
3006 .setPositiveButton(R.string.ok, null)
3007 .show();
3008 return false;
3009 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3010 new AlertDialog.Builder(BrowserActivity.this)
3011 .setTitle(R.string.too_many_windows_dialog_title)
3012 .setIcon(android.R.drawable.ic_dialog_alert)
3013 .setMessage(R.string.too_many_windows_dialog_message)
3014 .setPositiveButton(R.string.ok, null)
3015 .show();
3016 return false;
3017 }
3018
3019 // Short-circuit if this was a user gesture.
3020 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003021 createWindow(dialog, resultMsg);
3022 return true;
3023 }
3024
3025 // Allow the popup and create the appropriate window.
3026 final AlertDialog.OnClickListener allowListener =
3027 new AlertDialog.OnClickListener() {
3028 public void onClick(DialogInterface d,
3029 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003030 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003031 }
3032 };
3033
3034 // Block the popup by returning a null WebView.
3035 final AlertDialog.OnClickListener blockListener =
3036 new AlertDialog.OnClickListener() {
3037 public void onClick(DialogInterface d, int which) {
3038 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003039 }
3040 };
3041
3042 // Build a confirmation dialog to display to the user.
3043 final AlertDialog d =
3044 new AlertDialog.Builder(BrowserActivity.this)
3045 .setTitle(R.string.attention)
3046 .setIcon(android.R.drawable.ic_dialog_alert)
3047 .setMessage(R.string.popup_window_attempt)
3048 .setPositiveButton(R.string.allow, allowListener)
3049 .setNegativeButton(R.string.block, blockListener)
3050 .setCancelable(false)
3051 .create();
3052
3053 // Show the confirmation dialog.
3054 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003055 return true;
3056 }
3057
3058 @Override
3059 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003060 final TabControl.Tab current = mTabControl.getCurrentTab();
3061 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003062 if (parent != null) {
3063 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003064 switchToTab(mTabControl.getTabIndex(parent));
3065 // Now we need to close the window
3066 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003067 }
3068 }
3069
3070 @Override
3071 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003072 mTitleBar.setProgress(newProgress);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003073 if (mFakeTitleBar != null) {
3074 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003075 }
3076
3077 if (newProgress == 100) {
3078 // onProgressChanged() is called for sub-frame too while
3079 // onPageFinished() is only called for the main frame. sync
3080 // cookie and cache promptly here.
3081 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003082 if (mInLoad) {
3083 mInLoad = false;
3084 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003085 // If the options menu is open, leave the title bar
3086 if (!mOptionsMenuOpen || !mIconView) {
3087 hideFakeTitleBar();
3088 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003089 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003090 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003091 // onPageFinished may have already been called but a subframe
3092 // is still loading and updating the progress. Reset mInLoad
3093 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003094 mInLoad = true;
3095 updateInLoadMenuItems();
3096 WebView currentWebView = mTabControl.getCurrentWebView();
3097 if ((currentWebView == null || currentWebView.getScrollY() != 0)
3098 && (!mOptionsMenuOpen || mIconView)) {
3099 // This page has begun to load, so show the title bar
3100 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003101 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003102 }
3103 }
3104
3105 @Override
3106 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003107 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003108
3109 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003110 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003111
3112 if (url == null ||
3113 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3114 return;
3115 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003116 // See if we can find the current url in our history database and
3117 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003118 if (url.startsWith("http://www.")) {
3119 url = url.substring(11);
3120 } else if (url.startsWith("http://")) {
3121 url = url.substring(4);
3122 }
3123 try {
3124 url = "%" + url;
3125 String [] selArgs = new String[] { url };
3126
3127 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3128 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3129 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3130 Browser.HISTORY_PROJECTION, where, selArgs, null);
3131 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003132 // Current implementation of database only has one entry per
3133 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003134 ContentValues map = new ContentValues();
3135 map.put(Browser.BookmarkColumns.TITLE, title);
3136 mResolver.update(Browser.BOOKMARKS_URI, map,
3137 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003138 }
3139 c.close();
3140 } catch (IllegalStateException e) {
3141 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3142 } catch (SQLiteException ex) {
3143 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3144 }
3145 }
3146
3147 @Override
3148 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003149 updateIcon(view, icon);
3150 }
3151
3152 @Override
3153 public void onReceivedTouchIconUrl(WebView view, String url) {
3154 final ContentResolver cr = getContentResolver();
3155 final Cursor c =
3156 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003157 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003158 if (c != null) {
3159 if (c.getCount() > 0) {
3160 new DownloadTouchIcon(cr, c, view).execute(url);
3161 } else {
3162 c.close();
3163 }
3164 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003165 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003166
Andrei Popescuadc008d2009-06-26 14:11:30 +01003167 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003168 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003169 if (mCustomView != null)
3170 return;
3171
3172 // Add the custom view to its container.
3173 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3174 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003175 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003176 // Save the menu state and set it to empty while the custom
3177 // view is showing.
3178 mOldMenuState = mMenuState;
3179 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003180 // Hide the content view.
3181 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003182 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003183 mCustomViewContainer.setVisibility(View.VISIBLE);
3184 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003185 }
3186
3187 @Override
3188 public void onHideCustomView() {
3189 if (mCustomView == null)
3190 return;
3191
Andrei Popescuc9b55562009-07-07 10:51:15 +01003192 // Hide the custom view.
3193 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003194 // Remove the custom view from its container.
3195 mCustomViewContainer.removeView(mCustomView);
3196 mCustomView = null;
3197 // Reset the old menu state.
3198 mMenuState = mOldMenuState;
3199 mOldMenuState = EMPTY_MENU;
3200 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003201 mCustomViewCallback.onCustomViewHidden();
3202 // Show the content view.
3203 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003204 }
3205
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003206 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003207 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003208 * @param url the URL that exceeded the quota
3209 * @param databaseIdentifier the identifier of the database on
3210 * which the transaction that caused the quota overflow was run
3211 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003212 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003213 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003214 * @param quotaUpdater The callback to run when a decision to allow or
3215 * deny quota has been made. Don't forget to call this!
3216 */
3217 @Override
3218 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003219 String databaseIdentifier, long currentQuota, long estimatedSize,
3220 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003221 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003222 url, databaseIdentifier, currentQuota, estimatedSize,
3223 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003224 }
3225
3226 /**
3227 * The Application Cache has exceeded its max size.
3228 * @param spaceNeeded is the amount of disk space that would be needed
3229 * in order for the last appcache operation to succeed.
3230 * @param totalUsedQuota is the sum of all origins' quota.
3231 * @param quotaUpdater A callback to inform the WebCore thread that a new
3232 * app cache size is available. This callback must always be executed at
3233 * some point to ensure that the sleeping WebCore thread is woken up.
3234 */
3235 @Override
3236 public void onReachedMaxAppCacheSize(long spaceNeeded,
3237 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3238 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3239 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003240 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003241
Steve Block2bc69912009-07-30 14:45:13 +01003242 /**
3243 * Instructs the browser to show a prompt to ask the user to set the
3244 * Geolocation permission state for the specified origin.
3245 * @param origin The origin for which Geolocation permissions are
3246 * requested.
3247 * @param callback The callback to call once the user has set the
3248 * Geolocation permission state.
3249 */
3250 @Override
3251 public void onGeolocationPermissionsShowPrompt(String origin,
3252 GeolocationPermissions.Callback callback) {
3253 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3254 origin, callback);
3255 }
3256
3257 /**
3258 * Instructs the browser to hide the Geolocation permissions prompt.
3259 */
3260 @Override
3261 public void onGeolocationPermissionsHidePrompt() {
3262 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3263 }
3264
Ben Murdoch7db26342009-06-03 18:21:19 +01003265 /* Adds a JavaScript error message to the system log.
3266 * @param message The error message to report.
3267 * @param lineNumber The line number of the error.
3268 * @param sourceID The name of the source file that caused the error.
3269 */
3270 @Override
3271 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003272 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3273 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3274 if (mShouldShowErrorConsole &&
3275 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3276 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3277 }
3278 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003279 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003280 };
3281
3282 /**
3283 * Notify the host application a download should be done, or that
3284 * the data should be streamed if a streaming viewer is available.
3285 * @param url The full url to the content that should be downloaded
3286 * @param contentDisposition Content-disposition http header, if
3287 * present.
3288 * @param mimetype The mimetype of the content reported by the server
3289 * @param contentLength The file size reported by the server
3290 */
3291 public void onDownloadStart(String url, String userAgent,
3292 String contentDisposition, String mimetype, long contentLength) {
3293 // if we're dealing wih A/V content that's not explicitly marked
3294 // for download, check if it's streamable.
3295 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003296 || !contentDisposition.regionMatches(
3297 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003298 // query the package manager to see if there's a registered handler
3299 // that matches.
3300 Intent intent = new Intent(Intent.ACTION_VIEW);
3301 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003302 ResolveInfo info = getPackageManager().resolveActivity(intent,
3303 PackageManager.MATCH_DEFAULT_ONLY);
3304 if (info != null) {
3305 ComponentName myName = getComponentName();
3306 // If we resolved to ourselves, we don't want to attempt to
3307 // load the url only to try and download it again.
3308 if (!myName.getPackageName().equals(
3309 info.activityInfo.packageName)
3310 || !myName.getClassName().equals(
3311 info.activityInfo.name)) {
3312 // someone (other than us) knows how to handle this mime
3313 // type with this scheme, don't download.
3314 try {
3315 startActivity(intent);
3316 return;
3317 } catch (ActivityNotFoundException ex) {
3318 if (LOGD_ENABLED) {
3319 Log.d(LOGTAG, "activity not found for " + mimetype
3320 + " over " + Uri.parse(url).getScheme(),
3321 ex);
3322 }
3323 // Best behavior is to fall back to a download in this
3324 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003325 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003326 }
3327 }
3328 }
3329 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3330 }
3331
3332 /**
3333 * Notify the host application a download should be done, even if there
3334 * is a streaming viewer available for thise type.
3335 * @param url The full url to the content that should be downloaded
3336 * @param contentDisposition Content-disposition http header, if
3337 * present.
3338 * @param mimetype The mimetype of the content reported by the server
3339 * @param contentLength The file size reported by the server
3340 */
3341 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3342 String contentDisposition, String mimetype, long contentLength) {
3343
3344 String filename = URLUtil.guessFileName(url,
3345 contentDisposition, mimetype);
3346
3347 // Check to see if we have an SDCard
3348 String status = Environment.getExternalStorageState();
3349 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3350 int title;
3351 String msg;
3352
3353 // Check to see if the SDCard is busy, same as the music app
3354 if (status.equals(Environment.MEDIA_SHARED)) {
3355 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3356 title = R.string.download_sdcard_busy_dlg_title;
3357 } else {
3358 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3359 title = R.string.download_no_sdcard_dlg_title;
3360 }
3361
3362 new AlertDialog.Builder(this)
3363 .setTitle(title)
3364 .setIcon(android.R.drawable.ic_dialog_alert)
3365 .setMessage(msg)
3366 .setPositiveButton(R.string.ok, null)
3367 .show();
3368 return;
3369 }
3370
3371 // java.net.URI is a lot stricter than KURL so we have to undo
3372 // KURL's percent-encoding and redo the encoding using java.net.URI.
3373 URI uri = null;
3374 try {
3375 // Undo the percent-encoding that KURL may have done.
3376 String newUrl = new String(URLUtil.decode(url.getBytes()));
3377 // Parse the url into pieces
3378 WebAddress w = new WebAddress(newUrl);
3379 String frag = null;
3380 String query = null;
3381 String path = w.mPath;
3382 // Break the path into path, query, and fragment
3383 if (path.length() > 0) {
3384 // Strip the fragment
3385 int idx = path.lastIndexOf('#');
3386 if (idx != -1) {
3387 frag = path.substring(idx + 1);
3388 path = path.substring(0, idx);
3389 }
3390 idx = path.lastIndexOf('?');
3391 if (idx != -1) {
3392 query = path.substring(idx + 1);
3393 path = path.substring(0, idx);
3394 }
3395 }
3396 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3397 query, frag);
3398 } catch (Exception e) {
3399 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3400 return;
3401 }
3402
3403 // XXX: Have to use the old url since the cookies were stored using the
3404 // old percent-encoded url.
3405 String cookies = CookieManager.getInstance().getCookie(url);
3406
3407 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003408 values.put(Downloads.COLUMN_URI, uri.toString());
3409 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3410 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3411 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003412 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003413 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003414 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003415 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3416 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3417 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3418 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003419 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003420 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003421 }
3422 if (mimetype == null) {
3423 // We must have long pressed on a link or image to download it. We
3424 // are not sure of the mimetype in this case, so do a head request
3425 new FetchUrlMimeType(this).execute(values);
3426 } else {
3427 final Uri contentUri =
3428 getContentResolver().insert(Downloads.CONTENT_URI, values);
3429 viewDownloads(contentUri);
3430 }
3431
3432 }
3433
3434 /**
3435 * Resets the lock icon. This method is called when we start a new load and
3436 * know the url to be loaded.
3437 */
3438 private void resetLockIcon(String url) {
3439 // Save the lock-icon state (we revert to it if the load gets cancelled)
3440 saveLockIcon();
3441
3442 mLockIconType = LOCK_ICON_UNSECURE;
3443 if (URLUtil.isHttpsUrl(url)) {
3444 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003445 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003446 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3447 " reset lock icon to " + mLockIconType);
3448 }
3449 }
3450
3451 updateLockIconImage(LOCK_ICON_UNSECURE);
3452 }
3453
3454 /**
3455 * Resets the lock icon. This method is called when the icon needs to be
3456 * reset but we do not know whether we are loading a secure or not secure
3457 * page.
3458 */
3459 private void resetLockIcon() {
3460 // Save the lock-icon state (we revert to it if the load gets cancelled)
3461 saveLockIcon();
3462
3463 mLockIconType = LOCK_ICON_UNSECURE;
3464
Dave Bort31a6d1c2009-04-13 15:56:49 -07003465 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003466 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3467 " reset lock icon to " + mLockIconType);
3468 }
3469
3470 updateLockIconImage(LOCK_ICON_UNSECURE);
3471 }
3472
3473 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003474 * Update the lock icon to correspond to our latest state.
3475 */
3476 /* package */ void updateLockIconToLatest() {
3477 updateLockIconImage(mLockIconType);
3478 }
3479
3480 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003481 * Updates the lock-icon image in the title-bar.
3482 */
3483 private void updateLockIconImage(int lockIconType) {
3484 Drawable d = null;
3485 if (lockIconType == LOCK_ICON_SECURE) {
3486 d = mSecLockIcon;
3487 } else if (lockIconType == LOCK_ICON_MIXED) {
3488 d = mMixLockIcon;
3489 }
Leon Scroggins68579392009-09-15 15:31:54 -04003490 mTitleBar.setLock(d);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003491 if (mFakeTitleBar != null) {
3492 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003493 }
3494 }
3495
3496 /**
3497 * Displays a page-info dialog.
3498 * @param tab The tab to show info about
3499 * @param fromShowSSLCertificateOnError The flag that indicates whether
3500 * this dialog was opened from the SSL-certificate-on-error dialog or
3501 * not. This is important, since we need to know whether to return to
3502 * the parent dialog or simply dismiss.
3503 */
3504 private void showPageInfo(final TabControl.Tab tab,
3505 final boolean fromShowSSLCertificateOnError) {
3506 final LayoutInflater factory = LayoutInflater
3507 .from(this);
3508
3509 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3510
3511 final WebView view = tab.getWebView();
3512
3513 String url = null;
3514 String title = null;
3515
3516 if (view == null) {
3517 url = tab.getUrl();
3518 title = tab.getTitle();
3519 } else if (view == mTabControl.getCurrentWebView()) {
3520 // Use the cached title and url if this is the current WebView
3521 url = mUrl;
3522 title = mTitle;
3523 } else {
3524 url = view.getUrl();
3525 title = view.getTitle();
3526 }
3527
3528 if (url == null) {
3529 url = "";
3530 }
3531 if (title == null) {
3532 title = "";
3533 }
3534
3535 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3536 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3537
3538 mPageInfoView = tab;
3539 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3540
3541 AlertDialog.Builder alertDialogBuilder =
3542 new AlertDialog.Builder(this)
3543 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3544 .setView(pageInfoView)
3545 .setPositiveButton(
3546 R.string.ok,
3547 new DialogInterface.OnClickListener() {
3548 public void onClick(DialogInterface dialog,
3549 int whichButton) {
3550 mPageInfoDialog = null;
3551 mPageInfoView = null;
3552 mPageInfoFromShowSSLCertificateOnError = null;
3553
3554 // if we came here from the SSL error dialog
3555 if (fromShowSSLCertificateOnError) {
3556 // go back to the SSL error dialog
3557 showSSLCertificateOnError(
3558 mSSLCertificateOnErrorView,
3559 mSSLCertificateOnErrorHandler,
3560 mSSLCertificateOnErrorError);
3561 }
3562 }
3563 })
3564 .setOnCancelListener(
3565 new DialogInterface.OnCancelListener() {
3566 public void onCancel(DialogInterface dialog) {
3567 mPageInfoDialog = null;
3568 mPageInfoView = null;
3569 mPageInfoFromShowSSLCertificateOnError = null;
3570
3571 // if we came here from the SSL error dialog
3572 if (fromShowSSLCertificateOnError) {
3573 // go back to the SSL error dialog
3574 showSSLCertificateOnError(
3575 mSSLCertificateOnErrorView,
3576 mSSLCertificateOnErrorHandler,
3577 mSSLCertificateOnErrorError);
3578 }
3579 }
3580 });
3581
3582 // if we have a main top-level page SSL certificate set or a certificate
3583 // error
3584 if (fromShowSSLCertificateOnError ||
3585 (view != null && view.getCertificate() != null)) {
3586 // add a 'View Certificate' button
3587 alertDialogBuilder.setNeutralButton(
3588 R.string.view_certificate,
3589 new DialogInterface.OnClickListener() {
3590 public void onClick(DialogInterface dialog,
3591 int whichButton) {
3592 mPageInfoDialog = null;
3593 mPageInfoView = null;
3594 mPageInfoFromShowSSLCertificateOnError = null;
3595
3596 // if we came here from the SSL error dialog
3597 if (fromShowSSLCertificateOnError) {
3598 // go back to the SSL error dialog
3599 showSSLCertificateOnError(
3600 mSSLCertificateOnErrorView,
3601 mSSLCertificateOnErrorHandler,
3602 mSSLCertificateOnErrorError);
3603 } else {
3604 // otherwise, display the top-most certificate from
3605 // the chain
3606 if (view.getCertificate() != null) {
3607 showSSLCertificate(tab);
3608 }
3609 }
3610 }
3611 });
3612 }
3613
3614 mPageInfoDialog = alertDialogBuilder.show();
3615 }
3616
3617 /**
3618 * Displays the main top-level page SSL certificate dialog
3619 * (accessible from the Page-Info dialog).
3620 * @param tab The tab to show certificate for.
3621 */
3622 private void showSSLCertificate(final TabControl.Tab tab) {
3623 final View certificateView =
3624 inflateCertificateView(tab.getWebView().getCertificate());
3625 if (certificateView == null) {
3626 return;
3627 }
3628
3629 LayoutInflater factory = LayoutInflater.from(this);
3630
3631 final LinearLayout placeholder =
3632 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3633
3634 LinearLayout ll = (LinearLayout) factory.inflate(
3635 R.layout.ssl_success, placeholder);
3636 ((TextView)ll.findViewById(R.id.success))
3637 .setText(R.string.ssl_certificate_is_valid);
3638
3639 mSSLCertificateView = tab;
3640 mSSLCertificateDialog =
3641 new AlertDialog.Builder(this)
3642 .setTitle(R.string.ssl_certificate).setIcon(
3643 R.drawable.ic_dialog_browser_certificate_secure)
3644 .setView(certificateView)
3645 .setPositiveButton(R.string.ok,
3646 new DialogInterface.OnClickListener() {
3647 public void onClick(DialogInterface dialog,
3648 int whichButton) {
3649 mSSLCertificateDialog = null;
3650 mSSLCertificateView = null;
3651
3652 showPageInfo(tab, false);
3653 }
3654 })
3655 .setOnCancelListener(
3656 new DialogInterface.OnCancelListener() {
3657 public void onCancel(DialogInterface dialog) {
3658 mSSLCertificateDialog = null;
3659 mSSLCertificateView = null;
3660
3661 showPageInfo(tab, false);
3662 }
3663 })
3664 .show();
3665 }
3666
3667 /**
3668 * Displays the SSL error certificate dialog.
3669 * @param view The target web-view.
3670 * @param handler The SSL error handler responsible for cancelling the
3671 * connection that resulted in an SSL error or proceeding per user request.
3672 * @param error The SSL error object.
3673 */
3674 private void showSSLCertificateOnError(
3675 final WebView view, final SslErrorHandler handler, final SslError error) {
3676
3677 final View certificateView =
3678 inflateCertificateView(error.getCertificate());
3679 if (certificateView == null) {
3680 return;
3681 }
3682
3683 LayoutInflater factory = LayoutInflater.from(this);
3684
3685 final LinearLayout placeholder =
3686 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3687
3688 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3689 LinearLayout ll = (LinearLayout)factory
3690 .inflate(R.layout.ssl_warning, placeholder);
3691 ((TextView)ll.findViewById(R.id.warning))
3692 .setText(R.string.ssl_untrusted);
3693 }
3694
3695 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3696 LinearLayout ll = (LinearLayout)factory
3697 .inflate(R.layout.ssl_warning, placeholder);
3698 ((TextView)ll.findViewById(R.id.warning))
3699 .setText(R.string.ssl_mismatch);
3700 }
3701
3702 if (error.hasError(SslError.SSL_EXPIRED)) {
3703 LinearLayout ll = (LinearLayout)factory
3704 .inflate(R.layout.ssl_warning, placeholder);
3705 ((TextView)ll.findViewById(R.id.warning))
3706 .setText(R.string.ssl_expired);
3707 }
3708
3709 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3710 LinearLayout ll = (LinearLayout)factory
3711 .inflate(R.layout.ssl_warning, placeholder);
3712 ((TextView)ll.findViewById(R.id.warning))
3713 .setText(R.string.ssl_not_yet_valid);
3714 }
3715
3716 mSSLCertificateOnErrorHandler = handler;
3717 mSSLCertificateOnErrorView = view;
3718 mSSLCertificateOnErrorError = error;
3719 mSSLCertificateOnErrorDialog =
3720 new AlertDialog.Builder(this)
3721 .setTitle(R.string.ssl_certificate).setIcon(
3722 R.drawable.ic_dialog_browser_certificate_partially_secure)
3723 .setView(certificateView)
3724 .setPositiveButton(R.string.ok,
3725 new DialogInterface.OnClickListener() {
3726 public void onClick(DialogInterface dialog,
3727 int whichButton) {
3728 mSSLCertificateOnErrorDialog = null;
3729 mSSLCertificateOnErrorView = null;
3730 mSSLCertificateOnErrorHandler = null;
3731 mSSLCertificateOnErrorError = null;
3732
3733 mWebViewClient.onReceivedSslError(
3734 view, handler, error);
3735 }
3736 })
3737 .setNeutralButton(R.string.page_info_view,
3738 new DialogInterface.OnClickListener() {
3739 public void onClick(DialogInterface dialog,
3740 int whichButton) {
3741 mSSLCertificateOnErrorDialog = null;
3742
3743 // do not clear the dialog state: we will
3744 // need to show the dialog again once the
3745 // user is done exploring the page-info details
3746
3747 showPageInfo(mTabControl.getTabFromView(view),
3748 true);
3749 }
3750 })
3751 .setOnCancelListener(
3752 new DialogInterface.OnCancelListener() {
3753 public void onCancel(DialogInterface dialog) {
3754 mSSLCertificateOnErrorDialog = null;
3755 mSSLCertificateOnErrorView = null;
3756 mSSLCertificateOnErrorHandler = null;
3757 mSSLCertificateOnErrorError = null;
3758
3759 mWebViewClient.onReceivedSslError(
3760 view, handler, error);
3761 }
3762 })
3763 .show();
3764 }
3765
3766 /**
3767 * Inflates the SSL certificate view (helper method).
3768 * @param certificate The SSL certificate.
3769 * @return The resultant certificate view with issued-to, issued-by,
3770 * issued-on, expires-on, and possibly other fields set.
3771 * If the input certificate is null, returns null.
3772 */
3773 private View inflateCertificateView(SslCertificate certificate) {
3774 if (certificate == null) {
3775 return null;
3776 }
3777
3778 LayoutInflater factory = LayoutInflater.from(this);
3779
3780 View certificateView = factory.inflate(
3781 R.layout.ssl_certificate, null);
3782
3783 // issued to:
3784 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3785 if (issuedTo != null) {
3786 ((TextView) certificateView.findViewById(R.id.to_common))
3787 .setText(issuedTo.getCName());
3788 ((TextView) certificateView.findViewById(R.id.to_org))
3789 .setText(issuedTo.getOName());
3790 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3791 .setText(issuedTo.getUName());
3792 }
3793
3794 // issued by:
3795 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3796 if (issuedBy != null) {
3797 ((TextView) certificateView.findViewById(R.id.by_common))
3798 .setText(issuedBy.getCName());
3799 ((TextView) certificateView.findViewById(R.id.by_org))
3800 .setText(issuedBy.getOName());
3801 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3802 .setText(issuedBy.getUName());
3803 }
3804
3805 // issued on:
3806 String issuedOn = reformatCertificateDate(
3807 certificate.getValidNotBefore());
3808 ((TextView) certificateView.findViewById(R.id.issued_on))
3809 .setText(issuedOn);
3810
3811 // expires on:
3812 String expiresOn = reformatCertificateDate(
3813 certificate.getValidNotAfter());
3814 ((TextView) certificateView.findViewById(R.id.expires_on))
3815 .setText(expiresOn);
3816
3817 return certificateView;
3818 }
3819
3820 /**
3821 * Re-formats the certificate date (Date.toString()) string to
3822 * a properly localized date string.
3823 * @return Properly localized version of the certificate date string and
3824 * the original certificate date string if fails to localize.
3825 * If the original string is null, returns an empty string "".
3826 */
3827 private String reformatCertificateDate(String certificateDate) {
3828 String reformattedDate = null;
3829
3830 if (certificateDate != null) {
3831 Date date = null;
3832 try {
3833 date = java.text.DateFormat.getInstance().parse(certificateDate);
3834 } catch (ParseException e) {
3835 date = null;
3836 }
3837
3838 if (date != null) {
3839 reformattedDate =
3840 DateFormat.getDateFormat(this).format(date);
3841 }
3842 }
3843
3844 return reformattedDate != null ? reformattedDate :
3845 (certificateDate != null ? certificateDate : "");
3846 }
3847
3848 /**
3849 * Displays an http-authentication dialog.
3850 */
3851 private void showHttpAuthentication(final HttpAuthHandler handler,
3852 final String host, final String realm, final String title,
3853 final String name, final String password, int focusId) {
3854 LayoutInflater factory = LayoutInflater.from(this);
3855 final View v = factory
3856 .inflate(R.layout.http_authentication, null);
3857 if (name != null) {
3858 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3859 }
3860 if (password != null) {
3861 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3862 }
3863
3864 String titleText = title;
3865 if (titleText == null) {
3866 titleText = getText(R.string.sign_in_to).toString().replace(
3867 "%s1", host).replace("%s2", realm);
3868 }
3869
3870 mHttpAuthHandler = handler;
3871 AlertDialog dialog = new AlertDialog.Builder(this)
3872 .setTitle(titleText)
3873 .setIcon(android.R.drawable.ic_dialog_alert)
3874 .setView(v)
3875 .setPositiveButton(R.string.action,
3876 new DialogInterface.OnClickListener() {
3877 public void onClick(DialogInterface dialog,
3878 int whichButton) {
3879 String nm = ((EditText) v
3880 .findViewById(R.id.username_edit))
3881 .getText().toString();
3882 String pw = ((EditText) v
3883 .findViewById(R.id.password_edit))
3884 .getText().toString();
3885 BrowserActivity.this.setHttpAuthUsernamePassword
3886 (host, realm, nm, pw);
3887 handler.proceed(nm, pw);
3888 mHttpAuthenticationDialog = null;
3889 mHttpAuthHandler = null;
3890 }})
3891 .setNegativeButton(R.string.cancel,
3892 new DialogInterface.OnClickListener() {
3893 public void onClick(DialogInterface dialog,
3894 int whichButton) {
3895 handler.cancel();
3896 BrowserActivity.this.resetTitleAndRevertLockIcon();
3897 mHttpAuthenticationDialog = null;
3898 mHttpAuthHandler = null;
3899 }})
3900 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3901 public void onCancel(DialogInterface dialog) {
3902 handler.cancel();
3903 BrowserActivity.this.resetTitleAndRevertLockIcon();
3904 mHttpAuthenticationDialog = null;
3905 mHttpAuthHandler = null;
3906 }})
3907 .create();
3908 // Make the IME appear when the dialog is displayed if applicable.
3909 dialog.getWindow().setSoftInputMode(
3910 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3911 dialog.show();
3912 if (focusId != 0) {
3913 dialog.findViewById(focusId).requestFocus();
3914 } else {
3915 v.findViewById(R.id.username_edit).requestFocus();
3916 }
3917 mHttpAuthenticationDialog = dialog;
3918 }
3919
3920 public int getProgress() {
3921 WebView w = mTabControl.getCurrentWebView();
3922 if (w != null) {
3923 return w.getProgress();
3924 } else {
3925 return 100;
3926 }
3927 }
3928
3929 /**
3930 * Set HTTP authentication password.
3931 *
3932 * @param host The host for the password
3933 * @param realm The realm for the password
3934 * @param username The username for the password. If it is null, it means
3935 * password can't be saved.
3936 * @param password The password
3937 */
3938 public void setHttpAuthUsernamePassword(String host, String realm,
3939 String username,
3940 String password) {
3941 WebView w = mTabControl.getCurrentWebView();
3942 if (w != null) {
3943 w.setHttpAuthUsernamePassword(host, realm, username, password);
3944 }
3945 }
3946
3947 /**
3948 * connectivity manager says net has come or gone... inform the user
3949 * @param up true if net has come up, false if net has gone down
3950 */
3951 public void onNetworkToggle(boolean up) {
3952 if (up == mIsNetworkUp) {
3953 return;
3954 } else if (up) {
3955 mIsNetworkUp = true;
3956 if (mAlertDialog != null) {
3957 mAlertDialog.cancel();
3958 mAlertDialog = null;
3959 }
3960 } else {
3961 mIsNetworkUp = false;
3962 if (mInLoad && mAlertDialog == null) {
3963 mAlertDialog = new AlertDialog.Builder(this)
3964 .setTitle(R.string.loadSuspendedTitle)
3965 .setMessage(R.string.loadSuspended)
3966 .setPositiveButton(R.string.ok, null)
3967 .show();
3968 }
3969 }
3970 WebView w = mTabControl.getCurrentWebView();
3971 if (w != null) {
3972 w.setNetworkAvailable(up);
3973 }
3974 }
3975
3976 @Override
3977 protected void onActivityResult(int requestCode, int resultCode,
3978 Intent intent) {
3979 switch (requestCode) {
3980 case COMBO_PAGE:
3981 if (resultCode == RESULT_OK && intent != null) {
3982 String data = intent.getAction();
3983 Bundle extras = intent.getExtras();
3984 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003985 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003986 } else {
3987 final TabControl.Tab currentTab =
3988 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003989 dismissSubWindow(currentTab);
3990 if (data != null && data.length() != 0) {
3991 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003992 }
3993 }
3994 }
3995 break;
3996 default:
3997 break;
3998 }
Leon Scroggins30444232009-09-04 18:36:20 -04003999 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004000 }
4001
4002 /*
4003 * This method is called as a result of the user selecting the options
4004 * menu to see the download window, or when a download changes state. It
4005 * shows the download window ontop of the current window.
4006 */
4007 /* package */ void viewDownloads(Uri downloadRecord) {
4008 Intent intent = new Intent(this,
4009 BrowserDownloadPage.class);
4010 intent.setData(downloadRecord);
4011 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4012
4013 }
4014
Leon Scroggins160a7e72009-08-14 18:28:01 -04004015 /**
4016 * Open the Go page.
4017 * @param startWithHistory If true, open starting on the history tab.
4018 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004019 */
Leon Scroggins30444232009-09-04 18:36:20 -04004020 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004021 WebView current = mTabControl.getCurrentWebView();
4022 if (current == null) {
4023 return;
4024 }
4025 Intent intent = new Intent(this,
4026 CombinedBookmarkHistoryActivity.class);
4027 String title = current.getTitle();
4028 String url = current.getUrl();
4029 // Just in case the user opens bookmarks before a page finishes loading
4030 // so the current history item, and therefore the page, is null.
4031 if (null == url) {
4032 url = mLastEnteredUrl;
4033 // This can happen.
4034 if (null == url) {
4035 url = mSettings.getHomePage();
4036 }
4037 }
4038 // In case the web page has not yet received its associated title.
4039 if (title == null) {
4040 title = url;
4041 }
4042 intent.putExtra("title", title);
4043 intent.putExtra("url", url);
Leon Scroggins30444232009-09-04 18:36:20 -04004044 // Disable opening in a new window if we have maxed out the windows
4045 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4046 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004047 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004048 if (startWithHistory) {
4049 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4050 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4051 }
4052 startActivityForResult(intent, COMBO_PAGE);
4053 }
4054
4055 // Called when loading from context menu or LOAD_URL message
4056 private void loadURL(WebView view, String url) {
4057 // In case the user enters nothing.
4058 if (url != null && url.length() != 0 && view != null) {
4059 url = smartUrlFilter(url);
4060 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4061 view.loadUrl(url);
4062 }
4063 }
4064 }
4065
The Android Open Source Project0c908882009-03-03 19:32:16 -08004066 private String smartUrlFilter(Uri inUri) {
4067 if (inUri != null) {
4068 return smartUrlFilter(inUri.toString());
4069 }
4070 return null;
4071 }
4072
4073
4074 // get window count
4075
4076 int getWindowCount(){
4077 if(mTabControl != null){
4078 return mTabControl.getTabCount();
4079 }
4080 return 0;
4081 }
4082
Feng Qianb34f87a2009-03-24 21:27:26 -07004083 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004084 "(?i)" + // switch on case insensitive matching
4085 "(" + // begin group for schema
4086 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004087 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004088 ")" +
4089 "(.*)" );
4090
4091 /**
4092 * Attempts to determine whether user input is a URL or search
4093 * terms. Anything with a space is passed to search.
4094 *
4095 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4096 * "Http://" converts to "http://"
4097 *
4098 * @return Original or modified URL
4099 *
4100 */
4101 String smartUrlFilter(String url) {
4102
4103 String inUrl = url.trim();
4104 boolean hasSpace = inUrl.indexOf(' ') != -1;
4105
4106 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4107 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004108 // force scheme to lowercase
4109 String scheme = matcher.group(1);
4110 String lcScheme = scheme.toLowerCase();
4111 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004112 inUrl = lcScheme + matcher.group(2);
4113 }
4114 if (hasSpace) {
4115 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004116 }
4117 return inUrl;
4118 }
4119 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004120 // FIXME: Is this the correct place to add to searches?
4121 // what if someone else calls this function?
4122 int shortcut = parseUrlShortcut(inUrl);
4123 if (shortcut != SHORTCUT_INVALID) {
4124 Browser.addSearchUrl(mResolver, inUrl);
4125 String query = inUrl.substring(2);
4126 switch (shortcut) {
4127 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004128 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004129 case SHORTCUT_WIKIPEDIA_SEARCH:
4130 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4131 case SHORTCUT_DICTIONARY_SEARCH:
4132 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4133 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004134 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004135 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004136 }
4137 }
4138 } else {
4139 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4140 return URLUtil.guessUrl(inUrl);
4141 }
4142 }
4143
4144 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004145 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004146 }
4147
Ben Murdochbff2d602009-07-01 20:19:05 +01004148 /* package */ void setShouldShowErrorConsole(boolean flag) {
4149 if (flag == mShouldShowErrorConsole) {
4150 // Nothing to do.
4151 return;
4152 }
4153
4154 mShouldShowErrorConsole = flag;
4155
4156 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4157
4158 if (flag) {
4159 // Setting the show state of the console will cause it's the layout to be inflated.
4160 if (errorConsole.numberOfErrors() > 0) {
4161 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4162 } else {
4163 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4164 }
4165
4166 // Now we can add it to the main view.
4167 mErrorConsoleContainer.addView(errorConsole,
4168 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4169 ViewGroup.LayoutParams.WRAP_CONTENT));
4170 } else {
4171 mErrorConsoleContainer.removeView(errorConsole);
4172 }
4173
4174 }
4175
The Android Open Source Project0c908882009-03-03 19:32:16 -08004176 private final static int LOCK_ICON_UNSECURE = 0;
4177 private final static int LOCK_ICON_SECURE = 1;
4178 private final static int LOCK_ICON_MIXED = 2;
4179
4180 private int mLockIconType = LOCK_ICON_UNSECURE;
4181 private int mPrevLockType = LOCK_ICON_UNSECURE;
4182
4183 private BrowserSettings mSettings;
4184 private TabControl mTabControl;
4185 private ContentResolver mResolver;
4186 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004187 private View mCustomView;
4188 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004189 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004190
4191 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4192 // view, we should rewrite this.
4193 private int mCurrentMenuState = 0;
4194 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004195 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004196 private static final int EMPTY_MENU = -1;
4197 private Menu mMenu;
4198
4199 private FindDialog mFindDialog;
4200 // Used to prevent chording to result in firing two shortcuts immediately
4201 // one after another. Fixes bug 1211714.
4202 boolean mCanChord;
4203
4204 private boolean mInLoad;
4205 private boolean mIsNetworkUp;
4206
4207 private boolean mPageStarted;
4208 private boolean mActivityInPause = true;
4209
4210 private boolean mMenuIsDown;
4211
4212 private final KeyTracker mKeyTracker = new KeyTracker(this);
4213
4214 // As trackball doesn't send repeat down, we have to track it ourselves
4215 private boolean mTrackTrackball;
4216
4217 private static boolean mInTrace;
4218
4219 // Performance probe
4220 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4221 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4222 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4223 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4224 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4225 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4226 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4227 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4228 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4229 };
4230
4231 private long mStart;
4232 private long mProcessStart;
4233 private long mUserStart;
4234 private long mSystemStart;
4235 private long mIdleStart;
4236 private long mIrqStart;
4237
4238 private long mUiStart;
4239
4240 private Drawable mMixLockIcon;
4241 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004242
4243 /* hold a ref so we can auto-cancel if necessary */
4244 private AlertDialog mAlertDialog;
4245
4246 // Wait for credentials before loading google.com
4247 private ProgressDialog mCredsDlg;
4248
4249 // The up-to-date URL and title (these can be different from those stored
4250 // in WebView, since it takes some time for the information in WebView to
4251 // get updated)
4252 private String mUrl;
4253 private String mTitle;
4254
4255 // As PageInfo has different style for landscape / portrait, we have
4256 // to re-open it when configuration changed
4257 private AlertDialog mPageInfoDialog;
4258 private TabControl.Tab mPageInfoView;
4259 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4260 // dialog, we should not just dismiss it, but should get back to the
4261 // SSL-certificate-on-error dialog. This flag is used to store this state
4262 private Boolean mPageInfoFromShowSSLCertificateOnError;
4263
4264 // as SSLCertificateOnError has different style for landscape / portrait,
4265 // we have to re-open it when configuration changed
4266 private AlertDialog mSSLCertificateOnErrorDialog;
4267 private WebView mSSLCertificateOnErrorView;
4268 private SslErrorHandler mSSLCertificateOnErrorHandler;
4269 private SslError mSSLCertificateOnErrorError;
4270
4271 // as SSLCertificate has different style for landscape / portrait, we
4272 // have to re-open it when configuration changed
4273 private AlertDialog mSSLCertificateDialog;
4274 private TabControl.Tab mSSLCertificateView;
4275
4276 // as HttpAuthentication has different style for landscape / portrait, we
4277 // have to re-open it when configuration changed
4278 private AlertDialog mHttpAuthenticationDialog;
4279 private HttpAuthHandler mHttpAuthHandler;
4280
4281 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4282 new FrameLayout.LayoutParams(
4283 ViewGroup.LayoutParams.FILL_PARENT,
4284 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004285 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4286 new FrameLayout.LayoutParams(
4287 ViewGroup.LayoutParams.FILL_PARENT,
4288 ViewGroup.LayoutParams.FILL_PARENT,
4289 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004290 // Google search
4291 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004292 // Wikipedia search
4293 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4294 // Dictionary search
4295 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4296 // Google Mobile Local search
4297 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4298
4299 final static String QUERY_PLACE_HOLDER = "%s";
4300
4301 // "source" parameter for Google search through search key
4302 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4303 // "source" parameter for Google search through goto menu
4304 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4305 // "source" parameter for Google search through simplily type
4306 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4307 // "source" parameter for Google search suggested by the browser
4308 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4309 // "source" parameter for Google search from unknown source
4310 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4311
4312 private final static String LOGTAG = "browser";
4313
The Android Open Source Project0c908882009-03-03 19:32:16 -08004314 private String mLastEnteredUrl;
4315
4316 private PowerManager.WakeLock mWakeLock;
4317 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4318
4319 private Toast mStopToast;
4320
Leon Scroggins68579392009-09-15 15:31:54 -04004321 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004322
Ben Murdochbff2d602009-07-01 20:19:05 +01004323 private LinearLayout mErrorConsoleContainer = null;
4324 private boolean mShouldShowErrorConsole = false;
4325
The Android Open Source Project0c908882009-03-03 19:32:16 -08004326 // As the ids are dynamically created, we can't guarantee that they will
4327 // be in sequence, so this static array maps ids to a window number.
4328 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4329 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4330 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4331 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4332
4333 // monitor platform changes
4334 private IntentFilter mNetworkStateChangedFilter;
4335 private BroadcastReceiver mNetworkStateIntentReceiver;
4336
Grace Klobab4da0ad2009-05-14 14:45:40 -07004337 private BroadcastReceiver mPackageInstallationReceiver;
4338
The Android Open Source Project0c908882009-03-03 19:32:16 -08004339 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004340 final static int COMBO_PAGE = 1;
4341 final static int DOWNLOAD_PAGE = 2;
4342 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004343
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004344 /**
4345 * A UrlData class to abstract how the content will be set to WebView.
4346 * This base class uses loadUrl to show the content.
4347 */
4348 private static class UrlData {
4349 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004350 byte[] mPostData;
4351
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004352 UrlData(String url) {
4353 this.mUrl = url;
4354 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004355
4356 void setPostData(byte[] postData) {
4357 mPostData = postData;
4358 }
4359
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004360 boolean isEmpty() {
4361 return mUrl == null || mUrl.length() == 0;
4362 }
4363
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004364 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004365 if (mPostData != null) {
4366 webView.postUrl(mUrl, mPostData);
4367 } else {
4368 webView.loadUrl(mUrl);
4369 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004370 }
4371 };
4372
4373 /**
4374 * A subclass of UrlData class that can display inlined content using
4375 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4376 */
4377 private static class InlinedUrlData extends UrlData {
4378 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4379 super(failUrl);
4380 mInlined = inlined;
4381 mMimeType = mimeType;
4382 mEncoding = encoding;
4383 }
4384 String mMimeType;
4385 String mInlined;
4386 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004387 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004388 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004389 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004390 }
4391
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004392 @Override
4393 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004394 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4395 }
4396 }
4397
Leon Scroggins1f005d32009-08-10 17:36:42 -04004398 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004399}