blob: bee8175c68dbbd2959e483bb3007525108af1f2d [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
19import com.google.android.googleapps.IGoogleLoginService;
20import com.google.android.googlelogin.GoogleLoginServiceConstants;
21
22import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080023import android.app.AlertDialog;
24import android.app.ProgressDialog;
25import android.app.SearchManager;
26import android.content.ActivityNotFoundException;
27import android.content.BroadcastReceiver;
28import android.content.ComponentName;
29import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040030import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080031import android.content.ContentValues;
32import android.content.Context;
33import android.content.DialogInterface;
34import android.content.Intent;
35import android.content.IntentFilter;
36import android.content.ServiceConnection;
37import android.content.DialogInterface.OnCancelListener;
Grace Klobab4da0ad2009-05-14 14:45:40 -070038import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080039import android.content.pm.PackageManager;
40import android.content.pm.ResolveInfo;
41import android.content.res.AssetManager;
42import android.content.res.Configuration;
43import android.content.res.Resources;
44import android.database.Cursor;
45import android.database.sqlite.SQLiteDatabase;
46import android.database.sqlite.SQLiteException;
47import android.graphics.Bitmap;
48import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.DrawFilter;
50import android.graphics.Paint;
51import android.graphics.PaintFlagsDrawFilter;
52import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040053import android.graphics.PixelFormat;
54import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080055import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080056import android.hardware.SensorListener;
57import android.hardware.SensorManager;
58import android.net.ConnectivityManager;
59import android.net.Uri;
60import android.net.WebAddress;
61import android.net.http.EventHandler;
62import android.net.http.SslCertificate;
63import android.net.http.SslError;
64import android.os.AsyncTask;
65import android.os.Bundle;
66import android.os.Debug;
67import android.os.Environment;
68import android.os.Handler;
69import android.os.IBinder;
70import android.os.Message;
71import android.os.PowerManager;
72import android.os.Process;
73import android.os.RemoteException;
74import android.os.ServiceManager;
75import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080076import android.provider.Browser;
77import android.provider.Contacts;
78import android.provider.Downloads;
79import android.provider.MediaStore;
80import android.provider.Contacts.Intents.Insert;
81import android.text.IClipboard;
82import android.text.TextUtils;
83import android.text.format.DateFormat;
84import android.text.util.Regex;
The Android Open Source Project0c908882009-03-03 19:32:16 -080085import android.util.Log;
86import android.view.ContextMenu;
87import android.view.Gravity;
88import android.view.KeyEvent;
89import android.view.LayoutInflater;
90import android.view.Menu;
91import android.view.MenuInflater;
92import android.view.MenuItem;
93import android.view.View;
94import android.view.ViewGroup;
95import android.view.Window;
96import android.view.WindowManager;
97import android.view.ContextMenu.ContextMenuInfo;
98import android.view.MenuItem.OnMenuItemClickListener;
99import android.view.animation.AlphaAnimation;
100import android.view.animation.Animation;
101import android.view.animation.AnimationSet;
102import android.view.animation.DecelerateInterpolator;
103import android.view.animation.ScaleAnimation;
104import android.view.animation.TranslateAnimation;
105import android.webkit.CookieManager;
106import android.webkit.CookieSyncManager;
107import android.webkit.DownloadListener;
Steve Block2bc69912009-07-30 14:45:13 +0100108import android.webkit.GeolocationPermissions;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800109import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -0700110import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800111import android.webkit.SslErrorHandler;
112import android.webkit.URLUtil;
113import android.webkit.WebChromeClient;
Andrei Popescuc9b55562009-07-07 10:51:15 +0100114import android.webkit.WebChromeClient.CustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800115import android.webkit.WebHistoryItem;
116import android.webkit.WebIconDatabase;
Ben Murdoch092dd5d2009-04-22 12:34:12 +0100117import android.webkit.WebStorage;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import android.webkit.WebView;
119import android.webkit.WebViewClient;
120import android.widget.EditText;
121import android.widget.FrameLayout;
122import android.widget.LinearLayout;
123import android.widget.TextView;
124import android.widget.Toast;
125
126import java.io.BufferedOutputStream;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400127import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128import java.io.File;
129import java.io.FileInputStream;
130import java.io.FileOutputStream;
131import java.io.IOException;
132import java.io.InputStream;
133import java.net.MalformedURLException;
134import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700135import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800136import java.net.URL;
137import java.net.URLEncoder;
138import java.text.ParseException;
139import java.util.Date;
140import java.util.Enumeration;
141import java.util.HashMap;
Patrick Scott37911c72009-03-24 18:02:58 -0700142import java.util.LinkedList;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800143import java.util.Vector;
144import java.util.regex.Matcher;
145import java.util.regex.Pattern;
146import java.util.zip.ZipEntry;
147import java.util.zip.ZipFile;
148
149public class BrowserActivity extends Activity
150 implements KeyTracker.OnKeyTracker,
151 View.OnCreateContextMenuListener,
152 DownloadListener {
153
Dave Bort31a6d1c2009-04-13 15:56:49 -0700154 /* Define some aliases to make these debugging flags easier to refer to.
155 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
156 */
157 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
158 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
159 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
160
The Android Open Source Project0c908882009-03-03 19:32:16 -0800161 private IGoogleLoginService mGls = null;
162 private ServiceConnection mGlsConnection = null;
163
164 private SensorManager mSensorManager = null;
165
Satish Sampath565505b2009-05-29 15:37:27 +0100166 // These are single-character shortcuts for searching popular sources.
167 private static final int SHORTCUT_INVALID = 0;
168 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
169 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
170 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
171 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
172
The Android Open Source Project0c908882009-03-03 19:32:16 -0800173 /* Whitelisted webpages
174 private static HashSet<String> sWhiteList;
175
176 static {
177 sWhiteList = new HashSet<String>();
178 sWhiteList.add("cnn.com/");
179 sWhiteList.add("espn.go.com/");
180 sWhiteList.add("nytimes.com/");
181 sWhiteList.add("engadget.com/");
182 sWhiteList.add("yahoo.com/");
183 sWhiteList.add("msn.com/");
184 sWhiteList.add("amazon.com/");
185 sWhiteList.add("consumerist.com/");
186 sWhiteList.add("google.com/m/news");
187 }
188 */
189
190 private void setupHomePage() {
191 final Runnable getAccount = new Runnable() {
192 public void run() {
193 // Lower priority
194 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
195 // get the default home page
196 String homepage = mSettings.getHomePage();
197
198 try {
199 if (mGls == null) return;
200
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700201 if (!homepage.startsWith("http://www.google.")) return;
202 if (homepage.indexOf('?') == -1) return;
203
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
205 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
206
207 // three cases:
208 //
209 // hostedUser == googleUser
210 // The device has only a google account
211 //
212 // hostedUser != googleUser
213 // The device has a hosted account and a google account
214 //
215 // hostedUser != null, googleUser == null
216 // The device has only a hosted account (so far)
217
218 // developers might have no accounts at all
219 if (hostedUser == null) return;
220
221 if (googleUser == null || !hostedUser.equals(googleUser)) {
222 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700223 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800224 }
225 } catch (RemoteException ignore) {
226 // Login service died; carry on
227 } catch (RuntimeException ignore) {
228 // Login service died; carry on
229 } finally {
230 finish(homepage);
231 }
232 }
233
234 private void finish(final String homepage) {
235 mHandler.post(new Runnable() {
236 public void run() {
237 mSettings.setHomePage(BrowserActivity.this, homepage);
238 resumeAfterCredentials();
239
240 // as this is running in a separate thread,
241 // BrowserActivity's onDestroy() may have been called,
242 // which also calls unbindService().
243 if (mGlsConnection != null) {
244 // we no longer need to keep GLS open
245 unbindService(mGlsConnection);
246 mGlsConnection = null;
247 }
248 } });
249 } };
250
251 final boolean[] done = { false };
252
253 // Open a connection to the Google Login Service. The first
254 // time the connection is established, set up the homepage depending on
255 // the account in a background thread.
256 mGlsConnection = new ServiceConnection() {
257 public void onServiceConnected(ComponentName className, IBinder service) {
258 mGls = IGoogleLoginService.Stub.asInterface(service);
259 if (done[0] == false) {
260 done[0] = true;
261 Thread account = new Thread(getAccount);
262 account.setName("GLSAccount");
263 account.start();
264 }
265 }
266 public void onServiceDisconnected(ComponentName className) {
267 mGls = null;
268 }
269 };
270
271 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
272 mGlsConnection, Context.BIND_AUTO_CREATE);
273 }
274
Cary Clarka9771242009-08-11 16:42:26 -0400275 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800276 @Override
277 public Void doInBackground(File... files) {
278 if (files != null) {
279 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400280 if (!f.delete()) {
281 Log.e(LOGTAG, f.getPath() + " was not deleted");
282 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800283 }
284 }
285 return null;
286 }
287 }
288
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400289 /**
290 * This layout holds everything you see below the status bar, including the
291 * error console, the custom view container, and the webviews.
292 */
293 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400294
The Android Open Source Project0c908882009-03-03 19:32:16 -0800295 @Override public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700296 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800297 Log.v(LOGTAG, this + " onStart");
298 }
299 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800300 // test the browser in OpenGL
301 // requestWindowFeature(Window.FEATURE_OPENGL);
302
303 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
304
305 mResolver = getContentResolver();
306
The Android Open Source Project0c908882009-03-03 19:32:16 -0800307 //
308 // start MASF proxy service
309 //
310 //Intent proxyServiceIntent = new Intent();
311 //proxyServiceIntent.setComponent
312 // (new ComponentName(
313 // "com.android.masfproxyservice",
314 // "com.android.masfproxyservice.MasfProxyService"));
315 //startService(proxyServiceIntent, null);
316
317 mSecLockIcon = Resources.getSystem().getDrawable(
318 android.R.drawable.ic_secure);
319 mMixLockIcon = Resources.getSystem().getDrawable(
320 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800321
Leon Scroggins81db3662009-06-04 17:45:11 -0400322 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
323 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400324 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
325 .inflate(R.layout.custom_screen, null);
326 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
327 R.id.main_content);
328 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
329 .findViewById(R.id.error_console);
330 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
331 .findViewById(R.id.fullscreen_custom_content);
332 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400333 mTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800334
335 // Create the tab control and our initial tab
336 mTabControl = new TabControl(this);
337
338 // Open the icon database and retain all the bookmark urls for favicons
339 retainIconsOnStartup();
340
341 // Keep a settings instance handy.
342 mSettings = BrowserSettings.getInstance();
343 mSettings.setTabControl(mTabControl);
344 mSettings.loadFromDb(this);
345
346 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
347 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
348
Grace Klobaa34f6862009-07-31 16:28:17 -0700349 /* enables registration for changes in network status from
350 http stack */
351 mNetworkStateChangedFilter = new IntentFilter();
352 mNetworkStateChangedFilter.addAction(
353 ConnectivityManager.CONNECTIVITY_ACTION);
354 mNetworkStateIntentReceiver = new BroadcastReceiver() {
355 @Override
356 public void onReceive(Context context, Intent intent) {
357 if (intent.getAction().equals(
358 ConnectivityManager.CONNECTIVITY_ACTION)) {
359 boolean down = intent.getBooleanExtra(
360 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
361 onNetworkToggle(!down);
362 }
363 }
364 };
365
Grace Kloba615c6c92009-08-03 10:22:44 -0700366 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
367 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
368 filter.addDataScheme("package");
369 mPackageInstallationReceiver = new BroadcastReceiver() {
370 @Override
371 public void onReceive(Context context, Intent intent) {
372 final String action = intent.getAction();
373 final String packageName = intent.getData()
374 .getSchemeSpecificPart();
375 final boolean replacing = intent.getBooleanExtra(
376 Intent.EXTRA_REPLACING, false);
377 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
378 // if it is replacing, refreshPlugins() when adding
379 return;
380 }
381 PackageManager pm = BrowserActivity.this.getPackageManager();
382 PackageInfo pkgInfo = null;
383 try {
384 pkgInfo = pm.getPackageInfo(packageName,
385 PackageManager.GET_PERMISSIONS);
386 } catch (PackageManager.NameNotFoundException e) {
387 return;
388 }
389 if (pkgInfo != null) {
390 String permissions[] = pkgInfo.requestedPermissions;
391 if (permissions == null) {
392 return;
393 }
394 boolean permissionOk = false;
395 for (String permit : permissions) {
396 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
397 permissionOk = true;
398 break;
399 }
400 }
401 if (permissionOk) {
402 PluginManager.getInstance(BrowserActivity.this)
403 .refreshPlugins(
404 Intent.ACTION_PACKAGE_ADDED
405 .equals(action));
406 }
407 }
408 }
409 };
410 registerReceiver(mPackageInstallationReceiver, filter);
411
Satish Sampath565505b2009-05-29 15:37:27 +0100412 // If this was a web search request, pass it on to the default web search provider.
413 if (handleWebSearchIntent(getIntent())) {
414 moveTaskToBack(true);
415 return;
416 }
417
The Android Open Source Project0c908882009-03-03 19:32:16 -0800418 if (!mTabControl.restoreState(icicle)) {
419 // clear up the thumbnail directory if we can't restore the state as
420 // none of the files in the directory are referenced any more.
421 new ClearThumbnails().execute(
422 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700423 // there is no quit on Android. But if we can't restore the state,
424 // we can treat it as a new Browser, remove the old session cookies.
425 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800426 final Intent intent = getIntent();
427 final Bundle extra = intent.getExtras();
428 // Create an initial tab.
429 // If the intent is ACTION_VIEW and data is not null, the Browser is
430 // invoked to view the content by another application. In this case,
431 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700432 UrlData urlData = getUrlDataFromIntent(intent);
433
The Android Open Source Project0c908882009-03-03 19:32:16 -0800434 final TabControl.Tab t = mTabControl.createNewTab(
435 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700436 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700437 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800438 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800439 attachTabToContentView(t);
440 WebView webView = t.getWebView();
441 if (extra != null) {
442 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
443 if (scale > 0 && scale <= 1000) {
444 webView.setInitialScale(scale);
445 }
446 }
447 // If we are not restoring from an icicle, then there is a high
448 // likely hood this is the first run. So, check to see if the
449 // homepage needs to be configured and copy any plugins from our
450 // asset directory to the data partition.
451 if ((extra == null || !extra.getBoolean("testing"))
452 && !mSettings.isLoginInitialized()) {
453 setupHomePage();
454 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800455
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700456 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400457 if (mSettings.isLoginInitialized()) {
458 webView.loadUrl(mSettings.getHomePage());
459 } else {
460 waitForCredentials();
461 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800462 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700463 if (extra != null) {
464 urlData.setPostData(extra
465 .getByteArray(Browser.EXTRA_POST_DATA));
466 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700467 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800468 }
469 } else {
470 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400471 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800472 attachTabToContentView(mTabControl.getCurrentTab());
473 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700474
Feng Qianb3c02da2009-06-29 15:58:08 -0700475 // Read JavaScript flags if it exists.
476 String jsFlags = mSettings.getJsFlags();
477 if (jsFlags.trim().length() != 0) {
478 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
479 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800480 }
481
482 @Override
483 protected void onNewIntent(Intent intent) {
484 TabControl.Tab current = mTabControl.getCurrentTab();
485 // When a tab is closed on exit, the current tab index is set to -1.
486 // Reset before proceed as Browser requires the current tab to be set.
487 if (current == null) {
488 // Try to reset the tab in case the index was incorrect.
489 current = mTabControl.getTab(0);
490 if (current == null) {
491 // No tabs at all so just ignore this intent.
492 return;
493 }
494 mTabControl.setCurrentTab(current);
495 attachTabToContentView(current);
496 resetTitleAndIcon(current.getWebView());
497 }
498 final String action = intent.getAction();
499 final int flags = intent.getFlags();
500 if (Intent.ACTION_MAIN.equals(action) ||
501 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
502 // just resume the browser
503 return;
504 }
505 if (Intent.ACTION_VIEW.equals(action)
506 || Intent.ACTION_SEARCH.equals(action)
507 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
508 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100509 // If this was a search request (e.g. search query directly typed into the address bar),
510 // pass it on to the default web search provider.
511 if (handleWebSearchIntent(intent)) {
512 return;
513 }
514
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700515 UrlData urlData = getUrlDataFromIntent(intent);
516 if (urlData.isEmpty()) {
517 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800518 }
Grace Kloba81678d92009-06-30 07:09:56 -0700519 urlData.setPostData(intent
520 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700521
Grace Klobacc634032009-07-28 15:58:19 -0700522 final String appId = intent
523 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
524 if (Intent.ACTION_VIEW.equals(action)
525 && !getPackageName().equals(appId)
526 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Patrick Scottcd115892009-07-16 09:42:58 -0400527 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700528 if (appTab != null) {
529 Log.i(LOGTAG, "Reusing tab for " + appId);
530 // Dismiss the subwindow if applicable.
531 dismissSubWindow(appTab);
532 // Since we might kill the WebView, remove it from the
533 // content view first.
534 removeTabFromContentView(appTab);
535 // Recreate the main WebView after destroying the old one.
536 // If the WebView has the same original url and is on that
537 // page, it can be reused.
538 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700539 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100540
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700541 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400542 switchToTab(mTabControl.getTabIndex(appTab));
543 if (needsLoad) {
544 urlData.loadIn(appTab.getWebView());
545 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700546 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400547 // If the tab was the current tab, we have to attach
548 // it to the view system again.
549 attachTabToContentView(appTab);
550 if (needsLoad) {
551 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700552 }
553 }
554 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400555 } else {
556 // No matching application tab, try to find a regular tab
557 // with a matching url.
558 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400559 if (appTab != null) {
560 if (current != appTab) {
561 switchToTab(mTabControl.getTabIndex(appTab));
562 }
563 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400564 } else {
565 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
566 // will be opened in a new tab unless we have reached
567 // MAX_TABS. Then the url will be opened in the current
568 // tab. If a new tab is created, it will have "true" for
569 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400570 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400571 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700572 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800573 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700574 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800575 mSettings.toggleDebugSettings();
576 return;
577 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400578 // Get rid of the subwindow if it exists
579 dismissSubWindow(current);
580 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800581 }
582 }
583 }
584
Satish Sampath565505b2009-05-29 15:37:27 +0100585 private int parseUrlShortcut(String url) {
586 if (url == null) return SHORTCUT_INVALID;
587
588 // FIXME: quick search, need to be customized by setting
589 if (url.length() > 2 && url.charAt(1) == ' ') {
590 switch (url.charAt(0)) {
591 case 'g': return SHORTCUT_GOOGLE_SEARCH;
592 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
593 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
594 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
595 }
596 }
597 return SHORTCUT_INVALID;
598 }
599
600 /**
601 * Launches the default web search activity with the query parameters if the given intent's data
602 * are identified as plain search terms and not URLs/shortcuts.
603 * @return true if the intent was handled and web search activity was launched, false if not.
604 */
605 private boolean handleWebSearchIntent(Intent intent) {
606 if (intent == null) return false;
607
608 String url = null;
609 final String action = intent.getAction();
610 if (Intent.ACTION_VIEW.equals(action)) {
611 url = intent.getData().toString();
612 } else if (Intent.ACTION_SEARCH.equals(action)
613 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
614 || Intent.ACTION_WEB_SEARCH.equals(action)) {
615 url = intent.getStringExtra(SearchManager.QUERY);
616 }
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100617 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA));
Satish Sampath565505b2009-05-29 15:37:27 +0100618 }
619
620 /**
621 * Launches the default web search activity with the query parameters if the given url string
622 * was identified as plain search terms and not URL/shortcut.
623 * @return true if the request was handled and web search activity was launched, false if not.
624 */
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100625 private boolean handleWebSearchRequest(String inUrl, Bundle appData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100626 if (inUrl == null) return false;
627
628 // In general, we shouldn't modify URL from Intent.
629 // But currently, we get the user-typed URL from search box as well.
630 String url = fixUrl(inUrl).trim();
631
632 // URLs and site specific search shortcuts are handled by the regular flow of control, so
633 // return early.
634 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100635 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100636 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
637 return false;
638 }
639
640 Browser.updateVisitedHistory(mResolver, url, false);
641 Browser.addSearchUrl(mResolver, url);
642
643 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
644 intent.addCategory(Intent.CATEGORY_DEFAULT);
645 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100646 if (appData != null) {
647 intent.putExtra(SearchManager.APP_DATA, appData);
648 }
Grace Klobacc634032009-07-28 15:58:19 -0700649 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100650 startActivity(intent);
651
652 return true;
653 }
654
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700655 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800656 String url = null;
657 if (intent != null) {
658 final String action = intent.getAction();
659 if (Intent.ACTION_VIEW.equals(action)) {
660 url = smartUrlFilter(intent.getData());
661 if (url != null && url.startsWith("content:")) {
662 /* Append mimetype so webview knows how to display */
663 String mimeType = intent.resolveType(getContentResolver());
664 if (mimeType != null) {
665 url += "?" + mimeType;
666 }
667 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700668 if ("inline:".equals(url)) {
669 return new InlinedUrlData(
670 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
671 intent.getType(),
672 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
673 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
674 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800675 } else if (Intent.ACTION_SEARCH.equals(action)
676 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
677 || Intent.ACTION_WEB_SEARCH.equals(action)) {
678 url = intent.getStringExtra(SearchManager.QUERY);
679 if (url != null) {
680 mLastEnteredUrl = url;
681 // Don't add Urls, just search terms.
682 // Urls will get added when the page is loaded.
683 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
684 Browser.updateVisitedHistory(mResolver, url, false);
685 }
686 // In general, we shouldn't modify URL from Intent.
687 // But currently, we get the user-typed URL from search box as well.
688 url = fixUrl(url);
689 url = smartUrlFilter(url);
690 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
691 if (url.contains(searchSource)) {
692 String source = null;
693 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
694 if (appData != null) {
695 source = appData.getString(SearchManager.SOURCE);
696 }
697 if (TextUtils.isEmpty(source)) {
698 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
699 }
700 url = url.replace(searchSource, "&source=android-"+source+"&");
701 }
702 }
703 }
704 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700705 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800706 }
707
708 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400709 // FIXME: Converting the url to lower case
710 // duplicates functionality in smartUrlFilter().
711 // However, changing all current callers of fixUrl to
712 // call smartUrlFilter in addition may have unwanted
713 // consequences, and is deferred for now.
714 int colon = inUrl.indexOf(':');
715 boolean allLower = true;
716 for (int index = 0; index < colon; index++) {
717 char ch = inUrl.charAt(index);
718 if (!Character.isLetter(ch)) {
719 break;
720 }
721 allLower &= Character.isLowerCase(ch);
722 if (index == colon - 1 && !allLower) {
723 inUrl = inUrl.substring(0, colon).toLowerCase()
724 + inUrl.substring(colon);
725 }
726 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800727 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
728 return inUrl;
729 if (inUrl.startsWith("http:") ||
730 inUrl.startsWith("https:")) {
731 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
732 inUrl = inUrl.replaceFirst("/", "//");
733 } else inUrl = inUrl.replaceFirst(":", "://");
734 }
735 return inUrl;
736 }
737
738 /**
739 * Looking for the pattern like this
740 *
741 * *
742 * * *
743 * *** * *******
744 * * *
745 * * *
746 * *
747 */
748 private final SensorListener mSensorListener = new SensorListener() {
749 private long mLastGestureTime;
750 private float[] mPrev = new float[3];
751 private float[] mPrevDiff = new float[3];
752 private float[] mDiff = new float[3];
753 private float[] mRevertDiff = new float[3];
754
755 public void onSensorChanged(int sensor, float[] values) {
756 boolean show = false;
757 float[] diff = new float[3];
758
759 for (int i = 0; i < 3; i++) {
760 diff[i] = values[i] - mPrev[i];
761 if (Math.abs(diff[i]) > 1) {
762 show = true;
763 }
764 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
765 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
766 // start track when there is a big move, or revert
767 mRevertDiff[i] = mDiff[i];
768 mDiff[i] = 0;
769 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
770 // reset when it is flat
771 mDiff[i] = mRevertDiff[i] = 0;
772 }
773 mDiff[i] += diff[i];
774 mPrevDiff[i] = diff[i];
775 mPrev[i] = values[i];
776 }
777
778 if (false) {
779 // only shows if we think the delta is big enough, in an attempt
780 // to detect "serious" moves left/right or up/down
781 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
782 + values[0] + ", " + values[1] + ", " + values[2] + ")"
783 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
784 + ")");
785 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
786 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
787 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
788 + mRevertDiff[2] + ")");
789 }
790
791 long now = android.os.SystemClock.uptimeMillis();
792 if (now - mLastGestureTime > 1000) {
793 mLastGestureTime = 0;
794
795 float y = mDiff[1];
796 float z = mDiff[2];
797 float ay = Math.abs(y);
798 float az = Math.abs(z);
799 float ry = mRevertDiff[1];
800 float rz = mRevertDiff[2];
801 float ary = Math.abs(ry);
802 float arz = Math.abs(rz);
803 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
804 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
805
806 if ((gestY || gestZ) && !(gestY && gestZ)) {
807 WebView view = mTabControl.getCurrentWebView();
808
809 if (view != null) {
810 if (gestZ) {
811 if (z < 0) {
812 view.zoomOut();
813 } else {
814 view.zoomIn();
815 }
816 } else {
817 view.flingScroll(0, Math.round(y * 100));
818 }
819 }
820 mLastGestureTime = now;
821 }
822 }
823 }
824
825 public void onAccuracyChanged(int sensor, int accuracy) {
826 // TODO Auto-generated method stub
827
828 }
829 };
830
831 @Override protected void onResume() {
832 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700833 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800834 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
835 }
836
837 if (!mActivityInPause) {
838 Log.e(LOGTAG, "BrowserActivity is already resumed.");
839 return;
840 }
841
Mike Reed7bfa63b2009-05-28 11:08:32 -0400842 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800843 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400844 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800845
846 if (mWakeLock.isHeld()) {
847 mHandler.removeMessages(RELEASE_WAKELOCK);
848 mWakeLock.release();
849 }
850
851 if (mCredsDlg != null) {
852 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
853 // In case credential request never comes back
854 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
855 }
856 }
857
858 registerReceiver(mNetworkStateIntentReceiver,
859 mNetworkStateChangedFilter);
860 WebView.enablePlatformNotifications();
861
862 if (mSettings.doFlick()) {
863 if (mSensorManager == null) {
864 mSensorManager = (SensorManager) getSystemService(
865 Context.SENSOR_SERVICE);
866 }
867 mSensorManager.registerListener(mSensorListener,
868 SensorManager.SENSOR_ACCELEROMETER,
869 SensorManager.SENSOR_DELAY_FASTEST);
870 } else {
871 mSensorManager = null;
872 }
873 }
874
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400875 /**
876 * Since the actual title bar is embedded in the WebView, and removing it
877 * would change its appearance, create a temporary title bar to go at
878 * the top of the screen while the menu is open.
879 */
880 private TitleBar mFakeTitleBar;
881
882 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400883 * Holder for the fake title bar. It will have a foreground shadow, as well
884 * as a white background, so the fake title bar looks like the real one.
885 */
886 private ViewGroup mFakeTitleBarHolder;
887
888 /**
889 * Layout parameters for the fake title bar within mFakeTitleBarHolder
890 */
891 private FrameLayout.LayoutParams mFakeTitleBarParams
892 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400893 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400894 ViewGroup.LayoutParams.WRAP_CONTENT);
895 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400896 * Keeps track of whether the options menu is open. This is important in
897 * determining whether to show or hide the title bar overlay.
898 */
899 private boolean mOptionsMenuOpen;
900
901 /**
902 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
903 * of whether the configuration has changed. The first onMenuOpened call
904 * after a configuration change is simply a reopening of the same menu
905 * (i.e. mIconView did not change).
906 */
907 private boolean mConfigChanged;
908
909 /**
910 * Whether or not the options menu is in its smaller, icon menu form. When
911 * true, we want the title bar overlay to be up. When false, we do not.
912 * Only meaningful if mOptionsMenuOpen is true.
913 */
914 private boolean mIconView;
915
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400916 @Override
917 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400918 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
919 if (mOptionsMenuOpen) {
920 if (mConfigChanged) {
921 // We do not need to make any changes to the state of the
922 // title bar, since the only thing that happened was a
923 // change in orientation
924 mConfigChanged = false;
925 } else {
926 if (mIconView) {
927 // Switching the menu to expanded view, so hide the
928 // title bar.
929 hideFakeTitleBar();
930 mIconView = false;
931 } else {
932 // Switching the menu back to icon view, so show the
933 // title bar once again.
934 showFakeTitleBar();
935 mIconView = true;
936 }
937 }
938 } else {
939 // The options menu is closed, so open it, and show the title
940 showFakeTitleBar();
941 mOptionsMenuOpen = true;
942 mConfigChanged = false;
943 mIconView = true;
944 }
945 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400946 return true;
947 }
948
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400949 private void showFakeTitleBar() {
Leon Scroggins4d7e4062009-09-15 15:49:45 -0400950 if (mFakeTitleBar == null && mActiveTabsPage == null
951 && !mActivityInPause) {
Leon Scrogginsf4bb18a2009-09-11 18:37:53 -0400952 final WebView webView = getTopWindow();
Leon Scroggins68579392009-09-15 15:31:54 -0400953 mFakeTitleBar = new TitleBar(this);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400954 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
955 mFakeTitleBar.setProgress(webView.getProgress());
956 mFakeTitleBar.setFavicon(webView.getFavicon());
957 updateLockIconToLatest();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400958
959 WindowManager manager
960 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
961
962 // Add the title bar to the window manager so it can receive touches
963 // while the menu is up
964 WindowManager.LayoutParams params
965 = new WindowManager.LayoutParams(
966 ViewGroup.LayoutParams.FILL_PARENT,
967 ViewGroup.LayoutParams.WRAP_CONTENT,
968 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
969 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
970 PixelFormat.OPAQUE);
971 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400972 WebView mainView = mTabControl.getCurrentWebView();
973 params.windowAnimations = mainView == null
974 || mainView.getScrollY() != 0
975 ? com.android.internal.R.style.Animation_DropDownDown : 0;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400976 // XXX : Without providing an offset, the fake title bar will be
977 // placed underneath the status bar. Use the global visible rect
978 // of mBrowserFrameLayout to determine the bottom of the status bar
979 Rect rectangle = new Rect();
980 mBrowserFrameLayout.getGlobalVisibleRect(rectangle);
981 params.y = rectangle.top;
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400982 // Add a holder for the title bar. It is a FrameLayout, which
983 // allows it to have an overlay shadow. It also has a white
984 // background, which is the same as the background when it is
985 // placed in a WebView.
986 if (mFakeTitleBarHolder == null) {
987 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
988 .inflate(R.layout.title_bar_bg, null);
989 }
990 mFakeTitleBarHolder.addView(mFakeTitleBar, mFakeTitleBarParams);
991 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400992 }
993 }
994
995 @Override
996 public void onOptionsMenuClosed(Menu menu) {
997 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400998 if (!mInLoad) {
999 hideFakeTitleBar();
1000 } else if (!mIconView) {
1001 // The page is currently loading, and we are in expanded mode, so
1002 // we were not showing the menu. Show it once again. It will be
1003 // removed when the page finishes.
1004 showFakeTitleBar();
1005 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001006 }
1007 private void hideFakeTitleBar() {
1008 if (mFakeTitleBar == null) return;
1009 WindowManager manager
1010 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001011 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1012 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001013 mFakeTitleBar = null;
1014 }
1015
The Android Open Source Project0c908882009-03-03 19:32:16 -08001016 /**
1017 * onSaveInstanceState(Bundle map)
1018 * onSaveInstanceState is called right before onStop(). The map contains
1019 * the saved state.
1020 */
1021 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001022 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001023 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1024 }
1025 // the default implementation requires each view to have an id. As the
1026 // browser handles the state itself and it doesn't use id for the views,
1027 // don't call the default implementation. Otherwise it will trigger the
1028 // warning like this, "couldn't save which view has focus because the
1029 // focused view XXX has no id".
1030
1031 // Save all the tabs
1032 mTabControl.saveState(outState);
1033 }
1034
1035 @Override protected void onPause() {
1036 super.onPause();
1037
1038 if (mActivityInPause) {
1039 Log.e(LOGTAG, "BrowserActivity is already paused.");
1040 return;
1041 }
1042
Mike Reed7bfa63b2009-05-28 11:08:32 -04001043 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001044 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001045 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001046 mWakeLock.acquire();
1047 mHandler.sendMessageDelayed(mHandler
1048 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1049 }
1050
1051 // Clear the credentials toast if it is up
1052 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1053 mCredsDlg.dismiss();
1054 }
1055 mCredsDlg = null;
1056
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001057 // FIXME: This removes the active tabs page and resets the menu to
1058 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1059 // but then we would need to save it in onSaveInstanceState and restore
1060 // it in onCreate/onRestoreInstanceState
1061 if (mActiveTabsPage != null) {
1062 removeActiveTabPage(true);
1063 }
1064
The Android Open Source Project0c908882009-03-03 19:32:16 -08001065 cancelStopToast();
1066
1067 // unregister network state listener
1068 unregisterReceiver(mNetworkStateIntentReceiver);
1069 WebView.disablePlatformNotifications();
1070
1071 if (mSensorManager != null) {
1072 mSensorManager.unregisterListener(mSensorListener);
1073 }
1074 }
1075
1076 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001077 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001078 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1079 }
1080 super.onDestroy();
1081 // Remove the current tab and sub window
1082 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001083 if (t != null) {
1084 dismissSubWindow(t);
1085 removeTabFromContentView(t);
1086 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001087 // Destroy all the tabs
1088 mTabControl.destroy();
1089 WebIconDatabase.getInstance().close();
1090 if (mGlsConnection != null) {
1091 unbindService(mGlsConnection);
1092 mGlsConnection = null;
1093 }
1094
1095 //
1096 // stop MASF proxy service
1097 //
1098 //Intent proxyServiceIntent = new Intent();
1099 //proxyServiceIntent.setComponent
1100 // (new ComponentName(
1101 // "com.android.masfproxyservice",
1102 // "com.android.masfproxyservice.MasfProxyService"));
1103 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001104
1105 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001106 }
1107
1108 @Override
1109 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001110 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001111 super.onConfigurationChanged(newConfig);
1112
1113 if (mPageInfoDialog != null) {
1114 mPageInfoDialog.dismiss();
1115 showPageInfo(
1116 mPageInfoView,
1117 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1118 }
1119 if (mSSLCertificateDialog != null) {
1120 mSSLCertificateDialog.dismiss();
1121 showSSLCertificate(
1122 mSSLCertificateView);
1123 }
1124 if (mSSLCertificateOnErrorDialog != null) {
1125 mSSLCertificateOnErrorDialog.dismiss();
1126 showSSLCertificateOnError(
1127 mSSLCertificateOnErrorView,
1128 mSSLCertificateOnErrorHandler,
1129 mSSLCertificateOnErrorError);
1130 }
1131 if (mHttpAuthenticationDialog != null) {
1132 String title = ((TextView) mHttpAuthenticationDialog
1133 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1134 .toString();
1135 String name = ((TextView) mHttpAuthenticationDialog
1136 .findViewById(R.id.username_edit)).getText().toString();
1137 String password = ((TextView) mHttpAuthenticationDialog
1138 .findViewById(R.id.password_edit)).getText().toString();
1139 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1140 .getId();
1141 mHttpAuthenticationDialog.dismiss();
1142 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1143 name, password, focusId);
1144 }
1145 if (mFindDialog != null && mFindDialog.isShowing()) {
1146 mFindDialog.onConfigurationChanged(newConfig);
1147 }
1148 }
1149
1150 @Override public void onLowMemory() {
1151 super.onLowMemory();
1152 mTabControl.freeMemory();
1153 }
1154
Mike Reed7bfa63b2009-05-28 11:08:32 -04001155 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001156 if ((!mActivityInPause && !mPageStarted) ||
1157 (mActivityInPause && mPageStarted)) {
1158 CookieSyncManager.getInstance().startSync();
1159 WebView w = mTabControl.getCurrentWebView();
1160 if (w != null) {
1161 w.resumeTimers();
1162 }
1163 return true;
1164 } else {
1165 return false;
1166 }
1167 }
1168
Mike Reed7bfa63b2009-05-28 11:08:32 -04001169 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001170 if (mActivityInPause && !mPageStarted) {
1171 CookieSyncManager.getInstance().stopSync();
1172 WebView w = mTabControl.getCurrentWebView();
1173 if (w != null) {
1174 w.pauseTimers();
1175 }
1176 return true;
1177 } else {
1178 return false;
1179 }
1180 }
1181
Leon Scroggins1f005d32009-08-10 17:36:42 -04001182 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001183 /*
1184 * This function is called when we are launching for the first time. We
1185 * are waiting for the login credentials before loading Google home
1186 * pages. This way the user will be logged in straight away.
1187 */
1188 private void waitForCredentials() {
1189 // Show a toast
1190 mCredsDlg = new ProgressDialog(this);
1191 mCredsDlg.setIndeterminate(true);
1192 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1193 // If the user cancels the operation, then cancel the Google
1194 // Credentials request.
1195 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1196 mCredsDlg.show();
1197
1198 // We set a timeout for the retrieval of credentials in onResume()
1199 // as that is when we have freed up some CPU time to get
1200 // the login credentials.
1201 }
1202
1203 /*
1204 * If we have received the credentials or we have timed out and we are
1205 * showing the credentials dialog, then it is time to move on.
1206 */
1207 private void resumeAfterCredentials() {
1208 if (mCredsDlg == null) {
1209 return;
1210 }
1211
1212 // Clear the toast
1213 if (mCredsDlg.isShowing()) {
1214 mCredsDlg.dismiss();
1215 }
1216 mCredsDlg = null;
1217
1218 // Clear any pending timeout
1219 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1220
1221 // Load the page
1222 WebView w = mTabControl.getCurrentWebView();
1223 if (w != null) {
1224 w.loadUrl(mSettings.getHomePage());
1225 }
1226
1227 // Update the settings, need to do this last as it can take a moment
1228 // to persist the settings. In the mean time we could be loading
1229 // content.
1230 mSettings.setLoginInitialized(this);
1231 }
1232
1233 // Open the icon database and retain all the icons for visited sites.
1234 private void retainIconsOnStartup() {
1235 final WebIconDatabase db = WebIconDatabase.getInstance();
1236 db.open(getDir("icons", 0).getPath());
1237 try {
1238 Cursor c = Browser.getAllBookmarks(mResolver);
1239 if (!c.moveToFirst()) {
1240 c.deactivate();
1241 return;
1242 }
1243 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1244 do {
1245 String url = c.getString(urlIndex);
1246 db.retainIconForPageUrl(url);
1247 } while (c.moveToNext());
1248 c.deactivate();
1249 } catch (IllegalStateException e) {
1250 Log.e(LOGTAG, "retainIconsOnStartup", e);
1251 }
1252 }
1253
1254 // Helper method for getting the top window.
1255 WebView getTopWindow() {
1256 return mTabControl.getCurrentTopWebView();
1257 }
1258
1259 @Override
1260 public boolean onCreateOptionsMenu(Menu menu) {
1261 super.onCreateOptionsMenu(menu);
1262
1263 MenuInflater inflater = getMenuInflater();
1264 inflater.inflate(R.menu.browser, menu);
1265 mMenu = menu;
1266 updateInLoadMenuItems();
1267 return true;
1268 }
1269
1270 /**
1271 * As the menu can be open when loading state changes
1272 * we must manually update the state of the stop/reload menu
1273 * item
1274 */
1275 private void updateInLoadMenuItems() {
1276 if (mMenu == null) {
1277 return;
1278 }
1279 MenuItem src = mInLoad ?
1280 mMenu.findItem(R.id.stop_menu_id):
1281 mMenu.findItem(R.id.reload_menu_id);
1282 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1283 dest.setIcon(src.getIcon());
1284 dest.setTitle(src.getTitle());
1285 }
1286
1287 @Override
1288 public boolean onContextItemSelected(MenuItem item) {
1289 // chording is not an issue with context menus, but we use the same
1290 // options selector, so set mCanChord to true so we can access them.
1291 mCanChord = true;
1292 int id = item.getItemId();
1293 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001294 if (null == webView) {
1295 return false;
1296 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001297 final HashMap hrefMap = new HashMap();
1298 hrefMap.put("webview", webView);
1299 final Message msg = mHandler.obtainMessage(
1300 FOCUS_NODE_HREF, id, 0, hrefMap);
1301 switch (id) {
1302 // -- Browser context menu
1303 case R.id.open_context_menu_id:
1304 case R.id.open_newtab_context_menu_id:
1305 case R.id.bookmark_context_menu_id:
1306 case R.id.save_link_context_menu_id:
1307 case R.id.share_link_context_menu_id:
1308 case R.id.copy_link_context_menu_id:
1309 webView.requestFocusNodeHref(msg);
1310 break;
1311
1312 default:
1313 // For other context menus
1314 return onOptionsItemSelected(item);
1315 }
1316 mCanChord = false;
1317 return true;
1318 }
1319
1320 private Bundle createGoogleSearchSourceBundle(String source) {
1321 Bundle bundle = new Bundle();
1322 bundle.putString(SearchManager.SOURCE, source);
1323 return bundle;
1324 }
1325
1326 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001327 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001328 */
1329 @Override
1330 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001331 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001332 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001333 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001334 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001335 return true;
1336 }
1337
1338 @Override
1339 public void startSearch(String initialQuery, boolean selectInitialQuery,
1340 Bundle appSearchData, boolean globalSearch) {
1341 if (appSearchData == null) {
1342 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1343 }
1344 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1345 }
1346
Leon Scroggins1f005d32009-08-10 17:36:42 -04001347 /**
1348 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1349 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001350 * @param index Index of the tab to change to, as defined by
1351 * mTabControl.getTabIndex(Tab t).
1352 * @return boolean True if we successfully switched to a different tab. If
1353 * the indexth tab is null, or if that tab is the same as
1354 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001355 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001356 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001357 TabControl.Tab tab = mTabControl.getTab(index);
1358 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1359 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001360 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001361 }
1362 if (currentTab != null) {
1363 // currentTab may be null if it was just removed. In that case,
1364 // we do not need to remove it
1365 removeTabFromContentView(currentTab);
1366 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001367 mTabControl.setCurrentTab(tab);
1368 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001369 resetTitleIconAndProgress();
1370 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001371 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001372 }
1373
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001374 /* package */ TabControl.Tab openTabToHomePage() {
1375 return openTabAndShow(mSettings.getHomePage(), false, null);
1376 }
1377
Leon Scroggins1f005d32009-08-10 17:36:42 -04001378 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001379 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001380 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001381 // This is the last tab. Open a new one, with the home
1382 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001383 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001384 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001385 return;
1386 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001387 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001388 int indexToShow = -1;
1389 if (parent != null) {
1390 indexToShow = mTabControl.getTabIndex(parent);
1391 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001392 final int currentIndex = mTabControl.getCurrentIndex();
1393 // Try to move to the tab to the right
1394 indexToShow = currentIndex + 1;
1395 if (indexToShow > mTabControl.getTabCount() - 1) {
1396 // Try to move to the tab to the left
1397 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001398 }
1399 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001400 if (switchToTab(indexToShow)) {
1401 // Close window
1402 closeTab(current);
1403 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001404 }
1405
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001406 private ActiveTabsPage mActiveTabsPage;
1407
1408 /**
1409 * Remove the active tabs page.
1410 * @param needToAttach If true, the active tabs page did not attach a tab
1411 * to the content view, so we need to do that here.
1412 */
1413 /* package */ void removeActiveTabPage(boolean needToAttach) {
1414 mContentView.removeView(mActiveTabsPage);
1415 mActiveTabsPage = null;
1416 mMenuState = R.id.MAIN_MENU;
1417 if (needToAttach) {
1418 attachTabToContentView(mTabControl.getCurrentTab());
1419 }
1420 getTopWindow().requestFocus();
1421 }
1422
The Android Open Source Project0c908882009-03-03 19:32:16 -08001423 @Override
1424 public boolean onOptionsItemSelected(MenuItem item) {
1425 if (!mCanChord) {
1426 // The user has already fired a shortcut with this hold down of the
1427 // menu key.
1428 return false;
1429 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001430 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001431 return false;
1432 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001433 if (mMenuIsDown) {
1434 // The shortcut action consumes the MENU. Even if it is still down,
1435 // it won't trigger the next shortcut action. In the case of the
1436 // shortcut action triggering a new activity, like Bookmarks, we
1437 // won't get onKeyUp for MENU. So it is important to reset it here.
1438 mMenuIsDown = false;
1439 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001440 switch (item.getItemId()) {
1441 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001442 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001443 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001444 break;
1445
Leon Scroggins64b80f32009-08-07 12:03:34 -04001446 case R.id.goto_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001447 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001448 break;
1449
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001450 case R.id.active_tabs_menu_id:
1451 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1452 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001453 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001454 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1455 mActiveTabsPage.requestFocus();
1456 mMenuState = EMPTY_MENU;
1457 break;
1458
Leon Scroggins1f005d32009-08-10 17:36:42 -04001459 case R.id.add_bookmark_menu_id:
1460 Intent i = new Intent(BrowserActivity.this,
1461 AddBookmarkPage.class);
1462 WebView w = getTopWindow();
1463 i.putExtra("url", w.getUrl());
1464 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001465 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Leon Scroggins1f005d32009-08-10 17:36:42 -04001466 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001467 break;
1468
1469 case R.id.stop_reload_menu_id:
1470 if (mInLoad) {
1471 stopLoading();
1472 } else {
1473 getTopWindow().reload();
1474 }
1475 break;
1476
1477 case R.id.back_menu_id:
1478 getTopWindow().goBack();
1479 break;
1480
1481 case R.id.forward_menu_id:
1482 getTopWindow().goForward();
1483 break;
1484
1485 case R.id.close_menu_id:
1486 // Close the subwindow if it exists.
1487 if (mTabControl.getCurrentSubWindow() != null) {
1488 dismissSubWindow(mTabControl.getCurrentTab());
1489 break;
1490 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001491 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001492 break;
1493
1494 case R.id.homepage_menu_id:
1495 TabControl.Tab current = mTabControl.getCurrentTab();
1496 if (current != null) {
1497 dismissSubWindow(current);
1498 current.getWebView().loadUrl(mSettings.getHomePage());
1499 }
1500 break;
1501
1502 case R.id.preferences_menu_id:
1503 Intent intent = new Intent(this,
1504 BrowserPreferencesPage.class);
1505 startActivityForResult(intent, PREFERENCES_PAGE);
1506 break;
1507
1508 case R.id.find_menu_id:
1509 if (null == mFindDialog) {
1510 mFindDialog = new FindDialog(this);
1511 }
1512 mFindDialog.setWebView(getTopWindow());
1513 mFindDialog.show();
1514 mMenuState = EMPTY_MENU;
1515 break;
1516
1517 case R.id.select_text_id:
1518 getTopWindow().emulateShiftHeld();
1519 break;
1520 case R.id.page_info_menu_id:
1521 showPageInfo(mTabControl.getCurrentTab(), false);
1522 break;
1523
1524 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001525 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001526 break;
1527
1528 case R.id.share_page_menu_id:
1529 Browser.sendString(this, getTopWindow().getUrl());
1530 break;
1531
1532 case R.id.dump_nav_menu_id:
1533 getTopWindow().debugDump();
1534 break;
1535
1536 case R.id.zoom_in_menu_id:
1537 getTopWindow().zoomIn();
1538 break;
1539
1540 case R.id.zoom_out_menu_id:
1541 getTopWindow().zoomOut();
1542 break;
1543
1544 case R.id.view_downloads_menu_id:
1545 viewDownloads(null);
1546 break;
1547
The Android Open Source Project0c908882009-03-03 19:32:16 -08001548 case R.id.window_one_menu_id:
1549 case R.id.window_two_menu_id:
1550 case R.id.window_three_menu_id:
1551 case R.id.window_four_menu_id:
1552 case R.id.window_five_menu_id:
1553 case R.id.window_six_menu_id:
1554 case R.id.window_seven_menu_id:
1555 case R.id.window_eight_menu_id:
1556 {
1557 int menuid = item.getItemId();
1558 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1559 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1560 TabControl.Tab desiredTab = mTabControl.getTab(id);
1561 if (desiredTab != null &&
1562 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001563 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001564 }
1565 break;
1566 }
1567 }
1568 }
1569 break;
1570
1571 default:
1572 if (!super.onOptionsItemSelected(item)) {
1573 return false;
1574 }
1575 // Otherwise fall through.
1576 }
1577 mCanChord = false;
1578 return true;
1579 }
1580
1581 public void closeFind() {
1582 mMenuState = R.id.MAIN_MENU;
1583 }
1584
1585 @Override public boolean onPrepareOptionsMenu(Menu menu)
1586 {
1587 // This happens when the user begins to hold down the menu key, so
1588 // allow them to chord to get a shortcut.
1589 mCanChord = true;
1590 // Note: setVisible will decide whether an item is visible; while
1591 // setEnabled() will decide whether an item is enabled, which also means
1592 // whether the matching shortcut key will function.
1593 super.onPrepareOptionsMenu(menu);
1594 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001595 case EMPTY_MENU:
1596 if (mCurrentMenuState != mMenuState) {
1597 menu.setGroupVisible(R.id.MAIN_MENU, false);
1598 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1599 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001600 }
1601 break;
1602 default:
1603 if (mCurrentMenuState != mMenuState) {
1604 menu.setGroupVisible(R.id.MAIN_MENU, true);
1605 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1606 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001607 }
1608 final WebView w = getTopWindow();
1609 boolean canGoBack = false;
1610 boolean canGoForward = false;
1611 boolean isHome = false;
1612 if (w != null) {
1613 canGoBack = w.canGoBack();
1614 canGoForward = w.canGoForward();
1615 isHome = mSettings.getHomePage().equals(w.getUrl());
1616 }
1617 final MenuItem back = menu.findItem(R.id.back_menu_id);
1618 back.setEnabled(canGoBack);
1619
1620 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1621 home.setEnabled(!isHome);
1622
1623 menu.findItem(R.id.forward_menu_id)
1624 .setEnabled(canGoForward);
1625
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001626 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1627 mTabControl.getTabCount() < TabControl.MAX_TABS);
1628
The Android Open Source Project0c908882009-03-03 19:32:16 -08001629 // decide whether to show the share link option
1630 PackageManager pm = getPackageManager();
1631 Intent send = new Intent(Intent.ACTION_SEND);
1632 send.setType("text/plain");
1633 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1634 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1635
The Android Open Source Project0c908882009-03-03 19:32:16 -08001636 boolean isNavDump = mSettings.isNavDump();
1637 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1638 nav.setVisible(isNavDump);
1639 nav.setEnabled(isNavDump);
1640 break;
1641 }
1642 mCurrentMenuState = mMenuState;
1643 return true;
1644 }
1645
1646 @Override
1647 public void onCreateContextMenu(ContextMenu menu, View v,
1648 ContextMenuInfo menuInfo) {
1649 WebView webview = (WebView) v;
1650 WebView.HitTestResult result = webview.getHitTestResult();
1651 if (result == null) {
1652 return;
1653 }
1654
1655 int type = result.getType();
1656 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1657 Log.w(LOGTAG,
1658 "We should not show context menu when nothing is touched");
1659 return;
1660 }
1661 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1662 // let TextView handles context menu
1663 return;
1664 }
1665
1666 // Note, http://b/issue?id=1106666 is requesting that
1667 // an inflated menu can be used again. This is not available
1668 // yet, so inflate each time (yuk!)
1669 MenuInflater inflater = getMenuInflater();
1670 inflater.inflate(R.menu.browsercontext, menu);
1671
1672 // Show the correct menu group
1673 String extra = result.getExtra();
1674 menu.setGroupVisible(R.id.PHONE_MENU,
1675 type == WebView.HitTestResult.PHONE_TYPE);
1676 menu.setGroupVisible(R.id.EMAIL_MENU,
1677 type == WebView.HitTestResult.EMAIL_TYPE);
1678 menu.setGroupVisible(R.id.GEO_MENU,
1679 type == WebView.HitTestResult.GEO_TYPE);
1680 menu.setGroupVisible(R.id.IMAGE_MENU,
1681 type == WebView.HitTestResult.IMAGE_TYPE
1682 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1683 menu.setGroupVisible(R.id.ANCHOR_MENU,
1684 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1685 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1686
1687 // Setup custom handling depending on the type
1688 switch (type) {
1689 case WebView.HitTestResult.PHONE_TYPE:
1690 menu.setHeaderTitle(Uri.decode(extra));
1691 menu.findItem(R.id.dial_context_menu_id).setIntent(
1692 new Intent(Intent.ACTION_VIEW, Uri
1693 .parse(WebView.SCHEME_TEL + extra)));
1694 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1695 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1696 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1697 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1698 addIntent);
1699 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1700 new Copy(extra));
1701 break;
1702
1703 case WebView.HitTestResult.EMAIL_TYPE:
1704 menu.setHeaderTitle(extra);
1705 menu.findItem(R.id.email_context_menu_id).setIntent(
1706 new Intent(Intent.ACTION_VIEW, Uri
1707 .parse(WebView.SCHEME_MAILTO + extra)));
1708 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1709 new Copy(extra));
1710 break;
1711
1712 case WebView.HitTestResult.GEO_TYPE:
1713 menu.setHeaderTitle(extra);
1714 menu.findItem(R.id.map_context_menu_id).setIntent(
1715 new Intent(Intent.ACTION_VIEW, Uri
1716 .parse(WebView.SCHEME_GEO
1717 + URLEncoder.encode(extra))));
1718 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1719 new Copy(extra));
1720 break;
1721
1722 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1723 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1724 TextView titleView = (TextView) LayoutInflater.from(this)
1725 .inflate(android.R.layout.browser_link_context_header,
1726 null);
1727 titleView.setText(extra);
1728 menu.setHeaderView(titleView);
1729 // decide whether to show the open link in new tab option
1730 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1731 mTabControl.getTabCount() < TabControl.MAX_TABS);
1732 PackageManager pm = getPackageManager();
1733 Intent send = new Intent(Intent.ACTION_SEND);
1734 send.setType("text/plain");
1735 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1736 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1737 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1738 break;
1739 }
1740 // otherwise fall through to handle image part
1741 case WebView.HitTestResult.IMAGE_TYPE:
1742 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1743 menu.setHeaderTitle(extra);
1744 }
1745 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1746 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1747 menu.findItem(R.id.download_context_menu_id).
1748 setOnMenuItemClickListener(new Download(extra));
1749 break;
1750
1751 default:
1752 Log.w(LOGTAG, "We should not get here.");
1753 break;
1754 }
1755 }
1756
The Android Open Source Project0c908882009-03-03 19:32:16 -08001757 // Attach the given tab to the content view.
1758 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001759 // Attach the container that contains the main WebView and any other UI
1760 // associated with the tab.
1761 mContentView.addView(t.getContainer(), COVER_SCREEN_PARAMS);
Ben Murdochbff2d602009-07-01 20:19:05 +01001762
1763 if (mShouldShowErrorConsole) {
1764 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1765 if (errorConsole.numberOfErrors() == 0) {
1766 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1767 } else {
1768 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1769 }
1770
1771 mErrorConsoleContainer.addView(errorConsole,
1772 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1773 ViewGroup.LayoutParams.WRAP_CONTENT));
1774 }
1775
Grace Klobaeb6eef42009-09-15 17:56:32 -07001776 if (t == mTabControl.getCurrentTab()) {
1777 setLockIconType(t.getLockIconType());
1778 setPrevLockType(t.getPrevLockIconType());
1779 }
1780
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001781 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001782 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001783 // Attach the sub window if necessary
1784 attachSubWindow(t);
1785 // Request focus on the top window.
1786 t.getTopWindow().requestFocus();
1787 }
1788
1789 // Attach a sub window to the main WebView of the given tab.
1790 private void attachSubWindow(TabControl.Tab t) {
1791 // If a sub window exists, attach it to the content view.
1792 final WebView subView = t.getSubWebView();
1793 if (subView != null) {
1794 final View container = t.getSubWebViewContainer();
1795 mContentView.addView(container, COVER_SCREEN_PARAMS);
1796 subView.requestFocus();
1797 }
1798 }
1799
1800 // Remove the given tab from the content view.
1801 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001802 // Remove the container that contains the main WebView.
1803 mContentView.removeView(t.getContainer());
Ben Murdochbff2d602009-07-01 20:19:05 +01001804
1805 if (mTabControl.getCurrentErrorConsole(false) != null) {
1806 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1807 }
1808
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001809 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001810 if (view != null) {
1811 view.setEmbeddedTitleBar(null);
1812 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001813
The Android Open Source Project0c908882009-03-03 19:32:16 -08001814 // Remove the sub window if it exists.
1815 if (t.getSubWebView() != null) {
1816 mContentView.removeView(t.getSubWebViewContainer());
1817 }
Grace Klobaeb6eef42009-09-15 17:56:32 -07001818
1819 if (t == mTabControl.getCurrentTab()) {
1820 t.setLockIconType(getLockIconType());
1821 t.setPrevLockIconType(getPrevLockType());
1822 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001823 }
1824
1825 // Remove the sub window if it exists. Also called by TabControl when the
1826 // user clicks the 'X' to dismiss a sub window.
1827 /* package */ void dismissSubWindow(TabControl.Tab t) {
1828 final WebView mainView = t.getWebView();
1829 if (t.getSubWebView() != null) {
1830 // Remove the container view and request focus on the main WebView.
1831 mContentView.removeView(t.getSubWebViewContainer());
1832 mainView.requestFocus();
1833 // Tell the TabControl to dismiss the subwindow. This will destroy
1834 // the WebView.
1835 mTabControl.dismissSubWindow(t);
1836 }
1837 }
1838
Leon Scroggins1f005d32009-08-10 17:36:42 -04001839 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001840 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001841 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1842 String appId) {
1843 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001844 }
1845
1846 // This method does a ton of stuff. It will attempt to create a new tab
1847 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001848 // url isn't null, it will load the given url.
1849 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001850 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001851 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1852 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1853 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001854 final TabControl.Tab tab = mTabControl.createNewTab(
1855 closeOnExit, appId, urlData.mUrl);
1856 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001857 // If the last tab was removed from the active tabs page, currentTab
1858 // will be null.
1859 if (currentTab != null) {
1860 removeTabFromContentView(currentTab);
1861 }
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);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001865 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001866 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001867 urlData.loadIn(webview);
1868 }
1869 return tab;
1870 } else {
1871 // Get rid of the subwindow if it exists
1872 dismissSubWindow(currentTab);
1873 if (!urlData.isEmpty()) {
1874 // Load the given url.
1875 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001876 }
1877 }
Grace Klobac9181842009-04-14 08:53:22 -07001878 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001879 }
1880
Grace Klobac9181842009-04-14 08:53:22 -07001881 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001882 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001883 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001884 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001885 WebView view = t.getWebView();
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 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001932 * Resets the browser title-view to whatever it must be
1933 * (for example, if we had a loading error)
1934 * When we have a new page, we call resetTitle, when we
1935 * have to reset the titlebar to whatever it used to be
1936 * (for example, if the user chose to stop loading), we
1937 * call resetTitleAndRevertLockIcon.
1938 */
1939 /* package */ void resetTitleAndRevertLockIcon() {
1940 revertLockIcon();
1941 resetTitleIconAndProgress();
1942 }
1943
1944 /**
1945 * Reset the title, favicon, and progress.
1946 */
1947 private void resetTitleIconAndProgress() {
1948 WebView current = mTabControl.getCurrentWebView();
1949 if (current == null) {
1950 return;
1951 }
1952 resetTitleAndIcon(current);
1953 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001954 mWebChromeClient.onProgressChanged(current, progress);
1955 }
1956
1957 // Reset the title and the icon based on the given item.
1958 private void resetTitleAndIcon(WebView view) {
1959 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1960 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001961 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001962 setFavicon(item.getFavicon());
1963 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001964 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001965 setFavicon(null);
1966 }
1967 }
1968
1969 /**
1970 * Sets a title composed of the URL and the title string.
1971 * @param url The URL of the site being loaded.
1972 * @param title The title of the site being loaded.
1973 */
Leon Scroggins68579392009-09-15 15:31:54 -04001974 private void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001975 mUrl = url;
1976 mTitle = title;
1977
Leon Scroggins68579392009-09-15 15:31:54 -04001978 mTitleBar.setTitleAndUrl(title, url);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001979 if (mFakeTitleBar != null) {
1980 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001981 }
1982 }
1983
1984 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001985 * @param url The URL to build a title version of the URL from.
1986 * @return The title version of the URL or null if fails.
1987 * The title version of the URL can be either the URL hostname,
1988 * or the hostname with an "https://" prefix (for secure URLs),
1989 * or an empty string if, for example, the URL in question is a
1990 * file:// URL with no hostname.
1991 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001992 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001993 String titleUrl = null;
1994
1995 if (url != null) {
1996 try {
1997 // parse the url string
1998 URL urlObj = new URL(url);
1999 if (urlObj != null) {
2000 titleUrl = "";
2001
2002 String protocol = urlObj.getProtocol();
2003 String host = urlObj.getHost();
2004
2005 if (host != null && 0 < host.length()) {
2006 titleUrl = host;
2007 if (protocol != null) {
2008 // if a secure site, add an "https://" prefix!
2009 if (protocol.equalsIgnoreCase("https")) {
2010 titleUrl = protocol + "://" + host;
2011 }
2012 }
2013 }
2014 }
2015 } catch (MalformedURLException e) {}
2016 }
2017
2018 return titleUrl;
2019 }
2020
2021 // Set the favicon in the title bar.
2022 private void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002023 mTitleBar.setFavicon(icon);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002024 if (mFakeTitleBar != null) {
2025 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002026 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002027 }
2028
2029 /**
2030 * Saves the current lock-icon state before resetting
2031 * the lock icon. If we have an error, we may need to
2032 * roll back to the previous state.
2033 */
2034 private void saveLockIcon() {
2035 mPrevLockType = mLockIconType;
2036 }
2037
2038 /**
2039 * Reverts the lock-icon state to the last saved state,
2040 * for example, if we had an error, and need to cancel
2041 * the load.
2042 */
2043 private void revertLockIcon() {
2044 mLockIconType = mPrevLockType;
2045
Dave Bort31a6d1c2009-04-13 15:56:49 -07002046 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002047 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2048 " revert lock icon to " + mLockIconType);
2049 }
2050
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002051 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002052 }
2053
Leon Scroggins1f005d32009-08-10 17:36:42 -04002054 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002055 * Close the tab, remove its associated title bar, and adjust mTabControl's
2056 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002057 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002058 /* package */ void closeTab(TabControl.Tab t) {
2059 int currentIndex = mTabControl.getCurrentIndex();
2060 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002061 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002062 if (currentIndex >= removeIndex && currentIndex != 0) {
2063 currentIndex--;
2064 }
2065 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
The Android Open Source Project0c908882009-03-03 19:32:16 -08002066 }
2067
2068 private void goBackOnePageOrQuit() {
2069 TabControl.Tab current = mTabControl.getCurrentTab();
2070 if (current == null) {
2071 /*
2072 * Instead of finishing the activity, simply push this to the back
2073 * of the stack and let ActivityManager to choose the foreground
2074 * activity. As BrowserActivity is singleTask, it will be always the
2075 * root of the task. So we can use either true or false for
2076 * moveTaskToBack().
2077 */
2078 moveTaskToBack(true);
2079 }
2080 WebView w = current.getWebView();
2081 if (w.canGoBack()) {
2082 w.goBack();
2083 } else {
2084 // Check to see if we are closing a window that was created by
2085 // another window. If so, we switch back to that window.
2086 TabControl.Tab parent = current.getParentTab();
2087 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002088 switchToTab(mTabControl.getTabIndex(parent));
2089 // Now we close the other tab
2090 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002091 } else {
2092 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002093 // force mPageStarted to be false as we are going to either
2094 // finish the activity or remove the tab. This will ensure
2095 // pauseWebView() taking action.
2096 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002097 if (mTabControl.getTabCount() == 1) {
2098 finish();
2099 return;
2100 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002101 // call pauseWebViewTimers() now, we won't be able to call
2102 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002103 // Temporarily change mActivityInPause to be true as
2104 // pauseWebViewTimers() will do nothing if mActivityInPause
2105 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002106 boolean savedState = mActivityInPause;
2107 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002108 Log.e(LOGTAG, "BrowserActivity is already paused "
2109 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002110 }
2111 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002112 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002113 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002114 removeTabFromContentView(current);
2115 mTabControl.removeTab(current);
2116 }
2117 /*
2118 * Instead of finishing the activity, simply push this to the back
2119 * of the stack and let ActivityManager to choose the foreground
2120 * activity. As BrowserActivity is singleTask, it will be always the
2121 * root of the task. So we can use either true or false for
2122 * moveTaskToBack().
2123 */
2124 moveTaskToBack(true);
2125 }
2126 }
2127 }
2128
2129 public KeyTracker.State onKeyTracker(int keyCode,
2130 KeyEvent event,
2131 KeyTracker.Stage stage,
2132 int duration) {
2133 // if onKeyTracker() is called after activity onStop()
2134 // because of accumulated key events,
2135 // we should ignore it as browser is not active any more.
2136 WebView topWindow = getTopWindow();
Andrei Popescuadc008d2009-06-26 14:11:30 +01002137 if (topWindow == null && mCustomView == null)
The Android Open Source Project0c908882009-03-03 19:32:16 -08002138 return KeyTracker.State.NOT_TRACKING;
2139
2140 if (keyCode == KeyEvent.KEYCODE_BACK) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01002141 // Check if a custom view is currently showing and, if it is, hide it.
2142 if (mCustomView != null) {
2143 mWebChromeClient.onHideCustomView();
2144 return KeyTracker.State.DONE_TRACKING;
2145 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002146 if (stage == KeyTracker.Stage.LONG_REPEAT) {
Leon Scroggins30444232009-09-04 18:36:20 -04002147 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002148 return KeyTracker.State.DONE_TRACKING;
2149 } else if (stage == KeyTracker.Stage.UP) {
2150 // FIXME: Currently, we do not have a notion of the
2151 // history picker for the subwindow, but maybe we
2152 // should?
2153 WebView subwindow = mTabControl.getCurrentSubWindow();
2154 if (subwindow != null) {
2155 if (subwindow.canGoBack()) {
2156 subwindow.goBack();
2157 } else {
2158 dismissSubWindow(mTabControl.getCurrentTab());
2159 }
2160 } else {
2161 goBackOnePageOrQuit();
2162 }
2163 return KeyTracker.State.DONE_TRACKING;
2164 }
2165 return KeyTracker.State.KEEP_TRACKING;
2166 }
2167 return KeyTracker.State.NOT_TRACKING;
2168 }
2169
2170 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2171 if (keyCode == KeyEvent.KEYCODE_MENU) {
2172 mMenuIsDown = true;
Grace Kloba6ee9c492009-07-13 10:04:34 -07002173 } else if (mMenuIsDown) {
2174 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2175 // still down, we don't want to trigger the search. Pretend to
2176 // consume the key and do nothing.
2177 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002178 }
2179 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2180 if (!handled) {
2181 switch (keyCode) {
2182 case KeyEvent.KEYCODE_SPACE:
2183 if (event.isShiftPressed()) {
2184 getTopWindow().pageUp(false);
2185 } else {
2186 getTopWindow().pageDown(false);
2187 }
2188 handled = true;
2189 break;
2190
2191 default:
2192 break;
2193 }
2194 }
2195 return handled || super.onKeyDown(keyCode, event);
2196 }
2197
2198 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2199 if (keyCode == KeyEvent.KEYCODE_MENU) {
2200 mMenuIsDown = false;
2201 }
2202 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2203 }
2204
Leon Scroggins68579392009-09-15 15:31:54 -04002205 /* package */ void stopLoading() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002206 resetTitleAndRevertLockIcon();
2207 WebView w = getTopWindow();
2208 w.stopLoading();
2209 mWebViewClient.onPageFinished(w, w.getUrl());
2210
2211 cancelStopToast();
2212 mStopToast = Toast
2213 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2214 mStopToast.show();
2215 }
2216
2217 private void cancelStopToast() {
2218 if (mStopToast != null) {
2219 mStopToast.cancel();
2220 mStopToast = null;
2221 }
2222 }
2223
2224 // called by a non-UI thread to post the message
2225 public void postMessage(int what, int arg1, int arg2, Object obj) {
2226 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2227 }
2228
2229 // public message ids
2230 public final static int LOAD_URL = 1001;
2231 public final static int STOP_LOAD = 1002;
2232
2233 // Message Ids
2234 private static final int FOCUS_NODE_HREF = 102;
2235 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002236 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002237
2238 // Private handler for handling javascript and saving passwords
2239 private Handler mHandler = new Handler() {
2240
2241 public void handleMessage(Message msg) {
2242 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002243 case FOCUS_NODE_HREF:
2244 String url = (String) msg.getData().get("url");
2245 if (url == null || url.length() == 0) {
2246 break;
2247 }
2248 HashMap focusNodeMap = (HashMap) msg.obj;
2249 WebView view = (WebView) focusNodeMap.get("webview");
2250 // Only apply the action if the top window did not change.
2251 if (getTopWindow() != view) {
2252 break;
2253 }
2254 switch (msg.arg1) {
2255 case R.id.open_context_menu_id:
2256 case R.id.view_image_context_menu_id:
2257 loadURL(getTopWindow(), url);
2258 break;
2259 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002260 final TabControl.Tab parent = mTabControl
2261 .getCurrentTab();
2262 final TabControl.Tab newTab = openTab(url);
2263 if (newTab != parent) {
2264 parent.addChildTab(newTab);
2265 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002266 break;
2267 case R.id.bookmark_context_menu_id:
2268 Intent intent = new Intent(BrowserActivity.this,
2269 AddBookmarkPage.class);
2270 intent.putExtra("url", url);
2271 startActivity(intent);
2272 break;
2273 case R.id.share_link_context_menu_id:
2274 Browser.sendString(BrowserActivity.this, url);
2275 break;
2276 case R.id.copy_link_context_menu_id:
2277 copy(url);
2278 break;
2279 case R.id.save_link_context_menu_id:
2280 case R.id.download_context_menu_id:
2281 onDownloadStartNoStream(url, null, null, null, -1);
2282 break;
2283 }
2284 break;
2285
2286 case LOAD_URL:
2287 loadURL(getTopWindow(), (String) msg.obj);
2288 break;
2289
2290 case STOP_LOAD:
2291 stopLoading();
2292 break;
2293
2294 case CANCEL_CREDS_REQUEST:
2295 resumeAfterCredentials();
2296 break;
2297
The Android Open Source Project0c908882009-03-03 19:32:16 -08002298 case RELEASE_WAKELOCK:
2299 if (mWakeLock.isHeld()) {
2300 mWakeLock.release();
2301 }
2302 break;
2303 }
2304 }
2305 };
2306
Leon Scroggins89c6d362009-07-15 16:54:37 -04002307 private void updateScreenshot(WebView view) {
2308 // If this is a bookmarked site, add a screenshot to the database.
2309 // FIXME: When should we update? Every time?
2310 // FIXME: Would like to make sure there is actually something to
2311 // draw, but the API for that (WebViewCore.pictureReady()) is not
2312 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002313 ContentResolver cr = getContentResolver();
2314 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002315 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002316 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002317 boolean succeed = c.moveToFirst();
2318 ContentValues values = null;
2319 while (succeed) {
2320 if (values == null) {
2321 final ByteArrayOutputStream os
2322 = new ByteArrayOutputStream();
2323 Picture thumbnail = view.capturePicture();
2324 // Keep width and height in sync with BrowserBookmarksPage
2325 // and bookmark_thumb
2326 Bitmap bm = Bitmap.createBitmap(100, 80,
2327 Bitmap.Config.ARGB_4444);
2328 Canvas canvas = new Canvas(bm);
2329 // May need to tweak these values to determine what is the
2330 // best scale factor
2331 canvas.scale(.5f, .5f);
2332 thumbnail.draw(canvas);
2333 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2334 values = new ContentValues();
2335 values.put(Browser.BookmarkColumns.THUMBNAIL,
2336 os.toByteArray());
2337 }
2338 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2339 c.getInt(0)), values, null, null);
2340 succeed = c.moveToNext();
2341 }
2342 c.close();
2343 }
2344 }
2345
The Android Open Source Project0c908882009-03-03 19:32:16 -08002346 // -------------------------------------------------------------------------
2347 // WebViewClient implementation.
2348 //-------------------------------------------------------------------------
2349
2350 // Use in overrideUrlLoading
2351 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2352 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2353 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2354 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2355
2356 /* package */ WebViewClient getWebViewClient() {
2357 return mWebViewClient;
2358 }
2359
Patrick Scott3918d442009-08-04 13:22:29 -04002360 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002361 if (icon != null) {
2362 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott3918d442009-08-04 13:22:29 -04002363 view, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002364 }
2365 setFavicon(icon);
2366 }
2367
2368 private final WebViewClient mWebViewClient = new WebViewClient() {
2369 @Override
2370 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2371 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002372 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002373
2374 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2375 if (errorConsole != null) {
2376 errorConsole.clearErrorMessages();
2377 if (mShouldShowErrorConsole) {
2378 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2379 }
2380 }
2381
The Android Open Source Project0c908882009-03-03 19:32:16 -08002382 // Call updateIcon instead of setFavicon so the bookmark
2383 // database can be updated.
Patrick Scott3918d442009-08-04 13:22:29 -04002384 updateIcon(view, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002385
Grace Kloba4d7880f2009-08-12 09:35:42 -07002386 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002387 String host;
2388 try {
2389 WebAddress uri = new WebAddress(url);
2390 host = uri.mHost;
2391 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002392 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002393 }
2394 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002395 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002396 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002397 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002398 }
2399
2400 // Performance probe
2401 if (false) {
2402 mStart = SystemClock.uptimeMillis();
2403 mProcessStart = Process.getElapsedCpuTime();
2404 long[] sysCpu = new long[7];
2405 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2406 sysCpu, null)) {
2407 mUserStart = sysCpu[0] + sysCpu[1];
2408 mSystemStart = sysCpu[2];
2409 mIdleStart = sysCpu[3];
2410 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2411 }
2412 mUiStart = SystemClock.currentThreadTimeMillis();
2413 }
2414
2415 if (!mPageStarted) {
2416 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002417 // if onResume() has been called, resumeWebViewTimers() does
2418 // nothing.
2419 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002420 }
2421
2422 // reset sync timer to avoid sync starts during loading a page
2423 CookieSyncManager.getInstance().resetSync();
2424
2425 mInLoad = true;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002426 WebView currentWebView = mTabControl.getCurrentWebView();
2427 if (currentWebView == null || currentWebView.getScrollY() != 0) {
2428 // This page has begun to load, so show the title bar
2429 showFakeTitleBar();
2430 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002431 updateInLoadMenuItems();
2432 if (!mIsNetworkUp) {
2433 if ( mAlertDialog == null) {
2434 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2435 .setTitle(R.string.loadSuspendedTitle)
2436 .setMessage(R.string.loadSuspended)
2437 .setPositiveButton(R.string.ok, null)
2438 .show();
2439 }
2440 if (view != null) {
2441 view.setNetworkAvailable(false);
2442 }
2443 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002444 }
2445
2446 @Override
2447 public void onPageFinished(WebView view, String url) {
2448 // Reset the title and icon in case we stopped a provisional
2449 // load.
2450 resetTitleAndIcon(view);
2451
2452 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002453 updateLockIconToLatest();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002454 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002455
The Android Open Source Project0c908882009-03-03 19:32:16 -08002456 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002457 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002458 long[] sysCpu = new long[7];
2459 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2460 sysCpu, null)) {
2461 String uiInfo = "UI thread used "
2462 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2463 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002464 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002465 Log.d(LOGTAG, uiInfo);
2466 }
2467 //The string that gets written to the log
2468 String performanceString = "It took total "
2469 + (SystemClock.uptimeMillis() - mStart)
2470 + " ms clock time to load the page."
2471 + "\nbrowser process used "
2472 + (Process.getElapsedCpuTime() - mProcessStart)
2473 + " ms, user processes used "
2474 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2475 + " ms, kernel used "
2476 + (sysCpu[2] - mSystemStart) * 10
2477 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2478 + " ms and irq took "
2479 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2480 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002481 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002482 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2483 }
2484 if (url != null) {
2485 // strip the url to maintain consistency
2486 String newUrl = new String(url);
2487 if (newUrl.startsWith("http://www.")) {
2488 newUrl = newUrl.substring(11);
2489 } else if (newUrl.startsWith("http://")) {
2490 newUrl = newUrl.substring(7);
2491 } else if (newUrl.startsWith("https://www.")) {
2492 newUrl = newUrl.substring(12);
2493 } else if (newUrl.startsWith("https://")) {
2494 newUrl = newUrl.substring(8);
2495 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002496 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002497 Log.d(LOGTAG, newUrl + " loaded");
2498 }
2499 /*
2500 if (sWhiteList.contains(newUrl)) {
2501 // The string that gets pushed to the statistcs
2502 // service
2503 performanceString = performanceString
2504 + "\nWebpage: "
2505 + newUrl
2506 + "\nCarrier: "
2507 + android.os.SystemProperties
2508 .get("gsm.sim.operator.alpha");
2509 if (mWebView != null
2510 && mWebView.getContext() != null
2511 && mWebView.getContext().getSystemService(
2512 Context.CONNECTIVITY_SERVICE) != null) {
2513 ConnectivityManager cManager =
2514 (ConnectivityManager) mWebView
2515 .getContext().getSystemService(
2516 Context.CONNECTIVITY_SERVICE);
2517 NetworkInfo nInfo = cManager
2518 .getActiveNetworkInfo();
2519 if (nInfo != null) {
2520 performanceString = performanceString
2521 + "\nNetwork Type: "
2522 + nInfo.getType().toString();
2523 }
2524 }
2525 Checkin.logEvent(mResolver,
2526 Checkin.Events.Tag.WEBPAGE_LOAD,
2527 performanceString);
2528 Log.w(LOGTAG, "pushed to the statistics service");
2529 }
2530 */
2531 }
2532 }
2533 }
2534
2535 if (mInTrace) {
2536 mInTrace = false;
2537 Debug.stopMethodTracing();
2538 }
2539
2540 if (mPageStarted) {
2541 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002542 // pauseWebViewTimers() will do nothing and return false if
2543 // onPause() is not called yet.
2544 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002545 if (mWakeLock.isHeld()) {
2546 mHandler.removeMessages(RELEASE_WAKELOCK);
2547 mWakeLock.release();
2548 }
2549 }
2550 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002551 }
2552
2553 // return true if want to hijack the url to let another app to handle it
2554 @Override
2555 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2556 if (url.startsWith(SCHEME_WTAI)) {
2557 // wtai://wp/mc;number
2558 // number=string(phone-number)
2559 if (url.startsWith(SCHEME_WTAI_MC)) {
2560 Intent intent = new Intent(Intent.ACTION_VIEW,
2561 Uri.parse(WebView.SCHEME_TEL +
2562 url.substring(SCHEME_WTAI_MC.length())));
2563 startActivity(intent);
2564 return true;
2565 }
2566 // wtai://wp/sd;dtmf
2567 // dtmf=string(dialstring)
2568 if (url.startsWith(SCHEME_WTAI_SD)) {
2569 // TODO
2570 // only send when there is active voice connection
2571 return false;
2572 }
2573 // wtai://wp/ap;number;name
2574 // number=string(phone-number)
2575 // name=string
2576 if (url.startsWith(SCHEME_WTAI_AP)) {
2577 // TODO
2578 return false;
2579 }
2580 }
2581
Dianne Hackborn99189432009-06-17 18:06:18 -07002582 // The "about:" schemes are internal to the browser; don't
2583 // want these to be dispatched to other apps.
2584 if (url.startsWith("about:")) {
2585 return false;
2586 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002587
Dianne Hackborn99189432009-06-17 18:06:18 -07002588 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002589
Dianne Hackborn99189432009-06-17 18:06:18 -07002590 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002591 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002592 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2593 } catch (URISyntaxException ex) {
2594 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002595 return false;
2596 }
2597
Grace Kloba5b078b52009-06-24 20:23:41 -07002598 // check whether the intent can be resolved. If not, we will see
2599 // whether we can download it from the Market.
2600 if (getPackageManager().resolveActivity(intent, 0) == null) {
2601 String packagename = intent.getPackage();
2602 if (packagename != null) {
2603 intent = new Intent(Intent.ACTION_VIEW, Uri
2604 .parse("market://search?q=pname:" + packagename));
2605 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2606 startActivity(intent);
2607 return true;
2608 } else {
2609 return false;
2610 }
2611 }
2612
Dianne Hackborn99189432009-06-17 18:06:18 -07002613 // sanitize the Intent, ensuring web pages can not bypass browser
2614 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002615 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002616 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002617 try {
2618 if (startActivityIfNeeded(intent, -1)) {
2619 return true;
2620 }
2621 } catch (ActivityNotFoundException ex) {
2622 // ignore the error. If no application can handle the URL,
2623 // eg about:blank, assume the browser can handle it.
2624 }
2625
2626 if (mMenuIsDown) {
2627 openTab(url);
2628 closeOptionsMenu();
2629 return true;
2630 }
2631
2632 return false;
2633 }
2634
2635 /**
2636 * Updates the lock icon. This method is called when we discover another
2637 * resource to be loaded for this page (for example, javascript). While
2638 * we update the icon type, we do not update the lock icon itself until
2639 * we are done loading, it is slightly more secure this way.
2640 */
2641 @Override
2642 public void onLoadResource(WebView view, String url) {
2643 if (url != null && url.length() > 0) {
2644 // It is only if the page claims to be secure
2645 // that we may have to update the lock:
2646 if (mLockIconType == LOCK_ICON_SECURE) {
2647 // If NOT a 'safe' url, change the lock to mixed content!
2648 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2649 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002650 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002651 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2652 " updated lock icon to " + mLockIconType + " due to " + url);
2653 }
2654 }
2655 }
2656 }
2657 }
2658
2659 /**
2660 * Show the dialog, asking the user if they would like to continue after
2661 * an excessive number of HTTP redirects.
2662 */
2663 @Override
2664 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2665 final Message continueMsg) {
2666 new AlertDialog.Builder(BrowserActivity.this)
2667 .setTitle(R.string.browserFrameRedirect)
2668 .setMessage(R.string.browserFrame307Post)
2669 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2670 public void onClick(DialogInterface dialog, int which) {
2671 continueMsg.sendToTarget();
2672 }})
2673 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2674 public void onClick(DialogInterface dialog, int which) {
2675 cancelMsg.sendToTarget();
2676 }})
2677 .setOnCancelListener(new OnCancelListener() {
2678 public void onCancel(DialogInterface dialog) {
2679 cancelMsg.sendToTarget();
2680 }})
2681 .show();
2682 }
2683
Patrick Scott37911c72009-03-24 18:02:58 -07002684 // Container class for the next error dialog that needs to be
2685 // displayed.
2686 class ErrorDialog {
2687 public final int mTitle;
2688 public final String mDescription;
2689 public final int mError;
2690 ErrorDialog(int title, String desc, int error) {
2691 mTitle = title;
2692 mDescription = desc;
2693 mError = error;
2694 }
2695 };
2696
2697 private void processNextError() {
2698 if (mQueuedErrors == null) {
2699 return;
2700 }
2701 // The first one is currently displayed so just remove it.
2702 mQueuedErrors.removeFirst();
2703 if (mQueuedErrors.size() == 0) {
2704 mQueuedErrors = null;
2705 return;
2706 }
2707 showError(mQueuedErrors.getFirst());
2708 }
2709
2710 private DialogInterface.OnDismissListener mDialogListener =
2711 new DialogInterface.OnDismissListener() {
2712 public void onDismiss(DialogInterface d) {
2713 processNextError();
2714 }
2715 };
2716 private LinkedList<ErrorDialog> mQueuedErrors;
2717
2718 private void queueError(int err, String desc) {
2719 if (mQueuedErrors == null) {
2720 mQueuedErrors = new LinkedList<ErrorDialog>();
2721 }
2722 for (ErrorDialog d : mQueuedErrors) {
2723 if (d.mError == err) {
2724 // Already saw a similar error, ignore the new one.
2725 return;
2726 }
2727 }
2728 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002729 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002730 R.string.browserFrameFileErrorLabel :
2731 R.string.browserFrameNetworkErrorLabel,
2732 desc, err);
2733 mQueuedErrors.addLast(errDialog);
2734
2735 // Show the dialog now if the queue was empty.
2736 if (mQueuedErrors.size() == 1) {
2737 showError(errDialog);
2738 }
2739 }
2740
2741 private void showError(ErrorDialog errDialog) {
2742 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2743 .setTitle(errDialog.mTitle)
2744 .setMessage(errDialog.mDescription)
2745 .setPositiveButton(R.string.ok, null)
2746 .create();
2747 d.setOnDismissListener(mDialogListener);
2748 d.show();
2749 }
2750
The Android Open Source Project0c908882009-03-03 19:32:16 -08002751 /**
2752 * Show a dialog informing the user of the network error reported by
2753 * WebCore.
2754 */
2755 @Override
2756 public void onReceivedError(WebView view, int errorCode,
2757 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002758 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2759 errorCode != WebViewClient.ERROR_CONNECT &&
2760 errorCode != WebViewClient.ERROR_BAD_URL &&
2761 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2762 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002763 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002764 }
Patrick Scott37911c72009-03-24 18:02:58 -07002765 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2766 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002767
2768 // We need to reset the title after an error.
2769 resetTitleAndRevertLockIcon();
2770 }
2771
2772 /**
2773 * Check with the user if it is ok to resend POST data as the page they
2774 * are trying to navigate to is the result of a POST.
2775 */
2776 @Override
2777 public void onFormResubmission(WebView view, final Message dontResend,
2778 final Message resend) {
2779 new AlertDialog.Builder(BrowserActivity.this)
2780 .setTitle(R.string.browserFrameFormResubmitLabel)
2781 .setMessage(R.string.browserFrameFormResubmitMessage)
2782 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2783 public void onClick(DialogInterface dialog, int which) {
2784 resend.sendToTarget();
2785 }})
2786 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2787 public void onClick(DialogInterface dialog, int which) {
2788 dontResend.sendToTarget();
2789 }})
2790 .setOnCancelListener(new OnCancelListener() {
2791 public void onCancel(DialogInterface dialog) {
2792 dontResend.sendToTarget();
2793 }})
2794 .show();
2795 }
2796
2797 /**
2798 * Insert the url into the visited history database.
2799 * @param url The url to be inserted.
2800 * @param isReload True if this url is being reloaded.
2801 * FIXME: Not sure what to do when reloading the page.
2802 */
2803 @Override
2804 public void doUpdateVisitedHistory(WebView view, String url,
2805 boolean isReload) {
2806 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2807 return;
2808 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002809 // remove "client" before updating it to the history so that it wont
2810 // show up in the auto-complete list.
2811 int index = url.indexOf("client=ms-");
2812 if (index > 0 && url.contains(".google.")) {
2813 int end = url.indexOf('&', index);
2814 if (end > 0) {
2815 url = url.substring(0, index-1).concat(url.substring(end));
2816 } else {
2817 url = url.substring(0, index-1);
2818 }
2819 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002820 Browser.updateVisitedHistory(mResolver, url, true);
2821 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2822 }
2823
2824 /**
2825 * Displays SSL error(s) dialog to the user.
2826 */
2827 @Override
2828 public void onReceivedSslError(
2829 final WebView view, final SslErrorHandler handler, final SslError error) {
2830
2831 if (mSettings.showSecurityWarnings()) {
2832 final LayoutInflater factory =
2833 LayoutInflater.from(BrowserActivity.this);
2834 final View warningsView =
2835 factory.inflate(R.layout.ssl_warnings, null);
2836 final LinearLayout placeholder =
2837 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2838
2839 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2840 LinearLayout ll = (LinearLayout)factory
2841 .inflate(R.layout.ssl_warning, null);
2842 ((TextView)ll.findViewById(R.id.warning))
2843 .setText(R.string.ssl_untrusted);
2844 placeholder.addView(ll);
2845 }
2846
2847 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2848 LinearLayout ll = (LinearLayout)factory
2849 .inflate(R.layout.ssl_warning, null);
2850 ((TextView)ll.findViewById(R.id.warning))
2851 .setText(R.string.ssl_mismatch);
2852 placeholder.addView(ll);
2853 }
2854
2855 if (error.hasError(SslError.SSL_EXPIRED)) {
2856 LinearLayout ll = (LinearLayout)factory
2857 .inflate(R.layout.ssl_warning, null);
2858 ((TextView)ll.findViewById(R.id.warning))
2859 .setText(R.string.ssl_expired);
2860 placeholder.addView(ll);
2861 }
2862
2863 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2864 LinearLayout ll = (LinearLayout)factory
2865 .inflate(R.layout.ssl_warning, null);
2866 ((TextView)ll.findViewById(R.id.warning))
2867 .setText(R.string.ssl_not_yet_valid);
2868 placeholder.addView(ll);
2869 }
2870
2871 new AlertDialog.Builder(BrowserActivity.this)
2872 .setTitle(R.string.security_warning)
2873 .setIcon(android.R.drawable.ic_dialog_alert)
2874 .setView(warningsView)
2875 .setPositiveButton(R.string.ssl_continue,
2876 new DialogInterface.OnClickListener() {
2877 public void onClick(DialogInterface dialog, int whichButton) {
2878 handler.proceed();
2879 }
2880 })
2881 .setNeutralButton(R.string.view_certificate,
2882 new DialogInterface.OnClickListener() {
2883 public void onClick(DialogInterface dialog, int whichButton) {
2884 showSSLCertificateOnError(view, handler, error);
2885 }
2886 })
2887 .setNegativeButton(R.string.cancel,
2888 new DialogInterface.OnClickListener() {
2889 public void onClick(DialogInterface dialog, int whichButton) {
2890 handler.cancel();
2891 BrowserActivity.this.resetTitleAndRevertLockIcon();
2892 }
2893 })
2894 .setOnCancelListener(
2895 new DialogInterface.OnCancelListener() {
2896 public void onCancel(DialogInterface dialog) {
2897 handler.cancel();
2898 BrowserActivity.this.resetTitleAndRevertLockIcon();
2899 }
2900 })
2901 .show();
2902 } else {
2903 handler.proceed();
2904 }
2905 }
2906
2907 /**
2908 * Handles an HTTP authentication request.
2909 *
2910 * @param handler The authentication handler
2911 * @param host The host
2912 * @param realm The realm
2913 */
2914 @Override
2915 public void onReceivedHttpAuthRequest(WebView view,
2916 final HttpAuthHandler handler, final String host, final String realm) {
2917 String username = null;
2918 String password = null;
2919
2920 boolean reuseHttpAuthUsernamePassword =
2921 handler.useHttpAuthUsernamePassword();
2922
2923 if (reuseHttpAuthUsernamePassword &&
2924 (mTabControl.getCurrentWebView() != null)) {
2925 String[] credentials =
2926 mTabControl.getCurrentWebView()
2927 .getHttpAuthUsernamePassword(host, realm);
2928 if (credentials != null && credentials.length == 2) {
2929 username = credentials[0];
2930 password = credentials[1];
2931 }
2932 }
2933
2934 if (username != null && password != null) {
2935 handler.proceed(username, password);
2936 } else {
2937 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2938 }
2939 }
2940
2941 @Override
2942 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2943 if (mMenuIsDown) {
2944 // only check shortcut key when MENU is held
2945 return getWindow().isShortcutKey(event.getKeyCode(), event);
2946 } else {
2947 return false;
2948 }
2949 }
2950
2951 @Override
2952 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2953 if (view != mTabControl.getCurrentTopWebView()) {
2954 return;
2955 }
2956 if (event.isDown()) {
2957 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2958 } else {
2959 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2960 }
2961 }
2962 };
2963
2964 //--------------------------------------------------------------------------
2965 // WebChromeClient implementation
2966 //--------------------------------------------------------------------------
2967
2968 /* package */ WebChromeClient getWebChromeClient() {
2969 return mWebChromeClient;
2970 }
2971
2972 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2973 // Helper method to create a new tab or sub window.
2974 private void createWindow(final boolean dialog, final Message msg) {
2975 if (dialog) {
2976 mTabControl.createSubWindow();
2977 final TabControl.Tab t = mTabControl.getCurrentTab();
2978 attachSubWindow(t);
2979 WebView.WebViewTransport transport =
2980 (WebView.WebViewTransport) msg.obj;
2981 transport.setWebView(t.getSubWebView());
2982 msg.sendToTarget();
2983 } else {
2984 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04002985 final TabControl.Tab newTab
2986 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07002987 if (newTab != parent) {
2988 parent.addChildTab(newTab);
2989 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002990 WebView.WebViewTransport transport =
2991 (WebView.WebViewTransport) msg.obj;
2992 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04002993 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002994 }
2995 }
2996
2997 @Override
2998 public boolean onCreateWindow(WebView view, final boolean dialog,
2999 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003000 // Short-circuit if we can't create any more tabs or sub windows.
3001 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3002 new AlertDialog.Builder(BrowserActivity.this)
3003 .setTitle(R.string.too_many_subwindows_dialog_title)
3004 .setIcon(android.R.drawable.ic_dialog_alert)
3005 .setMessage(R.string.too_many_subwindows_dialog_message)
3006 .setPositiveButton(R.string.ok, null)
3007 .show();
3008 return false;
3009 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3010 new AlertDialog.Builder(BrowserActivity.this)
3011 .setTitle(R.string.too_many_windows_dialog_title)
3012 .setIcon(android.R.drawable.ic_dialog_alert)
3013 .setMessage(R.string.too_many_windows_dialog_message)
3014 .setPositiveButton(R.string.ok, null)
3015 .show();
3016 return false;
3017 }
3018
3019 // Short-circuit if this was a user gesture.
3020 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003021 createWindow(dialog, resultMsg);
3022 return true;
3023 }
3024
3025 // Allow the popup and create the appropriate window.
3026 final AlertDialog.OnClickListener allowListener =
3027 new AlertDialog.OnClickListener() {
3028 public void onClick(DialogInterface d,
3029 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003030 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003031 }
3032 };
3033
3034 // Block the popup by returning a null WebView.
3035 final AlertDialog.OnClickListener blockListener =
3036 new AlertDialog.OnClickListener() {
3037 public void onClick(DialogInterface d, int which) {
3038 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003039 }
3040 };
3041
3042 // Build a confirmation dialog to display to the user.
3043 final AlertDialog d =
3044 new AlertDialog.Builder(BrowserActivity.this)
3045 .setTitle(R.string.attention)
3046 .setIcon(android.R.drawable.ic_dialog_alert)
3047 .setMessage(R.string.popup_window_attempt)
3048 .setPositiveButton(R.string.allow, allowListener)
3049 .setNegativeButton(R.string.block, blockListener)
3050 .setCancelable(false)
3051 .create();
3052
3053 // Show the confirmation dialog.
3054 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003055 return true;
3056 }
3057
3058 @Override
3059 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003060 final TabControl.Tab current = mTabControl.getCurrentTab();
3061 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003062 if (parent != null) {
3063 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003064 switchToTab(mTabControl.getTabIndex(parent));
3065 // Now we need to close the window
3066 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003067 }
3068 }
3069
3070 @Override
3071 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003072 mTitleBar.setProgress(newProgress);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003073 if (mFakeTitleBar != null) {
3074 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003075 }
3076
3077 if (newProgress == 100) {
3078 // onProgressChanged() is called for sub-frame too while
3079 // onPageFinished() is only called for the main frame. sync
3080 // cookie and cache promptly here.
3081 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003082 if (mInLoad) {
3083 mInLoad = false;
3084 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003085 // If the options menu is open, leave the title bar
3086 if (!mOptionsMenuOpen || !mIconView) {
3087 hideFakeTitleBar();
3088 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003089 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003090 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003091 // onPageFinished may have already been called but a subframe
3092 // is still loading and updating the progress. Reset mInLoad
3093 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003094 mInLoad = true;
3095 updateInLoadMenuItems();
3096 WebView currentWebView = mTabControl.getCurrentWebView();
3097 if ((currentWebView == null || currentWebView.getScrollY() != 0)
3098 && (!mOptionsMenuOpen || mIconView)) {
3099 // This page has begun to load, so show the title bar
3100 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003101 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003102 }
3103 }
3104
3105 @Override
3106 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003107 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003108
3109 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003110 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003111
3112 if (url == null ||
3113 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3114 return;
3115 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003116 // See if we can find the current url in our history database and
3117 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003118 if (url.startsWith("http://www.")) {
3119 url = url.substring(11);
3120 } else if (url.startsWith("http://")) {
3121 url = url.substring(4);
3122 }
3123 try {
3124 url = "%" + url;
3125 String [] selArgs = new String[] { url };
3126
3127 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3128 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3129 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3130 Browser.HISTORY_PROJECTION, where, selArgs, null);
3131 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003132 // Current implementation of database only has one entry per
3133 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003134 ContentValues map = new ContentValues();
3135 map.put(Browser.BookmarkColumns.TITLE, title);
3136 mResolver.update(Browser.BOOKMARKS_URI, map,
3137 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003138 }
3139 c.close();
3140 } catch (IllegalStateException e) {
3141 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3142 } catch (SQLiteException ex) {
3143 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3144 }
3145 }
3146
3147 @Override
3148 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003149 updateIcon(view, icon);
3150 }
3151
3152 @Override
3153 public void onReceivedTouchIconUrl(WebView view, String url) {
3154 final ContentResolver cr = getContentResolver();
3155 final Cursor c =
3156 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003157 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003158 if (c != null) {
3159 if (c.getCount() > 0) {
3160 new DownloadTouchIcon(cr, c, view).execute(url);
3161 } else {
3162 c.close();
3163 }
3164 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003165 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003166
Andrei Popescuadc008d2009-06-26 14:11:30 +01003167 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003168 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003169 if (mCustomView != null)
3170 return;
3171
3172 // Add the custom view to its container.
3173 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3174 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003175 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003176 // Save the menu state and set it to empty while the custom
3177 // view is showing.
3178 mOldMenuState = mMenuState;
3179 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003180 // Hide the content view.
3181 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003182 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003183 mCustomViewContainer.setVisibility(View.VISIBLE);
3184 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003185 }
3186
3187 @Override
3188 public void onHideCustomView() {
3189 if (mCustomView == null)
3190 return;
3191
Andrei Popescuc9b55562009-07-07 10:51:15 +01003192 // Hide the custom view.
3193 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003194 // Remove the custom view from its container.
3195 mCustomViewContainer.removeView(mCustomView);
3196 mCustomView = null;
3197 // Reset the old menu state.
3198 mMenuState = mOldMenuState;
3199 mOldMenuState = EMPTY_MENU;
3200 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003201 mCustomViewCallback.onCustomViewHidden();
3202 // Show the content view.
3203 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003204 }
3205
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003206 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003207 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003208 * @param url the URL that exceeded the quota
3209 * @param databaseIdentifier the identifier of the database on
3210 * which the transaction that caused the quota overflow was run
3211 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003212 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003213 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003214 * @param quotaUpdater The callback to run when a decision to allow or
3215 * deny quota has been made. Don't forget to call this!
3216 */
3217 @Override
3218 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003219 String databaseIdentifier, long currentQuota, long estimatedSize,
3220 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003221 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003222 url, databaseIdentifier, currentQuota, estimatedSize,
3223 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003224 }
3225
3226 /**
3227 * The Application Cache has exceeded its max size.
3228 * @param spaceNeeded is the amount of disk space that would be needed
3229 * in order for the last appcache operation to succeed.
3230 * @param totalUsedQuota is the sum of all origins' quota.
3231 * @param quotaUpdater A callback to inform the WebCore thread that a new
3232 * app cache size is available. This callback must always be executed at
3233 * some point to ensure that the sleeping WebCore thread is woken up.
3234 */
3235 @Override
3236 public void onReachedMaxAppCacheSize(long spaceNeeded,
3237 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3238 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3239 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003240 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003241
Steve Block2bc69912009-07-30 14:45:13 +01003242 /**
3243 * Instructs the browser to show a prompt to ask the user to set the
3244 * Geolocation permission state for the specified origin.
3245 * @param origin The origin for which Geolocation permissions are
3246 * requested.
3247 * @param callback The callback to call once the user has set the
3248 * Geolocation permission state.
3249 */
3250 @Override
3251 public void onGeolocationPermissionsShowPrompt(String origin,
3252 GeolocationPermissions.Callback callback) {
3253 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3254 origin, callback);
3255 }
3256
3257 /**
3258 * Instructs the browser to hide the Geolocation permissions prompt.
3259 */
3260 @Override
3261 public void onGeolocationPermissionsHidePrompt() {
3262 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3263 }
3264
Ben Murdoch7db26342009-06-03 18:21:19 +01003265 /* Adds a JavaScript error message to the system log.
3266 * @param message The error message to report.
3267 * @param lineNumber The line number of the error.
3268 * @param sourceID The name of the source file that caused the error.
3269 */
3270 @Override
3271 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003272 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3273 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3274 if (mShouldShowErrorConsole &&
3275 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3276 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3277 }
3278 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003279 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003280 };
3281
3282 /**
3283 * Notify the host application a download should be done, or that
3284 * the data should be streamed if a streaming viewer is available.
3285 * @param url The full url to the content that should be downloaded
3286 * @param contentDisposition Content-disposition http header, if
3287 * present.
3288 * @param mimetype The mimetype of the content reported by the server
3289 * @param contentLength The file size reported by the server
3290 */
3291 public void onDownloadStart(String url, String userAgent,
3292 String contentDisposition, String mimetype, long contentLength) {
3293 // if we're dealing wih A/V content that's not explicitly marked
3294 // for download, check if it's streamable.
3295 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003296 || !contentDisposition.regionMatches(
3297 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003298 // query the package manager to see if there's a registered handler
3299 // that matches.
3300 Intent intent = new Intent(Intent.ACTION_VIEW);
3301 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003302 ResolveInfo info = getPackageManager().resolveActivity(intent,
3303 PackageManager.MATCH_DEFAULT_ONLY);
3304 if (info != null) {
3305 ComponentName myName = getComponentName();
3306 // If we resolved to ourselves, we don't want to attempt to
3307 // load the url only to try and download it again.
3308 if (!myName.getPackageName().equals(
3309 info.activityInfo.packageName)
3310 || !myName.getClassName().equals(
3311 info.activityInfo.name)) {
3312 // someone (other than us) knows how to handle this mime
3313 // type with this scheme, don't download.
3314 try {
3315 startActivity(intent);
3316 return;
3317 } catch (ActivityNotFoundException ex) {
3318 if (LOGD_ENABLED) {
3319 Log.d(LOGTAG, "activity not found for " + mimetype
3320 + " over " + Uri.parse(url).getScheme(),
3321 ex);
3322 }
3323 // Best behavior is to fall back to a download in this
3324 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003325 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003326 }
3327 }
3328 }
3329 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3330 }
3331
3332 /**
3333 * Notify the host application a download should be done, even if there
3334 * is a streaming viewer available for thise type.
3335 * @param url The full url to the content that should be downloaded
3336 * @param contentDisposition Content-disposition http header, if
3337 * present.
3338 * @param mimetype The mimetype of the content reported by the server
3339 * @param contentLength The file size reported by the server
3340 */
3341 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3342 String contentDisposition, String mimetype, long contentLength) {
3343
3344 String filename = URLUtil.guessFileName(url,
3345 contentDisposition, mimetype);
3346
3347 // Check to see if we have an SDCard
3348 String status = Environment.getExternalStorageState();
3349 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3350 int title;
3351 String msg;
3352
3353 // Check to see if the SDCard is busy, same as the music app
3354 if (status.equals(Environment.MEDIA_SHARED)) {
3355 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3356 title = R.string.download_sdcard_busy_dlg_title;
3357 } else {
3358 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3359 title = R.string.download_no_sdcard_dlg_title;
3360 }
3361
3362 new AlertDialog.Builder(this)
3363 .setTitle(title)
3364 .setIcon(android.R.drawable.ic_dialog_alert)
3365 .setMessage(msg)
3366 .setPositiveButton(R.string.ok, null)
3367 .show();
3368 return;
3369 }
3370
3371 // java.net.URI is a lot stricter than KURL so we have to undo
3372 // KURL's percent-encoding and redo the encoding using java.net.URI.
3373 URI uri = null;
3374 try {
3375 // Undo the percent-encoding that KURL may have done.
3376 String newUrl = new String(URLUtil.decode(url.getBytes()));
3377 // Parse the url into pieces
3378 WebAddress w = new WebAddress(newUrl);
3379 String frag = null;
3380 String query = null;
3381 String path = w.mPath;
3382 // Break the path into path, query, and fragment
3383 if (path.length() > 0) {
3384 // Strip the fragment
3385 int idx = path.lastIndexOf('#');
3386 if (idx != -1) {
3387 frag = path.substring(idx + 1);
3388 path = path.substring(0, idx);
3389 }
3390 idx = path.lastIndexOf('?');
3391 if (idx != -1) {
3392 query = path.substring(idx + 1);
3393 path = path.substring(0, idx);
3394 }
3395 }
3396 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3397 query, frag);
3398 } catch (Exception e) {
3399 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3400 return;
3401 }
3402
3403 // XXX: Have to use the old url since the cookies were stored using the
3404 // old percent-encoded url.
3405 String cookies = CookieManager.getInstance().getCookie(url);
3406
3407 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003408 values.put(Downloads.COLUMN_URI, uri.toString());
3409 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3410 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3411 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003412 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003413 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003414 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003415 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3416 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3417 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3418 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003419 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003420 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003421 }
3422 if (mimetype == null) {
3423 // We must have long pressed on a link or image to download it. We
3424 // are not sure of the mimetype in this case, so do a head request
3425 new FetchUrlMimeType(this).execute(values);
3426 } else {
3427 final Uri contentUri =
3428 getContentResolver().insert(Downloads.CONTENT_URI, values);
3429 viewDownloads(contentUri);
3430 }
3431
3432 }
3433
3434 /**
3435 * Resets the lock icon. This method is called when we start a new load and
3436 * know the url to be loaded.
3437 */
3438 private void resetLockIcon(String url) {
3439 // Save the lock-icon state (we revert to it if the load gets cancelled)
3440 saveLockIcon();
3441
3442 mLockIconType = LOCK_ICON_UNSECURE;
3443 if (URLUtil.isHttpsUrl(url)) {
3444 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003445 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003446 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3447 " reset lock icon to " + mLockIconType);
3448 }
3449 }
3450
3451 updateLockIconImage(LOCK_ICON_UNSECURE);
3452 }
3453
Grace Klobaeb6eef42009-09-15 17:56:32 -07003454 /* package */ void setLockIconType(int type) {
3455 mLockIconType = type;
3456 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003457
Grace Klobaeb6eef42009-09-15 17:56:32 -07003458 /* package */ int getLockIconType() {
3459 return mLockIconType;
3460 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003461
Grace Klobaeb6eef42009-09-15 17:56:32 -07003462 /* package */ void setPrevLockType(int type) {
3463 mPrevLockType = type;
3464 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003465
Grace Klobaeb6eef42009-09-15 17:56:32 -07003466 /* package */ int getPrevLockType() {
3467 return mPrevLockType;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003468 }
3469
3470 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003471 * Update the lock icon to correspond to our latest state.
3472 */
3473 /* package */ void updateLockIconToLatest() {
3474 updateLockIconImage(mLockIconType);
3475 }
3476
3477 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003478 * Updates the lock-icon image in the title-bar.
3479 */
3480 private void updateLockIconImage(int lockIconType) {
3481 Drawable d = null;
3482 if (lockIconType == LOCK_ICON_SECURE) {
3483 d = mSecLockIcon;
3484 } else if (lockIconType == LOCK_ICON_MIXED) {
3485 d = mMixLockIcon;
3486 }
Leon Scroggins68579392009-09-15 15:31:54 -04003487 mTitleBar.setLock(d);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003488 if (mFakeTitleBar != null) {
3489 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003490 }
3491 }
3492
3493 /**
3494 * Displays a page-info dialog.
3495 * @param tab The tab to show info about
3496 * @param fromShowSSLCertificateOnError The flag that indicates whether
3497 * this dialog was opened from the SSL-certificate-on-error dialog or
3498 * not. This is important, since we need to know whether to return to
3499 * the parent dialog or simply dismiss.
3500 */
3501 private void showPageInfo(final TabControl.Tab tab,
3502 final boolean fromShowSSLCertificateOnError) {
3503 final LayoutInflater factory = LayoutInflater
3504 .from(this);
3505
3506 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3507
3508 final WebView view = tab.getWebView();
3509
3510 String url = null;
3511 String title = null;
3512
3513 if (view == null) {
3514 url = tab.getUrl();
3515 title = tab.getTitle();
3516 } else if (view == mTabControl.getCurrentWebView()) {
3517 // Use the cached title and url if this is the current WebView
3518 url = mUrl;
3519 title = mTitle;
3520 } else {
3521 url = view.getUrl();
3522 title = view.getTitle();
3523 }
3524
3525 if (url == null) {
3526 url = "";
3527 }
3528 if (title == null) {
3529 title = "";
3530 }
3531
3532 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3533 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3534
3535 mPageInfoView = tab;
3536 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3537
3538 AlertDialog.Builder alertDialogBuilder =
3539 new AlertDialog.Builder(this)
3540 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3541 .setView(pageInfoView)
3542 .setPositiveButton(
3543 R.string.ok,
3544 new DialogInterface.OnClickListener() {
3545 public void onClick(DialogInterface dialog,
3546 int whichButton) {
3547 mPageInfoDialog = null;
3548 mPageInfoView = null;
3549 mPageInfoFromShowSSLCertificateOnError = null;
3550
3551 // if we came here from the SSL error dialog
3552 if (fromShowSSLCertificateOnError) {
3553 // go back to the SSL error dialog
3554 showSSLCertificateOnError(
3555 mSSLCertificateOnErrorView,
3556 mSSLCertificateOnErrorHandler,
3557 mSSLCertificateOnErrorError);
3558 }
3559 }
3560 })
3561 .setOnCancelListener(
3562 new DialogInterface.OnCancelListener() {
3563 public void onCancel(DialogInterface dialog) {
3564 mPageInfoDialog = null;
3565 mPageInfoView = null;
3566 mPageInfoFromShowSSLCertificateOnError = null;
3567
3568 // if we came here from the SSL error dialog
3569 if (fromShowSSLCertificateOnError) {
3570 // go back to the SSL error dialog
3571 showSSLCertificateOnError(
3572 mSSLCertificateOnErrorView,
3573 mSSLCertificateOnErrorHandler,
3574 mSSLCertificateOnErrorError);
3575 }
3576 }
3577 });
3578
3579 // if we have a main top-level page SSL certificate set or a certificate
3580 // error
3581 if (fromShowSSLCertificateOnError ||
3582 (view != null && view.getCertificate() != null)) {
3583 // add a 'View Certificate' button
3584 alertDialogBuilder.setNeutralButton(
3585 R.string.view_certificate,
3586 new DialogInterface.OnClickListener() {
3587 public void onClick(DialogInterface dialog,
3588 int whichButton) {
3589 mPageInfoDialog = null;
3590 mPageInfoView = null;
3591 mPageInfoFromShowSSLCertificateOnError = null;
3592
3593 // if we came here from the SSL error dialog
3594 if (fromShowSSLCertificateOnError) {
3595 // go back to the SSL error dialog
3596 showSSLCertificateOnError(
3597 mSSLCertificateOnErrorView,
3598 mSSLCertificateOnErrorHandler,
3599 mSSLCertificateOnErrorError);
3600 } else {
3601 // otherwise, display the top-most certificate from
3602 // the chain
3603 if (view.getCertificate() != null) {
3604 showSSLCertificate(tab);
3605 }
3606 }
3607 }
3608 });
3609 }
3610
3611 mPageInfoDialog = alertDialogBuilder.show();
3612 }
3613
3614 /**
3615 * Displays the main top-level page SSL certificate dialog
3616 * (accessible from the Page-Info dialog).
3617 * @param tab The tab to show certificate for.
3618 */
3619 private void showSSLCertificate(final TabControl.Tab tab) {
3620 final View certificateView =
3621 inflateCertificateView(tab.getWebView().getCertificate());
3622 if (certificateView == null) {
3623 return;
3624 }
3625
3626 LayoutInflater factory = LayoutInflater.from(this);
3627
3628 final LinearLayout placeholder =
3629 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3630
3631 LinearLayout ll = (LinearLayout) factory.inflate(
3632 R.layout.ssl_success, placeholder);
3633 ((TextView)ll.findViewById(R.id.success))
3634 .setText(R.string.ssl_certificate_is_valid);
3635
3636 mSSLCertificateView = tab;
3637 mSSLCertificateDialog =
3638 new AlertDialog.Builder(this)
3639 .setTitle(R.string.ssl_certificate).setIcon(
3640 R.drawable.ic_dialog_browser_certificate_secure)
3641 .setView(certificateView)
3642 .setPositiveButton(R.string.ok,
3643 new DialogInterface.OnClickListener() {
3644 public void onClick(DialogInterface dialog,
3645 int whichButton) {
3646 mSSLCertificateDialog = null;
3647 mSSLCertificateView = null;
3648
3649 showPageInfo(tab, false);
3650 }
3651 })
3652 .setOnCancelListener(
3653 new DialogInterface.OnCancelListener() {
3654 public void onCancel(DialogInterface dialog) {
3655 mSSLCertificateDialog = null;
3656 mSSLCertificateView = null;
3657
3658 showPageInfo(tab, false);
3659 }
3660 })
3661 .show();
3662 }
3663
3664 /**
3665 * Displays the SSL error certificate dialog.
3666 * @param view The target web-view.
3667 * @param handler The SSL error handler responsible for cancelling the
3668 * connection that resulted in an SSL error or proceeding per user request.
3669 * @param error The SSL error object.
3670 */
3671 private void showSSLCertificateOnError(
3672 final WebView view, final SslErrorHandler handler, final SslError error) {
3673
3674 final View certificateView =
3675 inflateCertificateView(error.getCertificate());
3676 if (certificateView == null) {
3677 return;
3678 }
3679
3680 LayoutInflater factory = LayoutInflater.from(this);
3681
3682 final LinearLayout placeholder =
3683 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3684
3685 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3686 LinearLayout ll = (LinearLayout)factory
3687 .inflate(R.layout.ssl_warning, placeholder);
3688 ((TextView)ll.findViewById(R.id.warning))
3689 .setText(R.string.ssl_untrusted);
3690 }
3691
3692 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3693 LinearLayout ll = (LinearLayout)factory
3694 .inflate(R.layout.ssl_warning, placeholder);
3695 ((TextView)ll.findViewById(R.id.warning))
3696 .setText(R.string.ssl_mismatch);
3697 }
3698
3699 if (error.hasError(SslError.SSL_EXPIRED)) {
3700 LinearLayout ll = (LinearLayout)factory
3701 .inflate(R.layout.ssl_warning, placeholder);
3702 ((TextView)ll.findViewById(R.id.warning))
3703 .setText(R.string.ssl_expired);
3704 }
3705
3706 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3707 LinearLayout ll = (LinearLayout)factory
3708 .inflate(R.layout.ssl_warning, placeholder);
3709 ((TextView)ll.findViewById(R.id.warning))
3710 .setText(R.string.ssl_not_yet_valid);
3711 }
3712
3713 mSSLCertificateOnErrorHandler = handler;
3714 mSSLCertificateOnErrorView = view;
3715 mSSLCertificateOnErrorError = error;
3716 mSSLCertificateOnErrorDialog =
3717 new AlertDialog.Builder(this)
3718 .setTitle(R.string.ssl_certificate).setIcon(
3719 R.drawable.ic_dialog_browser_certificate_partially_secure)
3720 .setView(certificateView)
3721 .setPositiveButton(R.string.ok,
3722 new DialogInterface.OnClickListener() {
3723 public void onClick(DialogInterface dialog,
3724 int whichButton) {
3725 mSSLCertificateOnErrorDialog = null;
3726 mSSLCertificateOnErrorView = null;
3727 mSSLCertificateOnErrorHandler = null;
3728 mSSLCertificateOnErrorError = null;
3729
3730 mWebViewClient.onReceivedSslError(
3731 view, handler, error);
3732 }
3733 })
3734 .setNeutralButton(R.string.page_info_view,
3735 new DialogInterface.OnClickListener() {
3736 public void onClick(DialogInterface dialog,
3737 int whichButton) {
3738 mSSLCertificateOnErrorDialog = null;
3739
3740 // do not clear the dialog state: we will
3741 // need to show the dialog again once the
3742 // user is done exploring the page-info details
3743
3744 showPageInfo(mTabControl.getTabFromView(view),
3745 true);
3746 }
3747 })
3748 .setOnCancelListener(
3749 new DialogInterface.OnCancelListener() {
3750 public void onCancel(DialogInterface dialog) {
3751 mSSLCertificateOnErrorDialog = null;
3752 mSSLCertificateOnErrorView = null;
3753 mSSLCertificateOnErrorHandler = null;
3754 mSSLCertificateOnErrorError = null;
3755
3756 mWebViewClient.onReceivedSslError(
3757 view, handler, error);
3758 }
3759 })
3760 .show();
3761 }
3762
3763 /**
3764 * Inflates the SSL certificate view (helper method).
3765 * @param certificate The SSL certificate.
3766 * @return The resultant certificate view with issued-to, issued-by,
3767 * issued-on, expires-on, and possibly other fields set.
3768 * If the input certificate is null, returns null.
3769 */
3770 private View inflateCertificateView(SslCertificate certificate) {
3771 if (certificate == null) {
3772 return null;
3773 }
3774
3775 LayoutInflater factory = LayoutInflater.from(this);
3776
3777 View certificateView = factory.inflate(
3778 R.layout.ssl_certificate, null);
3779
3780 // issued to:
3781 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3782 if (issuedTo != null) {
3783 ((TextView) certificateView.findViewById(R.id.to_common))
3784 .setText(issuedTo.getCName());
3785 ((TextView) certificateView.findViewById(R.id.to_org))
3786 .setText(issuedTo.getOName());
3787 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3788 .setText(issuedTo.getUName());
3789 }
3790
3791 // issued by:
3792 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3793 if (issuedBy != null) {
3794 ((TextView) certificateView.findViewById(R.id.by_common))
3795 .setText(issuedBy.getCName());
3796 ((TextView) certificateView.findViewById(R.id.by_org))
3797 .setText(issuedBy.getOName());
3798 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3799 .setText(issuedBy.getUName());
3800 }
3801
3802 // issued on:
3803 String issuedOn = reformatCertificateDate(
3804 certificate.getValidNotBefore());
3805 ((TextView) certificateView.findViewById(R.id.issued_on))
3806 .setText(issuedOn);
3807
3808 // expires on:
3809 String expiresOn = reformatCertificateDate(
3810 certificate.getValidNotAfter());
3811 ((TextView) certificateView.findViewById(R.id.expires_on))
3812 .setText(expiresOn);
3813
3814 return certificateView;
3815 }
3816
3817 /**
3818 * Re-formats the certificate date (Date.toString()) string to
3819 * a properly localized date string.
3820 * @return Properly localized version of the certificate date string and
3821 * the original certificate date string if fails to localize.
3822 * If the original string is null, returns an empty string "".
3823 */
3824 private String reformatCertificateDate(String certificateDate) {
3825 String reformattedDate = null;
3826
3827 if (certificateDate != null) {
3828 Date date = null;
3829 try {
3830 date = java.text.DateFormat.getInstance().parse(certificateDate);
3831 } catch (ParseException e) {
3832 date = null;
3833 }
3834
3835 if (date != null) {
3836 reformattedDate =
3837 DateFormat.getDateFormat(this).format(date);
3838 }
3839 }
3840
3841 return reformattedDate != null ? reformattedDate :
3842 (certificateDate != null ? certificateDate : "");
3843 }
3844
3845 /**
3846 * Displays an http-authentication dialog.
3847 */
3848 private void showHttpAuthentication(final HttpAuthHandler handler,
3849 final String host, final String realm, final String title,
3850 final String name, final String password, int focusId) {
3851 LayoutInflater factory = LayoutInflater.from(this);
3852 final View v = factory
3853 .inflate(R.layout.http_authentication, null);
3854 if (name != null) {
3855 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3856 }
3857 if (password != null) {
3858 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3859 }
3860
3861 String titleText = title;
3862 if (titleText == null) {
3863 titleText = getText(R.string.sign_in_to).toString().replace(
3864 "%s1", host).replace("%s2", realm);
3865 }
3866
3867 mHttpAuthHandler = handler;
3868 AlertDialog dialog = new AlertDialog.Builder(this)
3869 .setTitle(titleText)
3870 .setIcon(android.R.drawable.ic_dialog_alert)
3871 .setView(v)
3872 .setPositiveButton(R.string.action,
3873 new DialogInterface.OnClickListener() {
3874 public void onClick(DialogInterface dialog,
3875 int whichButton) {
3876 String nm = ((EditText) v
3877 .findViewById(R.id.username_edit))
3878 .getText().toString();
3879 String pw = ((EditText) v
3880 .findViewById(R.id.password_edit))
3881 .getText().toString();
3882 BrowserActivity.this.setHttpAuthUsernamePassword
3883 (host, realm, nm, pw);
3884 handler.proceed(nm, pw);
3885 mHttpAuthenticationDialog = null;
3886 mHttpAuthHandler = null;
3887 }})
3888 .setNegativeButton(R.string.cancel,
3889 new DialogInterface.OnClickListener() {
3890 public void onClick(DialogInterface dialog,
3891 int whichButton) {
3892 handler.cancel();
3893 BrowserActivity.this.resetTitleAndRevertLockIcon();
3894 mHttpAuthenticationDialog = null;
3895 mHttpAuthHandler = null;
3896 }})
3897 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3898 public void onCancel(DialogInterface dialog) {
3899 handler.cancel();
3900 BrowserActivity.this.resetTitleAndRevertLockIcon();
3901 mHttpAuthenticationDialog = null;
3902 mHttpAuthHandler = null;
3903 }})
3904 .create();
3905 // Make the IME appear when the dialog is displayed if applicable.
3906 dialog.getWindow().setSoftInputMode(
3907 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3908 dialog.show();
3909 if (focusId != 0) {
3910 dialog.findViewById(focusId).requestFocus();
3911 } else {
3912 v.findViewById(R.id.username_edit).requestFocus();
3913 }
3914 mHttpAuthenticationDialog = dialog;
3915 }
3916
3917 public int getProgress() {
3918 WebView w = mTabControl.getCurrentWebView();
3919 if (w != null) {
3920 return w.getProgress();
3921 } else {
3922 return 100;
3923 }
3924 }
3925
3926 /**
3927 * Set HTTP authentication password.
3928 *
3929 * @param host The host for the password
3930 * @param realm The realm for the password
3931 * @param username The username for the password. If it is null, it means
3932 * password can't be saved.
3933 * @param password The password
3934 */
3935 public void setHttpAuthUsernamePassword(String host, String realm,
3936 String username,
3937 String password) {
3938 WebView w = mTabControl.getCurrentWebView();
3939 if (w != null) {
3940 w.setHttpAuthUsernamePassword(host, realm, username, password);
3941 }
3942 }
3943
3944 /**
3945 * connectivity manager says net has come or gone... inform the user
3946 * @param up true if net has come up, false if net has gone down
3947 */
3948 public void onNetworkToggle(boolean up) {
3949 if (up == mIsNetworkUp) {
3950 return;
3951 } else if (up) {
3952 mIsNetworkUp = true;
3953 if (mAlertDialog != null) {
3954 mAlertDialog.cancel();
3955 mAlertDialog = null;
3956 }
3957 } else {
3958 mIsNetworkUp = false;
3959 if (mInLoad && mAlertDialog == null) {
3960 mAlertDialog = new AlertDialog.Builder(this)
3961 .setTitle(R.string.loadSuspendedTitle)
3962 .setMessage(R.string.loadSuspended)
3963 .setPositiveButton(R.string.ok, null)
3964 .show();
3965 }
3966 }
3967 WebView w = mTabControl.getCurrentWebView();
3968 if (w != null) {
3969 w.setNetworkAvailable(up);
3970 }
3971 }
3972
3973 @Override
3974 protected void onActivityResult(int requestCode, int resultCode,
3975 Intent intent) {
3976 switch (requestCode) {
3977 case COMBO_PAGE:
3978 if (resultCode == RESULT_OK && intent != null) {
3979 String data = intent.getAction();
3980 Bundle extras = intent.getExtras();
3981 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003982 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003983 } else {
3984 final TabControl.Tab currentTab =
3985 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003986 dismissSubWindow(currentTab);
3987 if (data != null && data.length() != 0) {
3988 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003989 }
3990 }
3991 }
3992 break;
3993 default:
3994 break;
3995 }
Leon Scroggins30444232009-09-04 18:36:20 -04003996 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003997 }
3998
3999 /*
4000 * This method is called as a result of the user selecting the options
4001 * menu to see the download window, or when a download changes state. It
4002 * shows the download window ontop of the current window.
4003 */
4004 /* package */ void viewDownloads(Uri downloadRecord) {
4005 Intent intent = new Intent(this,
4006 BrowserDownloadPage.class);
4007 intent.setData(downloadRecord);
4008 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4009
4010 }
4011
Leon Scroggins160a7e72009-08-14 18:28:01 -04004012 /**
4013 * Open the Go page.
4014 * @param startWithHistory If true, open starting on the history tab.
4015 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004016 */
Leon Scroggins30444232009-09-04 18:36:20 -04004017 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004018 WebView current = mTabControl.getCurrentWebView();
4019 if (current == null) {
4020 return;
4021 }
4022 Intent intent = new Intent(this,
4023 CombinedBookmarkHistoryActivity.class);
4024 String title = current.getTitle();
4025 String url = current.getUrl();
4026 // Just in case the user opens bookmarks before a page finishes loading
4027 // so the current history item, and therefore the page, is null.
4028 if (null == url) {
4029 url = mLastEnteredUrl;
4030 // This can happen.
4031 if (null == url) {
4032 url = mSettings.getHomePage();
4033 }
4034 }
4035 // In case the web page has not yet received its associated title.
4036 if (title == null) {
4037 title = url;
4038 }
4039 intent.putExtra("title", title);
4040 intent.putExtra("url", url);
Leon Scroggins30444232009-09-04 18:36:20 -04004041 // Disable opening in a new window if we have maxed out the windows
4042 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4043 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004044 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004045 if (startWithHistory) {
4046 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4047 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4048 }
4049 startActivityForResult(intent, COMBO_PAGE);
4050 }
4051
4052 // Called when loading from context menu or LOAD_URL message
4053 private void loadURL(WebView view, String url) {
4054 // In case the user enters nothing.
4055 if (url != null && url.length() != 0 && view != null) {
4056 url = smartUrlFilter(url);
4057 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4058 view.loadUrl(url);
4059 }
4060 }
4061 }
4062
The Android Open Source Project0c908882009-03-03 19:32:16 -08004063 private String smartUrlFilter(Uri inUri) {
4064 if (inUri != null) {
4065 return smartUrlFilter(inUri.toString());
4066 }
4067 return null;
4068 }
4069
4070
4071 // get window count
4072
4073 int getWindowCount(){
4074 if(mTabControl != null){
4075 return mTabControl.getTabCount();
4076 }
4077 return 0;
4078 }
4079
Feng Qianb34f87a2009-03-24 21:27:26 -07004080 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004081 "(?i)" + // switch on case insensitive matching
4082 "(" + // begin group for schema
4083 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004084 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004085 ")" +
4086 "(.*)" );
4087
4088 /**
4089 * Attempts to determine whether user input is a URL or search
4090 * terms. Anything with a space is passed to search.
4091 *
4092 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4093 * "Http://" converts to "http://"
4094 *
4095 * @return Original or modified URL
4096 *
4097 */
4098 String smartUrlFilter(String url) {
4099
4100 String inUrl = url.trim();
4101 boolean hasSpace = inUrl.indexOf(' ') != -1;
4102
4103 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4104 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004105 // force scheme to lowercase
4106 String scheme = matcher.group(1);
4107 String lcScheme = scheme.toLowerCase();
4108 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004109 inUrl = lcScheme + matcher.group(2);
4110 }
4111 if (hasSpace) {
4112 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004113 }
4114 return inUrl;
4115 }
4116 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004117 // FIXME: Is this the correct place to add to searches?
4118 // what if someone else calls this function?
4119 int shortcut = parseUrlShortcut(inUrl);
4120 if (shortcut != SHORTCUT_INVALID) {
4121 Browser.addSearchUrl(mResolver, inUrl);
4122 String query = inUrl.substring(2);
4123 switch (shortcut) {
4124 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004125 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004126 case SHORTCUT_WIKIPEDIA_SEARCH:
4127 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4128 case SHORTCUT_DICTIONARY_SEARCH:
4129 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4130 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004131 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004132 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004133 }
4134 }
4135 } else {
4136 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4137 return URLUtil.guessUrl(inUrl);
4138 }
4139 }
4140
4141 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004142 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004143 }
4144
Ben Murdochbff2d602009-07-01 20:19:05 +01004145 /* package */ void setShouldShowErrorConsole(boolean flag) {
4146 if (flag == mShouldShowErrorConsole) {
4147 // Nothing to do.
4148 return;
4149 }
4150
4151 mShouldShowErrorConsole = flag;
4152
4153 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4154
4155 if (flag) {
4156 // Setting the show state of the console will cause it's the layout to be inflated.
4157 if (errorConsole.numberOfErrors() > 0) {
4158 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4159 } else {
4160 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4161 }
4162
4163 // Now we can add it to the main view.
4164 mErrorConsoleContainer.addView(errorConsole,
4165 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4166 ViewGroup.LayoutParams.WRAP_CONTENT));
4167 } else {
4168 mErrorConsoleContainer.removeView(errorConsole);
4169 }
4170
4171 }
4172
Grace Klobaeb6eef42009-09-15 17:56:32 -07004173 final static int LOCK_ICON_UNSECURE = 0;
4174 final static int LOCK_ICON_SECURE = 1;
4175 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004176
4177 private int mLockIconType = LOCK_ICON_UNSECURE;
4178 private int mPrevLockType = LOCK_ICON_UNSECURE;
4179
4180 private BrowserSettings mSettings;
4181 private TabControl mTabControl;
4182 private ContentResolver mResolver;
4183 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004184 private View mCustomView;
4185 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004186 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004187
4188 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4189 // view, we should rewrite this.
4190 private int mCurrentMenuState = 0;
4191 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004192 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004193 private static final int EMPTY_MENU = -1;
4194 private Menu mMenu;
4195
4196 private FindDialog mFindDialog;
4197 // Used to prevent chording to result in firing two shortcuts immediately
4198 // one after another. Fixes bug 1211714.
4199 boolean mCanChord;
4200
4201 private boolean mInLoad;
4202 private boolean mIsNetworkUp;
4203
4204 private boolean mPageStarted;
4205 private boolean mActivityInPause = true;
4206
4207 private boolean mMenuIsDown;
4208
4209 private final KeyTracker mKeyTracker = new KeyTracker(this);
4210
4211 // As trackball doesn't send repeat down, we have to track it ourselves
4212 private boolean mTrackTrackball;
4213
4214 private static boolean mInTrace;
4215
4216 // Performance probe
4217 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4218 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4219 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4220 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4221 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4222 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4223 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4224 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4225 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4226 };
4227
4228 private long mStart;
4229 private long mProcessStart;
4230 private long mUserStart;
4231 private long mSystemStart;
4232 private long mIdleStart;
4233 private long mIrqStart;
4234
4235 private long mUiStart;
4236
4237 private Drawable mMixLockIcon;
4238 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004239
4240 /* hold a ref so we can auto-cancel if necessary */
4241 private AlertDialog mAlertDialog;
4242
4243 // Wait for credentials before loading google.com
4244 private ProgressDialog mCredsDlg;
4245
4246 // The up-to-date URL and title (these can be different from those stored
4247 // in WebView, since it takes some time for the information in WebView to
4248 // get updated)
4249 private String mUrl;
4250 private String mTitle;
4251
4252 // As PageInfo has different style for landscape / portrait, we have
4253 // to re-open it when configuration changed
4254 private AlertDialog mPageInfoDialog;
4255 private TabControl.Tab mPageInfoView;
4256 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4257 // dialog, we should not just dismiss it, but should get back to the
4258 // SSL-certificate-on-error dialog. This flag is used to store this state
4259 private Boolean mPageInfoFromShowSSLCertificateOnError;
4260
4261 // as SSLCertificateOnError has different style for landscape / portrait,
4262 // we have to re-open it when configuration changed
4263 private AlertDialog mSSLCertificateOnErrorDialog;
4264 private WebView mSSLCertificateOnErrorView;
4265 private SslErrorHandler mSSLCertificateOnErrorHandler;
4266 private SslError mSSLCertificateOnErrorError;
4267
4268 // as SSLCertificate has different style for landscape / portrait, we
4269 // have to re-open it when configuration changed
4270 private AlertDialog mSSLCertificateDialog;
4271 private TabControl.Tab mSSLCertificateView;
4272
4273 // as HttpAuthentication has different style for landscape / portrait, we
4274 // have to re-open it when configuration changed
4275 private AlertDialog mHttpAuthenticationDialog;
4276 private HttpAuthHandler mHttpAuthHandler;
4277
4278 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4279 new FrameLayout.LayoutParams(
4280 ViewGroup.LayoutParams.FILL_PARENT,
4281 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004282 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4283 new FrameLayout.LayoutParams(
4284 ViewGroup.LayoutParams.FILL_PARENT,
4285 ViewGroup.LayoutParams.FILL_PARENT,
4286 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004287 // Google search
4288 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004289 // Wikipedia search
4290 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4291 // Dictionary search
4292 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4293 // Google Mobile Local search
4294 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4295
4296 final static String QUERY_PLACE_HOLDER = "%s";
4297
4298 // "source" parameter for Google search through search key
4299 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4300 // "source" parameter for Google search through goto menu
4301 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4302 // "source" parameter for Google search through simplily type
4303 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4304 // "source" parameter for Google search suggested by the browser
4305 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4306 // "source" parameter for Google search from unknown source
4307 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4308
4309 private final static String LOGTAG = "browser";
4310
The Android Open Source Project0c908882009-03-03 19:32:16 -08004311 private String mLastEnteredUrl;
4312
4313 private PowerManager.WakeLock mWakeLock;
4314 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4315
4316 private Toast mStopToast;
4317
Leon Scroggins68579392009-09-15 15:31:54 -04004318 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004319
Ben Murdochbff2d602009-07-01 20:19:05 +01004320 private LinearLayout mErrorConsoleContainer = null;
4321 private boolean mShouldShowErrorConsole = false;
4322
The Android Open Source Project0c908882009-03-03 19:32:16 -08004323 // As the ids are dynamically created, we can't guarantee that they will
4324 // be in sequence, so this static array maps ids to a window number.
4325 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4326 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4327 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4328 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4329
4330 // monitor platform changes
4331 private IntentFilter mNetworkStateChangedFilter;
4332 private BroadcastReceiver mNetworkStateIntentReceiver;
4333
Grace Klobab4da0ad2009-05-14 14:45:40 -07004334 private BroadcastReceiver mPackageInstallationReceiver;
4335
The Android Open Source Project0c908882009-03-03 19:32:16 -08004336 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004337 final static int COMBO_PAGE = 1;
4338 final static int DOWNLOAD_PAGE = 2;
4339 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004340
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004341 /**
4342 * A UrlData class to abstract how the content will be set to WebView.
4343 * This base class uses loadUrl to show the content.
4344 */
4345 private static class UrlData {
4346 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004347 byte[] mPostData;
4348
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004349 UrlData(String url) {
4350 this.mUrl = url;
4351 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004352
4353 void setPostData(byte[] postData) {
4354 mPostData = postData;
4355 }
4356
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004357 boolean isEmpty() {
4358 return mUrl == null || mUrl.length() == 0;
4359 }
4360
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004361 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004362 if (mPostData != null) {
4363 webView.postUrl(mUrl, mPostData);
4364 } else {
4365 webView.loadUrl(mUrl);
4366 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004367 }
4368 };
4369
4370 /**
4371 * A subclass of UrlData class that can display inlined content using
4372 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4373 */
4374 private static class InlinedUrlData extends UrlData {
4375 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4376 super(failUrl);
4377 mInlined = inlined;
4378 mMimeType = mimeType;
4379 mEncoding = encoding;
4380 }
4381 String mMimeType;
4382 String mInlined;
4383 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004384 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004385 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004386 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004387 }
4388
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004389 @Override
4390 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004391 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4392 }
4393 }
4394
Leon Scroggins1f005d32009-08-10 17:36:42 -04004395 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004396}