blob: 4188fc75de8bc697174cccb7f7d1b46878f65677 [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() {
Leon Scroggins43de6162009-09-14 19:59:58 -0400949 if (mFakeTitleBar == null || mActiveTabsPage != 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);
Patrick Scottdb22ea72009-09-15 10:57:22 -04001379 resetTitle();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001380 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001381 }
1382
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001383 /* package */ TabControl.Tab openTabToHomePage() {
1384 return openTabAndShow(mSettings.getHomePage(), false, null);
1385 }
1386
Leon Scroggins1f005d32009-08-10 17:36:42 -04001387 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001388 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001389 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001390 // This is the last tab. Open a new one, with the home
1391 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001392 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001393 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001394 return;
1395 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001396 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001397 int indexToShow = -1;
1398 if (parent != null) {
1399 indexToShow = mTabControl.getTabIndex(parent);
1400 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001401 final int currentIndex = mTabControl.getCurrentIndex();
1402 // Try to move to the tab to the right
1403 indexToShow = currentIndex + 1;
1404 if (indexToShow > mTabControl.getTabCount() - 1) {
1405 // Try to move to the tab to the left
1406 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001407 }
1408 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001409 if (switchToTab(indexToShow)) {
1410 // Close window
1411 closeTab(current);
1412 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001413 }
1414
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001415 private ActiveTabsPage mActiveTabsPage;
1416
1417 /**
1418 * Remove the active tabs page.
1419 * @param needToAttach If true, the active tabs page did not attach a tab
1420 * to the content view, so we need to do that here.
1421 */
1422 /* package */ void removeActiveTabPage(boolean needToAttach) {
1423 mContentView.removeView(mActiveTabsPage);
1424 mActiveTabsPage = null;
1425 mMenuState = R.id.MAIN_MENU;
1426 if (needToAttach) {
1427 attachTabToContentView(mTabControl.getCurrentTab());
1428 }
1429 getTopWindow().requestFocus();
1430 }
1431
The Android Open Source Project0c908882009-03-03 19:32:16 -08001432 @Override
1433 public boolean onOptionsItemSelected(MenuItem item) {
1434 if (!mCanChord) {
1435 // The user has already fired a shortcut with this hold down of the
1436 // menu key.
1437 return false;
1438 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001439 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001440 return false;
1441 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001442 if (mMenuIsDown) {
1443 // The shortcut action consumes the MENU. Even if it is still down,
1444 // it won't trigger the next shortcut action. In the case of the
1445 // shortcut action triggering a new activity, like Bookmarks, we
1446 // won't get onKeyUp for MENU. So it is important to reset it here.
1447 mMenuIsDown = false;
1448 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001449 switch (item.getItemId()) {
1450 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001451 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001452 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001453 break;
1454
Leon Scroggins64b80f32009-08-07 12:03:34 -04001455 case R.id.goto_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001456 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001457 break;
1458
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001459 case R.id.active_tabs_menu_id:
1460 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1461 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001462 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001463 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1464 mActiveTabsPage.requestFocus();
1465 mMenuState = EMPTY_MENU;
1466 break;
1467
Leon Scroggins1f005d32009-08-10 17:36:42 -04001468 case R.id.add_bookmark_menu_id:
1469 Intent i = new Intent(BrowserActivity.this,
1470 AddBookmarkPage.class);
1471 WebView w = getTopWindow();
1472 i.putExtra("url", w.getUrl());
1473 i.putExtra("title", w.getTitle());
1474 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001475 break;
1476
1477 case R.id.stop_reload_menu_id:
1478 if (mInLoad) {
1479 stopLoading();
1480 } else {
1481 getTopWindow().reload();
1482 }
1483 break;
1484
1485 case R.id.back_menu_id:
1486 getTopWindow().goBack();
1487 break;
1488
1489 case R.id.forward_menu_id:
1490 getTopWindow().goForward();
1491 break;
1492
1493 case R.id.close_menu_id:
1494 // Close the subwindow if it exists.
1495 if (mTabControl.getCurrentSubWindow() != null) {
1496 dismissSubWindow(mTabControl.getCurrentTab());
1497 break;
1498 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001499 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001500 break;
1501
1502 case R.id.homepage_menu_id:
1503 TabControl.Tab current = mTabControl.getCurrentTab();
1504 if (current != null) {
1505 dismissSubWindow(current);
1506 current.getWebView().loadUrl(mSettings.getHomePage());
1507 }
1508 break;
1509
1510 case R.id.preferences_menu_id:
1511 Intent intent = new Intent(this,
1512 BrowserPreferencesPage.class);
1513 startActivityForResult(intent, PREFERENCES_PAGE);
1514 break;
1515
1516 case R.id.find_menu_id:
1517 if (null == mFindDialog) {
1518 mFindDialog = new FindDialog(this);
1519 }
1520 mFindDialog.setWebView(getTopWindow());
1521 mFindDialog.show();
1522 mMenuState = EMPTY_MENU;
1523 break;
1524
1525 case R.id.select_text_id:
1526 getTopWindow().emulateShiftHeld();
1527 break;
1528 case R.id.page_info_menu_id:
1529 showPageInfo(mTabControl.getCurrentTab(), false);
1530 break;
1531
1532 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001533 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001534 break;
1535
1536 case R.id.share_page_menu_id:
1537 Browser.sendString(this, getTopWindow().getUrl());
1538 break;
1539
1540 case R.id.dump_nav_menu_id:
1541 getTopWindow().debugDump();
1542 break;
1543
1544 case R.id.zoom_in_menu_id:
1545 getTopWindow().zoomIn();
1546 break;
1547
1548 case R.id.zoom_out_menu_id:
1549 getTopWindow().zoomOut();
1550 break;
1551
1552 case R.id.view_downloads_menu_id:
1553 viewDownloads(null);
1554 break;
1555
The Android Open Source Project0c908882009-03-03 19:32:16 -08001556 case R.id.window_one_menu_id:
1557 case R.id.window_two_menu_id:
1558 case R.id.window_three_menu_id:
1559 case R.id.window_four_menu_id:
1560 case R.id.window_five_menu_id:
1561 case R.id.window_six_menu_id:
1562 case R.id.window_seven_menu_id:
1563 case R.id.window_eight_menu_id:
1564 {
1565 int menuid = item.getItemId();
1566 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1567 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1568 TabControl.Tab desiredTab = mTabControl.getTab(id);
1569 if (desiredTab != null &&
1570 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001571 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001572 }
1573 break;
1574 }
1575 }
1576 }
1577 break;
1578
1579 default:
1580 if (!super.onOptionsItemSelected(item)) {
1581 return false;
1582 }
1583 // Otherwise fall through.
1584 }
1585 mCanChord = false;
1586 return true;
1587 }
1588
1589 public void closeFind() {
1590 mMenuState = R.id.MAIN_MENU;
1591 }
1592
1593 @Override public boolean onPrepareOptionsMenu(Menu menu)
1594 {
1595 // This happens when the user begins to hold down the menu key, so
1596 // allow them to chord to get a shortcut.
1597 mCanChord = true;
1598 // Note: setVisible will decide whether an item is visible; while
1599 // setEnabled() will decide whether an item is enabled, which also means
1600 // whether the matching shortcut key will function.
1601 super.onPrepareOptionsMenu(menu);
1602 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001603 case EMPTY_MENU:
1604 if (mCurrentMenuState != mMenuState) {
1605 menu.setGroupVisible(R.id.MAIN_MENU, false);
1606 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1607 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001608 }
1609 break;
1610 default:
1611 if (mCurrentMenuState != mMenuState) {
1612 menu.setGroupVisible(R.id.MAIN_MENU, true);
1613 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1614 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001615 }
1616 final WebView w = getTopWindow();
1617 boolean canGoBack = false;
1618 boolean canGoForward = false;
1619 boolean isHome = false;
1620 if (w != null) {
1621 canGoBack = w.canGoBack();
1622 canGoForward = w.canGoForward();
1623 isHome = mSettings.getHomePage().equals(w.getUrl());
1624 }
1625 final MenuItem back = menu.findItem(R.id.back_menu_id);
1626 back.setEnabled(canGoBack);
1627
1628 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1629 home.setEnabled(!isHome);
1630
1631 menu.findItem(R.id.forward_menu_id)
1632 .setEnabled(canGoForward);
1633
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001634 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1635 mTabControl.getTabCount() < TabControl.MAX_TABS);
1636
The Android Open Source Project0c908882009-03-03 19:32:16 -08001637 // decide whether to show the share link option
1638 PackageManager pm = getPackageManager();
1639 Intent send = new Intent(Intent.ACTION_SEND);
1640 send.setType("text/plain");
1641 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1642 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1643
The Android Open Source Project0c908882009-03-03 19:32:16 -08001644 boolean isNavDump = mSettings.isNavDump();
1645 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1646 nav.setVisible(isNavDump);
1647 nav.setEnabled(isNavDump);
1648 break;
1649 }
1650 mCurrentMenuState = mMenuState;
1651 return true;
1652 }
1653
1654 @Override
1655 public void onCreateContextMenu(ContextMenu menu, View v,
1656 ContextMenuInfo menuInfo) {
1657 WebView webview = (WebView) v;
1658 WebView.HitTestResult result = webview.getHitTestResult();
1659 if (result == null) {
1660 return;
1661 }
1662
1663 int type = result.getType();
1664 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1665 Log.w(LOGTAG,
1666 "We should not show context menu when nothing is touched");
1667 return;
1668 }
1669 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1670 // let TextView handles context menu
1671 return;
1672 }
1673
1674 // Note, http://b/issue?id=1106666 is requesting that
1675 // an inflated menu can be used again. This is not available
1676 // yet, so inflate each time (yuk!)
1677 MenuInflater inflater = getMenuInflater();
1678 inflater.inflate(R.menu.browsercontext, menu);
1679
1680 // Show the correct menu group
1681 String extra = result.getExtra();
1682 menu.setGroupVisible(R.id.PHONE_MENU,
1683 type == WebView.HitTestResult.PHONE_TYPE);
1684 menu.setGroupVisible(R.id.EMAIL_MENU,
1685 type == WebView.HitTestResult.EMAIL_TYPE);
1686 menu.setGroupVisible(R.id.GEO_MENU,
1687 type == WebView.HitTestResult.GEO_TYPE);
1688 menu.setGroupVisible(R.id.IMAGE_MENU,
1689 type == WebView.HitTestResult.IMAGE_TYPE
1690 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1691 menu.setGroupVisible(R.id.ANCHOR_MENU,
1692 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1693 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1694
1695 // Setup custom handling depending on the type
1696 switch (type) {
1697 case WebView.HitTestResult.PHONE_TYPE:
1698 menu.setHeaderTitle(Uri.decode(extra));
1699 menu.findItem(R.id.dial_context_menu_id).setIntent(
1700 new Intent(Intent.ACTION_VIEW, Uri
1701 .parse(WebView.SCHEME_TEL + extra)));
1702 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1703 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1704 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1705 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1706 addIntent);
1707 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1708 new Copy(extra));
1709 break;
1710
1711 case WebView.HitTestResult.EMAIL_TYPE:
1712 menu.setHeaderTitle(extra);
1713 menu.findItem(R.id.email_context_menu_id).setIntent(
1714 new Intent(Intent.ACTION_VIEW, Uri
1715 .parse(WebView.SCHEME_MAILTO + extra)));
1716 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1717 new Copy(extra));
1718 break;
1719
1720 case WebView.HitTestResult.GEO_TYPE:
1721 menu.setHeaderTitle(extra);
1722 menu.findItem(R.id.map_context_menu_id).setIntent(
1723 new Intent(Intent.ACTION_VIEW, Uri
1724 .parse(WebView.SCHEME_GEO
1725 + URLEncoder.encode(extra))));
1726 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1727 new Copy(extra));
1728 break;
1729
1730 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1731 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1732 TextView titleView = (TextView) LayoutInflater.from(this)
1733 .inflate(android.R.layout.browser_link_context_header,
1734 null);
1735 titleView.setText(extra);
1736 menu.setHeaderView(titleView);
1737 // decide whether to show the open link in new tab option
1738 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1739 mTabControl.getTabCount() < TabControl.MAX_TABS);
1740 PackageManager pm = getPackageManager();
1741 Intent send = new Intent(Intent.ACTION_SEND);
1742 send.setType("text/plain");
1743 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1744 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1745 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1746 break;
1747 }
1748 // otherwise fall through to handle image part
1749 case WebView.HitTestResult.IMAGE_TYPE:
1750 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1751 menu.setHeaderTitle(extra);
1752 }
1753 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1754 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1755 menu.findItem(R.id.download_context_menu_id).
1756 setOnMenuItemClickListener(new Download(extra));
1757 break;
1758
1759 default:
1760 Log.w(LOGTAG, "We should not get here.");
1761 break;
1762 }
1763 }
1764
The Android Open Source Project0c908882009-03-03 19:32:16 -08001765 // Attach the given tab to the content view.
1766 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001767 // Attach the container that contains the main WebView and any other UI
1768 // associated with the tab.
1769 mContentView.addView(t.getContainer(), COVER_SCREEN_PARAMS);
Ben Murdochbff2d602009-07-01 20:19:05 +01001770
1771 if (mShouldShowErrorConsole) {
1772 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1773 if (errorConsole.numberOfErrors() == 0) {
1774 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1775 } else {
1776 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1777 }
1778
1779 mErrorConsoleContainer.addView(errorConsole,
1780 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1781 ViewGroup.LayoutParams.WRAP_CONTENT));
1782 }
1783
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001784 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001785 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001786 // Attach the sub window if necessary
1787 attachSubWindow(t);
1788 // Request focus on the top window.
1789 t.getTopWindow().requestFocus();
1790 }
1791
1792 // Attach a sub window to the main WebView of the given tab.
1793 private void attachSubWindow(TabControl.Tab t) {
1794 // If a sub window exists, attach it to the content view.
1795 final WebView subView = t.getSubWebView();
1796 if (subView != null) {
1797 final View container = t.getSubWebViewContainer();
1798 mContentView.addView(container, COVER_SCREEN_PARAMS);
1799 subView.requestFocus();
1800 }
1801 }
1802
1803 // Remove the given tab from the content view.
1804 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001805 // Remove the container that contains the main WebView.
1806 mContentView.removeView(t.getContainer());
Ben Murdochbff2d602009-07-01 20:19:05 +01001807
1808 if (mTabControl.getCurrentErrorConsole(false) != null) {
1809 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1810 }
1811
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001812 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001813 if (view != null) {
1814 view.setEmbeddedTitleBar(null);
1815 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001816
The Android Open Source Project0c908882009-03-03 19:32:16 -08001817 // Remove the sub window if it exists.
1818 if (t.getSubWebView() != null) {
1819 mContentView.removeView(t.getSubWebViewContainer());
1820 }
1821 }
1822
1823 // Remove the sub window if it exists. Also called by TabControl when the
1824 // user clicks the 'X' to dismiss a sub window.
1825 /* package */ void dismissSubWindow(TabControl.Tab t) {
1826 final WebView mainView = t.getWebView();
1827 if (t.getSubWebView() != null) {
1828 // Remove the container view and request focus on the main WebView.
1829 mContentView.removeView(t.getSubWebViewContainer());
1830 mainView.requestFocus();
1831 // Tell the TabControl to dismiss the subwindow. This will destroy
1832 // the WebView.
1833 mTabControl.dismissSubWindow(t);
1834 }
1835 }
1836
Leon Scroggins1f005d32009-08-10 17:36:42 -04001837 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001838 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001839 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1840 String appId) {
1841 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001842 }
1843
1844 // This method does a ton of stuff. It will attempt to create a new tab
1845 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001846 // url isn't null, it will load the given url.
1847 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001848 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001849 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1850 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1851 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001852 final TabControl.Tab tab = mTabControl.createNewTab(
1853 closeOnExit, appId, urlData.mUrl);
1854 WebView webview = tab.getWebView();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001855 mTitleBar.addTab(webview, true);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001856 // If the last tab was removed from the active tabs page, currentTab
1857 // will be null.
1858 if (currentTab != null) {
1859 removeTabFromContentView(currentTab);
1860 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001861 attachTabToContentView(tab);
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001862 // We must set the new tab as the current tab to reflect the old
1863 // animation behavior.
1864 mTabControl.setCurrentTab(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001865 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001866 urlData.loadIn(webview);
1867 }
1868 return tab;
1869 } else {
1870 // Get rid of the subwindow if it exists
1871 dismissSubWindow(currentTab);
1872 if (!urlData.isEmpty()) {
1873 // Load the given url.
1874 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001875 }
1876 }
Grace Klobac9181842009-04-14 08:53:22 -07001877 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001878 }
1879
Grace Klobac9181842009-04-14 08:53:22 -07001880 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001881 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001882 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001883 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001884 WebView view = t.getWebView();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001885 mTitleBar.addTab(view, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001886 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001887 }
Grace Klobac9181842009-04-14 08:53:22 -07001888 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001889 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001890 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001891 }
1892 }
1893
1894 private class Copy implements OnMenuItemClickListener {
1895 private CharSequence mText;
1896
1897 public boolean onMenuItemClick(MenuItem item) {
1898 copy(mText);
1899 return true;
1900 }
1901
1902 public Copy(CharSequence toCopy) {
1903 mText = toCopy;
1904 }
1905 }
1906
1907 private class Download implements OnMenuItemClickListener {
1908 private String mText;
1909
1910 public boolean onMenuItemClick(MenuItem item) {
1911 onDownloadStartNoStream(mText, null, null, null, -1);
1912 return true;
1913 }
1914
1915 public Download(String toDownload) {
1916 mText = toDownload;
1917 }
1918 }
1919
1920 private void copy(CharSequence text) {
1921 try {
1922 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1923 if (clip != null) {
1924 clip.setClipboardText(text);
1925 }
1926 } catch (android.os.RemoteException e) {
1927 Log.e(LOGTAG, "Copy failed", e);
1928 }
1929 }
1930
1931 /**
1932 * Resets the browser title-view to whatever it must be (for example, if we
1933 * load a page from history).
1934 */
1935 private void resetTitle() {
1936 resetLockIcon();
1937 resetTitleIconAndProgress();
1938 }
1939
1940 /**
1941 * Resets the browser title-view to whatever it must be
1942 * (for example, if we had a loading error)
1943 * When we have a new page, we call resetTitle, when we
1944 * have to reset the titlebar to whatever it used to be
1945 * (for example, if the user chose to stop loading), we
1946 * call resetTitleAndRevertLockIcon.
1947 */
1948 /* package */ void resetTitleAndRevertLockIcon() {
1949 revertLockIcon();
1950 resetTitleIconAndProgress();
1951 }
1952
1953 /**
1954 * Reset the title, favicon, and progress.
1955 */
1956 private void resetTitleIconAndProgress() {
1957 WebView current = mTabControl.getCurrentWebView();
1958 if (current == null) {
1959 return;
1960 }
1961 resetTitleAndIcon(current);
1962 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001963 mWebChromeClient.onProgressChanged(current, progress);
1964 }
1965
1966 // Reset the title and the icon based on the given item.
1967 private void resetTitleAndIcon(WebView view) {
1968 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1969 if (item != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001970 setUrlTitle(item.getUrl(), item.getTitle(), view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001971 setFavicon(item.getFavicon());
1972 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001973 setUrlTitle(null, null, view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001974 setFavicon(null);
1975 }
1976 }
1977
1978 /**
1979 * Sets a title composed of the URL and the title string.
1980 * @param url The URL of the site being loaded.
1981 * @param title The title of the site being loaded.
1982 */
Leon Scroggins1f005d32009-08-10 17:36:42 -04001983 private void setUrlTitle(String url, String title, WebView view) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001984 mUrl = url;
1985 mTitle = title;
1986
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001987 mTitleBar.setTitleAndUrl(title, url, view);
1988 if (mFakeTitleBar != null) {
1989 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001990 }
1991 }
1992
1993 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001994 * @param url The URL to build a title version of the URL from.
1995 * @return The title version of the URL or null if fails.
1996 * The title version of the URL can be either the URL hostname,
1997 * or the hostname with an "https://" prefix (for secure URLs),
1998 * or an empty string if, for example, the URL in question is a
1999 * file:// URL with no hostname.
2000 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002001 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002002 String titleUrl = null;
2003
2004 if (url != null) {
2005 try {
2006 // parse the url string
2007 URL urlObj = new URL(url);
2008 if (urlObj != null) {
2009 titleUrl = "";
2010
2011 String protocol = urlObj.getProtocol();
2012 String host = urlObj.getHost();
2013
2014 if (host != null && 0 < host.length()) {
2015 titleUrl = host;
2016 if (protocol != null) {
2017 // if a secure site, add an "https://" prefix!
2018 if (protocol.equalsIgnoreCase("https")) {
2019 titleUrl = protocol + "://" + host;
2020 }
2021 }
2022 }
2023 }
2024 } catch (MalformedURLException e) {}
2025 }
2026
2027 return titleUrl;
2028 }
2029
2030 // Set the favicon in the title bar.
2031 private void setFavicon(Bitmap icon) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002032 mTitleBar.setFavicon(icon, getTopWindow());
2033 if (mFakeTitleBar != null) {
2034 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002035 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002036 }
2037
2038 /**
2039 * Saves the current lock-icon state before resetting
2040 * the lock icon. If we have an error, we may need to
2041 * roll back to the previous state.
2042 */
2043 private void saveLockIcon() {
2044 mPrevLockType = mLockIconType;
2045 }
2046
2047 /**
2048 * Reverts the lock-icon state to the last saved state,
2049 * for example, if we had an error, and need to cancel
2050 * the load.
2051 */
2052 private void revertLockIcon() {
2053 mLockIconType = mPrevLockType;
2054
Dave Bort31a6d1c2009-04-13 15:56:49 -07002055 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002056 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2057 " revert lock icon to " + mLockIconType);
2058 }
2059
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002060 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002061 }
2062
Leon Scroggins1f005d32009-08-10 17:36:42 -04002063 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002064 * Close the tab, remove its associated title bar, and adjust mTabControl's
2065 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002066 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002067 /* package */ void closeTab(TabControl.Tab t) {
2068 int currentIndex = mTabControl.getCurrentIndex();
2069 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002070 mTitleBar.removeTab(removeIndex);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002071 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002072 if (currentIndex >= removeIndex && currentIndex != 0) {
2073 currentIndex--;
2074 }
2075 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
The Android Open Source Project0c908882009-03-03 19:32:16 -08002076 }
2077
2078 private void goBackOnePageOrQuit() {
2079 TabControl.Tab current = mTabControl.getCurrentTab();
2080 if (current == null) {
2081 /*
2082 * Instead of finishing the activity, simply push this to the back
2083 * of the stack and let ActivityManager to choose the foreground
2084 * activity. As BrowserActivity is singleTask, it will be always the
2085 * root of the task. So we can use either true or false for
2086 * moveTaskToBack().
2087 */
2088 moveTaskToBack(true);
2089 }
2090 WebView w = current.getWebView();
2091 if (w.canGoBack()) {
2092 w.goBack();
2093 } else {
2094 // Check to see if we are closing a window that was created by
2095 // another window. If so, we switch back to that window.
2096 TabControl.Tab parent = current.getParentTab();
2097 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002098 switchToTab(mTabControl.getTabIndex(parent));
2099 // Now we close the other tab
2100 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002101 } else {
2102 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002103 // force mPageStarted to be false as we are going to either
2104 // finish the activity or remove the tab. This will ensure
2105 // pauseWebView() taking action.
2106 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002107 if (mTabControl.getTabCount() == 1) {
2108 finish();
2109 return;
2110 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002111 // call pauseWebViewTimers() now, we won't be able to call
2112 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002113 // Temporarily change mActivityInPause to be true as
2114 // pauseWebViewTimers() will do nothing if mActivityInPause
2115 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002116 boolean savedState = mActivityInPause;
2117 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002118 Log.e(LOGTAG, "BrowserActivity is already paused "
2119 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002120 }
2121 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002122 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002123 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002124 removeTabFromContentView(current);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002125 mTitleBar.removeTab(mTabControl.getTabIndex(current));
The Android Open Source Project0c908882009-03-03 19:32:16 -08002126 mTabControl.removeTab(current);
2127 }
2128 /*
2129 * Instead of finishing the activity, simply push this to the back
2130 * of the stack and let ActivityManager to choose the foreground
2131 * activity. As BrowserActivity is singleTask, it will be always the
2132 * root of the task. So we can use either true or false for
2133 * moveTaskToBack().
2134 */
2135 moveTaskToBack(true);
2136 }
2137 }
2138 }
2139
2140 public KeyTracker.State onKeyTracker(int keyCode,
2141 KeyEvent event,
2142 KeyTracker.Stage stage,
2143 int duration) {
2144 // if onKeyTracker() is called after activity onStop()
2145 // because of accumulated key events,
2146 // we should ignore it as browser is not active any more.
2147 WebView topWindow = getTopWindow();
Andrei Popescuadc008d2009-06-26 14:11:30 +01002148 if (topWindow == null && mCustomView == null)
The Android Open Source Project0c908882009-03-03 19:32:16 -08002149 return KeyTracker.State.NOT_TRACKING;
2150
2151 if (keyCode == KeyEvent.KEYCODE_BACK) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01002152 // Check if a custom view is currently showing and, if it is, hide it.
2153 if (mCustomView != null) {
2154 mWebChromeClient.onHideCustomView();
2155 return KeyTracker.State.DONE_TRACKING;
2156 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002157 if (stage == KeyTracker.Stage.LONG_REPEAT) {
Leon Scroggins30444232009-09-04 18:36:20 -04002158 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002159 return KeyTracker.State.DONE_TRACKING;
2160 } else if (stage == KeyTracker.Stage.UP) {
2161 // FIXME: Currently, we do not have a notion of the
2162 // history picker for the subwindow, but maybe we
2163 // should?
2164 WebView subwindow = mTabControl.getCurrentSubWindow();
2165 if (subwindow != null) {
2166 if (subwindow.canGoBack()) {
2167 subwindow.goBack();
2168 } else {
2169 dismissSubWindow(mTabControl.getCurrentTab());
2170 }
2171 } else {
2172 goBackOnePageOrQuit();
2173 }
2174 return KeyTracker.State.DONE_TRACKING;
2175 }
2176 return KeyTracker.State.KEEP_TRACKING;
2177 }
2178 return KeyTracker.State.NOT_TRACKING;
2179 }
2180
2181 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2182 if (keyCode == KeyEvent.KEYCODE_MENU) {
2183 mMenuIsDown = true;
Grace Kloba6ee9c492009-07-13 10:04:34 -07002184 } else if (mMenuIsDown) {
2185 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2186 // still down, we don't want to trigger the search. Pretend to
2187 // consume the key and do nothing.
2188 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002189 }
2190 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2191 if (!handled) {
2192 switch (keyCode) {
2193 case KeyEvent.KEYCODE_SPACE:
2194 if (event.isShiftPressed()) {
2195 getTopWindow().pageUp(false);
2196 } else {
2197 getTopWindow().pageDown(false);
2198 }
2199 handled = true;
2200 break;
2201
2202 default:
2203 break;
2204 }
2205 }
2206 return handled || super.onKeyDown(keyCode, event);
2207 }
2208
2209 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2210 if (keyCode == KeyEvent.KEYCODE_MENU) {
2211 mMenuIsDown = false;
2212 }
2213 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2214 }
2215
2216 private void stopLoading() {
2217 resetTitleAndRevertLockIcon();
2218 WebView w = getTopWindow();
2219 w.stopLoading();
2220 mWebViewClient.onPageFinished(w, w.getUrl());
2221
2222 cancelStopToast();
2223 mStopToast = Toast
2224 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2225 mStopToast.show();
2226 }
2227
2228 private void cancelStopToast() {
2229 if (mStopToast != null) {
2230 mStopToast.cancel();
2231 mStopToast = null;
2232 }
2233 }
2234
2235 // called by a non-UI thread to post the message
2236 public void postMessage(int what, int arg1, int arg2, Object obj) {
2237 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2238 }
2239
2240 // public message ids
2241 public final static int LOAD_URL = 1001;
2242 public final static int STOP_LOAD = 1002;
2243
2244 // Message Ids
2245 private static final int FOCUS_NODE_HREF = 102;
2246 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002247 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002248
2249 // Private handler for handling javascript and saving passwords
2250 private Handler mHandler = new Handler() {
2251
2252 public void handleMessage(Message msg) {
2253 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002254 case FOCUS_NODE_HREF:
2255 String url = (String) msg.getData().get("url");
2256 if (url == null || url.length() == 0) {
2257 break;
2258 }
2259 HashMap focusNodeMap = (HashMap) msg.obj;
2260 WebView view = (WebView) focusNodeMap.get("webview");
2261 // Only apply the action if the top window did not change.
2262 if (getTopWindow() != view) {
2263 break;
2264 }
2265 switch (msg.arg1) {
2266 case R.id.open_context_menu_id:
2267 case R.id.view_image_context_menu_id:
2268 loadURL(getTopWindow(), url);
2269 break;
2270 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002271 final TabControl.Tab parent = mTabControl
2272 .getCurrentTab();
2273 final TabControl.Tab newTab = openTab(url);
2274 if (newTab != parent) {
2275 parent.addChildTab(newTab);
2276 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002277 break;
2278 case R.id.bookmark_context_menu_id:
2279 Intent intent = new Intent(BrowserActivity.this,
2280 AddBookmarkPage.class);
2281 intent.putExtra("url", url);
2282 startActivity(intent);
2283 break;
2284 case R.id.share_link_context_menu_id:
2285 Browser.sendString(BrowserActivity.this, url);
2286 break;
2287 case R.id.copy_link_context_menu_id:
2288 copy(url);
2289 break;
2290 case R.id.save_link_context_menu_id:
2291 case R.id.download_context_menu_id:
2292 onDownloadStartNoStream(url, null, null, null, -1);
2293 break;
2294 }
2295 break;
2296
2297 case LOAD_URL:
2298 loadURL(getTopWindow(), (String) msg.obj);
2299 break;
2300
2301 case STOP_LOAD:
2302 stopLoading();
2303 break;
2304
2305 case CANCEL_CREDS_REQUEST:
2306 resumeAfterCredentials();
2307 break;
2308
The Android Open Source Project0c908882009-03-03 19:32:16 -08002309 case RELEASE_WAKELOCK:
2310 if (mWakeLock.isHeld()) {
2311 mWakeLock.release();
2312 }
2313 break;
2314 }
2315 }
2316 };
2317
Leon Scroggins89c6d362009-07-15 16:54:37 -04002318 private void updateScreenshot(WebView view) {
2319 // If this is a bookmarked site, add a screenshot to the database.
2320 // FIXME: When should we update? Every time?
2321 // FIXME: Would like to make sure there is actually something to
2322 // draw, but the API for that (WebViewCore.pictureReady()) is not
2323 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002324 ContentResolver cr = getContentResolver();
2325 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002326 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002327 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002328 boolean succeed = c.moveToFirst();
2329 ContentValues values = null;
2330 while (succeed) {
2331 if (values == null) {
2332 final ByteArrayOutputStream os
2333 = new ByteArrayOutputStream();
2334 Picture thumbnail = view.capturePicture();
2335 // Keep width and height in sync with BrowserBookmarksPage
2336 // and bookmark_thumb
2337 Bitmap bm = Bitmap.createBitmap(100, 80,
2338 Bitmap.Config.ARGB_4444);
2339 Canvas canvas = new Canvas(bm);
2340 // May need to tweak these values to determine what is the
2341 // best scale factor
2342 canvas.scale(.5f, .5f);
2343 thumbnail.draw(canvas);
2344 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2345 values = new ContentValues();
2346 values.put(Browser.BookmarkColumns.THUMBNAIL,
2347 os.toByteArray());
2348 }
2349 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2350 c.getInt(0)), values, null, null);
2351 succeed = c.moveToNext();
2352 }
2353 c.close();
2354 }
2355 }
2356
The Android Open Source Project0c908882009-03-03 19:32:16 -08002357 // -------------------------------------------------------------------------
2358 // WebViewClient implementation.
2359 //-------------------------------------------------------------------------
2360
2361 // Use in overrideUrlLoading
2362 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2363 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2364 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2365 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2366
2367 /* package */ WebViewClient getWebViewClient() {
2368 return mWebViewClient;
2369 }
2370
Patrick Scott3918d442009-08-04 13:22:29 -04002371 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002372 if (icon != null) {
2373 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott3918d442009-08-04 13:22:29 -04002374 view, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002375 }
2376 setFavicon(icon);
2377 }
2378
2379 private final WebViewClient mWebViewClient = new WebViewClient() {
2380 @Override
2381 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2382 resetLockIcon(url);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002383 setUrlTitle(url, null, view);
Ben Murdochbff2d602009-07-01 20:19:05 +01002384
2385 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2386 if (errorConsole != null) {
2387 errorConsole.clearErrorMessages();
2388 if (mShouldShowErrorConsole) {
2389 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2390 }
2391 }
2392
The Android Open Source Project0c908882009-03-03 19:32:16 -08002393 // Call updateIcon instead of setFavicon so the bookmark
2394 // database can be updated.
Patrick Scott3918d442009-08-04 13:22:29 -04002395 updateIcon(view, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002396
Grace Kloba4d7880f2009-08-12 09:35:42 -07002397 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002398 String host;
2399 try {
2400 WebAddress uri = new WebAddress(url);
2401 host = uri.mHost;
2402 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002403 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002404 }
2405 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002406 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002407 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002408 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002409 }
2410
2411 // Performance probe
2412 if (false) {
2413 mStart = SystemClock.uptimeMillis();
2414 mProcessStart = Process.getElapsedCpuTime();
2415 long[] sysCpu = new long[7];
2416 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2417 sysCpu, null)) {
2418 mUserStart = sysCpu[0] + sysCpu[1];
2419 mSystemStart = sysCpu[2];
2420 mIdleStart = sysCpu[3];
2421 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2422 }
2423 mUiStart = SystemClock.currentThreadTimeMillis();
2424 }
2425
2426 if (!mPageStarted) {
2427 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002428 // if onResume() has been called, resumeWebViewTimers() does
2429 // nothing.
2430 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002431 }
2432
2433 // reset sync timer to avoid sync starts during loading a page
2434 CookieSyncManager.getInstance().resetSync();
2435
2436 mInLoad = true;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002437 WebView currentWebView = mTabControl.getCurrentWebView();
2438 if (currentWebView == null || currentWebView.getScrollY() != 0) {
2439 // This page has begun to load, so show the title bar
2440 showFakeTitleBar();
2441 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002442 updateInLoadMenuItems();
2443 if (!mIsNetworkUp) {
2444 if ( mAlertDialog == null) {
2445 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2446 .setTitle(R.string.loadSuspendedTitle)
2447 .setMessage(R.string.loadSuspended)
2448 .setPositiveButton(R.string.ok, null)
2449 .show();
2450 }
2451 if (view != null) {
2452 view.setNetworkAvailable(false);
2453 }
2454 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002455 }
2456
2457 @Override
2458 public void onPageFinished(WebView view, String url) {
2459 // Reset the title and icon in case we stopped a provisional
2460 // load.
2461 resetTitleAndIcon(view);
2462
2463 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002464 updateLockIconToLatest();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002465 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002466
The Android Open Source Project0c908882009-03-03 19:32:16 -08002467 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002468 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002469 long[] sysCpu = new long[7];
2470 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2471 sysCpu, null)) {
2472 String uiInfo = "UI thread used "
2473 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2474 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002475 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002476 Log.d(LOGTAG, uiInfo);
2477 }
2478 //The string that gets written to the log
2479 String performanceString = "It took total "
2480 + (SystemClock.uptimeMillis() - mStart)
2481 + " ms clock time to load the page."
2482 + "\nbrowser process used "
2483 + (Process.getElapsedCpuTime() - mProcessStart)
2484 + " ms, user processes used "
2485 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2486 + " ms, kernel used "
2487 + (sysCpu[2] - mSystemStart) * 10
2488 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2489 + " ms and irq took "
2490 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2491 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002492 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002493 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2494 }
2495 if (url != null) {
2496 // strip the url to maintain consistency
2497 String newUrl = new String(url);
2498 if (newUrl.startsWith("http://www.")) {
2499 newUrl = newUrl.substring(11);
2500 } else if (newUrl.startsWith("http://")) {
2501 newUrl = newUrl.substring(7);
2502 } else if (newUrl.startsWith("https://www.")) {
2503 newUrl = newUrl.substring(12);
2504 } else if (newUrl.startsWith("https://")) {
2505 newUrl = newUrl.substring(8);
2506 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002507 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002508 Log.d(LOGTAG, newUrl + " loaded");
2509 }
2510 /*
2511 if (sWhiteList.contains(newUrl)) {
2512 // The string that gets pushed to the statistcs
2513 // service
2514 performanceString = performanceString
2515 + "\nWebpage: "
2516 + newUrl
2517 + "\nCarrier: "
2518 + android.os.SystemProperties
2519 .get("gsm.sim.operator.alpha");
2520 if (mWebView != null
2521 && mWebView.getContext() != null
2522 && mWebView.getContext().getSystemService(
2523 Context.CONNECTIVITY_SERVICE) != null) {
2524 ConnectivityManager cManager =
2525 (ConnectivityManager) mWebView
2526 .getContext().getSystemService(
2527 Context.CONNECTIVITY_SERVICE);
2528 NetworkInfo nInfo = cManager
2529 .getActiveNetworkInfo();
2530 if (nInfo != null) {
2531 performanceString = performanceString
2532 + "\nNetwork Type: "
2533 + nInfo.getType().toString();
2534 }
2535 }
2536 Checkin.logEvent(mResolver,
2537 Checkin.Events.Tag.WEBPAGE_LOAD,
2538 performanceString);
2539 Log.w(LOGTAG, "pushed to the statistics service");
2540 }
2541 */
2542 }
2543 }
2544 }
2545
2546 if (mInTrace) {
2547 mInTrace = false;
2548 Debug.stopMethodTracing();
2549 }
2550
2551 if (mPageStarted) {
2552 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002553 // pauseWebViewTimers() will do nothing and return false if
2554 // onPause() is not called yet.
2555 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002556 if (mWakeLock.isHeld()) {
2557 mHandler.removeMessages(RELEASE_WAKELOCK);
2558 mWakeLock.release();
2559 }
2560 }
2561 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002562 }
2563
2564 // return true if want to hijack the url to let another app to handle it
2565 @Override
2566 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2567 if (url.startsWith(SCHEME_WTAI)) {
2568 // wtai://wp/mc;number
2569 // number=string(phone-number)
2570 if (url.startsWith(SCHEME_WTAI_MC)) {
2571 Intent intent = new Intent(Intent.ACTION_VIEW,
2572 Uri.parse(WebView.SCHEME_TEL +
2573 url.substring(SCHEME_WTAI_MC.length())));
2574 startActivity(intent);
2575 return true;
2576 }
2577 // wtai://wp/sd;dtmf
2578 // dtmf=string(dialstring)
2579 if (url.startsWith(SCHEME_WTAI_SD)) {
2580 // TODO
2581 // only send when there is active voice connection
2582 return false;
2583 }
2584 // wtai://wp/ap;number;name
2585 // number=string(phone-number)
2586 // name=string
2587 if (url.startsWith(SCHEME_WTAI_AP)) {
2588 // TODO
2589 return false;
2590 }
2591 }
2592
Dianne Hackborn99189432009-06-17 18:06:18 -07002593 // The "about:" schemes are internal to the browser; don't
2594 // want these to be dispatched to other apps.
2595 if (url.startsWith("about:")) {
2596 return false;
2597 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002598
Dianne Hackborn99189432009-06-17 18:06:18 -07002599 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002600
Dianne Hackborn99189432009-06-17 18:06:18 -07002601 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002602 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002603 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2604 } catch (URISyntaxException ex) {
2605 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002606 return false;
2607 }
2608
Grace Kloba5b078b52009-06-24 20:23:41 -07002609 // check whether the intent can be resolved. If not, we will see
2610 // whether we can download it from the Market.
2611 if (getPackageManager().resolveActivity(intent, 0) == null) {
2612 String packagename = intent.getPackage();
2613 if (packagename != null) {
2614 intent = new Intent(Intent.ACTION_VIEW, Uri
2615 .parse("market://search?q=pname:" + packagename));
2616 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2617 startActivity(intent);
2618 return true;
2619 } else {
2620 return false;
2621 }
2622 }
2623
Dianne Hackborn99189432009-06-17 18:06:18 -07002624 // sanitize the Intent, ensuring web pages can not bypass browser
2625 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002626 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002627 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002628 try {
2629 if (startActivityIfNeeded(intent, -1)) {
2630 return true;
2631 }
2632 } catch (ActivityNotFoundException ex) {
2633 // ignore the error. If no application can handle the URL,
2634 // eg about:blank, assume the browser can handle it.
2635 }
2636
2637 if (mMenuIsDown) {
2638 openTab(url);
2639 closeOptionsMenu();
2640 return true;
2641 }
2642
2643 return false;
2644 }
2645
2646 /**
2647 * Updates the lock icon. This method is called when we discover another
2648 * resource to be loaded for this page (for example, javascript). While
2649 * we update the icon type, we do not update the lock icon itself until
2650 * we are done loading, it is slightly more secure this way.
2651 */
2652 @Override
2653 public void onLoadResource(WebView view, String url) {
2654 if (url != null && url.length() > 0) {
2655 // It is only if the page claims to be secure
2656 // that we may have to update the lock:
2657 if (mLockIconType == LOCK_ICON_SECURE) {
2658 // If NOT a 'safe' url, change the lock to mixed content!
2659 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2660 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002661 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002662 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2663 " updated lock icon to " + mLockIconType + " due to " + url);
2664 }
2665 }
2666 }
2667 }
2668 }
2669
2670 /**
2671 * Show the dialog, asking the user if they would like to continue after
2672 * an excessive number of HTTP redirects.
2673 */
2674 @Override
2675 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2676 final Message continueMsg) {
2677 new AlertDialog.Builder(BrowserActivity.this)
2678 .setTitle(R.string.browserFrameRedirect)
2679 .setMessage(R.string.browserFrame307Post)
2680 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2681 public void onClick(DialogInterface dialog, int which) {
2682 continueMsg.sendToTarget();
2683 }})
2684 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2685 public void onClick(DialogInterface dialog, int which) {
2686 cancelMsg.sendToTarget();
2687 }})
2688 .setOnCancelListener(new OnCancelListener() {
2689 public void onCancel(DialogInterface dialog) {
2690 cancelMsg.sendToTarget();
2691 }})
2692 .show();
2693 }
2694
Patrick Scott37911c72009-03-24 18:02:58 -07002695 // Container class for the next error dialog that needs to be
2696 // displayed.
2697 class ErrorDialog {
2698 public final int mTitle;
2699 public final String mDescription;
2700 public final int mError;
2701 ErrorDialog(int title, String desc, int error) {
2702 mTitle = title;
2703 mDescription = desc;
2704 mError = error;
2705 }
2706 };
2707
2708 private void processNextError() {
2709 if (mQueuedErrors == null) {
2710 return;
2711 }
2712 // The first one is currently displayed so just remove it.
2713 mQueuedErrors.removeFirst();
2714 if (mQueuedErrors.size() == 0) {
2715 mQueuedErrors = null;
2716 return;
2717 }
2718 showError(mQueuedErrors.getFirst());
2719 }
2720
2721 private DialogInterface.OnDismissListener mDialogListener =
2722 new DialogInterface.OnDismissListener() {
2723 public void onDismiss(DialogInterface d) {
2724 processNextError();
2725 }
2726 };
2727 private LinkedList<ErrorDialog> mQueuedErrors;
2728
2729 private void queueError(int err, String desc) {
2730 if (mQueuedErrors == null) {
2731 mQueuedErrors = new LinkedList<ErrorDialog>();
2732 }
2733 for (ErrorDialog d : mQueuedErrors) {
2734 if (d.mError == err) {
2735 // Already saw a similar error, ignore the new one.
2736 return;
2737 }
2738 }
2739 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002740 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002741 R.string.browserFrameFileErrorLabel :
2742 R.string.browserFrameNetworkErrorLabel,
2743 desc, err);
2744 mQueuedErrors.addLast(errDialog);
2745
2746 // Show the dialog now if the queue was empty.
2747 if (mQueuedErrors.size() == 1) {
2748 showError(errDialog);
2749 }
2750 }
2751
2752 private void showError(ErrorDialog errDialog) {
2753 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2754 .setTitle(errDialog.mTitle)
2755 .setMessage(errDialog.mDescription)
2756 .setPositiveButton(R.string.ok, null)
2757 .create();
2758 d.setOnDismissListener(mDialogListener);
2759 d.show();
2760 }
2761
The Android Open Source Project0c908882009-03-03 19:32:16 -08002762 /**
2763 * Show a dialog informing the user of the network error reported by
2764 * WebCore.
2765 */
2766 @Override
2767 public void onReceivedError(WebView view, int errorCode,
2768 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002769 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2770 errorCode != WebViewClient.ERROR_CONNECT &&
2771 errorCode != WebViewClient.ERROR_BAD_URL &&
2772 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2773 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002774 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002775 }
Patrick Scott37911c72009-03-24 18:02:58 -07002776 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2777 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002778
2779 // We need to reset the title after an error.
2780 resetTitleAndRevertLockIcon();
2781 }
2782
2783 /**
2784 * Check with the user if it is ok to resend POST data as the page they
2785 * are trying to navigate to is the result of a POST.
2786 */
2787 @Override
2788 public void onFormResubmission(WebView view, final Message dontResend,
2789 final Message resend) {
2790 new AlertDialog.Builder(BrowserActivity.this)
2791 .setTitle(R.string.browserFrameFormResubmitLabel)
2792 .setMessage(R.string.browserFrameFormResubmitMessage)
2793 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2794 public void onClick(DialogInterface dialog, int which) {
2795 resend.sendToTarget();
2796 }})
2797 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2798 public void onClick(DialogInterface dialog, int which) {
2799 dontResend.sendToTarget();
2800 }})
2801 .setOnCancelListener(new OnCancelListener() {
2802 public void onCancel(DialogInterface dialog) {
2803 dontResend.sendToTarget();
2804 }})
2805 .show();
2806 }
2807
2808 /**
2809 * Insert the url into the visited history database.
2810 * @param url The url to be inserted.
2811 * @param isReload True if this url is being reloaded.
2812 * FIXME: Not sure what to do when reloading the page.
2813 */
2814 @Override
2815 public void doUpdateVisitedHistory(WebView view, String url,
2816 boolean isReload) {
2817 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2818 return;
2819 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002820 // remove "client" before updating it to the history so that it wont
2821 // show up in the auto-complete list.
2822 int index = url.indexOf("client=ms-");
2823 if (index > 0 && url.contains(".google.")) {
2824 int end = url.indexOf('&', index);
2825 if (end > 0) {
2826 url = url.substring(0, index-1).concat(url.substring(end));
2827 } else {
2828 url = url.substring(0, index-1);
2829 }
2830 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002831 Browser.updateVisitedHistory(mResolver, url, true);
2832 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2833 }
2834
2835 /**
2836 * Displays SSL error(s) dialog to the user.
2837 */
2838 @Override
2839 public void onReceivedSslError(
2840 final WebView view, final SslErrorHandler handler, final SslError error) {
2841
2842 if (mSettings.showSecurityWarnings()) {
2843 final LayoutInflater factory =
2844 LayoutInflater.from(BrowserActivity.this);
2845 final View warningsView =
2846 factory.inflate(R.layout.ssl_warnings, null);
2847 final LinearLayout placeholder =
2848 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2849
2850 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2851 LinearLayout ll = (LinearLayout)factory
2852 .inflate(R.layout.ssl_warning, null);
2853 ((TextView)ll.findViewById(R.id.warning))
2854 .setText(R.string.ssl_untrusted);
2855 placeholder.addView(ll);
2856 }
2857
2858 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2859 LinearLayout ll = (LinearLayout)factory
2860 .inflate(R.layout.ssl_warning, null);
2861 ((TextView)ll.findViewById(R.id.warning))
2862 .setText(R.string.ssl_mismatch);
2863 placeholder.addView(ll);
2864 }
2865
2866 if (error.hasError(SslError.SSL_EXPIRED)) {
2867 LinearLayout ll = (LinearLayout)factory
2868 .inflate(R.layout.ssl_warning, null);
2869 ((TextView)ll.findViewById(R.id.warning))
2870 .setText(R.string.ssl_expired);
2871 placeholder.addView(ll);
2872 }
2873
2874 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2875 LinearLayout ll = (LinearLayout)factory
2876 .inflate(R.layout.ssl_warning, null);
2877 ((TextView)ll.findViewById(R.id.warning))
2878 .setText(R.string.ssl_not_yet_valid);
2879 placeholder.addView(ll);
2880 }
2881
2882 new AlertDialog.Builder(BrowserActivity.this)
2883 .setTitle(R.string.security_warning)
2884 .setIcon(android.R.drawable.ic_dialog_alert)
2885 .setView(warningsView)
2886 .setPositiveButton(R.string.ssl_continue,
2887 new DialogInterface.OnClickListener() {
2888 public void onClick(DialogInterface dialog, int whichButton) {
2889 handler.proceed();
2890 }
2891 })
2892 .setNeutralButton(R.string.view_certificate,
2893 new DialogInterface.OnClickListener() {
2894 public void onClick(DialogInterface dialog, int whichButton) {
2895 showSSLCertificateOnError(view, handler, error);
2896 }
2897 })
2898 .setNegativeButton(R.string.cancel,
2899 new DialogInterface.OnClickListener() {
2900 public void onClick(DialogInterface dialog, int whichButton) {
2901 handler.cancel();
2902 BrowserActivity.this.resetTitleAndRevertLockIcon();
2903 }
2904 })
2905 .setOnCancelListener(
2906 new DialogInterface.OnCancelListener() {
2907 public void onCancel(DialogInterface dialog) {
2908 handler.cancel();
2909 BrowserActivity.this.resetTitleAndRevertLockIcon();
2910 }
2911 })
2912 .show();
2913 } else {
2914 handler.proceed();
2915 }
2916 }
2917
2918 /**
2919 * Handles an HTTP authentication request.
2920 *
2921 * @param handler The authentication handler
2922 * @param host The host
2923 * @param realm The realm
2924 */
2925 @Override
2926 public void onReceivedHttpAuthRequest(WebView view,
2927 final HttpAuthHandler handler, final String host, final String realm) {
2928 String username = null;
2929 String password = null;
2930
2931 boolean reuseHttpAuthUsernamePassword =
2932 handler.useHttpAuthUsernamePassword();
2933
2934 if (reuseHttpAuthUsernamePassword &&
2935 (mTabControl.getCurrentWebView() != null)) {
2936 String[] credentials =
2937 mTabControl.getCurrentWebView()
2938 .getHttpAuthUsernamePassword(host, realm);
2939 if (credentials != null && credentials.length == 2) {
2940 username = credentials[0];
2941 password = credentials[1];
2942 }
2943 }
2944
2945 if (username != null && password != null) {
2946 handler.proceed(username, password);
2947 } else {
2948 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2949 }
2950 }
2951
2952 @Override
2953 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2954 if (mMenuIsDown) {
2955 // only check shortcut key when MENU is held
2956 return getWindow().isShortcutKey(event.getKeyCode(), event);
2957 } else {
2958 return false;
2959 }
2960 }
2961
2962 @Override
2963 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2964 if (view != mTabControl.getCurrentTopWebView()) {
2965 return;
2966 }
2967 if (event.isDown()) {
2968 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2969 } else {
2970 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2971 }
2972 }
2973 };
2974
2975 //--------------------------------------------------------------------------
2976 // WebChromeClient implementation
2977 //--------------------------------------------------------------------------
2978
2979 /* package */ WebChromeClient getWebChromeClient() {
2980 return mWebChromeClient;
2981 }
2982
2983 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2984 // Helper method to create a new tab or sub window.
2985 private void createWindow(final boolean dialog, final Message msg) {
2986 if (dialog) {
2987 mTabControl.createSubWindow();
2988 final TabControl.Tab t = mTabControl.getCurrentTab();
2989 attachSubWindow(t);
2990 WebView.WebViewTransport transport =
2991 (WebView.WebViewTransport) msg.obj;
2992 transport.setWebView(t.getSubWebView());
2993 msg.sendToTarget();
2994 } else {
2995 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04002996 final TabControl.Tab newTab
2997 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07002998 if (newTab != parent) {
2999 parent.addChildTab(newTab);
3000 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003001 WebView.WebViewTransport transport =
3002 (WebView.WebViewTransport) msg.obj;
3003 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04003004 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003005 }
3006 }
3007
3008 @Override
3009 public boolean onCreateWindow(WebView view, final boolean dialog,
3010 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003011 // Short-circuit if we can't create any more tabs or sub windows.
3012 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3013 new AlertDialog.Builder(BrowserActivity.this)
3014 .setTitle(R.string.too_many_subwindows_dialog_title)
3015 .setIcon(android.R.drawable.ic_dialog_alert)
3016 .setMessage(R.string.too_many_subwindows_dialog_message)
3017 .setPositiveButton(R.string.ok, null)
3018 .show();
3019 return false;
3020 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3021 new AlertDialog.Builder(BrowserActivity.this)
3022 .setTitle(R.string.too_many_windows_dialog_title)
3023 .setIcon(android.R.drawable.ic_dialog_alert)
3024 .setMessage(R.string.too_many_windows_dialog_message)
3025 .setPositiveButton(R.string.ok, null)
3026 .show();
3027 return false;
3028 }
3029
3030 // Short-circuit if this was a user gesture.
3031 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003032 createWindow(dialog, resultMsg);
3033 return true;
3034 }
3035
3036 // Allow the popup and create the appropriate window.
3037 final AlertDialog.OnClickListener allowListener =
3038 new AlertDialog.OnClickListener() {
3039 public void onClick(DialogInterface d,
3040 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003041 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003042 }
3043 };
3044
3045 // Block the popup by returning a null WebView.
3046 final AlertDialog.OnClickListener blockListener =
3047 new AlertDialog.OnClickListener() {
3048 public void onClick(DialogInterface d, int which) {
3049 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003050 }
3051 };
3052
3053 // Build a confirmation dialog to display to the user.
3054 final AlertDialog d =
3055 new AlertDialog.Builder(BrowserActivity.this)
3056 .setTitle(R.string.attention)
3057 .setIcon(android.R.drawable.ic_dialog_alert)
3058 .setMessage(R.string.popup_window_attempt)
3059 .setPositiveButton(R.string.allow, allowListener)
3060 .setNegativeButton(R.string.block, blockListener)
3061 .setCancelable(false)
3062 .create();
3063
3064 // Show the confirmation dialog.
3065 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003066 return true;
3067 }
3068
3069 @Override
3070 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003071 final TabControl.Tab current = mTabControl.getCurrentTab();
3072 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003073 if (parent != null) {
3074 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003075 switchToTab(mTabControl.getTabIndex(parent));
3076 // Now we need to close the window
3077 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003078 }
3079 }
3080
3081 @Override
3082 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003083 mTitleBar.setProgress(newProgress, view);
3084 if (mFakeTitleBar != null) {
3085 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003086 }
3087
3088 if (newProgress == 100) {
3089 // onProgressChanged() is called for sub-frame too while
3090 // onPageFinished() is only called for the main frame. sync
3091 // cookie and cache promptly here.
3092 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003093 if (mInLoad) {
3094 mInLoad = false;
3095 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003096 // If the options menu is open, leave the title bar
3097 if (!mOptionsMenuOpen || !mIconView) {
3098 hideFakeTitleBar();
3099 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003100 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003101 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003102 // onPageFinished may have already been called but a subframe
3103 // is still loading and updating the progress. Reset mInLoad
3104 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003105 mInLoad = true;
3106 updateInLoadMenuItems();
3107 WebView currentWebView = mTabControl.getCurrentWebView();
3108 if ((currentWebView == null || currentWebView.getScrollY() != 0)
3109 && (!mOptionsMenuOpen || mIconView)) {
3110 // This page has begun to load, so show the title bar
3111 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003112 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003113 }
3114 }
3115
3116 @Override
3117 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003118 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003119
3120 // here, if url is null, we want to reset the title
Leon Scroggins1f005d32009-08-10 17:36:42 -04003121 setUrlTitle(url, title, view);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003122
3123 if (url == null ||
3124 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3125 return;
3126 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003127 // See if we can find the current url in our history database and
3128 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003129 if (url.startsWith("http://www.")) {
3130 url = url.substring(11);
3131 } else if (url.startsWith("http://")) {
3132 url = url.substring(4);
3133 }
3134 try {
3135 url = "%" + url;
3136 String [] selArgs = new String[] { url };
3137
3138 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3139 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3140 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3141 Browser.HISTORY_PROJECTION, where, selArgs, null);
3142 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003143 // Current implementation of database only has one entry per
3144 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003145 ContentValues map = new ContentValues();
3146 map.put(Browser.BookmarkColumns.TITLE, title);
3147 mResolver.update(Browser.BOOKMARKS_URI, map,
3148 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003149 }
3150 c.close();
3151 } catch (IllegalStateException e) {
3152 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3153 } catch (SQLiteException ex) {
3154 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3155 }
3156 }
3157
3158 @Override
3159 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003160 updateIcon(view, icon);
3161 }
3162
3163 @Override
3164 public void onReceivedTouchIconUrl(WebView view, String url) {
3165 final ContentResolver cr = getContentResolver();
3166 final Cursor c =
3167 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003168 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003169 if (c != null) {
3170 if (c.getCount() > 0) {
3171 new DownloadTouchIcon(cr, c, view).execute(url);
3172 } else {
3173 c.close();
3174 }
3175 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003176 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003177
Andrei Popescuadc008d2009-06-26 14:11:30 +01003178 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003179 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003180 if (mCustomView != null)
3181 return;
3182
3183 // Add the custom view to its container.
3184 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3185 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003186 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003187 // Save the menu state and set it to empty while the custom
3188 // view is showing.
3189 mOldMenuState = mMenuState;
3190 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003191 // Hide the content view.
3192 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003193 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003194 mCustomViewContainer.setVisibility(View.VISIBLE);
3195 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003196 }
3197
3198 @Override
3199 public void onHideCustomView() {
3200 if (mCustomView == null)
3201 return;
3202
Andrei Popescuc9b55562009-07-07 10:51:15 +01003203 // Hide the custom view.
3204 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003205 // Remove the custom view from its container.
3206 mCustomViewContainer.removeView(mCustomView);
3207 mCustomView = null;
3208 // Reset the old menu state.
3209 mMenuState = mOldMenuState;
3210 mOldMenuState = EMPTY_MENU;
3211 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003212 mCustomViewCallback.onCustomViewHidden();
3213 // Show the content view.
3214 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003215 }
3216
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003217 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003218 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003219 * @param url the URL that exceeded the quota
3220 * @param databaseIdentifier the identifier of the database on
3221 * which the transaction that caused the quota overflow was run
3222 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003223 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003224 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003225 * @param quotaUpdater The callback to run when a decision to allow or
3226 * deny quota has been made. Don't forget to call this!
3227 */
3228 @Override
3229 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003230 String databaseIdentifier, long currentQuota, long estimatedSize,
3231 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003232 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003233 url, databaseIdentifier, currentQuota, estimatedSize,
3234 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003235 }
3236
3237 /**
3238 * The Application Cache has exceeded its max size.
3239 * @param spaceNeeded is the amount of disk space that would be needed
3240 * in order for the last appcache operation to succeed.
3241 * @param totalUsedQuota is the sum of all origins' quota.
3242 * @param quotaUpdater A callback to inform the WebCore thread that a new
3243 * app cache size is available. This callback must always be executed at
3244 * some point to ensure that the sleeping WebCore thread is woken up.
3245 */
3246 @Override
3247 public void onReachedMaxAppCacheSize(long spaceNeeded,
3248 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3249 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3250 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003251 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003252
Steve Block2bc69912009-07-30 14:45:13 +01003253 /**
3254 * Instructs the browser to show a prompt to ask the user to set the
3255 * Geolocation permission state for the specified origin.
3256 * @param origin The origin for which Geolocation permissions are
3257 * requested.
3258 * @param callback The callback to call once the user has set the
3259 * Geolocation permission state.
3260 */
3261 @Override
3262 public void onGeolocationPermissionsShowPrompt(String origin,
3263 GeolocationPermissions.Callback callback) {
3264 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3265 origin, callback);
3266 }
3267
3268 /**
3269 * Instructs the browser to hide the Geolocation permissions prompt.
3270 */
3271 @Override
3272 public void onGeolocationPermissionsHidePrompt() {
3273 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3274 }
3275
Ben Murdoch7db26342009-06-03 18:21:19 +01003276 /* Adds a JavaScript error message to the system log.
3277 * @param message The error message to report.
3278 * @param lineNumber The line number of the error.
3279 * @param sourceID The name of the source file that caused the error.
3280 */
3281 @Override
3282 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003283 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3284 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3285 if (mShouldShowErrorConsole &&
3286 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3287 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3288 }
3289 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003290 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003291 };
3292
3293 /**
3294 * Notify the host application a download should be done, or that
3295 * the data should be streamed if a streaming viewer is available.
3296 * @param url The full url to the content that should be downloaded
3297 * @param contentDisposition Content-disposition http header, if
3298 * present.
3299 * @param mimetype The mimetype of the content reported by the server
3300 * @param contentLength The file size reported by the server
3301 */
3302 public void onDownloadStart(String url, String userAgent,
3303 String contentDisposition, String mimetype, long contentLength) {
3304 // if we're dealing wih A/V content that's not explicitly marked
3305 // for download, check if it's streamable.
3306 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003307 || !contentDisposition.regionMatches(
3308 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003309 // query the package manager to see if there's a registered handler
3310 // that matches.
3311 Intent intent = new Intent(Intent.ACTION_VIEW);
3312 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003313 ResolveInfo info = getPackageManager().resolveActivity(intent,
3314 PackageManager.MATCH_DEFAULT_ONLY);
3315 if (info != null) {
3316 ComponentName myName = getComponentName();
3317 // If we resolved to ourselves, we don't want to attempt to
3318 // load the url only to try and download it again.
3319 if (!myName.getPackageName().equals(
3320 info.activityInfo.packageName)
3321 || !myName.getClassName().equals(
3322 info.activityInfo.name)) {
3323 // someone (other than us) knows how to handle this mime
3324 // type with this scheme, don't download.
3325 try {
3326 startActivity(intent);
3327 return;
3328 } catch (ActivityNotFoundException ex) {
3329 if (LOGD_ENABLED) {
3330 Log.d(LOGTAG, "activity not found for " + mimetype
3331 + " over " + Uri.parse(url).getScheme(),
3332 ex);
3333 }
3334 // Best behavior is to fall back to a download in this
3335 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003336 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003337 }
3338 }
3339 }
3340 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3341 }
3342
3343 /**
3344 * Notify the host application a download should be done, even if there
3345 * is a streaming viewer available for thise type.
3346 * @param url The full url to the content that should be downloaded
3347 * @param contentDisposition Content-disposition http header, if
3348 * present.
3349 * @param mimetype The mimetype of the content reported by the server
3350 * @param contentLength The file size reported by the server
3351 */
3352 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3353 String contentDisposition, String mimetype, long contentLength) {
3354
3355 String filename = URLUtil.guessFileName(url,
3356 contentDisposition, mimetype);
3357
3358 // Check to see if we have an SDCard
3359 String status = Environment.getExternalStorageState();
3360 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3361 int title;
3362 String msg;
3363
3364 // Check to see if the SDCard is busy, same as the music app
3365 if (status.equals(Environment.MEDIA_SHARED)) {
3366 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3367 title = R.string.download_sdcard_busy_dlg_title;
3368 } else {
3369 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3370 title = R.string.download_no_sdcard_dlg_title;
3371 }
3372
3373 new AlertDialog.Builder(this)
3374 .setTitle(title)
3375 .setIcon(android.R.drawable.ic_dialog_alert)
3376 .setMessage(msg)
3377 .setPositiveButton(R.string.ok, null)
3378 .show();
3379 return;
3380 }
3381
3382 // java.net.URI is a lot stricter than KURL so we have to undo
3383 // KURL's percent-encoding and redo the encoding using java.net.URI.
3384 URI uri = null;
3385 try {
3386 // Undo the percent-encoding that KURL may have done.
3387 String newUrl = new String(URLUtil.decode(url.getBytes()));
3388 // Parse the url into pieces
3389 WebAddress w = new WebAddress(newUrl);
3390 String frag = null;
3391 String query = null;
3392 String path = w.mPath;
3393 // Break the path into path, query, and fragment
3394 if (path.length() > 0) {
3395 // Strip the fragment
3396 int idx = path.lastIndexOf('#');
3397 if (idx != -1) {
3398 frag = path.substring(idx + 1);
3399 path = path.substring(0, idx);
3400 }
3401 idx = path.lastIndexOf('?');
3402 if (idx != -1) {
3403 query = path.substring(idx + 1);
3404 path = path.substring(0, idx);
3405 }
3406 }
3407 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3408 query, frag);
3409 } catch (Exception e) {
3410 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3411 return;
3412 }
3413
3414 // XXX: Have to use the old url since the cookies were stored using the
3415 // old percent-encoded url.
3416 String cookies = CookieManager.getInstance().getCookie(url);
3417
3418 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003419 values.put(Downloads.COLUMN_URI, uri.toString());
3420 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3421 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3422 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003423 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003424 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003425 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003426 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3427 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3428 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3429 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003430 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003431 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003432 }
3433 if (mimetype == null) {
3434 // We must have long pressed on a link or image to download it. We
3435 // are not sure of the mimetype in this case, so do a head request
3436 new FetchUrlMimeType(this).execute(values);
3437 } else {
3438 final Uri contentUri =
3439 getContentResolver().insert(Downloads.CONTENT_URI, values);
3440 viewDownloads(contentUri);
3441 }
3442
3443 }
3444
3445 /**
3446 * Resets the lock icon. This method is called when we start a new load and
3447 * know the url to be loaded.
3448 */
3449 private void resetLockIcon(String url) {
3450 // Save the lock-icon state (we revert to it if the load gets cancelled)
3451 saveLockIcon();
3452
3453 mLockIconType = LOCK_ICON_UNSECURE;
3454 if (URLUtil.isHttpsUrl(url)) {
3455 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003456 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003457 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3458 " reset lock icon to " + mLockIconType);
3459 }
3460 }
3461
3462 updateLockIconImage(LOCK_ICON_UNSECURE);
3463 }
3464
3465 /**
3466 * Resets the lock icon. This method is called when the icon needs to be
3467 * reset but we do not know whether we are loading a secure or not secure
3468 * page.
3469 */
3470 private void resetLockIcon() {
3471 // Save the lock-icon state (we revert to it if the load gets cancelled)
3472 saveLockIcon();
3473
3474 mLockIconType = LOCK_ICON_UNSECURE;
3475
Dave Bort31a6d1c2009-04-13 15:56:49 -07003476 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003477 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3478 " reset lock icon to " + mLockIconType);
3479 }
3480
3481 updateLockIconImage(LOCK_ICON_UNSECURE);
3482 }
3483
3484 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003485 * Update the lock icon to correspond to our latest state.
3486 */
3487 /* package */ void updateLockIconToLatest() {
3488 updateLockIconImage(mLockIconType);
3489 }
3490
3491 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003492 * Updates the lock-icon image in the title-bar.
3493 */
3494 private void updateLockIconImage(int lockIconType) {
3495 Drawable d = null;
3496 if (lockIconType == LOCK_ICON_SECURE) {
3497 d = mSecLockIcon;
3498 } else if (lockIconType == LOCK_ICON_MIXED) {
3499 d = mMixLockIcon;
3500 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003501 mTitleBar.setLock(d, getTopWindow());
3502 if (mFakeTitleBar != null) {
3503 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003504 }
3505 }
3506
3507 /**
3508 * Displays a page-info dialog.
3509 * @param tab The tab to show info about
3510 * @param fromShowSSLCertificateOnError The flag that indicates whether
3511 * this dialog was opened from the SSL-certificate-on-error dialog or
3512 * not. This is important, since we need to know whether to return to
3513 * the parent dialog or simply dismiss.
3514 */
3515 private void showPageInfo(final TabControl.Tab tab,
3516 final boolean fromShowSSLCertificateOnError) {
3517 final LayoutInflater factory = LayoutInflater
3518 .from(this);
3519
3520 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3521
3522 final WebView view = tab.getWebView();
3523
3524 String url = null;
3525 String title = null;
3526
3527 if (view == null) {
3528 url = tab.getUrl();
3529 title = tab.getTitle();
3530 } else if (view == mTabControl.getCurrentWebView()) {
3531 // Use the cached title and url if this is the current WebView
3532 url = mUrl;
3533 title = mTitle;
3534 } else {
3535 url = view.getUrl();
3536 title = view.getTitle();
3537 }
3538
3539 if (url == null) {
3540 url = "";
3541 }
3542 if (title == null) {
3543 title = "";
3544 }
3545
3546 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3547 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3548
3549 mPageInfoView = tab;
3550 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3551
3552 AlertDialog.Builder alertDialogBuilder =
3553 new AlertDialog.Builder(this)
3554 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3555 .setView(pageInfoView)
3556 .setPositiveButton(
3557 R.string.ok,
3558 new DialogInterface.OnClickListener() {
3559 public void onClick(DialogInterface dialog,
3560 int whichButton) {
3561 mPageInfoDialog = null;
3562 mPageInfoView = null;
3563 mPageInfoFromShowSSLCertificateOnError = null;
3564
3565 // if we came here from the SSL error dialog
3566 if (fromShowSSLCertificateOnError) {
3567 // go back to the SSL error dialog
3568 showSSLCertificateOnError(
3569 mSSLCertificateOnErrorView,
3570 mSSLCertificateOnErrorHandler,
3571 mSSLCertificateOnErrorError);
3572 }
3573 }
3574 })
3575 .setOnCancelListener(
3576 new DialogInterface.OnCancelListener() {
3577 public void onCancel(DialogInterface dialog) {
3578 mPageInfoDialog = null;
3579 mPageInfoView = null;
3580 mPageInfoFromShowSSLCertificateOnError = null;
3581
3582 // if we came here from the SSL error dialog
3583 if (fromShowSSLCertificateOnError) {
3584 // go back to the SSL error dialog
3585 showSSLCertificateOnError(
3586 mSSLCertificateOnErrorView,
3587 mSSLCertificateOnErrorHandler,
3588 mSSLCertificateOnErrorError);
3589 }
3590 }
3591 });
3592
3593 // if we have a main top-level page SSL certificate set or a certificate
3594 // error
3595 if (fromShowSSLCertificateOnError ||
3596 (view != null && view.getCertificate() != null)) {
3597 // add a 'View Certificate' button
3598 alertDialogBuilder.setNeutralButton(
3599 R.string.view_certificate,
3600 new DialogInterface.OnClickListener() {
3601 public void onClick(DialogInterface dialog,
3602 int whichButton) {
3603 mPageInfoDialog = null;
3604 mPageInfoView = null;
3605 mPageInfoFromShowSSLCertificateOnError = null;
3606
3607 // if we came here from the SSL error dialog
3608 if (fromShowSSLCertificateOnError) {
3609 // go back to the SSL error dialog
3610 showSSLCertificateOnError(
3611 mSSLCertificateOnErrorView,
3612 mSSLCertificateOnErrorHandler,
3613 mSSLCertificateOnErrorError);
3614 } else {
3615 // otherwise, display the top-most certificate from
3616 // the chain
3617 if (view.getCertificate() != null) {
3618 showSSLCertificate(tab);
3619 }
3620 }
3621 }
3622 });
3623 }
3624
3625 mPageInfoDialog = alertDialogBuilder.show();
3626 }
3627
3628 /**
3629 * Displays the main top-level page SSL certificate dialog
3630 * (accessible from the Page-Info dialog).
3631 * @param tab The tab to show certificate for.
3632 */
3633 private void showSSLCertificate(final TabControl.Tab tab) {
3634 final View certificateView =
3635 inflateCertificateView(tab.getWebView().getCertificate());
3636 if (certificateView == null) {
3637 return;
3638 }
3639
3640 LayoutInflater factory = LayoutInflater.from(this);
3641
3642 final LinearLayout placeholder =
3643 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3644
3645 LinearLayout ll = (LinearLayout) factory.inflate(
3646 R.layout.ssl_success, placeholder);
3647 ((TextView)ll.findViewById(R.id.success))
3648 .setText(R.string.ssl_certificate_is_valid);
3649
3650 mSSLCertificateView = tab;
3651 mSSLCertificateDialog =
3652 new AlertDialog.Builder(this)
3653 .setTitle(R.string.ssl_certificate).setIcon(
3654 R.drawable.ic_dialog_browser_certificate_secure)
3655 .setView(certificateView)
3656 .setPositiveButton(R.string.ok,
3657 new DialogInterface.OnClickListener() {
3658 public void onClick(DialogInterface dialog,
3659 int whichButton) {
3660 mSSLCertificateDialog = null;
3661 mSSLCertificateView = null;
3662
3663 showPageInfo(tab, false);
3664 }
3665 })
3666 .setOnCancelListener(
3667 new DialogInterface.OnCancelListener() {
3668 public void onCancel(DialogInterface dialog) {
3669 mSSLCertificateDialog = null;
3670 mSSLCertificateView = null;
3671
3672 showPageInfo(tab, false);
3673 }
3674 })
3675 .show();
3676 }
3677
3678 /**
3679 * Displays the SSL error certificate dialog.
3680 * @param view The target web-view.
3681 * @param handler The SSL error handler responsible for cancelling the
3682 * connection that resulted in an SSL error or proceeding per user request.
3683 * @param error The SSL error object.
3684 */
3685 private void showSSLCertificateOnError(
3686 final WebView view, final SslErrorHandler handler, final SslError error) {
3687
3688 final View certificateView =
3689 inflateCertificateView(error.getCertificate());
3690 if (certificateView == null) {
3691 return;
3692 }
3693
3694 LayoutInflater factory = LayoutInflater.from(this);
3695
3696 final LinearLayout placeholder =
3697 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3698
3699 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3700 LinearLayout ll = (LinearLayout)factory
3701 .inflate(R.layout.ssl_warning, placeholder);
3702 ((TextView)ll.findViewById(R.id.warning))
3703 .setText(R.string.ssl_untrusted);
3704 }
3705
3706 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3707 LinearLayout ll = (LinearLayout)factory
3708 .inflate(R.layout.ssl_warning, placeholder);
3709 ((TextView)ll.findViewById(R.id.warning))
3710 .setText(R.string.ssl_mismatch);
3711 }
3712
3713 if (error.hasError(SslError.SSL_EXPIRED)) {
3714 LinearLayout ll = (LinearLayout)factory
3715 .inflate(R.layout.ssl_warning, placeholder);
3716 ((TextView)ll.findViewById(R.id.warning))
3717 .setText(R.string.ssl_expired);
3718 }
3719
3720 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3721 LinearLayout ll = (LinearLayout)factory
3722 .inflate(R.layout.ssl_warning, placeholder);
3723 ((TextView)ll.findViewById(R.id.warning))
3724 .setText(R.string.ssl_not_yet_valid);
3725 }
3726
3727 mSSLCertificateOnErrorHandler = handler;
3728 mSSLCertificateOnErrorView = view;
3729 mSSLCertificateOnErrorError = error;
3730 mSSLCertificateOnErrorDialog =
3731 new AlertDialog.Builder(this)
3732 .setTitle(R.string.ssl_certificate).setIcon(
3733 R.drawable.ic_dialog_browser_certificate_partially_secure)
3734 .setView(certificateView)
3735 .setPositiveButton(R.string.ok,
3736 new DialogInterface.OnClickListener() {
3737 public void onClick(DialogInterface dialog,
3738 int whichButton) {
3739 mSSLCertificateOnErrorDialog = null;
3740 mSSLCertificateOnErrorView = null;
3741 mSSLCertificateOnErrorHandler = null;
3742 mSSLCertificateOnErrorError = null;
3743
3744 mWebViewClient.onReceivedSslError(
3745 view, handler, error);
3746 }
3747 })
3748 .setNeutralButton(R.string.page_info_view,
3749 new DialogInterface.OnClickListener() {
3750 public void onClick(DialogInterface dialog,
3751 int whichButton) {
3752 mSSLCertificateOnErrorDialog = null;
3753
3754 // do not clear the dialog state: we will
3755 // need to show the dialog again once the
3756 // user is done exploring the page-info details
3757
3758 showPageInfo(mTabControl.getTabFromView(view),
3759 true);
3760 }
3761 })
3762 .setOnCancelListener(
3763 new DialogInterface.OnCancelListener() {
3764 public void onCancel(DialogInterface dialog) {
3765 mSSLCertificateOnErrorDialog = null;
3766 mSSLCertificateOnErrorView = null;
3767 mSSLCertificateOnErrorHandler = null;
3768 mSSLCertificateOnErrorError = null;
3769
3770 mWebViewClient.onReceivedSslError(
3771 view, handler, error);
3772 }
3773 })
3774 .show();
3775 }
3776
3777 /**
3778 * Inflates the SSL certificate view (helper method).
3779 * @param certificate The SSL certificate.
3780 * @return The resultant certificate view with issued-to, issued-by,
3781 * issued-on, expires-on, and possibly other fields set.
3782 * If the input certificate is null, returns null.
3783 */
3784 private View inflateCertificateView(SslCertificate certificate) {
3785 if (certificate == null) {
3786 return null;
3787 }
3788
3789 LayoutInflater factory = LayoutInflater.from(this);
3790
3791 View certificateView = factory.inflate(
3792 R.layout.ssl_certificate, null);
3793
3794 // issued to:
3795 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3796 if (issuedTo != null) {
3797 ((TextView) certificateView.findViewById(R.id.to_common))
3798 .setText(issuedTo.getCName());
3799 ((TextView) certificateView.findViewById(R.id.to_org))
3800 .setText(issuedTo.getOName());
3801 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3802 .setText(issuedTo.getUName());
3803 }
3804
3805 // issued by:
3806 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3807 if (issuedBy != null) {
3808 ((TextView) certificateView.findViewById(R.id.by_common))
3809 .setText(issuedBy.getCName());
3810 ((TextView) certificateView.findViewById(R.id.by_org))
3811 .setText(issuedBy.getOName());
3812 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3813 .setText(issuedBy.getUName());
3814 }
3815
3816 // issued on:
3817 String issuedOn = reformatCertificateDate(
3818 certificate.getValidNotBefore());
3819 ((TextView) certificateView.findViewById(R.id.issued_on))
3820 .setText(issuedOn);
3821
3822 // expires on:
3823 String expiresOn = reformatCertificateDate(
3824 certificate.getValidNotAfter());
3825 ((TextView) certificateView.findViewById(R.id.expires_on))
3826 .setText(expiresOn);
3827
3828 return certificateView;
3829 }
3830
3831 /**
3832 * Re-formats the certificate date (Date.toString()) string to
3833 * a properly localized date string.
3834 * @return Properly localized version of the certificate date string and
3835 * the original certificate date string if fails to localize.
3836 * If the original string is null, returns an empty string "".
3837 */
3838 private String reformatCertificateDate(String certificateDate) {
3839 String reformattedDate = null;
3840
3841 if (certificateDate != null) {
3842 Date date = null;
3843 try {
3844 date = java.text.DateFormat.getInstance().parse(certificateDate);
3845 } catch (ParseException e) {
3846 date = null;
3847 }
3848
3849 if (date != null) {
3850 reformattedDate =
3851 DateFormat.getDateFormat(this).format(date);
3852 }
3853 }
3854
3855 return reformattedDate != null ? reformattedDate :
3856 (certificateDate != null ? certificateDate : "");
3857 }
3858
3859 /**
3860 * Displays an http-authentication dialog.
3861 */
3862 private void showHttpAuthentication(final HttpAuthHandler handler,
3863 final String host, final String realm, final String title,
3864 final String name, final String password, int focusId) {
3865 LayoutInflater factory = LayoutInflater.from(this);
3866 final View v = factory
3867 .inflate(R.layout.http_authentication, null);
3868 if (name != null) {
3869 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3870 }
3871 if (password != null) {
3872 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3873 }
3874
3875 String titleText = title;
3876 if (titleText == null) {
3877 titleText = getText(R.string.sign_in_to).toString().replace(
3878 "%s1", host).replace("%s2", realm);
3879 }
3880
3881 mHttpAuthHandler = handler;
3882 AlertDialog dialog = new AlertDialog.Builder(this)
3883 .setTitle(titleText)
3884 .setIcon(android.R.drawable.ic_dialog_alert)
3885 .setView(v)
3886 .setPositiveButton(R.string.action,
3887 new DialogInterface.OnClickListener() {
3888 public void onClick(DialogInterface dialog,
3889 int whichButton) {
3890 String nm = ((EditText) v
3891 .findViewById(R.id.username_edit))
3892 .getText().toString();
3893 String pw = ((EditText) v
3894 .findViewById(R.id.password_edit))
3895 .getText().toString();
3896 BrowserActivity.this.setHttpAuthUsernamePassword
3897 (host, realm, nm, pw);
3898 handler.proceed(nm, pw);
3899 mHttpAuthenticationDialog = null;
3900 mHttpAuthHandler = null;
3901 }})
3902 .setNegativeButton(R.string.cancel,
3903 new DialogInterface.OnClickListener() {
3904 public void onClick(DialogInterface dialog,
3905 int whichButton) {
3906 handler.cancel();
3907 BrowserActivity.this.resetTitleAndRevertLockIcon();
3908 mHttpAuthenticationDialog = null;
3909 mHttpAuthHandler = null;
3910 }})
3911 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3912 public void onCancel(DialogInterface dialog) {
3913 handler.cancel();
3914 BrowserActivity.this.resetTitleAndRevertLockIcon();
3915 mHttpAuthenticationDialog = null;
3916 mHttpAuthHandler = null;
3917 }})
3918 .create();
3919 // Make the IME appear when the dialog is displayed if applicable.
3920 dialog.getWindow().setSoftInputMode(
3921 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3922 dialog.show();
3923 if (focusId != 0) {
3924 dialog.findViewById(focusId).requestFocus();
3925 } else {
3926 v.findViewById(R.id.username_edit).requestFocus();
3927 }
3928 mHttpAuthenticationDialog = dialog;
3929 }
3930
3931 public int getProgress() {
3932 WebView w = mTabControl.getCurrentWebView();
3933 if (w != null) {
3934 return w.getProgress();
3935 } else {
3936 return 100;
3937 }
3938 }
3939
3940 /**
3941 * Set HTTP authentication password.
3942 *
3943 * @param host The host for the password
3944 * @param realm The realm for the password
3945 * @param username The username for the password. If it is null, it means
3946 * password can't be saved.
3947 * @param password The password
3948 */
3949 public void setHttpAuthUsernamePassword(String host, String realm,
3950 String username,
3951 String password) {
3952 WebView w = mTabControl.getCurrentWebView();
3953 if (w != null) {
3954 w.setHttpAuthUsernamePassword(host, realm, username, password);
3955 }
3956 }
3957
3958 /**
3959 * connectivity manager says net has come or gone... inform the user
3960 * @param up true if net has come up, false if net has gone down
3961 */
3962 public void onNetworkToggle(boolean up) {
3963 if (up == mIsNetworkUp) {
3964 return;
3965 } else if (up) {
3966 mIsNetworkUp = true;
3967 if (mAlertDialog != null) {
3968 mAlertDialog.cancel();
3969 mAlertDialog = null;
3970 }
3971 } else {
3972 mIsNetworkUp = false;
3973 if (mInLoad && mAlertDialog == null) {
3974 mAlertDialog = new AlertDialog.Builder(this)
3975 .setTitle(R.string.loadSuspendedTitle)
3976 .setMessage(R.string.loadSuspended)
3977 .setPositiveButton(R.string.ok, null)
3978 .show();
3979 }
3980 }
3981 WebView w = mTabControl.getCurrentWebView();
3982 if (w != null) {
3983 w.setNetworkAvailable(up);
3984 }
3985 }
3986
3987 @Override
3988 protected void onActivityResult(int requestCode, int resultCode,
3989 Intent intent) {
3990 switch (requestCode) {
3991 case COMBO_PAGE:
3992 if (resultCode == RESULT_OK && intent != null) {
3993 String data = intent.getAction();
3994 Bundle extras = intent.getExtras();
3995 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003996 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003997 } else {
3998 final TabControl.Tab currentTab =
3999 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04004000 dismissSubWindow(currentTab);
4001 if (data != null && data.length() != 0) {
4002 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004003 }
4004 }
4005 }
4006 break;
4007 default:
4008 break;
4009 }
Leon Scroggins30444232009-09-04 18:36:20 -04004010 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004011 }
4012
4013 /*
4014 * This method is called as a result of the user selecting the options
4015 * menu to see the download window, or when a download changes state. It
4016 * shows the download window ontop of the current window.
4017 */
4018 /* package */ void viewDownloads(Uri downloadRecord) {
4019 Intent intent = new Intent(this,
4020 BrowserDownloadPage.class);
4021 intent.setData(downloadRecord);
4022 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4023
4024 }
4025
Leon Scroggins160a7e72009-08-14 18:28:01 -04004026 /**
4027 * Open the Go page.
4028 * @param startWithHistory If true, open starting on the history tab.
4029 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004030 */
Leon Scroggins30444232009-09-04 18:36:20 -04004031 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004032 WebView current = mTabControl.getCurrentWebView();
4033 if (current == null) {
4034 return;
4035 }
4036 Intent intent = new Intent(this,
4037 CombinedBookmarkHistoryActivity.class);
4038 String title = current.getTitle();
4039 String url = current.getUrl();
4040 // Just in case the user opens bookmarks before a page finishes loading
4041 // so the current history item, and therefore the page, is null.
4042 if (null == url) {
4043 url = mLastEnteredUrl;
4044 // This can happen.
4045 if (null == url) {
4046 url = mSettings.getHomePage();
4047 }
4048 }
4049 // In case the web page has not yet received its associated title.
4050 if (title == null) {
4051 title = url;
4052 }
4053 intent.putExtra("title", title);
4054 intent.putExtra("url", url);
Leon Scroggins30444232009-09-04 18:36:20 -04004055 // Disable opening in a new window if we have maxed out the windows
4056 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4057 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004058 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004059 if (startWithHistory) {
4060 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4061 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4062 }
4063 startActivityForResult(intent, COMBO_PAGE);
4064 }
4065
4066 // Called when loading from context menu or LOAD_URL message
4067 private void loadURL(WebView view, String url) {
4068 // In case the user enters nothing.
4069 if (url != null && url.length() != 0 && view != null) {
4070 url = smartUrlFilter(url);
4071 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4072 view.loadUrl(url);
4073 }
4074 }
4075 }
4076
The Android Open Source Project0c908882009-03-03 19:32:16 -08004077 private String smartUrlFilter(Uri inUri) {
4078 if (inUri != null) {
4079 return smartUrlFilter(inUri.toString());
4080 }
4081 return null;
4082 }
4083
4084
4085 // get window count
4086
4087 int getWindowCount(){
4088 if(mTabControl != null){
4089 return mTabControl.getTabCount();
4090 }
4091 return 0;
4092 }
4093
Feng Qianb34f87a2009-03-24 21:27:26 -07004094 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004095 "(?i)" + // switch on case insensitive matching
4096 "(" + // begin group for schema
4097 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004098 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004099 ")" +
4100 "(.*)" );
4101
4102 /**
4103 * Attempts to determine whether user input is a URL or search
4104 * terms. Anything with a space is passed to search.
4105 *
4106 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4107 * "Http://" converts to "http://"
4108 *
4109 * @return Original or modified URL
4110 *
4111 */
4112 String smartUrlFilter(String url) {
4113
4114 String inUrl = url.trim();
4115 boolean hasSpace = inUrl.indexOf(' ') != -1;
4116
4117 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4118 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004119 // force scheme to lowercase
4120 String scheme = matcher.group(1);
4121 String lcScheme = scheme.toLowerCase();
4122 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004123 inUrl = lcScheme + matcher.group(2);
4124 }
4125 if (hasSpace) {
4126 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004127 }
4128 return inUrl;
4129 }
4130 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004131 // FIXME: Is this the correct place to add to searches?
4132 // what if someone else calls this function?
4133 int shortcut = parseUrlShortcut(inUrl);
4134 if (shortcut != SHORTCUT_INVALID) {
4135 Browser.addSearchUrl(mResolver, inUrl);
4136 String query = inUrl.substring(2);
4137 switch (shortcut) {
4138 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004139 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004140 case SHORTCUT_WIKIPEDIA_SEARCH:
4141 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4142 case SHORTCUT_DICTIONARY_SEARCH:
4143 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4144 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004145 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004146 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004147 }
4148 }
4149 } else {
4150 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4151 return URLUtil.guessUrl(inUrl);
4152 }
4153 }
4154
4155 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004156 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004157 }
4158
Ben Murdochbff2d602009-07-01 20:19:05 +01004159 /* package */ void setShouldShowErrorConsole(boolean flag) {
4160 if (flag == mShouldShowErrorConsole) {
4161 // Nothing to do.
4162 return;
4163 }
4164
4165 mShouldShowErrorConsole = flag;
4166
4167 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4168
4169 if (flag) {
4170 // Setting the show state of the console will cause it's the layout to be inflated.
4171 if (errorConsole.numberOfErrors() > 0) {
4172 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4173 } else {
4174 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4175 }
4176
4177 // Now we can add it to the main view.
4178 mErrorConsoleContainer.addView(errorConsole,
4179 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4180 ViewGroup.LayoutParams.WRAP_CONTENT));
4181 } else {
4182 mErrorConsoleContainer.removeView(errorConsole);
4183 }
4184
4185 }
4186
The Android Open Source Project0c908882009-03-03 19:32:16 -08004187 private final static int LOCK_ICON_UNSECURE = 0;
4188 private final static int LOCK_ICON_SECURE = 1;
4189 private final static int LOCK_ICON_MIXED = 2;
4190
4191 private int mLockIconType = LOCK_ICON_UNSECURE;
4192 private int mPrevLockType = LOCK_ICON_UNSECURE;
4193
4194 private BrowserSettings mSettings;
4195 private TabControl mTabControl;
4196 private ContentResolver mResolver;
4197 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004198 private View mCustomView;
4199 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004200 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004201
4202 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4203 // view, we should rewrite this.
4204 private int mCurrentMenuState = 0;
4205 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004206 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004207 private static final int EMPTY_MENU = -1;
4208 private Menu mMenu;
4209
4210 private FindDialog mFindDialog;
4211 // Used to prevent chording to result in firing two shortcuts immediately
4212 // one after another. Fixes bug 1211714.
4213 boolean mCanChord;
4214
4215 private boolean mInLoad;
4216 private boolean mIsNetworkUp;
4217
4218 private boolean mPageStarted;
4219 private boolean mActivityInPause = true;
4220
4221 private boolean mMenuIsDown;
4222
4223 private final KeyTracker mKeyTracker = new KeyTracker(this);
4224
4225 // As trackball doesn't send repeat down, we have to track it ourselves
4226 private boolean mTrackTrackball;
4227
4228 private static boolean mInTrace;
4229
4230 // Performance probe
4231 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4232 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4233 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4234 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4235 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4236 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4237 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4238 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4239 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4240 };
4241
4242 private long mStart;
4243 private long mProcessStart;
4244 private long mUserStart;
4245 private long mSystemStart;
4246 private long mIdleStart;
4247 private long mIrqStart;
4248
4249 private long mUiStart;
4250
4251 private Drawable mMixLockIcon;
4252 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004253
4254 /* hold a ref so we can auto-cancel if necessary */
4255 private AlertDialog mAlertDialog;
4256
4257 // Wait for credentials before loading google.com
4258 private ProgressDialog mCredsDlg;
4259
4260 // The up-to-date URL and title (these can be different from those stored
4261 // in WebView, since it takes some time for the information in WebView to
4262 // get updated)
4263 private String mUrl;
4264 private String mTitle;
4265
4266 // As PageInfo has different style for landscape / portrait, we have
4267 // to re-open it when configuration changed
4268 private AlertDialog mPageInfoDialog;
4269 private TabControl.Tab mPageInfoView;
4270 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4271 // dialog, we should not just dismiss it, but should get back to the
4272 // SSL-certificate-on-error dialog. This flag is used to store this state
4273 private Boolean mPageInfoFromShowSSLCertificateOnError;
4274
4275 // as SSLCertificateOnError has different style for landscape / portrait,
4276 // we have to re-open it when configuration changed
4277 private AlertDialog mSSLCertificateOnErrorDialog;
4278 private WebView mSSLCertificateOnErrorView;
4279 private SslErrorHandler mSSLCertificateOnErrorHandler;
4280 private SslError mSSLCertificateOnErrorError;
4281
4282 // as SSLCertificate has different style for landscape / portrait, we
4283 // have to re-open it when configuration changed
4284 private AlertDialog mSSLCertificateDialog;
4285 private TabControl.Tab mSSLCertificateView;
4286
4287 // as HttpAuthentication has different style for landscape / portrait, we
4288 // have to re-open it when configuration changed
4289 private AlertDialog mHttpAuthenticationDialog;
4290 private HttpAuthHandler mHttpAuthHandler;
4291
4292 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4293 new FrameLayout.LayoutParams(
4294 ViewGroup.LayoutParams.FILL_PARENT,
4295 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004296 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4297 new FrameLayout.LayoutParams(
4298 ViewGroup.LayoutParams.FILL_PARENT,
4299 ViewGroup.LayoutParams.FILL_PARENT,
4300 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004301 // Google search
4302 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004303 // Wikipedia search
4304 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4305 // Dictionary search
4306 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4307 // Google Mobile Local search
4308 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4309
4310 final static String QUERY_PLACE_HOLDER = "%s";
4311
4312 // "source" parameter for Google search through search key
4313 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4314 // "source" parameter for Google search through goto menu
4315 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4316 // "source" parameter for Google search through simplily type
4317 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4318 // "source" parameter for Google search suggested by the browser
4319 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4320 // "source" parameter for Google search from unknown source
4321 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4322
4323 private final static String LOGTAG = "browser";
4324
The Android Open Source Project0c908882009-03-03 19:32:16 -08004325 private String mLastEnteredUrl;
4326
4327 private PowerManager.WakeLock mWakeLock;
4328 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4329
4330 private Toast mStopToast;
4331
Leon Scroggins1f005d32009-08-10 17:36:42 -04004332 private TitleBarSet mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004333
Ben Murdochbff2d602009-07-01 20:19:05 +01004334 private LinearLayout mErrorConsoleContainer = null;
4335 private boolean mShouldShowErrorConsole = false;
4336
The Android Open Source Project0c908882009-03-03 19:32:16 -08004337 // As the ids are dynamically created, we can't guarantee that they will
4338 // be in sequence, so this static array maps ids to a window number.
4339 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4340 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4341 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4342 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4343
4344 // monitor platform changes
4345 private IntentFilter mNetworkStateChangedFilter;
4346 private BroadcastReceiver mNetworkStateIntentReceiver;
4347
Grace Klobab4da0ad2009-05-14 14:45:40 -07004348 private BroadcastReceiver mPackageInstallationReceiver;
4349
The Android Open Source Project0c908882009-03-03 19:32:16 -08004350 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004351 final static int COMBO_PAGE = 1;
4352 final static int DOWNLOAD_PAGE = 2;
4353 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004354
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004355 /**
4356 * A UrlData class to abstract how the content will be set to WebView.
4357 * This base class uses loadUrl to show the content.
4358 */
4359 private static class UrlData {
4360 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004361 byte[] mPostData;
4362
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004363 UrlData(String url) {
4364 this.mUrl = url;
4365 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004366
4367 void setPostData(byte[] postData) {
4368 mPostData = postData;
4369 }
4370
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004371 boolean isEmpty() {
4372 return mUrl == null || mUrl.length() == 0;
4373 }
4374
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004375 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004376 if (mPostData != null) {
4377 webView.postUrl(mUrl, mPostData);
4378 } else {
4379 webView.loadUrl(mUrl);
4380 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004381 }
4382 };
4383
4384 /**
4385 * A subclass of UrlData class that can display inlined content using
4386 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4387 */
4388 private static class InlinedUrlData extends UrlData {
4389 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4390 super(failUrl);
4391 mInlined = inlined;
4392 mMimeType = mimeType;
4393 mEncoding = encoding;
4394 }
4395 String mMimeType;
4396 String mInlined;
4397 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004398 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004399 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004400 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004401 }
4402
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004403 @Override
4404 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004405 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4406 }
4407 }
4408
Leon Scroggins1f005d32009-08-10 17:36:42 -04004409 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004410}