blob: 31675db90ec7db7963efae45d41ebbff14c72c86 [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;
Leon Scrogginsf4bb18a2009-09-11 18:37:53 -040093import android.view.MotionEvent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080094import android.view.View;
95import android.view.ViewGroup;
96import android.view.Window;
97import android.view.WindowManager;
98import android.view.ContextMenu.ContextMenuInfo;
99import android.view.MenuItem.OnMenuItemClickListener;
100import android.view.animation.AlphaAnimation;
101import android.view.animation.Animation;
102import android.view.animation.AnimationSet;
103import android.view.animation.DecelerateInterpolator;
104import android.view.animation.ScaleAnimation;
105import android.view.animation.TranslateAnimation;
106import android.webkit.CookieManager;
107import android.webkit.CookieSyncManager;
108import android.webkit.DownloadListener;
Steve Block2bc69912009-07-30 14:45:13 +0100109import android.webkit.GeolocationPermissions;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800110import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -0700111import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800112import android.webkit.SslErrorHandler;
113import android.webkit.URLUtil;
114import android.webkit.WebChromeClient;
Andrei Popescuc9b55562009-07-07 10:51:15 +0100115import android.webkit.WebChromeClient.CustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800116import android.webkit.WebHistoryItem;
117import android.webkit.WebIconDatabase;
Ben Murdoch092dd5d2009-04-22 12:34:12 +0100118import android.webkit.WebStorage;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800119import android.webkit.WebView;
120import android.webkit.WebViewClient;
121import android.widget.EditText;
122import android.widget.FrameLayout;
123import android.widget.LinearLayout;
124import android.widget.TextView;
125import android.widget.Toast;
126
127import java.io.BufferedOutputStream;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400128import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800129import java.io.File;
130import java.io.FileInputStream;
131import java.io.FileOutputStream;
132import java.io.IOException;
133import java.io.InputStream;
134import java.net.MalformedURLException;
135import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700136import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800137import java.net.URL;
138import java.net.URLEncoder;
139import java.text.ParseException;
140import java.util.Date;
141import java.util.Enumeration;
142import java.util.HashMap;
Patrick Scott37911c72009-03-24 18:02:58 -0700143import java.util.LinkedList;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800144import java.util.Vector;
145import java.util.regex.Matcher;
146import java.util.regex.Pattern;
147import java.util.zip.ZipEntry;
148import java.util.zip.ZipFile;
149
150public class BrowserActivity extends Activity
151 implements KeyTracker.OnKeyTracker,
152 View.OnCreateContextMenuListener,
153 DownloadListener {
154
Dave Bort31a6d1c2009-04-13 15:56:49 -0700155 /* Define some aliases to make these debugging flags easier to refer to.
156 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
157 */
158 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
159 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
160 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
161
The Android Open Source Project0c908882009-03-03 19:32:16 -0800162 private IGoogleLoginService mGls = null;
163 private ServiceConnection mGlsConnection = null;
164
165 private SensorManager mSensorManager = null;
166
Satish Sampath565505b2009-05-29 15:37:27 +0100167 // These are single-character shortcuts for searching popular sources.
168 private static final int SHORTCUT_INVALID = 0;
169 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
170 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
171 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
172 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
173
The Android Open Source Project0c908882009-03-03 19:32:16 -0800174 /* Whitelisted webpages
175 private static HashSet<String> sWhiteList;
176
177 static {
178 sWhiteList = new HashSet<String>();
179 sWhiteList.add("cnn.com/");
180 sWhiteList.add("espn.go.com/");
181 sWhiteList.add("nytimes.com/");
182 sWhiteList.add("engadget.com/");
183 sWhiteList.add("yahoo.com/");
184 sWhiteList.add("msn.com/");
185 sWhiteList.add("amazon.com/");
186 sWhiteList.add("consumerist.com/");
187 sWhiteList.add("google.com/m/news");
188 }
189 */
190
191 private void setupHomePage() {
192 final Runnable getAccount = new Runnable() {
193 public void run() {
194 // Lower priority
195 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
196 // get the default home page
197 String homepage = mSettings.getHomePage();
198
199 try {
200 if (mGls == null) return;
201
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700202 if (!homepage.startsWith("http://www.google.")) return;
203 if (homepage.indexOf('?') == -1) return;
204
The Android Open Source Project0c908882009-03-03 19:32:16 -0800205 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
206 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
207
208 // three cases:
209 //
210 // hostedUser == googleUser
211 // The device has only a google account
212 //
213 // hostedUser != googleUser
214 // The device has a hosted account and a google account
215 //
216 // hostedUser != null, googleUser == null
217 // The device has only a hosted account (so far)
218
219 // developers might have no accounts at all
220 if (hostedUser == null) return;
221
222 if (googleUser == null || !hostedUser.equals(googleUser)) {
223 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700224 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800225 }
226 } catch (RemoteException ignore) {
227 // Login service died; carry on
228 } catch (RuntimeException ignore) {
229 // Login service died; carry on
230 } finally {
231 finish(homepage);
232 }
233 }
234
235 private void finish(final String homepage) {
236 mHandler.post(new Runnable() {
237 public void run() {
238 mSettings.setHomePage(BrowserActivity.this, homepage);
239 resumeAfterCredentials();
240
241 // as this is running in a separate thread,
242 // BrowserActivity's onDestroy() may have been called,
243 // which also calls unbindService().
244 if (mGlsConnection != null) {
245 // we no longer need to keep GLS open
246 unbindService(mGlsConnection);
247 mGlsConnection = null;
248 }
249 } });
250 } };
251
252 final boolean[] done = { false };
253
254 // Open a connection to the Google Login Service. The first
255 // time the connection is established, set up the homepage depending on
256 // the account in a background thread.
257 mGlsConnection = new ServiceConnection() {
258 public void onServiceConnected(ComponentName className, IBinder service) {
259 mGls = IGoogleLoginService.Stub.asInterface(service);
260 if (done[0] == false) {
261 done[0] = true;
262 Thread account = new Thread(getAccount);
263 account.setName("GLSAccount");
264 account.start();
265 }
266 }
267 public void onServiceDisconnected(ComponentName className) {
268 mGls = null;
269 }
270 };
271
272 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
273 mGlsConnection, Context.BIND_AUTO_CREATE);
274 }
275
Cary Clarka9771242009-08-11 16:42:26 -0400276 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800277 @Override
278 public Void doInBackground(File... files) {
279 if (files != null) {
280 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400281 if (!f.delete()) {
282 Log.e(LOGTAG, f.getPath() + " was not deleted");
283 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800284 }
285 }
286 return null;
287 }
288 }
289
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400290 /**
291 * This layout holds everything you see below the status bar, including the
292 * error console, the custom view container, and the webviews.
293 */
294 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400295
The Android Open Source Project0c908882009-03-03 19:32:16 -0800296 @Override public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700297 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800298 Log.v(LOGTAG, this + " onStart");
299 }
300 super.onCreate(icicle);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400301 this.requestWindowFeature(Window.FEATURE_NO_TITLE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800302 // test the browser in OpenGL
303 // requestWindowFeature(Window.FEATURE_OPENGL);
304
305 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
306
307 mResolver = getContentResolver();
308
The Android Open Source Project0c908882009-03-03 19:32:16 -0800309 //
310 // start MASF proxy service
311 //
312 //Intent proxyServiceIntent = new Intent();
313 //proxyServiceIntent.setComponent
314 // (new ComponentName(
315 // "com.android.masfproxyservice",
316 // "com.android.masfproxyservice.MasfProxyService"));
317 //startService(proxyServiceIntent, null);
318
319 mSecLockIcon = Resources.getSystem().getDrawable(
320 android.R.drawable.ic_secure);
321 mMixLockIcon = Resources.getSystem().getDrawable(
322 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800323
Leon Scroggins81db3662009-06-04 17:45:11 -0400324 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
325 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400326 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
327 .inflate(R.layout.custom_screen, null);
328 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
329 R.id.main_content);
330 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
331 .findViewById(R.id.error_console);
332 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
333 .findViewById(R.id.fullscreen_custom_content);
334 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
335 mTitleBar = new TitleBarSet(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800336
337 // Create the tab control and our initial tab
338 mTabControl = new TabControl(this);
339
340 // Open the icon database and retain all the bookmark urls for favicons
341 retainIconsOnStartup();
342
343 // Keep a settings instance handy.
344 mSettings = BrowserSettings.getInstance();
345 mSettings.setTabControl(mTabControl);
346 mSettings.loadFromDb(this);
347
348 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
349 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
350
Grace Klobaa34f6862009-07-31 16:28:17 -0700351 /* enables registration for changes in network status from
352 http stack */
353 mNetworkStateChangedFilter = new IntentFilter();
354 mNetworkStateChangedFilter.addAction(
355 ConnectivityManager.CONNECTIVITY_ACTION);
356 mNetworkStateIntentReceiver = new BroadcastReceiver() {
357 @Override
358 public void onReceive(Context context, Intent intent) {
359 if (intent.getAction().equals(
360 ConnectivityManager.CONNECTIVITY_ACTION)) {
361 boolean down = intent.getBooleanExtra(
362 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
363 onNetworkToggle(!down);
364 }
365 }
366 };
367
Grace Kloba615c6c92009-08-03 10:22:44 -0700368 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
369 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
370 filter.addDataScheme("package");
371 mPackageInstallationReceiver = new BroadcastReceiver() {
372 @Override
373 public void onReceive(Context context, Intent intent) {
374 final String action = intent.getAction();
375 final String packageName = intent.getData()
376 .getSchemeSpecificPart();
377 final boolean replacing = intent.getBooleanExtra(
378 Intent.EXTRA_REPLACING, false);
379 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
380 // if it is replacing, refreshPlugins() when adding
381 return;
382 }
383 PackageManager pm = BrowserActivity.this.getPackageManager();
384 PackageInfo pkgInfo = null;
385 try {
386 pkgInfo = pm.getPackageInfo(packageName,
387 PackageManager.GET_PERMISSIONS);
388 } catch (PackageManager.NameNotFoundException e) {
389 return;
390 }
391 if (pkgInfo != null) {
392 String permissions[] = pkgInfo.requestedPermissions;
393 if (permissions == null) {
394 return;
395 }
396 boolean permissionOk = false;
397 for (String permit : permissions) {
398 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
399 permissionOk = true;
400 break;
401 }
402 }
403 if (permissionOk) {
404 PluginManager.getInstance(BrowserActivity.this)
405 .refreshPlugins(
406 Intent.ACTION_PACKAGE_ADDED
407 .equals(action));
408 }
409 }
410 }
411 };
412 registerReceiver(mPackageInstallationReceiver, filter);
413
Satish Sampath565505b2009-05-29 15:37:27 +0100414 // If this was a web search request, pass it on to the default web search provider.
415 if (handleWebSearchIntent(getIntent())) {
416 moveTaskToBack(true);
417 return;
418 }
419
The Android Open Source Project0c908882009-03-03 19:32:16 -0800420 if (!mTabControl.restoreState(icicle)) {
421 // clear up the thumbnail directory if we can't restore the state as
422 // none of the files in the directory are referenced any more.
423 new ClearThumbnails().execute(
424 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700425 // there is no quit on Android. But if we can't restore the state,
426 // we can treat it as a new Browser, remove the old session cookies.
427 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800428 final Intent intent = getIntent();
429 final Bundle extra = intent.getExtras();
430 // Create an initial tab.
431 // If the intent is ACTION_VIEW and data is not null, the Browser is
432 // invoked to view the content by another application. In this case,
433 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700434 UrlData urlData = getUrlDataFromIntent(intent);
435
The Android Open Source Project0c908882009-03-03 19:32:16 -0800436 final TabControl.Tab t = mTabControl.createNewTab(
437 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700438 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700439 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800440 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800441 attachTabToContentView(t);
442 WebView webView = t.getWebView();
443 if (extra != null) {
444 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
445 if (scale > 0 && scale <= 1000) {
446 webView.setInitialScale(scale);
447 }
448 }
449 // If we are not restoring from an icicle, then there is a high
450 // likely hood this is the first run. So, check to see if the
451 // homepage needs to be configured and copy any plugins from our
452 // asset directory to the data partition.
453 if ((extra == null || !extra.getBoolean("testing"))
454 && !mSettings.isLoginInitialized()) {
455 setupHomePage();
456 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800457
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700458 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400459 if (mSettings.isLoginInitialized()) {
460 webView.loadUrl(mSettings.getHomePage());
461 } else {
462 waitForCredentials();
463 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800464 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700465 if (extra != null) {
466 urlData.setPostData(extra
467 .getByteArray(Browser.EXTRA_POST_DATA));
468 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700469 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800470 }
471 } else {
472 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400473 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800474 attachTabToContentView(mTabControl.getCurrentTab());
475 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700476
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400477 mTitleBar.init(this);
478 // Create title bars for all of the tabs that have been created
479 for (int i = 0; i < mTabControl.getTabCount(); i ++) {
480 WebView view = mTabControl.getTab(i).getWebView();
481 mTitleBar.addTab(view, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400482 }
483
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400484 mTitleBar.setCurrentTab(mTabControl.getCurrentIndex());
485
Feng Qianb3c02da2009-06-29 15:58:08 -0700486 // Read JavaScript flags if it exists.
487 String jsFlags = mSettings.getJsFlags();
488 if (jsFlags.trim().length() != 0) {
489 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
490 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800491 }
492
493 @Override
494 protected void onNewIntent(Intent intent) {
495 TabControl.Tab current = mTabControl.getCurrentTab();
496 // When a tab is closed on exit, the current tab index is set to -1.
497 // Reset before proceed as Browser requires the current tab to be set.
498 if (current == null) {
499 // Try to reset the tab in case the index was incorrect.
500 current = mTabControl.getTab(0);
501 if (current == null) {
502 // No tabs at all so just ignore this intent.
503 return;
504 }
505 mTabControl.setCurrentTab(current);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400506 mTitleBar.setCurrentTab(mTabControl.getTabIndex(current));
The Android Open Source Project0c908882009-03-03 19:32:16 -0800507 attachTabToContentView(current);
508 resetTitleAndIcon(current.getWebView());
509 }
510 final String action = intent.getAction();
511 final int flags = intent.getFlags();
512 if (Intent.ACTION_MAIN.equals(action) ||
513 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
514 // just resume the browser
515 return;
516 }
517 if (Intent.ACTION_VIEW.equals(action)
518 || Intent.ACTION_SEARCH.equals(action)
519 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
520 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100521 // If this was a search request (e.g. search query directly typed into the address bar),
522 // pass it on to the default web search provider.
523 if (handleWebSearchIntent(intent)) {
524 return;
525 }
526
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700527 UrlData urlData = getUrlDataFromIntent(intent);
528 if (urlData.isEmpty()) {
529 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800530 }
Grace Kloba81678d92009-06-30 07:09:56 -0700531 urlData.setPostData(intent
532 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700533
Grace Klobacc634032009-07-28 15:58:19 -0700534 final String appId = intent
535 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
536 if (Intent.ACTION_VIEW.equals(action)
537 && !getPackageName().equals(appId)
538 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Patrick Scottcd115892009-07-16 09:42:58 -0400539 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700540 if (appTab != null) {
541 Log.i(LOGTAG, "Reusing tab for " + appId);
542 // Dismiss the subwindow if applicable.
543 dismissSubWindow(appTab);
544 // Since we might kill the WebView, remove it from the
545 // content view first.
546 removeTabFromContentView(appTab);
547 // Recreate the main WebView after destroying the old one.
548 // If the WebView has the same original url and is on that
549 // page, it can be reused.
550 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700551 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100552
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700553 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400554 switchToTab(mTabControl.getTabIndex(appTab));
555 if (needsLoad) {
556 urlData.loadIn(appTab.getWebView());
557 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700558 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400559 // If the tab was the current tab, we have to attach
560 // it to the view system again.
561 attachTabToContentView(appTab);
562 if (needsLoad) {
563 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700564 }
565 }
566 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400567 } else {
568 // No matching application tab, try to find a regular tab
569 // with a matching url.
570 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400571 if (appTab != null) {
572 if (current != appTab) {
573 switchToTab(mTabControl.getTabIndex(appTab));
574 }
575 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400576 } else {
577 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
578 // will be opened in a new tab unless we have reached
579 // MAX_TABS. Then the url will be opened in the current
580 // tab. If a new tab is created, it will have "true" for
581 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400582 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400583 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700584 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800585 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700586 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800587 mSettings.toggleDebugSettings();
588 return;
589 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400590 // Get rid of the subwindow if it exists
591 dismissSubWindow(current);
592 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800593 }
594 }
595 }
596
Satish Sampath565505b2009-05-29 15:37:27 +0100597 private int parseUrlShortcut(String url) {
598 if (url == null) return SHORTCUT_INVALID;
599
600 // FIXME: quick search, need to be customized by setting
601 if (url.length() > 2 && url.charAt(1) == ' ') {
602 switch (url.charAt(0)) {
603 case 'g': return SHORTCUT_GOOGLE_SEARCH;
604 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
605 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
606 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
607 }
608 }
609 return SHORTCUT_INVALID;
610 }
611
612 /**
613 * Launches the default web search activity with the query parameters if the given intent's data
614 * are identified as plain search terms and not URLs/shortcuts.
615 * @return true if the intent was handled and web search activity was launched, false if not.
616 */
617 private boolean handleWebSearchIntent(Intent intent) {
618 if (intent == null) return false;
619
620 String url = null;
621 final String action = intent.getAction();
622 if (Intent.ACTION_VIEW.equals(action)) {
623 url = intent.getData().toString();
624 } else if (Intent.ACTION_SEARCH.equals(action)
625 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
626 || Intent.ACTION_WEB_SEARCH.equals(action)) {
627 url = intent.getStringExtra(SearchManager.QUERY);
628 }
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100629 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA));
Satish Sampath565505b2009-05-29 15:37:27 +0100630 }
631
632 /**
633 * Launches the default web search activity with the query parameters if the given url string
634 * was identified as plain search terms and not URL/shortcut.
635 * @return true if the request was handled and web search activity was launched, false if not.
636 */
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100637 private boolean handleWebSearchRequest(String inUrl, Bundle appData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100638 if (inUrl == null) return false;
639
640 // In general, we shouldn't modify URL from Intent.
641 // But currently, we get the user-typed URL from search box as well.
642 String url = fixUrl(inUrl).trim();
643
644 // URLs and site specific search shortcuts are handled by the regular flow of control, so
645 // return early.
646 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100647 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100648 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
649 return false;
650 }
651
652 Browser.updateVisitedHistory(mResolver, url, false);
653 Browser.addSearchUrl(mResolver, url);
654
655 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
656 intent.addCategory(Intent.CATEGORY_DEFAULT);
657 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100658 if (appData != null) {
659 intent.putExtra(SearchManager.APP_DATA, appData);
660 }
Grace Klobacc634032009-07-28 15:58:19 -0700661 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100662 startActivity(intent);
663
664 return true;
665 }
666
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700667 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800668 String url = null;
669 if (intent != null) {
670 final String action = intent.getAction();
671 if (Intent.ACTION_VIEW.equals(action)) {
672 url = smartUrlFilter(intent.getData());
673 if (url != null && url.startsWith("content:")) {
674 /* Append mimetype so webview knows how to display */
675 String mimeType = intent.resolveType(getContentResolver());
676 if (mimeType != null) {
677 url += "?" + mimeType;
678 }
679 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700680 if ("inline:".equals(url)) {
681 return new InlinedUrlData(
682 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
683 intent.getType(),
684 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
685 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
686 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800687 } else if (Intent.ACTION_SEARCH.equals(action)
688 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
689 || Intent.ACTION_WEB_SEARCH.equals(action)) {
690 url = intent.getStringExtra(SearchManager.QUERY);
691 if (url != null) {
692 mLastEnteredUrl = url;
693 // Don't add Urls, just search terms.
694 // Urls will get added when the page is loaded.
695 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
696 Browser.updateVisitedHistory(mResolver, url, false);
697 }
698 // In general, we shouldn't modify URL from Intent.
699 // But currently, we get the user-typed URL from search box as well.
700 url = fixUrl(url);
701 url = smartUrlFilter(url);
702 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
703 if (url.contains(searchSource)) {
704 String source = null;
705 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
706 if (appData != null) {
707 source = appData.getString(SearchManager.SOURCE);
708 }
709 if (TextUtils.isEmpty(source)) {
710 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
711 }
712 url = url.replace(searchSource, "&source=android-"+source+"&");
713 }
714 }
715 }
716 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700717 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800718 }
719
720 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400721 // FIXME: Converting the url to lower case
722 // duplicates functionality in smartUrlFilter().
723 // However, changing all current callers of fixUrl to
724 // call smartUrlFilter in addition may have unwanted
725 // consequences, and is deferred for now.
726 int colon = inUrl.indexOf(':');
727 boolean allLower = true;
728 for (int index = 0; index < colon; index++) {
729 char ch = inUrl.charAt(index);
730 if (!Character.isLetter(ch)) {
731 break;
732 }
733 allLower &= Character.isLowerCase(ch);
734 if (index == colon - 1 && !allLower) {
735 inUrl = inUrl.substring(0, colon).toLowerCase()
736 + inUrl.substring(colon);
737 }
738 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800739 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
740 return inUrl;
741 if (inUrl.startsWith("http:") ||
742 inUrl.startsWith("https:")) {
743 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
744 inUrl = inUrl.replaceFirst("/", "//");
745 } else inUrl = inUrl.replaceFirst(":", "://");
746 }
747 return inUrl;
748 }
749
750 /**
751 * Looking for the pattern like this
752 *
753 * *
754 * * *
755 * *** * *******
756 * * *
757 * * *
758 * *
759 */
760 private final SensorListener mSensorListener = new SensorListener() {
761 private long mLastGestureTime;
762 private float[] mPrev = new float[3];
763 private float[] mPrevDiff = new float[3];
764 private float[] mDiff = new float[3];
765 private float[] mRevertDiff = new float[3];
766
767 public void onSensorChanged(int sensor, float[] values) {
768 boolean show = false;
769 float[] diff = new float[3];
770
771 for (int i = 0; i < 3; i++) {
772 diff[i] = values[i] - mPrev[i];
773 if (Math.abs(diff[i]) > 1) {
774 show = true;
775 }
776 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
777 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
778 // start track when there is a big move, or revert
779 mRevertDiff[i] = mDiff[i];
780 mDiff[i] = 0;
781 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
782 // reset when it is flat
783 mDiff[i] = mRevertDiff[i] = 0;
784 }
785 mDiff[i] += diff[i];
786 mPrevDiff[i] = diff[i];
787 mPrev[i] = values[i];
788 }
789
790 if (false) {
791 // only shows if we think the delta is big enough, in an attempt
792 // to detect "serious" moves left/right or up/down
793 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
794 + values[0] + ", " + values[1] + ", " + values[2] + ")"
795 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
796 + ")");
797 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
798 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
799 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
800 + mRevertDiff[2] + ")");
801 }
802
803 long now = android.os.SystemClock.uptimeMillis();
804 if (now - mLastGestureTime > 1000) {
805 mLastGestureTime = 0;
806
807 float y = mDiff[1];
808 float z = mDiff[2];
809 float ay = Math.abs(y);
810 float az = Math.abs(z);
811 float ry = mRevertDiff[1];
812 float rz = mRevertDiff[2];
813 float ary = Math.abs(ry);
814 float arz = Math.abs(rz);
815 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
816 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
817
818 if ((gestY || gestZ) && !(gestY && gestZ)) {
819 WebView view = mTabControl.getCurrentWebView();
820
821 if (view != null) {
822 if (gestZ) {
823 if (z < 0) {
824 view.zoomOut();
825 } else {
826 view.zoomIn();
827 }
828 } else {
829 view.flingScroll(0, Math.round(y * 100));
830 }
831 }
832 mLastGestureTime = now;
833 }
834 }
835 }
836
837 public void onAccuracyChanged(int sensor, int accuracy) {
838 // TODO Auto-generated method stub
839
840 }
841 };
842
843 @Override protected void onResume() {
844 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700845 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800846 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
847 }
848
849 if (!mActivityInPause) {
850 Log.e(LOGTAG, "BrowserActivity is already resumed.");
851 return;
852 }
853
Mike Reed7bfa63b2009-05-28 11:08:32 -0400854 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800855 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400856 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800857
858 if (mWakeLock.isHeld()) {
859 mHandler.removeMessages(RELEASE_WAKELOCK);
860 mWakeLock.release();
861 }
862
863 if (mCredsDlg != null) {
864 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
865 // In case credential request never comes back
866 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
867 }
868 }
869
870 registerReceiver(mNetworkStateIntentReceiver,
871 mNetworkStateChangedFilter);
872 WebView.enablePlatformNotifications();
873
874 if (mSettings.doFlick()) {
875 if (mSensorManager == null) {
876 mSensorManager = (SensorManager) getSystemService(
877 Context.SENSOR_SERVICE);
878 }
879 mSensorManager.registerListener(mSensorListener,
880 SensorManager.SENSOR_ACCELEROMETER,
881 SensorManager.SENSOR_DELAY_FASTEST);
882 } else {
883 mSensorManager = null;
884 }
885 }
886
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400887 /**
888 * Since the actual title bar is embedded in the WebView, and removing it
889 * would change its appearance, create a temporary title bar to go at
890 * the top of the screen while the menu is open.
891 */
892 private TitleBar mFakeTitleBar;
893
894 /**
895 * Keeps track of whether the options menu is open. This is important in
896 * determining whether to show or hide the title bar overlay.
897 */
898 private boolean mOptionsMenuOpen;
899
900 /**
901 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
902 * of whether the configuration has changed. The first onMenuOpened call
903 * after a configuration change is simply a reopening of the same menu
904 * (i.e. mIconView did not change).
905 */
906 private boolean mConfigChanged;
907
908 /**
909 * Whether or not the options menu is in its smaller, icon menu form. When
910 * true, we want the title bar overlay to be up. When false, we do not.
911 * Only meaningful if mOptionsMenuOpen is true.
912 */
913 private boolean mIconView;
914
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400915 @Override
916 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400917 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
918 if (mOptionsMenuOpen) {
919 if (mConfigChanged) {
920 // We do not need to make any changes to the state of the
921 // title bar, since the only thing that happened was a
922 // change in orientation
923 mConfigChanged = false;
924 } else {
925 if (mIconView) {
926 // Switching the menu to expanded view, so hide the
927 // title bar.
928 hideFakeTitleBar();
929 mIconView = false;
930 } else {
931 // Switching the menu back to icon view, so show the
932 // title bar once again.
933 showFakeTitleBar();
934 mIconView = true;
935 }
936 }
937 } else {
938 // The options menu is closed, so open it, and show the title
939 showFakeTitleBar();
940 mOptionsMenuOpen = true;
941 mConfigChanged = false;
942 mIconView = true;
943 }
944 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400945 return true;
946 }
947
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400948 private void showFakeTitleBar() {
949 if (mFakeTitleBar == null) {
Leon Scrogginsf4bb18a2009-09-11 18:37:53 -0400950 final WebView webView = getTopWindow();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400951 mFakeTitleBar = new TitleBar(this, webView);
952 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
953 mFakeTitleBar.setProgress(webView.getProgress());
954 mFakeTitleBar.setFavicon(webView.getFavicon());
955 updateLockIconToLatest();
Leon Scrogginsf4bb18a2009-09-11 18:37:53 -0400956 final View title = mFakeTitleBar.findViewById(R.id.title);
957 mFakeTitleBar.setOnTouchListener(new View.OnTouchListener() {
958 public boolean onTouch(View v, MotionEvent event) {
959 if (event.getAction() == MotionEvent.ACTION_UP) {
960 if (event.getX() > title.getRight()) {
961 if (webView != null
962 && webView.getProgress() < 100) {
963 if (webView != null) {
964 webView.stopLoading();
965 }
966 } else {
967 bookmarksOrHistoryPicker(false);
968 }
969 } else {
970 onSearchRequested();
971 }
972 closeOptionsMenu();
973 }
974 return true;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400975 }
976 });
977
978 WindowManager manager
979 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
980
981 // Add the title bar to the window manager so it can receive touches
982 // while the menu is up
983 WindowManager.LayoutParams params
984 = new WindowManager.LayoutParams(
985 ViewGroup.LayoutParams.FILL_PARENT,
986 ViewGroup.LayoutParams.WRAP_CONTENT,
987 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
988 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
989 PixelFormat.OPAQUE);
990 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400991 WebView mainView = mTabControl.getCurrentWebView();
992 params.windowAnimations = mainView == null
993 || mainView.getScrollY() != 0
994 ? com.android.internal.R.style.Animation_DropDownDown : 0;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400995 // XXX : Without providing an offset, the fake title bar will be
996 // placed underneath the status bar. Use the global visible rect
997 // of mBrowserFrameLayout to determine the bottom of the status bar
998 Rect rectangle = new Rect();
999 mBrowserFrameLayout.getGlobalVisibleRect(rectangle);
1000 params.y = rectangle.top;
1001 manager.addView(mFakeTitleBar, params);
1002 }
1003 }
1004
1005 @Override
1006 public void onOptionsMenuClosed(Menu menu) {
1007 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04001008 if (!mInLoad) {
1009 hideFakeTitleBar();
1010 } else if (!mIconView) {
1011 // The page is currently loading, and we are in expanded mode, so
1012 // we were not showing the menu. Show it once again. It will be
1013 // removed when the page finishes.
1014 showFakeTitleBar();
1015 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001016 }
1017 private void hideFakeTitleBar() {
1018 if (mFakeTitleBar == null) return;
1019 WindowManager manager
1020 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
1021 manager.removeView(mFakeTitleBar);
1022 mFakeTitleBar = null;
1023 }
1024
The Android Open Source Project0c908882009-03-03 19:32:16 -08001025 /**
1026 * onSaveInstanceState(Bundle map)
1027 * onSaveInstanceState is called right before onStop(). The map contains
1028 * the saved state.
1029 */
1030 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001031 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001032 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1033 }
1034 // the default implementation requires each view to have an id. As the
1035 // browser handles the state itself and it doesn't use id for the views,
1036 // don't call the default implementation. Otherwise it will trigger the
1037 // warning like this, "couldn't save which view has focus because the
1038 // focused view XXX has no id".
1039
1040 // Save all the tabs
1041 mTabControl.saveState(outState);
1042 }
1043
1044 @Override protected void onPause() {
1045 super.onPause();
1046
1047 if (mActivityInPause) {
1048 Log.e(LOGTAG, "BrowserActivity is already paused.");
1049 return;
1050 }
1051
Mike Reed7bfa63b2009-05-28 11:08:32 -04001052 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001053 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001054 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001055 mWakeLock.acquire();
1056 mHandler.sendMessageDelayed(mHandler
1057 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1058 }
1059
1060 // Clear the credentials toast if it is up
1061 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1062 mCredsDlg.dismiss();
1063 }
1064 mCredsDlg = null;
1065
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001066 // FIXME: This removes the active tabs page and resets the menu to
1067 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1068 // but then we would need to save it in onSaveInstanceState and restore
1069 // it in onCreate/onRestoreInstanceState
1070 if (mActiveTabsPage != null) {
1071 removeActiveTabPage(true);
1072 }
1073
The Android Open Source Project0c908882009-03-03 19:32:16 -08001074 cancelStopToast();
1075
1076 // unregister network state listener
1077 unregisterReceiver(mNetworkStateIntentReceiver);
1078 WebView.disablePlatformNotifications();
1079
1080 if (mSensorManager != null) {
1081 mSensorManager.unregisterListener(mSensorListener);
1082 }
1083 }
1084
1085 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001086 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001087 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1088 }
1089 super.onDestroy();
1090 // Remove the current tab and sub window
1091 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001092 if (t != null) {
1093 dismissSubWindow(t);
1094 removeTabFromContentView(t);
1095 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001096 // Destroy all the tabs
1097 mTabControl.destroy();
1098 WebIconDatabase.getInstance().close();
1099 if (mGlsConnection != null) {
1100 unbindService(mGlsConnection);
1101 mGlsConnection = null;
1102 }
1103
1104 //
1105 // stop MASF proxy service
1106 //
1107 //Intent proxyServiceIntent = new Intent();
1108 //proxyServiceIntent.setComponent
1109 // (new ComponentName(
1110 // "com.android.masfproxyservice",
1111 // "com.android.masfproxyservice.MasfProxyService"));
1112 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001113
1114 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001115 }
1116
1117 @Override
1118 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001119 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001120 super.onConfigurationChanged(newConfig);
1121
1122 if (mPageInfoDialog != null) {
1123 mPageInfoDialog.dismiss();
1124 showPageInfo(
1125 mPageInfoView,
1126 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1127 }
1128 if (mSSLCertificateDialog != null) {
1129 mSSLCertificateDialog.dismiss();
1130 showSSLCertificate(
1131 mSSLCertificateView);
1132 }
1133 if (mSSLCertificateOnErrorDialog != null) {
1134 mSSLCertificateOnErrorDialog.dismiss();
1135 showSSLCertificateOnError(
1136 mSSLCertificateOnErrorView,
1137 mSSLCertificateOnErrorHandler,
1138 mSSLCertificateOnErrorError);
1139 }
1140 if (mHttpAuthenticationDialog != null) {
1141 String title = ((TextView) mHttpAuthenticationDialog
1142 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1143 .toString();
1144 String name = ((TextView) mHttpAuthenticationDialog
1145 .findViewById(R.id.username_edit)).getText().toString();
1146 String password = ((TextView) mHttpAuthenticationDialog
1147 .findViewById(R.id.password_edit)).getText().toString();
1148 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1149 .getId();
1150 mHttpAuthenticationDialog.dismiss();
1151 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1152 name, password, focusId);
1153 }
1154 if (mFindDialog != null && mFindDialog.isShowing()) {
1155 mFindDialog.onConfigurationChanged(newConfig);
1156 }
1157 }
1158
1159 @Override public void onLowMemory() {
1160 super.onLowMemory();
1161 mTabControl.freeMemory();
1162 }
1163
Mike Reed7bfa63b2009-05-28 11:08:32 -04001164 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001165 if ((!mActivityInPause && !mPageStarted) ||
1166 (mActivityInPause && mPageStarted)) {
1167 CookieSyncManager.getInstance().startSync();
1168 WebView w = mTabControl.getCurrentWebView();
1169 if (w != null) {
1170 w.resumeTimers();
1171 }
1172 return true;
1173 } else {
1174 return false;
1175 }
1176 }
1177
Mike Reed7bfa63b2009-05-28 11:08:32 -04001178 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001179 if (mActivityInPause && !mPageStarted) {
1180 CookieSyncManager.getInstance().stopSync();
1181 WebView w = mTabControl.getCurrentWebView();
1182 if (w != null) {
1183 w.pauseTimers();
1184 }
1185 return true;
1186 } else {
1187 return false;
1188 }
1189 }
1190
Leon Scroggins1f005d32009-08-10 17:36:42 -04001191 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001192 /*
1193 * This function is called when we are launching for the first time. We
1194 * are waiting for the login credentials before loading Google home
1195 * pages. This way the user will be logged in straight away.
1196 */
1197 private void waitForCredentials() {
1198 // Show a toast
1199 mCredsDlg = new ProgressDialog(this);
1200 mCredsDlg.setIndeterminate(true);
1201 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1202 // If the user cancels the operation, then cancel the Google
1203 // Credentials request.
1204 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1205 mCredsDlg.show();
1206
1207 // We set a timeout for the retrieval of credentials in onResume()
1208 // as that is when we have freed up some CPU time to get
1209 // the login credentials.
1210 }
1211
1212 /*
1213 * If we have received the credentials or we have timed out and we are
1214 * showing the credentials dialog, then it is time to move on.
1215 */
1216 private void resumeAfterCredentials() {
1217 if (mCredsDlg == null) {
1218 return;
1219 }
1220
1221 // Clear the toast
1222 if (mCredsDlg.isShowing()) {
1223 mCredsDlg.dismiss();
1224 }
1225 mCredsDlg = null;
1226
1227 // Clear any pending timeout
1228 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1229
1230 // Load the page
1231 WebView w = mTabControl.getCurrentWebView();
1232 if (w != null) {
1233 w.loadUrl(mSettings.getHomePage());
1234 }
1235
1236 // Update the settings, need to do this last as it can take a moment
1237 // to persist the settings. In the mean time we could be loading
1238 // content.
1239 mSettings.setLoginInitialized(this);
1240 }
1241
1242 // Open the icon database and retain all the icons for visited sites.
1243 private void retainIconsOnStartup() {
1244 final WebIconDatabase db = WebIconDatabase.getInstance();
1245 db.open(getDir("icons", 0).getPath());
1246 try {
1247 Cursor c = Browser.getAllBookmarks(mResolver);
1248 if (!c.moveToFirst()) {
1249 c.deactivate();
1250 return;
1251 }
1252 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1253 do {
1254 String url = c.getString(urlIndex);
1255 db.retainIconForPageUrl(url);
1256 } while (c.moveToNext());
1257 c.deactivate();
1258 } catch (IllegalStateException e) {
1259 Log.e(LOGTAG, "retainIconsOnStartup", e);
1260 }
1261 }
1262
1263 // Helper method for getting the top window.
1264 WebView getTopWindow() {
1265 return mTabControl.getCurrentTopWebView();
1266 }
1267
1268 @Override
1269 public boolean onCreateOptionsMenu(Menu menu) {
1270 super.onCreateOptionsMenu(menu);
1271
1272 MenuInflater inflater = getMenuInflater();
1273 inflater.inflate(R.menu.browser, menu);
1274 mMenu = menu;
1275 updateInLoadMenuItems();
1276 return true;
1277 }
1278
1279 /**
1280 * As the menu can be open when loading state changes
1281 * we must manually update the state of the stop/reload menu
1282 * item
1283 */
1284 private void updateInLoadMenuItems() {
1285 if (mMenu == null) {
1286 return;
1287 }
1288 MenuItem src = mInLoad ?
1289 mMenu.findItem(R.id.stop_menu_id):
1290 mMenu.findItem(R.id.reload_menu_id);
1291 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1292 dest.setIcon(src.getIcon());
1293 dest.setTitle(src.getTitle());
1294 }
1295
1296 @Override
1297 public boolean onContextItemSelected(MenuItem item) {
1298 // chording is not an issue with context menus, but we use the same
1299 // options selector, so set mCanChord to true so we can access them.
1300 mCanChord = true;
1301 int id = item.getItemId();
1302 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001303 if (null == webView) {
1304 return false;
1305 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001306 final HashMap hrefMap = new HashMap();
1307 hrefMap.put("webview", webView);
1308 final Message msg = mHandler.obtainMessage(
1309 FOCUS_NODE_HREF, id, 0, hrefMap);
1310 switch (id) {
1311 // -- Browser context menu
1312 case R.id.open_context_menu_id:
1313 case R.id.open_newtab_context_menu_id:
1314 case R.id.bookmark_context_menu_id:
1315 case R.id.save_link_context_menu_id:
1316 case R.id.share_link_context_menu_id:
1317 case R.id.copy_link_context_menu_id:
1318 webView.requestFocusNodeHref(msg);
1319 break;
1320
1321 default:
1322 // For other context menus
1323 return onOptionsItemSelected(item);
1324 }
1325 mCanChord = false;
1326 return true;
1327 }
1328
1329 private Bundle createGoogleSearchSourceBundle(String source) {
1330 Bundle bundle = new Bundle();
1331 bundle.putString(SearchManager.SOURCE, source);
1332 return bundle;
1333 }
1334
1335 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001336 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001337 */
1338 @Override
1339 public boolean onSearchRequested() {
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001340 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001341 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001342 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001343 return true;
1344 }
1345
1346 @Override
1347 public void startSearch(String initialQuery, boolean selectInitialQuery,
1348 Bundle appSearchData, boolean globalSearch) {
1349 if (appSearchData == null) {
1350 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1351 }
1352 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1353 }
1354
Leon Scroggins1f005d32009-08-10 17:36:42 -04001355 /**
1356 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1357 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001358 * @param index Index of the tab to change to, as defined by
1359 * mTabControl.getTabIndex(Tab t).
1360 * @return boolean True if we successfully switched to a different tab. If
1361 * the indexth tab is null, or if that tab is the same as
1362 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001363 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001364 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001365 TabControl.Tab tab = mTabControl.getTab(index);
1366 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1367 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001368 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001369 }
1370 if (currentTab != null) {
1371 // currentTab may be null if it was just removed. In that case,
1372 // we do not need to remove it
1373 removeTabFromContentView(currentTab);
1374 }
1375 removeTabFromContentView(tab);
1376 mTabControl.setCurrentTab(tab);
1377 attachTabToContentView(tab);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001378 mTitleBar.setCurrentTab(index);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001379 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001380 }
1381
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001382 /* package */ TabControl.Tab openTabToHomePage() {
1383 return openTabAndShow(mSettings.getHomePage(), false, null);
1384 }
1385
Leon Scroggins1f005d32009-08-10 17:36:42 -04001386 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001387 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001388 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001389 // This is the last tab. Open a new one, with the home
1390 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001391 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001392 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001393 return;
1394 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001395 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001396 int indexToShow = -1;
1397 if (parent != null) {
1398 indexToShow = mTabControl.getTabIndex(parent);
1399 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001400 final int currentIndex = mTabControl.getCurrentIndex();
1401 // Try to move to the tab to the right
1402 indexToShow = currentIndex + 1;
1403 if (indexToShow > mTabControl.getTabCount() - 1) {
1404 // Try to move to the tab to the left
1405 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001406 }
1407 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001408 if (switchToTab(indexToShow)) {
1409 // Close window
1410 closeTab(current);
1411 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001412 }
1413
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001414 private ActiveTabsPage mActiveTabsPage;
1415
1416 /**
1417 * Remove the active tabs page.
1418 * @param needToAttach If true, the active tabs page did not attach a tab
1419 * to the content view, so we need to do that here.
1420 */
1421 /* package */ void removeActiveTabPage(boolean needToAttach) {
1422 mContentView.removeView(mActiveTabsPage);
1423 mActiveTabsPage = null;
1424 mMenuState = R.id.MAIN_MENU;
1425 if (needToAttach) {
1426 attachTabToContentView(mTabControl.getCurrentTab());
1427 }
1428 getTopWindow().requestFocus();
1429 }
1430
The Android Open Source Project0c908882009-03-03 19:32:16 -08001431 @Override
1432 public boolean onOptionsItemSelected(MenuItem item) {
1433 if (!mCanChord) {
1434 // The user has already fired a shortcut with this hold down of the
1435 // menu key.
1436 return false;
1437 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001438 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001439 return false;
1440 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001441 if (mMenuIsDown) {
1442 // The shortcut action consumes the MENU. Even if it is still down,
1443 // it won't trigger the next shortcut action. In the case of the
1444 // shortcut action triggering a new activity, like Bookmarks, we
1445 // won't get onKeyUp for MENU. So it is important to reset it here.
1446 mMenuIsDown = false;
1447 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001448 switch (item.getItemId()) {
1449 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001450 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001451 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001452 break;
1453
Leon Scroggins64b80f32009-08-07 12:03:34 -04001454 case R.id.goto_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001455 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001456 break;
1457
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001458 case R.id.active_tabs_menu_id:
1459 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1460 removeTabFromContentView(mTabControl.getCurrentTab());
1461 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1462 mActiveTabsPage.requestFocus();
1463 mMenuState = EMPTY_MENU;
1464 break;
1465
Leon Scroggins1f005d32009-08-10 17:36:42 -04001466 case R.id.add_bookmark_menu_id:
1467 Intent i = new Intent(BrowserActivity.this,
1468 AddBookmarkPage.class);
1469 WebView w = getTopWindow();
1470 i.putExtra("url", w.getUrl());
1471 i.putExtra("title", w.getTitle());
1472 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001473 break;
1474
1475 case R.id.stop_reload_menu_id:
1476 if (mInLoad) {
1477 stopLoading();
1478 } else {
1479 getTopWindow().reload();
1480 }
1481 break;
1482
1483 case R.id.back_menu_id:
1484 getTopWindow().goBack();
1485 break;
1486
1487 case R.id.forward_menu_id:
1488 getTopWindow().goForward();
1489 break;
1490
1491 case R.id.close_menu_id:
1492 // Close the subwindow if it exists.
1493 if (mTabControl.getCurrentSubWindow() != null) {
1494 dismissSubWindow(mTabControl.getCurrentTab());
1495 break;
1496 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001497 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001498 break;
1499
1500 case R.id.homepage_menu_id:
1501 TabControl.Tab current = mTabControl.getCurrentTab();
1502 if (current != null) {
1503 dismissSubWindow(current);
1504 current.getWebView().loadUrl(mSettings.getHomePage());
1505 }
1506 break;
1507
1508 case R.id.preferences_menu_id:
1509 Intent intent = new Intent(this,
1510 BrowserPreferencesPage.class);
1511 startActivityForResult(intent, PREFERENCES_PAGE);
1512 break;
1513
1514 case R.id.find_menu_id:
1515 if (null == mFindDialog) {
1516 mFindDialog = new FindDialog(this);
1517 }
1518 mFindDialog.setWebView(getTopWindow());
1519 mFindDialog.show();
1520 mMenuState = EMPTY_MENU;
1521 break;
1522
1523 case R.id.select_text_id:
1524 getTopWindow().emulateShiftHeld();
1525 break;
1526 case R.id.page_info_menu_id:
1527 showPageInfo(mTabControl.getCurrentTab(), false);
1528 break;
1529
1530 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001531 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001532 break;
1533
1534 case R.id.share_page_menu_id:
1535 Browser.sendString(this, getTopWindow().getUrl());
1536 break;
1537
1538 case R.id.dump_nav_menu_id:
1539 getTopWindow().debugDump();
1540 break;
1541
1542 case R.id.zoom_in_menu_id:
1543 getTopWindow().zoomIn();
1544 break;
1545
1546 case R.id.zoom_out_menu_id:
1547 getTopWindow().zoomOut();
1548 break;
1549
1550 case R.id.view_downloads_menu_id:
1551 viewDownloads(null);
1552 break;
1553
The Android Open Source Project0c908882009-03-03 19:32:16 -08001554 case R.id.window_one_menu_id:
1555 case R.id.window_two_menu_id:
1556 case R.id.window_three_menu_id:
1557 case R.id.window_four_menu_id:
1558 case R.id.window_five_menu_id:
1559 case R.id.window_six_menu_id:
1560 case R.id.window_seven_menu_id:
1561 case R.id.window_eight_menu_id:
1562 {
1563 int menuid = item.getItemId();
1564 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1565 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1566 TabControl.Tab desiredTab = mTabControl.getTab(id);
1567 if (desiredTab != null &&
1568 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001569 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001570 }
1571 break;
1572 }
1573 }
1574 }
1575 break;
1576
1577 default:
1578 if (!super.onOptionsItemSelected(item)) {
1579 return false;
1580 }
1581 // Otherwise fall through.
1582 }
1583 mCanChord = false;
1584 return true;
1585 }
1586
1587 public void closeFind() {
1588 mMenuState = R.id.MAIN_MENU;
1589 }
1590
1591 @Override public boolean onPrepareOptionsMenu(Menu menu)
1592 {
1593 // This happens when the user begins to hold down the menu key, so
1594 // allow them to chord to get a shortcut.
1595 mCanChord = true;
1596 // Note: setVisible will decide whether an item is visible; while
1597 // setEnabled() will decide whether an item is enabled, which also means
1598 // whether the matching shortcut key will function.
1599 super.onPrepareOptionsMenu(menu);
1600 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001601 case EMPTY_MENU:
1602 if (mCurrentMenuState != mMenuState) {
1603 menu.setGroupVisible(R.id.MAIN_MENU, false);
1604 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1605 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001606 }
1607 break;
1608 default:
1609 if (mCurrentMenuState != mMenuState) {
1610 menu.setGroupVisible(R.id.MAIN_MENU, true);
1611 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1612 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001613 }
1614 final WebView w = getTopWindow();
1615 boolean canGoBack = false;
1616 boolean canGoForward = false;
1617 boolean isHome = false;
1618 if (w != null) {
1619 canGoBack = w.canGoBack();
1620 canGoForward = w.canGoForward();
1621 isHome = mSettings.getHomePage().equals(w.getUrl());
1622 }
1623 final MenuItem back = menu.findItem(R.id.back_menu_id);
1624 back.setEnabled(canGoBack);
1625
1626 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1627 home.setEnabled(!isHome);
1628
1629 menu.findItem(R.id.forward_menu_id)
1630 .setEnabled(canGoForward);
1631
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001632 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1633 mTabControl.getTabCount() < TabControl.MAX_TABS);
1634
The Android Open Source Project0c908882009-03-03 19:32:16 -08001635 // decide whether to show the share link option
1636 PackageManager pm = getPackageManager();
1637 Intent send = new Intent(Intent.ACTION_SEND);
1638 send.setType("text/plain");
1639 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1640 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1641
The Android Open Source Project0c908882009-03-03 19:32:16 -08001642 boolean isNavDump = mSettings.isNavDump();
1643 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1644 nav.setVisible(isNavDump);
1645 nav.setEnabled(isNavDump);
1646 break;
1647 }
1648 mCurrentMenuState = mMenuState;
1649 return true;
1650 }
1651
1652 @Override
1653 public void onCreateContextMenu(ContextMenu menu, View v,
1654 ContextMenuInfo menuInfo) {
1655 WebView webview = (WebView) v;
1656 WebView.HitTestResult result = webview.getHitTestResult();
1657 if (result == null) {
1658 return;
1659 }
1660
1661 int type = result.getType();
1662 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1663 Log.w(LOGTAG,
1664 "We should not show context menu when nothing is touched");
1665 return;
1666 }
1667 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1668 // let TextView handles context menu
1669 return;
1670 }
1671
1672 // Note, http://b/issue?id=1106666 is requesting that
1673 // an inflated menu can be used again. This is not available
1674 // yet, so inflate each time (yuk!)
1675 MenuInflater inflater = getMenuInflater();
1676 inflater.inflate(R.menu.browsercontext, menu);
1677
1678 // Show the correct menu group
1679 String extra = result.getExtra();
1680 menu.setGroupVisible(R.id.PHONE_MENU,
1681 type == WebView.HitTestResult.PHONE_TYPE);
1682 menu.setGroupVisible(R.id.EMAIL_MENU,
1683 type == WebView.HitTestResult.EMAIL_TYPE);
1684 menu.setGroupVisible(R.id.GEO_MENU,
1685 type == WebView.HitTestResult.GEO_TYPE);
1686 menu.setGroupVisible(R.id.IMAGE_MENU,
1687 type == WebView.HitTestResult.IMAGE_TYPE
1688 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1689 menu.setGroupVisible(R.id.ANCHOR_MENU,
1690 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1691 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1692
1693 // Setup custom handling depending on the type
1694 switch (type) {
1695 case WebView.HitTestResult.PHONE_TYPE:
1696 menu.setHeaderTitle(Uri.decode(extra));
1697 menu.findItem(R.id.dial_context_menu_id).setIntent(
1698 new Intent(Intent.ACTION_VIEW, Uri
1699 .parse(WebView.SCHEME_TEL + extra)));
1700 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1701 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1702 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1703 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1704 addIntent);
1705 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1706 new Copy(extra));
1707 break;
1708
1709 case WebView.HitTestResult.EMAIL_TYPE:
1710 menu.setHeaderTitle(extra);
1711 menu.findItem(R.id.email_context_menu_id).setIntent(
1712 new Intent(Intent.ACTION_VIEW, Uri
1713 .parse(WebView.SCHEME_MAILTO + extra)));
1714 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1715 new Copy(extra));
1716 break;
1717
1718 case WebView.HitTestResult.GEO_TYPE:
1719 menu.setHeaderTitle(extra);
1720 menu.findItem(R.id.map_context_menu_id).setIntent(
1721 new Intent(Intent.ACTION_VIEW, Uri
1722 .parse(WebView.SCHEME_GEO
1723 + URLEncoder.encode(extra))));
1724 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1725 new Copy(extra));
1726 break;
1727
1728 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1729 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1730 TextView titleView = (TextView) LayoutInflater.from(this)
1731 .inflate(android.R.layout.browser_link_context_header,
1732 null);
1733 titleView.setText(extra);
1734 menu.setHeaderView(titleView);
1735 // decide whether to show the open link in new tab option
1736 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1737 mTabControl.getTabCount() < TabControl.MAX_TABS);
1738 PackageManager pm = getPackageManager();
1739 Intent send = new Intent(Intent.ACTION_SEND);
1740 send.setType("text/plain");
1741 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1742 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1743 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1744 break;
1745 }
1746 // otherwise fall through to handle image part
1747 case WebView.HitTestResult.IMAGE_TYPE:
1748 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1749 menu.setHeaderTitle(extra);
1750 }
1751 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1752 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1753 menu.findItem(R.id.download_context_menu_id).
1754 setOnMenuItemClickListener(new Download(extra));
1755 break;
1756
1757 default:
1758 Log.w(LOGTAG, "We should not get here.");
1759 break;
1760 }
1761 }
1762
The Android Open Source Project0c908882009-03-03 19:32:16 -08001763 // Attach the given tab to the content view.
1764 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001765 // Attach the container that contains the main WebView and any other UI
1766 // associated with the tab.
1767 mContentView.addView(t.getContainer(), COVER_SCREEN_PARAMS);
Ben Murdochbff2d602009-07-01 20:19:05 +01001768
1769 if (mShouldShowErrorConsole) {
1770 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1771 if (errorConsole.numberOfErrors() == 0) {
1772 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1773 } else {
1774 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1775 }
1776
1777 mErrorConsoleContainer.addView(errorConsole,
1778 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1779 ViewGroup.LayoutParams.WRAP_CONTENT));
1780 }
1781
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001782 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001783 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001784 // Attach the sub window if necessary
1785 attachSubWindow(t);
1786 // Request focus on the top window.
1787 t.getTopWindow().requestFocus();
1788 }
1789
1790 // Attach a sub window to the main WebView of the given tab.
1791 private void attachSubWindow(TabControl.Tab t) {
1792 // If a sub window exists, attach it to the content view.
1793 final WebView subView = t.getSubWebView();
1794 if (subView != null) {
1795 final View container = t.getSubWebViewContainer();
1796 mContentView.addView(container, COVER_SCREEN_PARAMS);
1797 subView.requestFocus();
1798 }
1799 }
1800
1801 // Remove the given tab from the content view.
1802 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001803 // Remove the container that contains the main WebView.
1804 mContentView.removeView(t.getContainer());
Ben Murdochbff2d602009-07-01 20:19:05 +01001805
1806 if (mTabControl.getCurrentErrorConsole(false) != null) {
1807 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1808 }
1809
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001810 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001811 if (view != null) {
1812 view.setEmbeddedTitleBar(null);
1813 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001814
The Android Open Source Project0c908882009-03-03 19:32:16 -08001815 // Remove the sub window if it exists.
1816 if (t.getSubWebView() != null) {
1817 mContentView.removeView(t.getSubWebViewContainer());
1818 }
1819 }
1820
1821 // Remove the sub window if it exists. Also called by TabControl when the
1822 // user clicks the 'X' to dismiss a sub window.
1823 /* package */ void dismissSubWindow(TabControl.Tab t) {
1824 final WebView mainView = t.getWebView();
1825 if (t.getSubWebView() != null) {
1826 // Remove the container view and request focus on the main WebView.
1827 mContentView.removeView(t.getSubWebViewContainer());
1828 mainView.requestFocus();
1829 // Tell the TabControl to dismiss the subwindow. This will destroy
1830 // the WebView.
1831 mTabControl.dismissSubWindow(t);
1832 }
1833 }
1834
Leon Scroggins1f005d32009-08-10 17:36:42 -04001835 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001836 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001837 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1838 String appId) {
1839 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001840 }
1841
1842 // This method does a ton of stuff. It will attempt to create a new tab
1843 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001844 // url isn't null, it will load the given url.
1845 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001846 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001847 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1848 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1849 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001850 final TabControl.Tab tab = mTabControl.createNewTab(
1851 closeOnExit, appId, urlData.mUrl);
1852 WebView webview = tab.getWebView();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001853 mTitleBar.addTab(webview, true);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001854 // If the last tab was removed from the active tabs page, currentTab
1855 // will be null.
1856 if (currentTab != null) {
1857 removeTabFromContentView(currentTab);
1858 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001859 attachTabToContentView(tab);
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001860 // We must set the new tab as the current tab to reflect the old
1861 // animation behavior.
1862 mTabControl.setCurrentTab(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001863 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001864 urlData.loadIn(webview);
1865 }
1866 return tab;
1867 } else {
1868 // Get rid of the subwindow if it exists
1869 dismissSubWindow(currentTab);
1870 if (!urlData.isEmpty()) {
1871 // Load the given url.
1872 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001873 }
1874 }
Grace Klobac9181842009-04-14 08:53:22 -07001875 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001876 }
1877
Grace Klobac9181842009-04-14 08:53:22 -07001878 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001879 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001880 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001881 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001882 WebView view = t.getWebView();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001883 mTitleBar.addTab(view, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001884 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001885 }
Grace Klobac9181842009-04-14 08:53:22 -07001886 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001887 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001888 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001889 }
1890 }
1891
1892 private class Copy implements OnMenuItemClickListener {
1893 private CharSequence mText;
1894
1895 public boolean onMenuItemClick(MenuItem item) {
1896 copy(mText);
1897 return true;
1898 }
1899
1900 public Copy(CharSequence toCopy) {
1901 mText = toCopy;
1902 }
1903 }
1904
1905 private class Download implements OnMenuItemClickListener {
1906 private String mText;
1907
1908 public boolean onMenuItemClick(MenuItem item) {
1909 onDownloadStartNoStream(mText, null, null, null, -1);
1910 return true;
1911 }
1912
1913 public Download(String toDownload) {
1914 mText = toDownload;
1915 }
1916 }
1917
1918 private void copy(CharSequence text) {
1919 try {
1920 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1921 if (clip != null) {
1922 clip.setClipboardText(text);
1923 }
1924 } catch (android.os.RemoteException e) {
1925 Log.e(LOGTAG, "Copy failed", e);
1926 }
1927 }
1928
1929 /**
1930 * Resets the browser title-view to whatever it must be (for example, if we
1931 * load a page from history).
1932 */
1933 private void resetTitle() {
1934 resetLockIcon();
1935 resetTitleIconAndProgress();
1936 }
1937
1938 /**
1939 * Resets the browser title-view to whatever it must be
1940 * (for example, if we had a loading error)
1941 * When we have a new page, we call resetTitle, when we
1942 * have to reset the titlebar to whatever it used to be
1943 * (for example, if the user chose to stop loading), we
1944 * call resetTitleAndRevertLockIcon.
1945 */
1946 /* package */ void resetTitleAndRevertLockIcon() {
1947 revertLockIcon();
1948 resetTitleIconAndProgress();
1949 }
1950
1951 /**
1952 * Reset the title, favicon, and progress.
1953 */
1954 private void resetTitleIconAndProgress() {
1955 WebView current = mTabControl.getCurrentWebView();
1956 if (current == null) {
1957 return;
1958 }
1959 resetTitleAndIcon(current);
1960 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001961 mWebChromeClient.onProgressChanged(current, progress);
1962 }
1963
1964 // Reset the title and the icon based on the given item.
1965 private void resetTitleAndIcon(WebView view) {
1966 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1967 if (item != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001968 setUrlTitle(item.getUrl(), item.getTitle(), view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001969 setFavicon(item.getFavicon());
1970 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001971 setUrlTitle(null, null, view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001972 setFavicon(null);
1973 }
1974 }
1975
1976 /**
1977 * Sets a title composed of the URL and the title string.
1978 * @param url The URL of the site being loaded.
1979 * @param title The title of the site being loaded.
1980 */
Leon Scroggins1f005d32009-08-10 17:36:42 -04001981 private void setUrlTitle(String url, String title, WebView view) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001982 mUrl = url;
1983 mTitle = title;
1984
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001985 mTitleBar.setTitleAndUrl(title, url, view);
1986 if (mFakeTitleBar != null) {
1987 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001988 }
1989 }
1990
1991 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001992 * @param url The URL to build a title version of the URL from.
1993 * @return The title version of the URL or null if fails.
1994 * The title version of the URL can be either the URL hostname,
1995 * or the hostname with an "https://" prefix (for secure URLs),
1996 * or an empty string if, for example, the URL in question is a
1997 * file:// URL with no hostname.
1998 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001999 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002000 String titleUrl = null;
2001
2002 if (url != null) {
2003 try {
2004 // parse the url string
2005 URL urlObj = new URL(url);
2006 if (urlObj != null) {
2007 titleUrl = "";
2008
2009 String protocol = urlObj.getProtocol();
2010 String host = urlObj.getHost();
2011
2012 if (host != null && 0 < host.length()) {
2013 titleUrl = host;
2014 if (protocol != null) {
2015 // if a secure site, add an "https://" prefix!
2016 if (protocol.equalsIgnoreCase("https")) {
2017 titleUrl = protocol + "://" + host;
2018 }
2019 }
2020 }
2021 }
2022 } catch (MalformedURLException e) {}
2023 }
2024
2025 return titleUrl;
2026 }
2027
2028 // Set the favicon in the title bar.
2029 private void setFavicon(Bitmap icon) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002030 mTitleBar.setFavicon(icon, getTopWindow());
2031 if (mFakeTitleBar != null) {
2032 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002033 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002034 }
2035
2036 /**
2037 * Saves the current lock-icon state before resetting
2038 * the lock icon. If we have an error, we may need to
2039 * roll back to the previous state.
2040 */
2041 private void saveLockIcon() {
2042 mPrevLockType = mLockIconType;
2043 }
2044
2045 /**
2046 * Reverts the lock-icon state to the last saved state,
2047 * for example, if we had an error, and need to cancel
2048 * the load.
2049 */
2050 private void revertLockIcon() {
2051 mLockIconType = mPrevLockType;
2052
Dave Bort31a6d1c2009-04-13 15:56:49 -07002053 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002054 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2055 " revert lock icon to " + mLockIconType);
2056 }
2057
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002058 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002059 }
2060
Leon Scroggins1f005d32009-08-10 17:36:42 -04002061 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002062 * Close the tab, remove its associated title bar, and adjust mTabControl's
2063 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002064 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002065 /* package */ void closeTab(TabControl.Tab t) {
2066 int currentIndex = mTabControl.getCurrentIndex();
2067 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002068 mTitleBar.removeTab(removeIndex);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002069 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002070 if (currentIndex >= removeIndex && currentIndex != 0) {
2071 currentIndex--;
2072 }
2073 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
The Android Open Source Project0c908882009-03-03 19:32:16 -08002074 }
2075
2076 private void goBackOnePageOrQuit() {
2077 TabControl.Tab current = mTabControl.getCurrentTab();
2078 if (current == null) {
2079 /*
2080 * Instead of finishing the activity, simply push this to the back
2081 * of the stack and let ActivityManager to choose the foreground
2082 * activity. As BrowserActivity is singleTask, it will be always the
2083 * root of the task. So we can use either true or false for
2084 * moveTaskToBack().
2085 */
2086 moveTaskToBack(true);
2087 }
2088 WebView w = current.getWebView();
2089 if (w.canGoBack()) {
2090 w.goBack();
2091 } else {
2092 // Check to see if we are closing a window that was created by
2093 // another window. If so, we switch back to that window.
2094 TabControl.Tab parent = current.getParentTab();
2095 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002096 switchToTab(mTabControl.getTabIndex(parent));
2097 // Now we close the other tab
2098 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002099 } else {
2100 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002101 // force mPageStarted to be false as we are going to either
2102 // finish the activity or remove the tab. This will ensure
2103 // pauseWebView() taking action.
2104 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002105 if (mTabControl.getTabCount() == 1) {
2106 finish();
2107 return;
2108 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002109 // call pauseWebViewTimers() now, we won't be able to call
2110 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002111 // Temporarily change mActivityInPause to be true as
2112 // pauseWebViewTimers() will do nothing if mActivityInPause
2113 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002114 boolean savedState = mActivityInPause;
2115 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002116 Log.e(LOGTAG, "BrowserActivity is already paused "
2117 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002118 }
2119 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002120 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002121 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002122 removeTabFromContentView(current);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002123 mTitleBar.removeTab(mTabControl.getTabIndex(current));
The Android Open Source Project0c908882009-03-03 19:32:16 -08002124 mTabControl.removeTab(current);
2125 }
2126 /*
2127 * Instead of finishing the activity, simply push this to the back
2128 * of the stack and let ActivityManager to choose the foreground
2129 * activity. As BrowserActivity is singleTask, it will be always the
2130 * root of the task. So we can use either true or false for
2131 * moveTaskToBack().
2132 */
2133 moveTaskToBack(true);
2134 }
2135 }
2136 }
2137
2138 public KeyTracker.State onKeyTracker(int keyCode,
2139 KeyEvent event,
2140 KeyTracker.Stage stage,
2141 int duration) {
2142 // if onKeyTracker() is called after activity onStop()
2143 // because of accumulated key events,
2144 // we should ignore it as browser is not active any more.
2145 WebView topWindow = getTopWindow();
Andrei Popescuadc008d2009-06-26 14:11:30 +01002146 if (topWindow == null && mCustomView == null)
The Android Open Source Project0c908882009-03-03 19:32:16 -08002147 return KeyTracker.State.NOT_TRACKING;
2148
2149 if (keyCode == KeyEvent.KEYCODE_BACK) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01002150 // Check if a custom view is currently showing and, if it is, hide it.
2151 if (mCustomView != null) {
2152 mWebChromeClient.onHideCustomView();
2153 return KeyTracker.State.DONE_TRACKING;
2154 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002155 if (stage == KeyTracker.Stage.LONG_REPEAT) {
Leon Scroggins30444232009-09-04 18:36:20 -04002156 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002157 return KeyTracker.State.DONE_TRACKING;
2158 } else if (stage == KeyTracker.Stage.UP) {
2159 // FIXME: Currently, we do not have a notion of the
2160 // history picker for the subwindow, but maybe we
2161 // should?
2162 WebView subwindow = mTabControl.getCurrentSubWindow();
2163 if (subwindow != null) {
2164 if (subwindow.canGoBack()) {
2165 subwindow.goBack();
2166 } else {
2167 dismissSubWindow(mTabControl.getCurrentTab());
2168 }
2169 } else {
2170 goBackOnePageOrQuit();
2171 }
2172 return KeyTracker.State.DONE_TRACKING;
2173 }
2174 return KeyTracker.State.KEEP_TRACKING;
2175 }
2176 return KeyTracker.State.NOT_TRACKING;
2177 }
2178
2179 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2180 if (keyCode == KeyEvent.KEYCODE_MENU) {
2181 mMenuIsDown = true;
Grace Kloba6ee9c492009-07-13 10:04:34 -07002182 } else if (mMenuIsDown) {
2183 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2184 // still down, we don't want to trigger the search. Pretend to
2185 // consume the key and do nothing.
2186 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002187 }
2188 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2189 if (!handled) {
2190 switch (keyCode) {
2191 case KeyEvent.KEYCODE_SPACE:
2192 if (event.isShiftPressed()) {
2193 getTopWindow().pageUp(false);
2194 } else {
2195 getTopWindow().pageDown(false);
2196 }
2197 handled = true;
2198 break;
2199
2200 default:
2201 break;
2202 }
2203 }
2204 return handled || super.onKeyDown(keyCode, event);
2205 }
2206
2207 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2208 if (keyCode == KeyEvent.KEYCODE_MENU) {
2209 mMenuIsDown = false;
2210 }
2211 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2212 }
2213
2214 private void stopLoading() {
2215 resetTitleAndRevertLockIcon();
2216 WebView w = getTopWindow();
2217 w.stopLoading();
2218 mWebViewClient.onPageFinished(w, w.getUrl());
2219
2220 cancelStopToast();
2221 mStopToast = Toast
2222 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2223 mStopToast.show();
2224 }
2225
2226 private void cancelStopToast() {
2227 if (mStopToast != null) {
2228 mStopToast.cancel();
2229 mStopToast = null;
2230 }
2231 }
2232
2233 // called by a non-UI thread to post the message
2234 public void postMessage(int what, int arg1, int arg2, Object obj) {
2235 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2236 }
2237
2238 // public message ids
2239 public final static int LOAD_URL = 1001;
2240 public final static int STOP_LOAD = 1002;
2241
2242 // Message Ids
2243 private static final int FOCUS_NODE_HREF = 102;
2244 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002245 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002246
2247 // Private handler for handling javascript and saving passwords
2248 private Handler mHandler = new Handler() {
2249
2250 public void handleMessage(Message msg) {
2251 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002252 case FOCUS_NODE_HREF:
2253 String url = (String) msg.getData().get("url");
2254 if (url == null || url.length() == 0) {
2255 break;
2256 }
2257 HashMap focusNodeMap = (HashMap) msg.obj;
2258 WebView view = (WebView) focusNodeMap.get("webview");
2259 // Only apply the action if the top window did not change.
2260 if (getTopWindow() != view) {
2261 break;
2262 }
2263 switch (msg.arg1) {
2264 case R.id.open_context_menu_id:
2265 case R.id.view_image_context_menu_id:
2266 loadURL(getTopWindow(), url);
2267 break;
2268 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002269 final TabControl.Tab parent = mTabControl
2270 .getCurrentTab();
2271 final TabControl.Tab newTab = openTab(url);
2272 if (newTab != parent) {
2273 parent.addChildTab(newTab);
2274 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002275 break;
2276 case R.id.bookmark_context_menu_id:
2277 Intent intent = new Intent(BrowserActivity.this,
2278 AddBookmarkPage.class);
2279 intent.putExtra("url", url);
2280 startActivity(intent);
2281 break;
2282 case R.id.share_link_context_menu_id:
2283 Browser.sendString(BrowserActivity.this, url);
2284 break;
2285 case R.id.copy_link_context_menu_id:
2286 copy(url);
2287 break;
2288 case R.id.save_link_context_menu_id:
2289 case R.id.download_context_menu_id:
2290 onDownloadStartNoStream(url, null, null, null, -1);
2291 break;
2292 }
2293 break;
2294
2295 case LOAD_URL:
2296 loadURL(getTopWindow(), (String) msg.obj);
2297 break;
2298
2299 case STOP_LOAD:
2300 stopLoading();
2301 break;
2302
2303 case CANCEL_CREDS_REQUEST:
2304 resumeAfterCredentials();
2305 break;
2306
The Android Open Source Project0c908882009-03-03 19:32:16 -08002307 case RELEASE_WAKELOCK:
2308 if (mWakeLock.isHeld()) {
2309 mWakeLock.release();
2310 }
2311 break;
2312 }
2313 }
2314 };
2315
Leon Scroggins89c6d362009-07-15 16:54:37 -04002316 private void updateScreenshot(WebView view) {
2317 // If this is a bookmarked site, add a screenshot to the database.
2318 // FIXME: When should we update? Every time?
2319 // FIXME: Would like to make sure there is actually something to
2320 // draw, but the API for that (WebViewCore.pictureReady()) is not
2321 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002322 ContentResolver cr = getContentResolver();
2323 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002324 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002325 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002326 boolean succeed = c.moveToFirst();
2327 ContentValues values = null;
2328 while (succeed) {
2329 if (values == null) {
2330 final ByteArrayOutputStream os
2331 = new ByteArrayOutputStream();
2332 Picture thumbnail = view.capturePicture();
2333 // Keep width and height in sync with BrowserBookmarksPage
2334 // and bookmark_thumb
2335 Bitmap bm = Bitmap.createBitmap(100, 80,
2336 Bitmap.Config.ARGB_4444);
2337 Canvas canvas = new Canvas(bm);
2338 // May need to tweak these values to determine what is the
2339 // best scale factor
2340 canvas.scale(.5f, .5f);
2341 thumbnail.draw(canvas);
2342 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2343 values = new ContentValues();
2344 values.put(Browser.BookmarkColumns.THUMBNAIL,
2345 os.toByteArray());
2346 }
2347 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2348 c.getInt(0)), values, null, null);
2349 succeed = c.moveToNext();
2350 }
2351 c.close();
2352 }
2353 }
2354
The Android Open Source Project0c908882009-03-03 19:32:16 -08002355 // -------------------------------------------------------------------------
2356 // WebViewClient implementation.
2357 //-------------------------------------------------------------------------
2358
2359 // Use in overrideUrlLoading
2360 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2361 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2362 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2363 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2364
2365 /* package */ WebViewClient getWebViewClient() {
2366 return mWebViewClient;
2367 }
2368
Patrick Scott3918d442009-08-04 13:22:29 -04002369 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002370 if (icon != null) {
2371 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott3918d442009-08-04 13:22:29 -04002372 view, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002373 }
2374 setFavicon(icon);
2375 }
2376
2377 private final WebViewClient mWebViewClient = new WebViewClient() {
2378 @Override
2379 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2380 resetLockIcon(url);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002381 setUrlTitle(url, null, view);
Ben Murdochbff2d602009-07-01 20:19:05 +01002382
2383 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2384 if (errorConsole != null) {
2385 errorConsole.clearErrorMessages();
2386 if (mShouldShowErrorConsole) {
2387 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2388 }
2389 }
2390
The Android Open Source Project0c908882009-03-03 19:32:16 -08002391 // Call updateIcon instead of setFavicon so the bookmark
2392 // database can be updated.
Patrick Scott3918d442009-08-04 13:22:29 -04002393 updateIcon(view, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002394
Grace Kloba4d7880f2009-08-12 09:35:42 -07002395 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002396 String host;
2397 try {
2398 WebAddress uri = new WebAddress(url);
2399 host = uri.mHost;
2400 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002401 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002402 }
2403 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002404 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002405 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002406 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002407 }
2408
2409 // Performance probe
2410 if (false) {
2411 mStart = SystemClock.uptimeMillis();
2412 mProcessStart = Process.getElapsedCpuTime();
2413 long[] sysCpu = new long[7];
2414 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2415 sysCpu, null)) {
2416 mUserStart = sysCpu[0] + sysCpu[1];
2417 mSystemStart = sysCpu[2];
2418 mIdleStart = sysCpu[3];
2419 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2420 }
2421 mUiStart = SystemClock.currentThreadTimeMillis();
2422 }
2423
2424 if (!mPageStarted) {
2425 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002426 // if onResume() has been called, resumeWebViewTimers() does
2427 // nothing.
2428 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002429 }
2430
2431 // reset sync timer to avoid sync starts during loading a page
2432 CookieSyncManager.getInstance().resetSync();
2433
2434 mInLoad = true;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002435 WebView currentWebView = mTabControl.getCurrentWebView();
2436 if (currentWebView == null || currentWebView.getScrollY() != 0) {
2437 // This page has begun to load, so show the title bar
2438 showFakeTitleBar();
2439 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002440 updateInLoadMenuItems();
2441 if (!mIsNetworkUp) {
2442 if ( mAlertDialog == null) {
2443 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2444 .setTitle(R.string.loadSuspendedTitle)
2445 .setMessage(R.string.loadSuspended)
2446 .setPositiveButton(R.string.ok, null)
2447 .show();
2448 }
2449 if (view != null) {
2450 view.setNetworkAvailable(false);
2451 }
2452 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002453 }
2454
2455 @Override
2456 public void onPageFinished(WebView view, String url) {
2457 // Reset the title and icon in case we stopped a provisional
2458 // load.
2459 resetTitleAndIcon(view);
2460
2461 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002462 updateLockIconToLatest();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002463 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002464
The Android Open Source Project0c908882009-03-03 19:32:16 -08002465 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002466 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002467 long[] sysCpu = new long[7];
2468 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2469 sysCpu, null)) {
2470 String uiInfo = "UI thread used "
2471 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2472 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002473 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002474 Log.d(LOGTAG, uiInfo);
2475 }
2476 //The string that gets written to the log
2477 String performanceString = "It took total "
2478 + (SystemClock.uptimeMillis() - mStart)
2479 + " ms clock time to load the page."
2480 + "\nbrowser process used "
2481 + (Process.getElapsedCpuTime() - mProcessStart)
2482 + " ms, user processes used "
2483 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2484 + " ms, kernel used "
2485 + (sysCpu[2] - mSystemStart) * 10
2486 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2487 + " ms and irq took "
2488 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2489 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002490 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002491 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2492 }
2493 if (url != null) {
2494 // strip the url to maintain consistency
2495 String newUrl = new String(url);
2496 if (newUrl.startsWith("http://www.")) {
2497 newUrl = newUrl.substring(11);
2498 } else if (newUrl.startsWith("http://")) {
2499 newUrl = newUrl.substring(7);
2500 } else if (newUrl.startsWith("https://www.")) {
2501 newUrl = newUrl.substring(12);
2502 } else if (newUrl.startsWith("https://")) {
2503 newUrl = newUrl.substring(8);
2504 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002505 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002506 Log.d(LOGTAG, newUrl + " loaded");
2507 }
2508 /*
2509 if (sWhiteList.contains(newUrl)) {
2510 // The string that gets pushed to the statistcs
2511 // service
2512 performanceString = performanceString
2513 + "\nWebpage: "
2514 + newUrl
2515 + "\nCarrier: "
2516 + android.os.SystemProperties
2517 .get("gsm.sim.operator.alpha");
2518 if (mWebView != null
2519 && mWebView.getContext() != null
2520 && mWebView.getContext().getSystemService(
2521 Context.CONNECTIVITY_SERVICE) != null) {
2522 ConnectivityManager cManager =
2523 (ConnectivityManager) mWebView
2524 .getContext().getSystemService(
2525 Context.CONNECTIVITY_SERVICE);
2526 NetworkInfo nInfo = cManager
2527 .getActiveNetworkInfo();
2528 if (nInfo != null) {
2529 performanceString = performanceString
2530 + "\nNetwork Type: "
2531 + nInfo.getType().toString();
2532 }
2533 }
2534 Checkin.logEvent(mResolver,
2535 Checkin.Events.Tag.WEBPAGE_LOAD,
2536 performanceString);
2537 Log.w(LOGTAG, "pushed to the statistics service");
2538 }
2539 */
2540 }
2541 }
2542 }
2543
2544 if (mInTrace) {
2545 mInTrace = false;
2546 Debug.stopMethodTracing();
2547 }
2548
2549 if (mPageStarted) {
2550 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002551 // pauseWebViewTimers() will do nothing and return false if
2552 // onPause() is not called yet.
2553 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002554 if (mWakeLock.isHeld()) {
2555 mHandler.removeMessages(RELEASE_WAKELOCK);
2556 mWakeLock.release();
2557 }
2558 }
2559 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002560 }
2561
2562 // return true if want to hijack the url to let another app to handle it
2563 @Override
2564 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2565 if (url.startsWith(SCHEME_WTAI)) {
2566 // wtai://wp/mc;number
2567 // number=string(phone-number)
2568 if (url.startsWith(SCHEME_WTAI_MC)) {
2569 Intent intent = new Intent(Intent.ACTION_VIEW,
2570 Uri.parse(WebView.SCHEME_TEL +
2571 url.substring(SCHEME_WTAI_MC.length())));
2572 startActivity(intent);
2573 return true;
2574 }
2575 // wtai://wp/sd;dtmf
2576 // dtmf=string(dialstring)
2577 if (url.startsWith(SCHEME_WTAI_SD)) {
2578 // TODO
2579 // only send when there is active voice connection
2580 return false;
2581 }
2582 // wtai://wp/ap;number;name
2583 // number=string(phone-number)
2584 // name=string
2585 if (url.startsWith(SCHEME_WTAI_AP)) {
2586 // TODO
2587 return false;
2588 }
2589 }
2590
Dianne Hackborn99189432009-06-17 18:06:18 -07002591 // The "about:" schemes are internal to the browser; don't
2592 // want these to be dispatched to other apps.
2593 if (url.startsWith("about:")) {
2594 return false;
2595 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002596
Dianne Hackborn99189432009-06-17 18:06:18 -07002597 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002598
Dianne Hackborn99189432009-06-17 18:06:18 -07002599 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002600 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002601 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2602 } catch (URISyntaxException ex) {
2603 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002604 return false;
2605 }
2606
Grace Kloba5b078b52009-06-24 20:23:41 -07002607 // check whether the intent can be resolved. If not, we will see
2608 // whether we can download it from the Market.
2609 if (getPackageManager().resolveActivity(intent, 0) == null) {
2610 String packagename = intent.getPackage();
2611 if (packagename != null) {
2612 intent = new Intent(Intent.ACTION_VIEW, Uri
2613 .parse("market://search?q=pname:" + packagename));
2614 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2615 startActivity(intent);
2616 return true;
2617 } else {
2618 return false;
2619 }
2620 }
2621
Dianne Hackborn99189432009-06-17 18:06:18 -07002622 // sanitize the Intent, ensuring web pages can not bypass browser
2623 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002624 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002625 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002626 try {
2627 if (startActivityIfNeeded(intent, -1)) {
2628 return true;
2629 }
2630 } catch (ActivityNotFoundException ex) {
2631 // ignore the error. If no application can handle the URL,
2632 // eg about:blank, assume the browser can handle it.
2633 }
2634
2635 if (mMenuIsDown) {
2636 openTab(url);
2637 closeOptionsMenu();
2638 return true;
2639 }
2640
2641 return false;
2642 }
2643
2644 /**
2645 * Updates the lock icon. This method is called when we discover another
2646 * resource to be loaded for this page (for example, javascript). While
2647 * we update the icon type, we do not update the lock icon itself until
2648 * we are done loading, it is slightly more secure this way.
2649 */
2650 @Override
2651 public void onLoadResource(WebView view, String url) {
2652 if (url != null && url.length() > 0) {
2653 // It is only if the page claims to be secure
2654 // that we may have to update the lock:
2655 if (mLockIconType == LOCK_ICON_SECURE) {
2656 // If NOT a 'safe' url, change the lock to mixed content!
2657 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2658 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002659 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002660 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2661 " updated lock icon to " + mLockIconType + " due to " + url);
2662 }
2663 }
2664 }
2665 }
2666 }
2667
2668 /**
2669 * Show the dialog, asking the user if they would like to continue after
2670 * an excessive number of HTTP redirects.
2671 */
2672 @Override
2673 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2674 final Message continueMsg) {
2675 new AlertDialog.Builder(BrowserActivity.this)
2676 .setTitle(R.string.browserFrameRedirect)
2677 .setMessage(R.string.browserFrame307Post)
2678 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2679 public void onClick(DialogInterface dialog, int which) {
2680 continueMsg.sendToTarget();
2681 }})
2682 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2683 public void onClick(DialogInterface dialog, int which) {
2684 cancelMsg.sendToTarget();
2685 }})
2686 .setOnCancelListener(new OnCancelListener() {
2687 public void onCancel(DialogInterface dialog) {
2688 cancelMsg.sendToTarget();
2689 }})
2690 .show();
2691 }
2692
Patrick Scott37911c72009-03-24 18:02:58 -07002693 // Container class for the next error dialog that needs to be
2694 // displayed.
2695 class ErrorDialog {
2696 public final int mTitle;
2697 public final String mDescription;
2698 public final int mError;
2699 ErrorDialog(int title, String desc, int error) {
2700 mTitle = title;
2701 mDescription = desc;
2702 mError = error;
2703 }
2704 };
2705
2706 private void processNextError() {
2707 if (mQueuedErrors == null) {
2708 return;
2709 }
2710 // The first one is currently displayed so just remove it.
2711 mQueuedErrors.removeFirst();
2712 if (mQueuedErrors.size() == 0) {
2713 mQueuedErrors = null;
2714 return;
2715 }
2716 showError(mQueuedErrors.getFirst());
2717 }
2718
2719 private DialogInterface.OnDismissListener mDialogListener =
2720 new DialogInterface.OnDismissListener() {
2721 public void onDismiss(DialogInterface d) {
2722 processNextError();
2723 }
2724 };
2725 private LinkedList<ErrorDialog> mQueuedErrors;
2726
2727 private void queueError(int err, String desc) {
2728 if (mQueuedErrors == null) {
2729 mQueuedErrors = new LinkedList<ErrorDialog>();
2730 }
2731 for (ErrorDialog d : mQueuedErrors) {
2732 if (d.mError == err) {
2733 // Already saw a similar error, ignore the new one.
2734 return;
2735 }
2736 }
2737 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002738 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002739 R.string.browserFrameFileErrorLabel :
2740 R.string.browserFrameNetworkErrorLabel,
2741 desc, err);
2742 mQueuedErrors.addLast(errDialog);
2743
2744 // Show the dialog now if the queue was empty.
2745 if (mQueuedErrors.size() == 1) {
2746 showError(errDialog);
2747 }
2748 }
2749
2750 private void showError(ErrorDialog errDialog) {
2751 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2752 .setTitle(errDialog.mTitle)
2753 .setMessage(errDialog.mDescription)
2754 .setPositiveButton(R.string.ok, null)
2755 .create();
2756 d.setOnDismissListener(mDialogListener);
2757 d.show();
2758 }
2759
The Android Open Source Project0c908882009-03-03 19:32:16 -08002760 /**
2761 * Show a dialog informing the user of the network error reported by
2762 * WebCore.
2763 */
2764 @Override
2765 public void onReceivedError(WebView view, int errorCode,
2766 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002767 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2768 errorCode != WebViewClient.ERROR_CONNECT &&
2769 errorCode != WebViewClient.ERROR_BAD_URL &&
2770 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2771 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002772 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002773 }
Patrick Scott37911c72009-03-24 18:02:58 -07002774 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2775 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002776
2777 // We need to reset the title after an error.
2778 resetTitleAndRevertLockIcon();
2779 }
2780
2781 /**
2782 * Check with the user if it is ok to resend POST data as the page they
2783 * are trying to navigate to is the result of a POST.
2784 */
2785 @Override
2786 public void onFormResubmission(WebView view, final Message dontResend,
2787 final Message resend) {
2788 new AlertDialog.Builder(BrowserActivity.this)
2789 .setTitle(R.string.browserFrameFormResubmitLabel)
2790 .setMessage(R.string.browserFrameFormResubmitMessage)
2791 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2792 public void onClick(DialogInterface dialog, int which) {
2793 resend.sendToTarget();
2794 }})
2795 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2796 public void onClick(DialogInterface dialog, int which) {
2797 dontResend.sendToTarget();
2798 }})
2799 .setOnCancelListener(new OnCancelListener() {
2800 public void onCancel(DialogInterface dialog) {
2801 dontResend.sendToTarget();
2802 }})
2803 .show();
2804 }
2805
2806 /**
2807 * Insert the url into the visited history database.
2808 * @param url The url to be inserted.
2809 * @param isReload True if this url is being reloaded.
2810 * FIXME: Not sure what to do when reloading the page.
2811 */
2812 @Override
2813 public void doUpdateVisitedHistory(WebView view, String url,
2814 boolean isReload) {
2815 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2816 return;
2817 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002818 // remove "client" before updating it to the history so that it wont
2819 // show up in the auto-complete list.
2820 int index = url.indexOf("client=ms-");
2821 if (index > 0 && url.contains(".google.")) {
2822 int end = url.indexOf('&', index);
2823 if (end > 0) {
2824 url = url.substring(0, index-1).concat(url.substring(end));
2825 } else {
2826 url = url.substring(0, index-1);
2827 }
2828 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002829 Browser.updateVisitedHistory(mResolver, url, true);
2830 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2831 }
2832
2833 /**
2834 * Displays SSL error(s) dialog to the user.
2835 */
2836 @Override
2837 public void onReceivedSslError(
2838 final WebView view, final SslErrorHandler handler, final SslError error) {
2839
2840 if (mSettings.showSecurityWarnings()) {
2841 final LayoutInflater factory =
2842 LayoutInflater.from(BrowserActivity.this);
2843 final View warningsView =
2844 factory.inflate(R.layout.ssl_warnings, null);
2845 final LinearLayout placeholder =
2846 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2847
2848 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2849 LinearLayout ll = (LinearLayout)factory
2850 .inflate(R.layout.ssl_warning, null);
2851 ((TextView)ll.findViewById(R.id.warning))
2852 .setText(R.string.ssl_untrusted);
2853 placeholder.addView(ll);
2854 }
2855
2856 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2857 LinearLayout ll = (LinearLayout)factory
2858 .inflate(R.layout.ssl_warning, null);
2859 ((TextView)ll.findViewById(R.id.warning))
2860 .setText(R.string.ssl_mismatch);
2861 placeholder.addView(ll);
2862 }
2863
2864 if (error.hasError(SslError.SSL_EXPIRED)) {
2865 LinearLayout ll = (LinearLayout)factory
2866 .inflate(R.layout.ssl_warning, null);
2867 ((TextView)ll.findViewById(R.id.warning))
2868 .setText(R.string.ssl_expired);
2869 placeholder.addView(ll);
2870 }
2871
2872 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2873 LinearLayout ll = (LinearLayout)factory
2874 .inflate(R.layout.ssl_warning, null);
2875 ((TextView)ll.findViewById(R.id.warning))
2876 .setText(R.string.ssl_not_yet_valid);
2877 placeholder.addView(ll);
2878 }
2879
2880 new AlertDialog.Builder(BrowserActivity.this)
2881 .setTitle(R.string.security_warning)
2882 .setIcon(android.R.drawable.ic_dialog_alert)
2883 .setView(warningsView)
2884 .setPositiveButton(R.string.ssl_continue,
2885 new DialogInterface.OnClickListener() {
2886 public void onClick(DialogInterface dialog, int whichButton) {
2887 handler.proceed();
2888 }
2889 })
2890 .setNeutralButton(R.string.view_certificate,
2891 new DialogInterface.OnClickListener() {
2892 public void onClick(DialogInterface dialog, int whichButton) {
2893 showSSLCertificateOnError(view, handler, error);
2894 }
2895 })
2896 .setNegativeButton(R.string.cancel,
2897 new DialogInterface.OnClickListener() {
2898 public void onClick(DialogInterface dialog, int whichButton) {
2899 handler.cancel();
2900 BrowserActivity.this.resetTitleAndRevertLockIcon();
2901 }
2902 })
2903 .setOnCancelListener(
2904 new DialogInterface.OnCancelListener() {
2905 public void onCancel(DialogInterface dialog) {
2906 handler.cancel();
2907 BrowserActivity.this.resetTitleAndRevertLockIcon();
2908 }
2909 })
2910 .show();
2911 } else {
2912 handler.proceed();
2913 }
2914 }
2915
2916 /**
2917 * Handles an HTTP authentication request.
2918 *
2919 * @param handler The authentication handler
2920 * @param host The host
2921 * @param realm The realm
2922 */
2923 @Override
2924 public void onReceivedHttpAuthRequest(WebView view,
2925 final HttpAuthHandler handler, final String host, final String realm) {
2926 String username = null;
2927 String password = null;
2928
2929 boolean reuseHttpAuthUsernamePassword =
2930 handler.useHttpAuthUsernamePassword();
2931
2932 if (reuseHttpAuthUsernamePassword &&
2933 (mTabControl.getCurrentWebView() != null)) {
2934 String[] credentials =
2935 mTabControl.getCurrentWebView()
2936 .getHttpAuthUsernamePassword(host, realm);
2937 if (credentials != null && credentials.length == 2) {
2938 username = credentials[0];
2939 password = credentials[1];
2940 }
2941 }
2942
2943 if (username != null && password != null) {
2944 handler.proceed(username, password);
2945 } else {
2946 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2947 }
2948 }
2949
2950 @Override
2951 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2952 if (mMenuIsDown) {
2953 // only check shortcut key when MENU is held
2954 return getWindow().isShortcutKey(event.getKeyCode(), event);
2955 } else {
2956 return false;
2957 }
2958 }
2959
2960 @Override
2961 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2962 if (view != mTabControl.getCurrentTopWebView()) {
2963 return;
2964 }
2965 if (event.isDown()) {
2966 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2967 } else {
2968 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2969 }
2970 }
2971 };
2972
2973 //--------------------------------------------------------------------------
2974 // WebChromeClient implementation
2975 //--------------------------------------------------------------------------
2976
2977 /* package */ WebChromeClient getWebChromeClient() {
2978 return mWebChromeClient;
2979 }
2980
2981 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2982 // Helper method to create a new tab or sub window.
2983 private void createWindow(final boolean dialog, final Message msg) {
2984 if (dialog) {
2985 mTabControl.createSubWindow();
2986 final TabControl.Tab t = mTabControl.getCurrentTab();
2987 attachSubWindow(t);
2988 WebView.WebViewTransport transport =
2989 (WebView.WebViewTransport) msg.obj;
2990 transport.setWebView(t.getSubWebView());
2991 msg.sendToTarget();
2992 } else {
2993 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04002994 final TabControl.Tab newTab
2995 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07002996 if (newTab != parent) {
2997 parent.addChildTab(newTab);
2998 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002999 WebView.WebViewTransport transport =
3000 (WebView.WebViewTransport) msg.obj;
3001 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04003002 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003003 }
3004 }
3005
3006 @Override
3007 public boolean onCreateWindow(WebView view, final boolean dialog,
3008 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003009 // Short-circuit if we can't create any more tabs or sub windows.
3010 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3011 new AlertDialog.Builder(BrowserActivity.this)
3012 .setTitle(R.string.too_many_subwindows_dialog_title)
3013 .setIcon(android.R.drawable.ic_dialog_alert)
3014 .setMessage(R.string.too_many_subwindows_dialog_message)
3015 .setPositiveButton(R.string.ok, null)
3016 .show();
3017 return false;
3018 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3019 new AlertDialog.Builder(BrowserActivity.this)
3020 .setTitle(R.string.too_many_windows_dialog_title)
3021 .setIcon(android.R.drawable.ic_dialog_alert)
3022 .setMessage(R.string.too_many_windows_dialog_message)
3023 .setPositiveButton(R.string.ok, null)
3024 .show();
3025 return false;
3026 }
3027
3028 // Short-circuit if this was a user gesture.
3029 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003030 createWindow(dialog, resultMsg);
3031 return true;
3032 }
3033
3034 // Allow the popup and create the appropriate window.
3035 final AlertDialog.OnClickListener allowListener =
3036 new AlertDialog.OnClickListener() {
3037 public void onClick(DialogInterface d,
3038 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003039 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003040 }
3041 };
3042
3043 // Block the popup by returning a null WebView.
3044 final AlertDialog.OnClickListener blockListener =
3045 new AlertDialog.OnClickListener() {
3046 public void onClick(DialogInterface d, int which) {
3047 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003048 }
3049 };
3050
3051 // Build a confirmation dialog to display to the user.
3052 final AlertDialog d =
3053 new AlertDialog.Builder(BrowserActivity.this)
3054 .setTitle(R.string.attention)
3055 .setIcon(android.R.drawable.ic_dialog_alert)
3056 .setMessage(R.string.popup_window_attempt)
3057 .setPositiveButton(R.string.allow, allowListener)
3058 .setNegativeButton(R.string.block, blockListener)
3059 .setCancelable(false)
3060 .create();
3061
3062 // Show the confirmation dialog.
3063 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003064 return true;
3065 }
3066
3067 @Override
3068 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003069 final TabControl.Tab current = mTabControl.getCurrentTab();
3070 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003071 if (parent != null) {
3072 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003073 switchToTab(mTabControl.getTabIndex(parent));
3074 // Now we need to close the window
3075 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003076 }
3077 }
3078
3079 @Override
3080 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003081 mTitleBar.setProgress(newProgress, view);
3082 if (mFakeTitleBar != null) {
3083 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003084 }
3085
3086 if (newProgress == 100) {
3087 // onProgressChanged() is called for sub-frame too while
3088 // onPageFinished() is only called for the main frame. sync
3089 // cookie and cache promptly here.
3090 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003091 if (mInLoad) {
3092 mInLoad = false;
3093 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003094 // If the options menu is open, leave the title bar
3095 if (!mOptionsMenuOpen || !mIconView) {
3096 hideFakeTitleBar();
3097 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003098 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003099 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003100 // onPageFinished may have already been called but a subframe
3101 // is still loading and updating the progress. Reset mInLoad
3102 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003103 mInLoad = true;
3104 updateInLoadMenuItems();
3105 WebView currentWebView = mTabControl.getCurrentWebView();
3106 if ((currentWebView == null || currentWebView.getScrollY() != 0)
3107 && (!mOptionsMenuOpen || mIconView)) {
3108 // This page has begun to load, so show the title bar
3109 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003110 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003111 }
3112 }
3113
3114 @Override
3115 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003116 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003117
3118 // here, if url is null, we want to reset the title
Leon Scroggins1f005d32009-08-10 17:36:42 -04003119 setUrlTitle(url, title, view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003120
3121 if (url == null ||
3122 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3123 return;
3124 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003125 // See if we can find the current url in our history database and
3126 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003127 if (url.startsWith("http://www.")) {
3128 url = url.substring(11);
3129 } else if (url.startsWith("http://")) {
3130 url = url.substring(4);
3131 }
3132 try {
3133 url = "%" + url;
3134 String [] selArgs = new String[] { url };
3135
3136 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3137 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3138 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3139 Browser.HISTORY_PROJECTION, where, selArgs, null);
3140 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003141 // Current implementation of database only has one entry per
3142 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003143 ContentValues map = new ContentValues();
3144 map.put(Browser.BookmarkColumns.TITLE, title);
3145 mResolver.update(Browser.BOOKMARKS_URI, map,
3146 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003147 }
3148 c.close();
3149 } catch (IllegalStateException e) {
3150 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3151 } catch (SQLiteException ex) {
3152 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3153 }
3154 }
3155
3156 @Override
3157 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003158 updateIcon(view, icon);
3159 }
3160
3161 @Override
3162 public void onReceivedTouchIconUrl(WebView view, String url) {
3163 final ContentResolver cr = getContentResolver();
3164 final Cursor c =
3165 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003166 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003167 if (c != null) {
3168 if (c.getCount() > 0) {
3169 new DownloadTouchIcon(cr, c, view).execute(url);
3170 } else {
3171 c.close();
3172 }
3173 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003174 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003175
Andrei Popescuadc008d2009-06-26 14:11:30 +01003176 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003177 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003178 if (mCustomView != null)
3179 return;
3180
3181 // Add the custom view to its container.
3182 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3183 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003184 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003185 // Save the menu state and set it to empty while the custom
3186 // view is showing.
3187 mOldMenuState = mMenuState;
3188 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003189 // Hide the content view.
3190 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003191 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003192 mCustomViewContainer.setVisibility(View.VISIBLE);
3193 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003194 }
3195
3196 @Override
3197 public void onHideCustomView() {
3198 if (mCustomView == null)
3199 return;
3200
Andrei Popescuc9b55562009-07-07 10:51:15 +01003201 // Hide the custom view.
3202 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003203 // Remove the custom view from its container.
3204 mCustomViewContainer.removeView(mCustomView);
3205 mCustomView = null;
3206 // Reset the old menu state.
3207 mMenuState = mOldMenuState;
3208 mOldMenuState = EMPTY_MENU;
3209 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003210 mCustomViewCallback.onCustomViewHidden();
3211 // Show the content view.
3212 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003213 }
3214
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003215 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003216 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003217 * @param url the URL that exceeded the quota
3218 * @param databaseIdentifier the identifier of the database on
3219 * which the transaction that caused the quota overflow was run
3220 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003221 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003222 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003223 * @param quotaUpdater The callback to run when a decision to allow or
3224 * deny quota has been made. Don't forget to call this!
3225 */
3226 @Override
3227 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003228 String databaseIdentifier, long currentQuota, long estimatedSize,
3229 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003230 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003231 url, databaseIdentifier, currentQuota, estimatedSize,
3232 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003233 }
3234
3235 /**
3236 * The Application Cache has exceeded its max size.
3237 * @param spaceNeeded is the amount of disk space that would be needed
3238 * in order for the last appcache operation to succeed.
3239 * @param totalUsedQuota is the sum of all origins' quota.
3240 * @param quotaUpdater A callback to inform the WebCore thread that a new
3241 * app cache size is available. This callback must always be executed at
3242 * some point to ensure that the sleeping WebCore thread is woken up.
3243 */
3244 @Override
3245 public void onReachedMaxAppCacheSize(long spaceNeeded,
3246 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3247 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3248 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003249 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003250
Steve Block2bc69912009-07-30 14:45:13 +01003251 /**
3252 * Instructs the browser to show a prompt to ask the user to set the
3253 * Geolocation permission state for the specified origin.
3254 * @param origin The origin for which Geolocation permissions are
3255 * requested.
3256 * @param callback The callback to call once the user has set the
3257 * Geolocation permission state.
3258 */
3259 @Override
3260 public void onGeolocationPermissionsShowPrompt(String origin,
3261 GeolocationPermissions.Callback callback) {
3262 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3263 origin, callback);
3264 }
3265
3266 /**
3267 * Instructs the browser to hide the Geolocation permissions prompt.
3268 */
3269 @Override
3270 public void onGeolocationPermissionsHidePrompt() {
3271 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3272 }
3273
Ben Murdoch7db26342009-06-03 18:21:19 +01003274 /* Adds a JavaScript error message to the system log.
3275 * @param message The error message to report.
3276 * @param lineNumber The line number of the error.
3277 * @param sourceID The name of the source file that caused the error.
3278 */
3279 @Override
3280 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003281 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3282 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3283 if (mShouldShowErrorConsole &&
3284 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3285 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3286 }
3287 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003288 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003289 };
3290
3291 /**
3292 * Notify the host application a download should be done, or that
3293 * the data should be streamed if a streaming viewer is available.
3294 * @param url The full url to the content that should be downloaded
3295 * @param contentDisposition Content-disposition http header, if
3296 * present.
3297 * @param mimetype The mimetype of the content reported by the server
3298 * @param contentLength The file size reported by the server
3299 */
3300 public void onDownloadStart(String url, String userAgent,
3301 String contentDisposition, String mimetype, long contentLength) {
3302 // if we're dealing wih A/V content that's not explicitly marked
3303 // for download, check if it's streamable.
3304 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003305 || !contentDisposition.regionMatches(
3306 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003307 // query the package manager to see if there's a registered handler
3308 // that matches.
3309 Intent intent = new Intent(Intent.ACTION_VIEW);
3310 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003311 ResolveInfo info = getPackageManager().resolveActivity(intent,
3312 PackageManager.MATCH_DEFAULT_ONLY);
3313 if (info != null) {
3314 ComponentName myName = getComponentName();
3315 // If we resolved to ourselves, we don't want to attempt to
3316 // load the url only to try and download it again.
3317 if (!myName.getPackageName().equals(
3318 info.activityInfo.packageName)
3319 || !myName.getClassName().equals(
3320 info.activityInfo.name)) {
3321 // someone (other than us) knows how to handle this mime
3322 // type with this scheme, don't download.
3323 try {
3324 startActivity(intent);
3325 return;
3326 } catch (ActivityNotFoundException ex) {
3327 if (LOGD_ENABLED) {
3328 Log.d(LOGTAG, "activity not found for " + mimetype
3329 + " over " + Uri.parse(url).getScheme(),
3330 ex);
3331 }
3332 // Best behavior is to fall back to a download in this
3333 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003334 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003335 }
3336 }
3337 }
3338 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3339 }
3340
3341 /**
3342 * Notify the host application a download should be done, even if there
3343 * is a streaming viewer available for thise type.
3344 * @param url The full url to the content that should be downloaded
3345 * @param contentDisposition Content-disposition http header, if
3346 * present.
3347 * @param mimetype The mimetype of the content reported by the server
3348 * @param contentLength The file size reported by the server
3349 */
3350 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3351 String contentDisposition, String mimetype, long contentLength) {
3352
3353 String filename = URLUtil.guessFileName(url,
3354 contentDisposition, mimetype);
3355
3356 // Check to see if we have an SDCard
3357 String status = Environment.getExternalStorageState();
3358 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3359 int title;
3360 String msg;
3361
3362 // Check to see if the SDCard is busy, same as the music app
3363 if (status.equals(Environment.MEDIA_SHARED)) {
3364 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3365 title = R.string.download_sdcard_busy_dlg_title;
3366 } else {
3367 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3368 title = R.string.download_no_sdcard_dlg_title;
3369 }
3370
3371 new AlertDialog.Builder(this)
3372 .setTitle(title)
3373 .setIcon(android.R.drawable.ic_dialog_alert)
3374 .setMessage(msg)
3375 .setPositiveButton(R.string.ok, null)
3376 .show();
3377 return;
3378 }
3379
3380 // java.net.URI is a lot stricter than KURL so we have to undo
3381 // KURL's percent-encoding and redo the encoding using java.net.URI.
3382 URI uri = null;
3383 try {
3384 // Undo the percent-encoding that KURL may have done.
3385 String newUrl = new String(URLUtil.decode(url.getBytes()));
3386 // Parse the url into pieces
3387 WebAddress w = new WebAddress(newUrl);
3388 String frag = null;
3389 String query = null;
3390 String path = w.mPath;
3391 // Break the path into path, query, and fragment
3392 if (path.length() > 0) {
3393 // Strip the fragment
3394 int idx = path.lastIndexOf('#');
3395 if (idx != -1) {
3396 frag = path.substring(idx + 1);
3397 path = path.substring(0, idx);
3398 }
3399 idx = path.lastIndexOf('?');
3400 if (idx != -1) {
3401 query = path.substring(idx + 1);
3402 path = path.substring(0, idx);
3403 }
3404 }
3405 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3406 query, frag);
3407 } catch (Exception e) {
3408 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3409 return;
3410 }
3411
3412 // XXX: Have to use the old url since the cookies were stored using the
3413 // old percent-encoded url.
3414 String cookies = CookieManager.getInstance().getCookie(url);
3415
3416 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003417 values.put(Downloads.COLUMN_URI, uri.toString());
3418 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3419 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3420 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003421 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003422 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003423 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003424 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3425 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3426 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3427 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003428 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003429 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003430 }
3431 if (mimetype == null) {
3432 // We must have long pressed on a link or image to download it. We
3433 // are not sure of the mimetype in this case, so do a head request
3434 new FetchUrlMimeType(this).execute(values);
3435 } else {
3436 final Uri contentUri =
3437 getContentResolver().insert(Downloads.CONTENT_URI, values);
3438 viewDownloads(contentUri);
3439 }
3440
3441 }
3442
3443 /**
3444 * Resets the lock icon. This method is called when we start a new load and
3445 * know the url to be loaded.
3446 */
3447 private void resetLockIcon(String url) {
3448 // Save the lock-icon state (we revert to it if the load gets cancelled)
3449 saveLockIcon();
3450
3451 mLockIconType = LOCK_ICON_UNSECURE;
3452 if (URLUtil.isHttpsUrl(url)) {
3453 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003454 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003455 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3456 " reset lock icon to " + mLockIconType);
3457 }
3458 }
3459
3460 updateLockIconImage(LOCK_ICON_UNSECURE);
3461 }
3462
3463 /**
3464 * Resets the lock icon. This method is called when the icon needs to be
3465 * reset but we do not know whether we are loading a secure or not secure
3466 * page.
3467 */
3468 private void resetLockIcon() {
3469 // Save the lock-icon state (we revert to it if the load gets cancelled)
3470 saveLockIcon();
3471
3472 mLockIconType = LOCK_ICON_UNSECURE;
3473
Dave Bort31a6d1c2009-04-13 15:56:49 -07003474 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003475 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3476 " reset lock icon to " + mLockIconType);
3477 }
3478
3479 updateLockIconImage(LOCK_ICON_UNSECURE);
3480 }
3481
3482 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003483 * Update the lock icon to correspond to our latest state.
3484 */
3485 /* package */ void updateLockIconToLatest() {
3486 updateLockIconImage(mLockIconType);
3487 }
3488
3489 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003490 * Updates the lock-icon image in the title-bar.
3491 */
3492 private void updateLockIconImage(int lockIconType) {
3493 Drawable d = null;
3494 if (lockIconType == LOCK_ICON_SECURE) {
3495 d = mSecLockIcon;
3496 } else if (lockIconType == LOCK_ICON_MIXED) {
3497 d = mMixLockIcon;
3498 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003499 mTitleBar.setLock(d, getTopWindow());
3500 if (mFakeTitleBar != null) {
3501 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003502 }
3503 }
3504
3505 /**
3506 * Displays a page-info dialog.
3507 * @param tab The tab to show info about
3508 * @param fromShowSSLCertificateOnError The flag that indicates whether
3509 * this dialog was opened from the SSL-certificate-on-error dialog or
3510 * not. This is important, since we need to know whether to return to
3511 * the parent dialog or simply dismiss.
3512 */
3513 private void showPageInfo(final TabControl.Tab tab,
3514 final boolean fromShowSSLCertificateOnError) {
3515 final LayoutInflater factory = LayoutInflater
3516 .from(this);
3517
3518 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3519
3520 final WebView view = tab.getWebView();
3521
3522 String url = null;
3523 String title = null;
3524
3525 if (view == null) {
3526 url = tab.getUrl();
3527 title = tab.getTitle();
3528 } else if (view == mTabControl.getCurrentWebView()) {
3529 // Use the cached title and url if this is the current WebView
3530 url = mUrl;
3531 title = mTitle;
3532 } else {
3533 url = view.getUrl();
3534 title = view.getTitle();
3535 }
3536
3537 if (url == null) {
3538 url = "";
3539 }
3540 if (title == null) {
3541 title = "";
3542 }
3543
3544 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3545 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3546
3547 mPageInfoView = tab;
3548 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3549
3550 AlertDialog.Builder alertDialogBuilder =
3551 new AlertDialog.Builder(this)
3552 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3553 .setView(pageInfoView)
3554 .setPositiveButton(
3555 R.string.ok,
3556 new DialogInterface.OnClickListener() {
3557 public void onClick(DialogInterface dialog,
3558 int whichButton) {
3559 mPageInfoDialog = null;
3560 mPageInfoView = null;
3561 mPageInfoFromShowSSLCertificateOnError = null;
3562
3563 // if we came here from the SSL error dialog
3564 if (fromShowSSLCertificateOnError) {
3565 // go back to the SSL error dialog
3566 showSSLCertificateOnError(
3567 mSSLCertificateOnErrorView,
3568 mSSLCertificateOnErrorHandler,
3569 mSSLCertificateOnErrorError);
3570 }
3571 }
3572 })
3573 .setOnCancelListener(
3574 new DialogInterface.OnCancelListener() {
3575 public void onCancel(DialogInterface dialog) {
3576 mPageInfoDialog = null;
3577 mPageInfoView = null;
3578 mPageInfoFromShowSSLCertificateOnError = null;
3579
3580 // if we came here from the SSL error dialog
3581 if (fromShowSSLCertificateOnError) {
3582 // go back to the SSL error dialog
3583 showSSLCertificateOnError(
3584 mSSLCertificateOnErrorView,
3585 mSSLCertificateOnErrorHandler,
3586 mSSLCertificateOnErrorError);
3587 }
3588 }
3589 });
3590
3591 // if we have a main top-level page SSL certificate set or a certificate
3592 // error
3593 if (fromShowSSLCertificateOnError ||
3594 (view != null && view.getCertificate() != null)) {
3595 // add a 'View Certificate' button
3596 alertDialogBuilder.setNeutralButton(
3597 R.string.view_certificate,
3598 new DialogInterface.OnClickListener() {
3599 public void onClick(DialogInterface dialog,
3600 int whichButton) {
3601 mPageInfoDialog = null;
3602 mPageInfoView = null;
3603 mPageInfoFromShowSSLCertificateOnError = null;
3604
3605 // if we came here from the SSL error dialog
3606 if (fromShowSSLCertificateOnError) {
3607 // go back to the SSL error dialog
3608 showSSLCertificateOnError(
3609 mSSLCertificateOnErrorView,
3610 mSSLCertificateOnErrorHandler,
3611 mSSLCertificateOnErrorError);
3612 } else {
3613 // otherwise, display the top-most certificate from
3614 // the chain
3615 if (view.getCertificate() != null) {
3616 showSSLCertificate(tab);
3617 }
3618 }
3619 }
3620 });
3621 }
3622
3623 mPageInfoDialog = alertDialogBuilder.show();
3624 }
3625
3626 /**
3627 * Displays the main top-level page SSL certificate dialog
3628 * (accessible from the Page-Info dialog).
3629 * @param tab The tab to show certificate for.
3630 */
3631 private void showSSLCertificate(final TabControl.Tab tab) {
3632 final View certificateView =
3633 inflateCertificateView(tab.getWebView().getCertificate());
3634 if (certificateView == null) {
3635 return;
3636 }
3637
3638 LayoutInflater factory = LayoutInflater.from(this);
3639
3640 final LinearLayout placeholder =
3641 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3642
3643 LinearLayout ll = (LinearLayout) factory.inflate(
3644 R.layout.ssl_success, placeholder);
3645 ((TextView)ll.findViewById(R.id.success))
3646 .setText(R.string.ssl_certificate_is_valid);
3647
3648 mSSLCertificateView = tab;
3649 mSSLCertificateDialog =
3650 new AlertDialog.Builder(this)
3651 .setTitle(R.string.ssl_certificate).setIcon(
3652 R.drawable.ic_dialog_browser_certificate_secure)
3653 .setView(certificateView)
3654 .setPositiveButton(R.string.ok,
3655 new DialogInterface.OnClickListener() {
3656 public void onClick(DialogInterface dialog,
3657 int whichButton) {
3658 mSSLCertificateDialog = null;
3659 mSSLCertificateView = null;
3660
3661 showPageInfo(tab, false);
3662 }
3663 })
3664 .setOnCancelListener(
3665 new DialogInterface.OnCancelListener() {
3666 public void onCancel(DialogInterface dialog) {
3667 mSSLCertificateDialog = null;
3668 mSSLCertificateView = null;
3669
3670 showPageInfo(tab, false);
3671 }
3672 })
3673 .show();
3674 }
3675
3676 /**
3677 * Displays the SSL error certificate dialog.
3678 * @param view The target web-view.
3679 * @param handler The SSL error handler responsible for cancelling the
3680 * connection that resulted in an SSL error or proceeding per user request.
3681 * @param error The SSL error object.
3682 */
3683 private void showSSLCertificateOnError(
3684 final WebView view, final SslErrorHandler handler, final SslError error) {
3685
3686 final View certificateView =
3687 inflateCertificateView(error.getCertificate());
3688 if (certificateView == null) {
3689 return;
3690 }
3691
3692 LayoutInflater factory = LayoutInflater.from(this);
3693
3694 final LinearLayout placeholder =
3695 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3696
3697 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3698 LinearLayout ll = (LinearLayout)factory
3699 .inflate(R.layout.ssl_warning, placeholder);
3700 ((TextView)ll.findViewById(R.id.warning))
3701 .setText(R.string.ssl_untrusted);
3702 }
3703
3704 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3705 LinearLayout ll = (LinearLayout)factory
3706 .inflate(R.layout.ssl_warning, placeholder);
3707 ((TextView)ll.findViewById(R.id.warning))
3708 .setText(R.string.ssl_mismatch);
3709 }
3710
3711 if (error.hasError(SslError.SSL_EXPIRED)) {
3712 LinearLayout ll = (LinearLayout)factory
3713 .inflate(R.layout.ssl_warning, placeholder);
3714 ((TextView)ll.findViewById(R.id.warning))
3715 .setText(R.string.ssl_expired);
3716 }
3717
3718 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3719 LinearLayout ll = (LinearLayout)factory
3720 .inflate(R.layout.ssl_warning, placeholder);
3721 ((TextView)ll.findViewById(R.id.warning))
3722 .setText(R.string.ssl_not_yet_valid);
3723 }
3724
3725 mSSLCertificateOnErrorHandler = handler;
3726 mSSLCertificateOnErrorView = view;
3727 mSSLCertificateOnErrorError = error;
3728 mSSLCertificateOnErrorDialog =
3729 new AlertDialog.Builder(this)
3730 .setTitle(R.string.ssl_certificate).setIcon(
3731 R.drawable.ic_dialog_browser_certificate_partially_secure)
3732 .setView(certificateView)
3733 .setPositiveButton(R.string.ok,
3734 new DialogInterface.OnClickListener() {
3735 public void onClick(DialogInterface dialog,
3736 int whichButton) {
3737 mSSLCertificateOnErrorDialog = null;
3738 mSSLCertificateOnErrorView = null;
3739 mSSLCertificateOnErrorHandler = null;
3740 mSSLCertificateOnErrorError = null;
3741
3742 mWebViewClient.onReceivedSslError(
3743 view, handler, error);
3744 }
3745 })
3746 .setNeutralButton(R.string.page_info_view,
3747 new DialogInterface.OnClickListener() {
3748 public void onClick(DialogInterface dialog,
3749 int whichButton) {
3750 mSSLCertificateOnErrorDialog = null;
3751
3752 // do not clear the dialog state: we will
3753 // need to show the dialog again once the
3754 // user is done exploring the page-info details
3755
3756 showPageInfo(mTabControl.getTabFromView(view),
3757 true);
3758 }
3759 })
3760 .setOnCancelListener(
3761 new DialogInterface.OnCancelListener() {
3762 public void onCancel(DialogInterface dialog) {
3763 mSSLCertificateOnErrorDialog = null;
3764 mSSLCertificateOnErrorView = null;
3765 mSSLCertificateOnErrorHandler = null;
3766 mSSLCertificateOnErrorError = null;
3767
3768 mWebViewClient.onReceivedSslError(
3769 view, handler, error);
3770 }
3771 })
3772 .show();
3773 }
3774
3775 /**
3776 * Inflates the SSL certificate view (helper method).
3777 * @param certificate The SSL certificate.
3778 * @return The resultant certificate view with issued-to, issued-by,
3779 * issued-on, expires-on, and possibly other fields set.
3780 * If the input certificate is null, returns null.
3781 */
3782 private View inflateCertificateView(SslCertificate certificate) {
3783 if (certificate == null) {
3784 return null;
3785 }
3786
3787 LayoutInflater factory = LayoutInflater.from(this);
3788
3789 View certificateView = factory.inflate(
3790 R.layout.ssl_certificate, null);
3791
3792 // issued to:
3793 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3794 if (issuedTo != null) {
3795 ((TextView) certificateView.findViewById(R.id.to_common))
3796 .setText(issuedTo.getCName());
3797 ((TextView) certificateView.findViewById(R.id.to_org))
3798 .setText(issuedTo.getOName());
3799 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3800 .setText(issuedTo.getUName());
3801 }
3802
3803 // issued by:
3804 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3805 if (issuedBy != null) {
3806 ((TextView) certificateView.findViewById(R.id.by_common))
3807 .setText(issuedBy.getCName());
3808 ((TextView) certificateView.findViewById(R.id.by_org))
3809 .setText(issuedBy.getOName());
3810 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3811 .setText(issuedBy.getUName());
3812 }
3813
3814 // issued on:
3815 String issuedOn = reformatCertificateDate(
3816 certificate.getValidNotBefore());
3817 ((TextView) certificateView.findViewById(R.id.issued_on))
3818 .setText(issuedOn);
3819
3820 // expires on:
3821 String expiresOn = reformatCertificateDate(
3822 certificate.getValidNotAfter());
3823 ((TextView) certificateView.findViewById(R.id.expires_on))
3824 .setText(expiresOn);
3825
3826 return certificateView;
3827 }
3828
3829 /**
3830 * Re-formats the certificate date (Date.toString()) string to
3831 * a properly localized date string.
3832 * @return Properly localized version of the certificate date string and
3833 * the original certificate date string if fails to localize.
3834 * If the original string is null, returns an empty string "".
3835 */
3836 private String reformatCertificateDate(String certificateDate) {
3837 String reformattedDate = null;
3838
3839 if (certificateDate != null) {
3840 Date date = null;
3841 try {
3842 date = java.text.DateFormat.getInstance().parse(certificateDate);
3843 } catch (ParseException e) {
3844 date = null;
3845 }
3846
3847 if (date != null) {
3848 reformattedDate =
3849 DateFormat.getDateFormat(this).format(date);
3850 }
3851 }
3852
3853 return reformattedDate != null ? reformattedDate :
3854 (certificateDate != null ? certificateDate : "");
3855 }
3856
3857 /**
3858 * Displays an http-authentication dialog.
3859 */
3860 private void showHttpAuthentication(final HttpAuthHandler handler,
3861 final String host, final String realm, final String title,
3862 final String name, final String password, int focusId) {
3863 LayoutInflater factory = LayoutInflater.from(this);
3864 final View v = factory
3865 .inflate(R.layout.http_authentication, null);
3866 if (name != null) {
3867 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3868 }
3869 if (password != null) {
3870 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3871 }
3872
3873 String titleText = title;
3874 if (titleText == null) {
3875 titleText = getText(R.string.sign_in_to).toString().replace(
3876 "%s1", host).replace("%s2", realm);
3877 }
3878
3879 mHttpAuthHandler = handler;
3880 AlertDialog dialog = new AlertDialog.Builder(this)
3881 .setTitle(titleText)
3882 .setIcon(android.R.drawable.ic_dialog_alert)
3883 .setView(v)
3884 .setPositiveButton(R.string.action,
3885 new DialogInterface.OnClickListener() {
3886 public void onClick(DialogInterface dialog,
3887 int whichButton) {
3888 String nm = ((EditText) v
3889 .findViewById(R.id.username_edit))
3890 .getText().toString();
3891 String pw = ((EditText) v
3892 .findViewById(R.id.password_edit))
3893 .getText().toString();
3894 BrowserActivity.this.setHttpAuthUsernamePassword
3895 (host, realm, nm, pw);
3896 handler.proceed(nm, pw);
3897 mHttpAuthenticationDialog = null;
3898 mHttpAuthHandler = null;
3899 }})
3900 .setNegativeButton(R.string.cancel,
3901 new DialogInterface.OnClickListener() {
3902 public void onClick(DialogInterface dialog,
3903 int whichButton) {
3904 handler.cancel();
3905 BrowserActivity.this.resetTitleAndRevertLockIcon();
3906 mHttpAuthenticationDialog = null;
3907 mHttpAuthHandler = null;
3908 }})
3909 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3910 public void onCancel(DialogInterface dialog) {
3911 handler.cancel();
3912 BrowserActivity.this.resetTitleAndRevertLockIcon();
3913 mHttpAuthenticationDialog = null;
3914 mHttpAuthHandler = null;
3915 }})
3916 .create();
3917 // Make the IME appear when the dialog is displayed if applicable.
3918 dialog.getWindow().setSoftInputMode(
3919 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3920 dialog.show();
3921 if (focusId != 0) {
3922 dialog.findViewById(focusId).requestFocus();
3923 } else {
3924 v.findViewById(R.id.username_edit).requestFocus();
3925 }
3926 mHttpAuthenticationDialog = dialog;
3927 }
3928
3929 public int getProgress() {
3930 WebView w = mTabControl.getCurrentWebView();
3931 if (w != null) {
3932 return w.getProgress();
3933 } else {
3934 return 100;
3935 }
3936 }
3937
3938 /**
3939 * Set HTTP authentication password.
3940 *
3941 * @param host The host for the password
3942 * @param realm The realm for the password
3943 * @param username The username for the password. If it is null, it means
3944 * password can't be saved.
3945 * @param password The password
3946 */
3947 public void setHttpAuthUsernamePassword(String host, String realm,
3948 String username,
3949 String password) {
3950 WebView w = mTabControl.getCurrentWebView();
3951 if (w != null) {
3952 w.setHttpAuthUsernamePassword(host, realm, username, password);
3953 }
3954 }
3955
3956 /**
3957 * connectivity manager says net has come or gone... inform the user
3958 * @param up true if net has come up, false if net has gone down
3959 */
3960 public void onNetworkToggle(boolean up) {
3961 if (up == mIsNetworkUp) {
3962 return;
3963 } else if (up) {
3964 mIsNetworkUp = true;
3965 if (mAlertDialog != null) {
3966 mAlertDialog.cancel();
3967 mAlertDialog = null;
3968 }
3969 } else {
3970 mIsNetworkUp = false;
3971 if (mInLoad && mAlertDialog == null) {
3972 mAlertDialog = new AlertDialog.Builder(this)
3973 .setTitle(R.string.loadSuspendedTitle)
3974 .setMessage(R.string.loadSuspended)
3975 .setPositiveButton(R.string.ok, null)
3976 .show();
3977 }
3978 }
3979 WebView w = mTabControl.getCurrentWebView();
3980 if (w != null) {
3981 w.setNetworkAvailable(up);
3982 }
3983 }
3984
3985 @Override
3986 protected void onActivityResult(int requestCode, int resultCode,
3987 Intent intent) {
3988 switch (requestCode) {
3989 case COMBO_PAGE:
3990 if (resultCode == RESULT_OK && intent != null) {
3991 String data = intent.getAction();
3992 Bundle extras = intent.getExtras();
3993 if (extras != null && extras.getBoolean("new_window", false)) {
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003994 final TabControl.Tab newTab = openTab(data);
3995 if (mSettings.openInBackground() &&
Leon Scroggins1f005d32009-08-10 17:36:42 -04003996 newTab != null) {
Patrick Scottb0e4fc72009-07-14 10:49:22 -04003997 mTabControl.populatePickerData(newTab);
3998 mTabControl.setCurrentTab(newTab);
Leon Scroggins1f005d32009-08-10 17:36:42 -04003999 int newIndex = mTabControl.getCurrentIndex();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04004000 mTitleBar.setCurrentTab(newIndex);
Patrick Scottb0e4fc72009-07-14 10:49:22 -04004001 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004002 } else {
4003 final TabControl.Tab currentTab =
4004 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04004005 dismissSubWindow(currentTab);
4006 if (data != null && data.length() != 0) {
4007 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004008 }
4009 }
4010 }
4011 break;
4012 default:
4013 break;
4014 }
Leon Scroggins30444232009-09-04 18:36:20 -04004015 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004016 }
4017
4018 /*
4019 * This method is called as a result of the user selecting the options
4020 * menu to see the download window, or when a download changes state. It
4021 * shows the download window ontop of the current window.
4022 */
4023 /* package */ void viewDownloads(Uri downloadRecord) {
4024 Intent intent = new Intent(this,
4025 BrowserDownloadPage.class);
4026 intent.setData(downloadRecord);
4027 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4028
4029 }
4030
Leon Scroggins160a7e72009-08-14 18:28:01 -04004031 /**
4032 * Open the Go page.
4033 * @param startWithHistory If true, open starting on the history tab.
4034 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004035 */
Leon Scroggins30444232009-09-04 18:36:20 -04004036 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004037 WebView current = mTabControl.getCurrentWebView();
4038 if (current == null) {
4039 return;
4040 }
4041 Intent intent = new Intent(this,
4042 CombinedBookmarkHistoryActivity.class);
4043 String title = current.getTitle();
4044 String url = current.getUrl();
4045 // Just in case the user opens bookmarks before a page finishes loading
4046 // so the current history item, and therefore the page, is null.
4047 if (null == url) {
4048 url = mLastEnteredUrl;
4049 // This can happen.
4050 if (null == url) {
4051 url = mSettings.getHomePage();
4052 }
4053 }
4054 // In case the web page has not yet received its associated title.
4055 if (title == null) {
4056 title = url;
4057 }
4058 intent.putExtra("title", title);
4059 intent.putExtra("url", url);
Leon Scroggins30444232009-09-04 18:36:20 -04004060 // Disable opening in a new window if we have maxed out the windows
4061 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4062 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004063 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004064 if (startWithHistory) {
4065 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4066 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4067 }
4068 startActivityForResult(intent, COMBO_PAGE);
4069 }
4070
4071 // Called when loading from context menu or LOAD_URL message
4072 private void loadURL(WebView view, String url) {
4073 // In case the user enters nothing.
4074 if (url != null && url.length() != 0 && view != null) {
4075 url = smartUrlFilter(url);
4076 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4077 view.loadUrl(url);
4078 }
4079 }
4080 }
4081
The Android Open Source Project0c908882009-03-03 19:32:16 -08004082 private String smartUrlFilter(Uri inUri) {
4083 if (inUri != null) {
4084 return smartUrlFilter(inUri.toString());
4085 }
4086 return null;
4087 }
4088
4089
4090 // get window count
4091
4092 int getWindowCount(){
4093 if(mTabControl != null){
4094 return mTabControl.getTabCount();
4095 }
4096 return 0;
4097 }
4098
Feng Qianb34f87a2009-03-24 21:27:26 -07004099 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004100 "(?i)" + // switch on case insensitive matching
4101 "(" + // begin group for schema
4102 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004103 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004104 ")" +
4105 "(.*)" );
4106
4107 /**
4108 * Attempts to determine whether user input is a URL or search
4109 * terms. Anything with a space is passed to search.
4110 *
4111 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4112 * "Http://" converts to "http://"
4113 *
4114 * @return Original or modified URL
4115 *
4116 */
4117 String smartUrlFilter(String url) {
4118
4119 String inUrl = url.trim();
4120 boolean hasSpace = inUrl.indexOf(' ') != -1;
4121
4122 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4123 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004124 // force scheme to lowercase
4125 String scheme = matcher.group(1);
4126 String lcScheme = scheme.toLowerCase();
4127 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004128 inUrl = lcScheme + matcher.group(2);
4129 }
4130 if (hasSpace) {
4131 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004132 }
4133 return inUrl;
4134 }
4135 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004136 // FIXME: Is this the correct place to add to searches?
4137 // what if someone else calls this function?
4138 int shortcut = parseUrlShortcut(inUrl);
4139 if (shortcut != SHORTCUT_INVALID) {
4140 Browser.addSearchUrl(mResolver, inUrl);
4141 String query = inUrl.substring(2);
4142 switch (shortcut) {
4143 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004144 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004145 case SHORTCUT_WIKIPEDIA_SEARCH:
4146 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4147 case SHORTCUT_DICTIONARY_SEARCH:
4148 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4149 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004150 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004151 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004152 }
4153 }
4154 } else {
4155 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4156 return URLUtil.guessUrl(inUrl);
4157 }
4158 }
4159
4160 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004161 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004162 }
4163
Ben Murdochbff2d602009-07-01 20:19:05 +01004164 /* package */ void setShouldShowErrorConsole(boolean flag) {
4165 if (flag == mShouldShowErrorConsole) {
4166 // Nothing to do.
4167 return;
4168 }
4169
4170 mShouldShowErrorConsole = flag;
4171
4172 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4173
4174 if (flag) {
4175 // Setting the show state of the console will cause it's the layout to be inflated.
4176 if (errorConsole.numberOfErrors() > 0) {
4177 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4178 } else {
4179 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4180 }
4181
4182 // Now we can add it to the main view.
4183 mErrorConsoleContainer.addView(errorConsole,
4184 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4185 ViewGroup.LayoutParams.WRAP_CONTENT));
4186 } else {
4187 mErrorConsoleContainer.removeView(errorConsole);
4188 }
4189
4190 }
4191
The Android Open Source Project0c908882009-03-03 19:32:16 -08004192 private final static int LOCK_ICON_UNSECURE = 0;
4193 private final static int LOCK_ICON_SECURE = 1;
4194 private final static int LOCK_ICON_MIXED = 2;
4195
4196 private int mLockIconType = LOCK_ICON_UNSECURE;
4197 private int mPrevLockType = LOCK_ICON_UNSECURE;
4198
4199 private BrowserSettings mSettings;
4200 private TabControl mTabControl;
4201 private ContentResolver mResolver;
4202 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004203 private View mCustomView;
4204 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004205 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004206
4207 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4208 // view, we should rewrite this.
4209 private int mCurrentMenuState = 0;
4210 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004211 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004212 private static final int EMPTY_MENU = -1;
4213 private Menu mMenu;
4214
4215 private FindDialog mFindDialog;
4216 // Used to prevent chording to result in firing two shortcuts immediately
4217 // one after another. Fixes bug 1211714.
4218 boolean mCanChord;
4219
4220 private boolean mInLoad;
4221 private boolean mIsNetworkUp;
4222
4223 private boolean mPageStarted;
4224 private boolean mActivityInPause = true;
4225
4226 private boolean mMenuIsDown;
4227
4228 private final KeyTracker mKeyTracker = new KeyTracker(this);
4229
4230 // As trackball doesn't send repeat down, we have to track it ourselves
4231 private boolean mTrackTrackball;
4232
4233 private static boolean mInTrace;
4234
4235 // Performance probe
4236 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4237 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4238 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4239 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4240 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4241 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4242 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4243 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4244 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4245 };
4246
4247 private long mStart;
4248 private long mProcessStart;
4249 private long mUserStart;
4250 private long mSystemStart;
4251 private long mIdleStart;
4252 private long mIrqStart;
4253
4254 private long mUiStart;
4255
4256 private Drawable mMixLockIcon;
4257 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004258
4259 /* hold a ref so we can auto-cancel if necessary */
4260 private AlertDialog mAlertDialog;
4261
4262 // Wait for credentials before loading google.com
4263 private ProgressDialog mCredsDlg;
4264
4265 // The up-to-date URL and title (these can be different from those stored
4266 // in WebView, since it takes some time for the information in WebView to
4267 // get updated)
4268 private String mUrl;
4269 private String mTitle;
4270
4271 // As PageInfo has different style for landscape / portrait, we have
4272 // to re-open it when configuration changed
4273 private AlertDialog mPageInfoDialog;
4274 private TabControl.Tab mPageInfoView;
4275 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4276 // dialog, we should not just dismiss it, but should get back to the
4277 // SSL-certificate-on-error dialog. This flag is used to store this state
4278 private Boolean mPageInfoFromShowSSLCertificateOnError;
4279
4280 // as SSLCertificateOnError has different style for landscape / portrait,
4281 // we have to re-open it when configuration changed
4282 private AlertDialog mSSLCertificateOnErrorDialog;
4283 private WebView mSSLCertificateOnErrorView;
4284 private SslErrorHandler mSSLCertificateOnErrorHandler;
4285 private SslError mSSLCertificateOnErrorError;
4286
4287 // as SSLCertificate has different style for landscape / portrait, we
4288 // have to re-open it when configuration changed
4289 private AlertDialog mSSLCertificateDialog;
4290 private TabControl.Tab mSSLCertificateView;
4291
4292 // as HttpAuthentication has different style for landscape / portrait, we
4293 // have to re-open it when configuration changed
4294 private AlertDialog mHttpAuthenticationDialog;
4295 private HttpAuthHandler mHttpAuthHandler;
4296
4297 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4298 new FrameLayout.LayoutParams(
4299 ViewGroup.LayoutParams.FILL_PARENT,
4300 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004301 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4302 new FrameLayout.LayoutParams(
4303 ViewGroup.LayoutParams.FILL_PARENT,
4304 ViewGroup.LayoutParams.FILL_PARENT,
4305 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004306 // Google search
4307 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004308 // Wikipedia search
4309 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4310 // Dictionary search
4311 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4312 // Google Mobile Local search
4313 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4314
4315 final static String QUERY_PLACE_HOLDER = "%s";
4316
4317 // "source" parameter for Google search through search key
4318 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4319 // "source" parameter for Google search through goto menu
4320 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4321 // "source" parameter for Google search through simplily type
4322 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4323 // "source" parameter for Google search suggested by the browser
4324 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4325 // "source" parameter for Google search from unknown source
4326 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4327
4328 private final static String LOGTAG = "browser";
4329
The Android Open Source Project0c908882009-03-03 19:32:16 -08004330 private String mLastEnteredUrl;
4331
4332 private PowerManager.WakeLock mWakeLock;
4333 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4334
4335 private Toast mStopToast;
4336
Leon Scroggins1f005d32009-08-10 17:36:42 -04004337 private TitleBarSet mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004338
Ben Murdochbff2d602009-07-01 20:19:05 +01004339 private LinearLayout mErrorConsoleContainer = null;
4340 private boolean mShouldShowErrorConsole = false;
4341
The Android Open Source Project0c908882009-03-03 19:32:16 -08004342 // As the ids are dynamically created, we can't guarantee that they will
4343 // be in sequence, so this static array maps ids to a window number.
4344 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4345 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4346 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4347 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4348
4349 // monitor platform changes
4350 private IntentFilter mNetworkStateChangedFilter;
4351 private BroadcastReceiver mNetworkStateIntentReceiver;
4352
Grace Klobab4da0ad2009-05-14 14:45:40 -07004353 private BroadcastReceiver mPackageInstallationReceiver;
4354
The Android Open Source Project0c908882009-03-03 19:32:16 -08004355 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004356 final static int COMBO_PAGE = 1;
4357 final static int DOWNLOAD_PAGE = 2;
4358 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004359
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004360 /**
4361 * A UrlData class to abstract how the content will be set to WebView.
4362 * This base class uses loadUrl to show the content.
4363 */
4364 private static class UrlData {
4365 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004366 byte[] mPostData;
4367
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004368 UrlData(String url) {
4369 this.mUrl = url;
4370 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004371
4372 void setPostData(byte[] postData) {
4373 mPostData = postData;
4374 }
4375
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004376 boolean isEmpty() {
4377 return mUrl == null || mUrl.length() == 0;
4378 }
4379
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004380 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004381 if (mPostData != null) {
4382 webView.postUrl(mUrl, mPostData);
4383 } else {
4384 webView.loadUrl(mUrl);
4385 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004386 }
4387 };
4388
4389 /**
4390 * A subclass of UrlData class that can display inlined content using
4391 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4392 */
4393 private static class InlinedUrlData extends UrlData {
4394 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4395 super(failUrl);
4396 mInlined = inlined;
4397 mMimeType = mimeType;
4398 mEncoding = encoding;
4399 }
4400 String mMimeType;
4401 String mInlined;
4402 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004403 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004404 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004405 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004406 }
4407
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004408 @Override
4409 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004410 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4411 }
4412 }
4413
Leon Scroggins1f005d32009-08-10 17:36:42 -04004414 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004415}