blob: 7e7426216dcc623ec41c910965a1443d8bd87f81 [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;
Grace Klobab4da0ad2009-05-14 14:45:40 -070037import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080038import android.content.pm.PackageManager;
39import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080040import android.content.res.Configuration;
41import android.content.res.Resources;
42import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010044import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080046import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040047import android.graphics.PixelFormat;
48import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.net.ConnectivityManager;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -040051import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080052import android.net.Uri;
53import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080054import android.net.http.SslCertificate;
55import android.net.http.SslError;
56import android.os.AsyncTask;
57import android.os.Bundle;
58import android.os.Debug;
59import android.os.Environment;
60import android.os.Handler;
61import android.os.IBinder;
62import android.os.Message;
63import android.os.PowerManager;
64import android.os.Process;
65import android.os.RemoteException;
66import android.os.ServiceManager;
67import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040069import android.provider.ContactsContract;
70import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080071import android.provider.Downloads;
72import android.provider.MediaStore;
The Android Open Source Project0c908882009-03-03 19:32:16 -080073import android.text.IClipboard;
74import android.text.TextUtils;
75import android.text.format.DateFormat;
76import android.text.util.Regex;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040077import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080078import android.util.Log;
79import android.view.ContextMenu;
80import android.view.Gravity;
81import android.view.KeyEvent;
82import android.view.LayoutInflater;
83import android.view.Menu;
84import android.view.MenuInflater;
85import android.view.MenuItem;
86import android.view.View;
87import android.view.ViewGroup;
88import android.view.Window;
89import android.view.WindowManager;
90import android.view.ContextMenu.ContextMenuInfo;
91import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080092import android.webkit.CookieManager;
93import android.webkit.CookieSyncManager;
94import android.webkit.DownloadListener;
95import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070096import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080097import android.webkit.SslErrorHandler;
98import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010099import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800100import android.webkit.WebChromeClient;
101import android.webkit.WebHistoryItem;
102import android.webkit.WebIconDatabase;
103import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800104import android.widget.EditText;
105import android.widget.FrameLayout;
106import android.widget.LinearLayout;
107import android.widget.TextView;
108import android.widget.Toast;
109
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400110import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800111import java.io.File;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800112import java.net.MalformedURLException;
113import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700114import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800115import java.net.URL;
116import java.net.URLEncoder;
117import java.text.ParseException;
118import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800119import java.util.HashMap;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.util.regex.Matcher;
121import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800122
123public class BrowserActivity extends Activity
Grace Kloba5942df02009-09-18 11:48:29 -0700124 implements View.OnCreateContextMenuListener,
The Android Open Source Project0c908882009-03-03 19:32:16 -0800125 DownloadListener {
126
Dave Bort31a6d1c2009-04-13 15:56:49 -0700127 /* Define some aliases to make these debugging flags easier to refer to.
128 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
129 */
130 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
131 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
132 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
133
The Android Open Source Project0c908882009-03-03 19:32:16 -0800134 private IGoogleLoginService mGls = null;
135 private ServiceConnection mGlsConnection = null;
136
Satish Sampath565505b2009-05-29 15:37:27 +0100137 // These are single-character shortcuts for searching popular sources.
138 private static final int SHORTCUT_INVALID = 0;
139 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
140 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
141 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
142 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
143
The Android Open Source Project0c908882009-03-03 19:32:16 -0800144 private void setupHomePage() {
145 final Runnable getAccount = new Runnable() {
146 public void run() {
147 // Lower priority
148 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
149 // get the default home page
150 String homepage = mSettings.getHomePage();
151
152 try {
153 if (mGls == null) return;
154
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700155 if (!homepage.startsWith("http://www.google.")) return;
156 if (homepage.indexOf('?') == -1) return;
157
The Android Open Source Project0c908882009-03-03 19:32:16 -0800158 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
159 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
160
161 // three cases:
162 //
163 // hostedUser == googleUser
164 // The device has only a google account
165 //
166 // hostedUser != googleUser
167 // The device has a hosted account and a google account
168 //
169 // hostedUser != null, googleUser == null
170 // The device has only a hosted account (so far)
171
172 // developers might have no accounts at all
173 if (hostedUser == null) return;
174
175 if (googleUser == null || !hostedUser.equals(googleUser)) {
176 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700177 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800178 }
179 } catch (RemoteException ignore) {
180 // Login service died; carry on
181 } catch (RuntimeException ignore) {
182 // Login service died; carry on
183 } finally {
184 finish(homepage);
185 }
186 }
187
188 private void finish(final String homepage) {
189 mHandler.post(new Runnable() {
190 public void run() {
191 mSettings.setHomePage(BrowserActivity.this, homepage);
192 resumeAfterCredentials();
193
194 // as this is running in a separate thread,
195 // BrowserActivity's onDestroy() may have been called,
196 // which also calls unbindService().
197 if (mGlsConnection != null) {
198 // we no longer need to keep GLS open
199 unbindService(mGlsConnection);
200 mGlsConnection = null;
201 }
202 } });
203 } };
204
205 final boolean[] done = { false };
206
207 // Open a connection to the Google Login Service. The first
208 // time the connection is established, set up the homepage depending on
209 // the account in a background thread.
210 mGlsConnection = new ServiceConnection() {
211 public void onServiceConnected(ComponentName className, IBinder service) {
212 mGls = IGoogleLoginService.Stub.asInterface(service);
213 if (done[0] == false) {
214 done[0] = true;
215 Thread account = new Thread(getAccount);
216 account.setName("GLSAccount");
217 account.start();
218 }
219 }
220 public void onServiceDisconnected(ComponentName className) {
221 mGls = null;
222 }
223 };
224
225 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
226 mGlsConnection, Context.BIND_AUTO_CREATE);
227 }
228
Cary Clarka9771242009-08-11 16:42:26 -0400229 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800230 @Override
231 public Void doInBackground(File... files) {
232 if (files != null) {
233 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400234 if (!f.delete()) {
235 Log.e(LOGTAG, f.getPath() + " was not deleted");
236 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800237 }
238 }
239 return null;
240 }
241 }
242
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400243 /**
244 * This layout holds everything you see below the status bar, including the
245 * error console, the custom view container, and the webviews.
246 */
247 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400248
Grace Kloba22ac16e2009-10-07 18:00:23 -0700249 @Override
250 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700251 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800252 Log.v(LOGTAG, this + " onStart");
253 }
254 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800255 // test the browser in OpenGL
256 // requestWindowFeature(Window.FEATURE_OPENGL);
257
258 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
259
260 mResolver = getContentResolver();
261
Grace Kloba0923d692009-09-23 21:37:25 -0700262 // If this was a web search request, pass it on to the default web
263 // search provider and finish this activity.
264 if (handleWebSearchIntent(getIntent())) {
265 finish();
266 return;
267 }
268
The Android Open Source Project0c908882009-03-03 19:32:16 -0800269 mSecLockIcon = Resources.getSystem().getDrawable(
270 android.R.drawable.ic_secure);
271 mMixLockIcon = Resources.getSystem().getDrawable(
272 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800273
Leon Scroggins81db3662009-06-04 17:45:11 -0400274 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
275 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400276 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
277 .inflate(R.layout.custom_screen, null);
278 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
279 R.id.main_content);
280 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
281 .findViewById(R.id.error_console);
282 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
283 .findViewById(R.id.fullscreen_custom_content);
284 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400285 mTitleBar = new TitleBar(this);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400286 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800287
288 // Create the tab control and our initial tab
289 mTabControl = new TabControl(this);
290
291 // Open the icon database and retain all the bookmark urls for favicons
292 retainIconsOnStartup();
293
294 // Keep a settings instance handy.
295 mSettings = BrowserSettings.getInstance();
296 mSettings.setTabControl(mTabControl);
297 mSettings.loadFromDb(this);
298
299 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
300 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
301
Grace Klobaa34f6862009-07-31 16:28:17 -0700302 /* enables registration for changes in network status from
303 http stack */
304 mNetworkStateChangedFilter = new IntentFilter();
305 mNetworkStateChangedFilter.addAction(
306 ConnectivityManager.CONNECTIVITY_ACTION);
307 mNetworkStateIntentReceiver = new BroadcastReceiver() {
308 @Override
309 public void onReceive(Context context, Intent intent) {
310 if (intent.getAction().equals(
311 ConnectivityManager.CONNECTIVITY_ACTION)) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -0400312 NetworkInfo info =
313 (NetworkInfo) intent.getParcelableExtra(
314 ConnectivityManager.EXTRA_NETWORK_INFO);
315 onNetworkToggle(
316 (info != null) ? info.isConnected() : false);
Grace Klobaa34f6862009-07-31 16:28:17 -0700317 }
318 }
319 };
320
Grace Kloba615c6c92009-08-03 10:22:44 -0700321 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
322 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
323 filter.addDataScheme("package");
324 mPackageInstallationReceiver = new BroadcastReceiver() {
325 @Override
326 public void onReceive(Context context, Intent intent) {
327 final String action = intent.getAction();
328 final String packageName = intent.getData()
329 .getSchemeSpecificPart();
330 final boolean replacing = intent.getBooleanExtra(
331 Intent.EXTRA_REPLACING, false);
332 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
333 // if it is replacing, refreshPlugins() when adding
334 return;
335 }
336 PackageManager pm = BrowserActivity.this.getPackageManager();
337 PackageInfo pkgInfo = null;
338 try {
339 pkgInfo = pm.getPackageInfo(packageName,
340 PackageManager.GET_PERMISSIONS);
341 } catch (PackageManager.NameNotFoundException e) {
342 return;
343 }
344 if (pkgInfo != null) {
345 String permissions[] = pkgInfo.requestedPermissions;
346 if (permissions == null) {
347 return;
348 }
349 boolean permissionOk = false;
350 for (String permit : permissions) {
351 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
352 permissionOk = true;
353 break;
354 }
355 }
356 if (permissionOk) {
357 PluginManager.getInstance(BrowserActivity.this)
358 .refreshPlugins(
359 Intent.ACTION_PACKAGE_ADDED
360 .equals(action));
361 }
362 }
363 }
364 };
365 registerReceiver(mPackageInstallationReceiver, filter);
366
The Android Open Source Project0c908882009-03-03 19:32:16 -0800367 if (!mTabControl.restoreState(icicle)) {
368 // clear up the thumbnail directory if we can't restore the state as
369 // none of the files in the directory are referenced any more.
370 new ClearThumbnails().execute(
371 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700372 // there is no quit on Android. But if we can't restore the state,
373 // we can treat it as a new Browser, remove the old session cookies.
374 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800375 final Intent intent = getIntent();
376 final Bundle extra = intent.getExtras();
377 // Create an initial tab.
378 // If the intent is ACTION_VIEW and data is not null, the Browser is
379 // invoked to view the content by another application. In this case,
380 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700381 UrlData urlData = getUrlDataFromIntent(intent);
382
Grace Kloba22ac16e2009-10-07 18:00:23 -0700383 final Tab t = mTabControl.createNewTab(
The Android Open Source Project0c908882009-03-03 19:32:16 -0800384 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700385 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700386 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800387 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800388 attachTabToContentView(t);
389 WebView webView = t.getWebView();
390 if (extra != null) {
391 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
392 if (scale > 0 && scale <= 1000) {
393 webView.setInitialScale(scale);
394 }
395 }
396 // If we are not restoring from an icicle, then there is a high
397 // likely hood this is the first run. So, check to see if the
398 // homepage needs to be configured and copy any plugins from our
399 // asset directory to the data partition.
400 if ((extra == null || !extra.getBoolean("testing"))
401 && !mSettings.isLoginInitialized()) {
402 setupHomePage();
403 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800404
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700405 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400406 if (mSettings.isLoginInitialized()) {
407 webView.loadUrl(mSettings.getHomePage());
408 } else {
409 waitForCredentials();
410 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800411 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700412 if (extra != null) {
413 urlData.setPostData(extra
414 .getByteArray(Browser.EXTRA_POST_DATA));
415 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700416 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800417 }
418 } else {
419 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400420 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800421 attachTabToContentView(mTabControl.getCurrentTab());
422 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700423
Feng Qianb3c02da2009-06-29 15:58:08 -0700424 // Read JavaScript flags if it exists.
425 String jsFlags = mSettings.getJsFlags();
426 if (jsFlags.trim().length() != 0) {
427 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
428 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800429 }
430
431 @Override
432 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700433 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800434 // When a tab is closed on exit, the current tab index is set to -1.
435 // Reset before proceed as Browser requires the current tab to be set.
436 if (current == null) {
437 // Try to reset the tab in case the index was incorrect.
438 current = mTabControl.getTab(0);
439 if (current == null) {
440 // No tabs at all so just ignore this intent.
441 return;
442 }
443 mTabControl.setCurrentTab(current);
444 attachTabToContentView(current);
445 resetTitleAndIcon(current.getWebView());
446 }
447 final String action = intent.getAction();
448 final int flags = intent.getFlags();
449 if (Intent.ACTION_MAIN.equals(action) ||
450 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
451 // just resume the browser
452 return;
453 }
454 if (Intent.ACTION_VIEW.equals(action)
455 || Intent.ACTION_SEARCH.equals(action)
456 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
457 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100458 // If this was a search request (e.g. search query directly typed into the address bar),
459 // pass it on to the default web search provider.
460 if (handleWebSearchIntent(intent)) {
461 return;
462 }
463
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700464 UrlData urlData = getUrlDataFromIntent(intent);
465 if (urlData.isEmpty()) {
466 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800467 }
Grace Kloba81678d92009-06-30 07:09:56 -0700468 urlData.setPostData(intent
469 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700470
Grace Klobacc634032009-07-28 15:58:19 -0700471 final String appId = intent
472 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
473 if (Intent.ACTION_VIEW.equals(action)
474 && !getPackageName().equals(appId)
475 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700476 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700477 if (appTab != null) {
478 Log.i(LOGTAG, "Reusing tab for " + appId);
479 // Dismiss the subwindow if applicable.
480 dismissSubWindow(appTab);
481 // Since we might kill the WebView, remove it from the
482 // content view first.
483 removeTabFromContentView(appTab);
484 // Recreate the main WebView after destroying the old one.
485 // If the WebView has the same original url and is on that
486 // page, it can be reused.
487 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700488 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100489
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700490 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400491 switchToTab(mTabControl.getTabIndex(appTab));
492 if (needsLoad) {
493 urlData.loadIn(appTab.getWebView());
494 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700495 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400496 // If the tab was the current tab, we have to attach
497 // it to the view system again.
498 attachTabToContentView(appTab);
499 if (needsLoad) {
500 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700501 }
502 }
503 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400504 } else {
505 // No matching application tab, try to find a regular tab
506 // with a matching url.
507 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400508 if (appTab != null) {
509 if (current != appTab) {
510 switchToTab(mTabControl.getTabIndex(appTab));
511 }
512 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400513 } else {
514 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
515 // will be opened in a new tab unless we have reached
516 // MAX_TABS. Then the url will be opened in the current
517 // tab. If a new tab is created, it will have "true" for
518 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400519 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400520 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700521 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800522 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700523 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800524 mSettings.toggleDebugSettings();
525 return;
526 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400527 // Get rid of the subwindow if it exists
528 dismissSubWindow(current);
529 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800530 }
531 }
532 }
533
Satish Sampath565505b2009-05-29 15:37:27 +0100534 private int parseUrlShortcut(String url) {
535 if (url == null) return SHORTCUT_INVALID;
536
537 // FIXME: quick search, need to be customized by setting
538 if (url.length() > 2 && url.charAt(1) == ' ') {
539 switch (url.charAt(0)) {
540 case 'g': return SHORTCUT_GOOGLE_SEARCH;
541 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
542 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
543 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
544 }
545 }
546 return SHORTCUT_INVALID;
547 }
548
549 /**
550 * Launches the default web search activity with the query parameters if the given intent's data
551 * are identified as plain search terms and not URLs/shortcuts.
552 * @return true if the intent was handled and web search activity was launched, false if not.
553 */
554 private boolean handleWebSearchIntent(Intent intent) {
555 if (intent == null) return false;
556
557 String url = null;
558 final String action = intent.getAction();
559 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700560 Uri data = intent.getData();
561 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100562 } else if (Intent.ACTION_SEARCH.equals(action)
563 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
564 || Intent.ACTION_WEB_SEARCH.equals(action)) {
565 url = intent.getStringExtra(SearchManager.QUERY);
566 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100567 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
568 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100569 }
570
571 /**
572 * Launches the default web search activity with the query parameters if the given url string
573 * was identified as plain search terms and not URL/shortcut.
574 * @return true if the request was handled and web search activity was launched, false if not.
575 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100576 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100577 if (inUrl == null) return false;
578
579 // In general, we shouldn't modify URL from Intent.
580 // But currently, we get the user-typed URL from search box as well.
581 String url = fixUrl(inUrl).trim();
582
583 // URLs and site specific search shortcuts are handled by the regular flow of control, so
584 // return early.
585 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100586 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100587 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
588 return false;
589 }
590
591 Browser.updateVisitedHistory(mResolver, url, false);
592 Browser.addSearchUrl(mResolver, url);
593
594 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
595 intent.addCategory(Intent.CATEGORY_DEFAULT);
596 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100597 if (appData != null) {
598 intent.putExtra(SearchManager.APP_DATA, appData);
599 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100600 if (extraData != null) {
601 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
602 }
Grace Klobacc634032009-07-28 15:58:19 -0700603 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100604 startActivity(intent);
605
606 return true;
607 }
608
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700609 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800610 String url = null;
611 if (intent != null) {
612 final String action = intent.getAction();
613 if (Intent.ACTION_VIEW.equals(action)) {
614 url = smartUrlFilter(intent.getData());
615 if (url != null && url.startsWith("content:")) {
616 /* Append mimetype so webview knows how to display */
617 String mimeType = intent.resolveType(getContentResolver());
618 if (mimeType != null) {
619 url += "?" + mimeType;
620 }
621 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700622 if ("inline:".equals(url)) {
623 return new InlinedUrlData(
624 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
625 intent.getType(),
626 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
627 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
628 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800629 } else if (Intent.ACTION_SEARCH.equals(action)
630 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
631 || Intent.ACTION_WEB_SEARCH.equals(action)) {
632 url = intent.getStringExtra(SearchManager.QUERY);
633 if (url != null) {
634 mLastEnteredUrl = url;
635 // Don't add Urls, just search terms.
636 // Urls will get added when the page is loaded.
637 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
638 Browser.updateVisitedHistory(mResolver, url, false);
639 }
640 // In general, we shouldn't modify URL from Intent.
641 // But currently, we get the user-typed URL from search box as well.
642 url = fixUrl(url);
643 url = smartUrlFilter(url);
644 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
645 if (url.contains(searchSource)) {
646 String source = null;
647 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
648 if (appData != null) {
649 source = appData.getString(SearchManager.SOURCE);
650 }
651 if (TextUtils.isEmpty(source)) {
652 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
653 }
654 url = url.replace(searchSource, "&source=android-"+source+"&");
655 }
656 }
657 }
658 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700659 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800660 }
661
662 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400663 // FIXME: Converting the url to lower case
664 // duplicates functionality in smartUrlFilter().
665 // However, changing all current callers of fixUrl to
666 // call smartUrlFilter in addition may have unwanted
667 // consequences, and is deferred for now.
668 int colon = inUrl.indexOf(':');
669 boolean allLower = true;
670 for (int index = 0; index < colon; index++) {
671 char ch = inUrl.charAt(index);
672 if (!Character.isLetter(ch)) {
673 break;
674 }
675 allLower &= Character.isLowerCase(ch);
676 if (index == colon - 1 && !allLower) {
677 inUrl = inUrl.substring(0, colon).toLowerCase()
678 + inUrl.substring(colon);
679 }
680 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800681 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
682 return inUrl;
683 if (inUrl.startsWith("http:") ||
684 inUrl.startsWith("https:")) {
685 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
686 inUrl = inUrl.replaceFirst("/", "//");
687 } else inUrl = inUrl.replaceFirst(":", "://");
688 }
689 return inUrl;
690 }
691
Grace Kloba22ac16e2009-10-07 18:00:23 -0700692 @Override
693 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800694 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700695 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800696 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
697 }
698
699 if (!mActivityInPause) {
700 Log.e(LOGTAG, "BrowserActivity is already resumed.");
701 return;
702 }
703
Mike Reed7bfa63b2009-05-28 11:08:32 -0400704 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800705 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400706 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800707
708 if (mWakeLock.isHeld()) {
709 mHandler.removeMessages(RELEASE_WAKELOCK);
710 mWakeLock.release();
711 }
712
713 if (mCredsDlg != null) {
714 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
715 // In case credential request never comes back
716 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
717 }
718 }
719
720 registerReceiver(mNetworkStateIntentReceiver,
721 mNetworkStateChangedFilter);
722 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800723 }
724
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400725 /**
726 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400727 * would change its appearance, use a different TitleBar to show overlayed
728 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400729 */
730 private TitleBar mFakeTitleBar;
731
732 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400733 * Holder for the fake title bar. It will have a foreground shadow, as well
734 * as a white background, so the fake title bar looks like the real one.
735 */
736 private ViewGroup mFakeTitleBarHolder;
737
738 /**
739 * Layout parameters for the fake title bar within mFakeTitleBarHolder
740 */
741 private FrameLayout.LayoutParams mFakeTitleBarParams
742 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400743 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400744 ViewGroup.LayoutParams.WRAP_CONTENT);
745 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400746 * Keeps track of whether the options menu is open. This is important in
747 * determining whether to show or hide the title bar overlay.
748 */
749 private boolean mOptionsMenuOpen;
750
751 /**
752 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
753 * of whether the configuration has changed. The first onMenuOpened call
754 * after a configuration change is simply a reopening of the same menu
755 * (i.e. mIconView did not change).
756 */
757 private boolean mConfigChanged;
758
759 /**
760 * Whether or not the options menu is in its smaller, icon menu form. When
761 * true, we want the title bar overlay to be up. When false, we do not.
762 * Only meaningful if mOptionsMenuOpen is true.
763 */
764 private boolean mIconView;
765
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400766 @Override
767 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400768 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
769 if (mOptionsMenuOpen) {
770 if (mConfigChanged) {
771 // We do not need to make any changes to the state of the
772 // title bar, since the only thing that happened was a
773 // change in orientation
774 mConfigChanged = false;
775 } else {
776 if (mIconView) {
777 // Switching the menu to expanded view, so hide the
778 // title bar.
779 hideFakeTitleBar();
780 mIconView = false;
781 } else {
782 // Switching the menu back to icon view, so show the
783 // title bar once again.
784 showFakeTitleBar();
785 mIconView = true;
786 }
787 }
788 } else {
789 // The options menu is closed, so open it, and show the title
790 showFakeTitleBar();
791 mOptionsMenuOpen = true;
792 mConfigChanged = false;
793 mIconView = true;
794 }
795 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400796 return true;
797 }
798
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400799 /**
800 * Special class used exclusively for the shadow drawn underneath the fake
801 * title bar. The shadow does not need to be drawn if the WebView
802 * underneath is scrolled to the top, because it will draw directly on top
803 * of the embedded shadow.
804 */
805 private static class Shadow extends View {
806 private WebView mWebView;
807
808 public Shadow(Context context, AttributeSet attrs) {
809 super(context, attrs);
810 }
811
812 public void setWebView(WebView view) {
813 mWebView = view;
814 }
815
816 @Override
817 public void draw(Canvas canvas) {
818 // In general onDraw is the method to override, but we care about
819 // whether or not the background gets drawn, which happens in draw()
820 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
821 super.draw(canvas);
822 }
823 // Need to invalidate so that if the scroll position changes, we
824 // still draw as appropriate.
825 invalidate();
826 }
827 }
828
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400829 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400830 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400831 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400832 && !mActivityInPause && decor != null
833 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400834 Rect visRect = new Rect();
835 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
836 if (LOGD_ENABLED) {
837 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
838 }
839 return;
840 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400841
842 WindowManager manager
843 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
844
845 // Add the title bar to the window manager so it can receive touches
846 // while the menu is up
847 WindowManager.LayoutParams params
848 = new WindowManager.LayoutParams(
849 ViewGroup.LayoutParams.FILL_PARENT,
850 ViewGroup.LayoutParams.WRAP_CONTENT,
851 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
852 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400853 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400854 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400855 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400856 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400857 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400858 // XXX : Without providing an offset, the fake title bar will be
859 // placed underneath the status bar. Use the global visible rect
860 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400861 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400862 // Add a holder for the title bar. It also holds a shadow to show
863 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400864 if (mFakeTitleBarHolder == null) {
865 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
866 .inflate(R.layout.title_bar_bg, null);
867 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400868 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
869 R.id.shadow);
870 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400871 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400872 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400873 }
874 }
875
876 @Override
877 public void onOptionsMenuClosed(Menu menu) {
878 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400879 if (!mInLoad) {
880 hideFakeTitleBar();
881 } else if (!mIconView) {
882 // The page is currently loading, and we are in expanded mode, so
883 // we were not showing the menu. Show it once again. It will be
884 // removed when the page finishes.
885 showFakeTitleBar();
886 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400887 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700888
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400889 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400890 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400891 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
892 mFakeTitleBarHolder.getLayoutParams();
893 WebView mainView = mTabControl.getCurrentWebView();
894 // Although we decided whether or not to animate based on the current
895 // scroll position, the scroll position may have changed since the
896 // fake title bar was displayed. Make sure it has the appropriate
897 // animation/lack thereof before removing.
898 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400899 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400900 WindowManager manager
901 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400902 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400903 mFakeTitleBarHolder.removeView(mFakeTitleBar);
904 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400905 }
906
The Android Open Source Project0c908882009-03-03 19:32:16 -0800907 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400908 * Special method for the fake title bar to call when displaying its context
909 * menu, since it is in its own Window, and its parent does not show a
910 * context menu.
911 */
912 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400913 if (null == mTitleBar.getParent()) {
914 return;
915 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400916 openContextMenu(mTitleBar);
917 }
918
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400919 @Override
920 public void onContextMenuClosed(Menu menu) {
921 super.onContextMenuClosed(menu);
922 if (mInLoad) {
923 showFakeTitleBar();
924 }
925 }
926
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400927 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800928 * onSaveInstanceState(Bundle map)
929 * onSaveInstanceState is called right before onStop(). The map contains
930 * the saved state.
931 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700932 @Override
933 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700934 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800935 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
936 }
937 // the default implementation requires each view to have an id. As the
938 // browser handles the state itself and it doesn't use id for the views,
939 // don't call the default implementation. Otherwise it will trigger the
940 // warning like this, "couldn't save which view has focus because the
941 // focused view XXX has no id".
942
943 // Save all the tabs
944 mTabControl.saveState(outState);
945 }
946
Grace Kloba22ac16e2009-10-07 18:00:23 -0700947 @Override
948 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800949 super.onPause();
950
951 if (mActivityInPause) {
952 Log.e(LOGTAG, "BrowserActivity is already paused.");
953 return;
954 }
955
Mike Reed7bfa63b2009-05-28 11:08:32 -0400956 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800957 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400958 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800959 mWakeLock.acquire();
960 mHandler.sendMessageDelayed(mHandler
961 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
962 }
963
964 // Clear the credentials toast if it is up
965 if (mCredsDlg != null && mCredsDlg.isShowing()) {
966 mCredsDlg.dismiss();
967 }
968 mCredsDlg = null;
969
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400970 // FIXME: This removes the active tabs page and resets the menu to
971 // MAIN_MENU. A better solution might be to do this work in onNewIntent
972 // but then we would need to save it in onSaveInstanceState and restore
973 // it in onCreate/onRestoreInstanceState
974 if (mActiveTabsPage != null) {
975 removeActiveTabPage(true);
976 }
977
The Android Open Source Project0c908882009-03-03 19:32:16 -0800978 cancelStopToast();
979
980 // unregister network state listener
981 unregisterReceiver(mNetworkStateIntentReceiver);
982 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800983 }
984
Grace Kloba22ac16e2009-10-07 18:00:23 -0700985 @Override
986 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700987 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800988 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
989 }
990 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700991
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400992 if (mUploadMessage != null) {
993 mUploadMessage.onReceiveValue(null);
994 mUploadMessage = null;
995 }
996
Grace Kloba0923d692009-09-23 21:37:25 -0700997 if (mTabControl == null) return;
998
The Android Open Source Project0c908882009-03-03 19:32:16 -0800999 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001000 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001001 if (t != null) {
1002 dismissSubWindow(t);
1003 removeTabFromContentView(t);
1004 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001005 // Destroy all the tabs
1006 mTabControl.destroy();
1007 WebIconDatabase.getInstance().close();
1008 if (mGlsConnection != null) {
1009 unbindService(mGlsConnection);
1010 mGlsConnection = null;
1011 }
1012
Grace Klobab4da0ad2009-05-14 14:45:40 -07001013 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001014 }
1015
1016 @Override
1017 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001018 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001019 super.onConfigurationChanged(newConfig);
1020
1021 if (mPageInfoDialog != null) {
1022 mPageInfoDialog.dismiss();
1023 showPageInfo(
1024 mPageInfoView,
1025 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1026 }
1027 if (mSSLCertificateDialog != null) {
1028 mSSLCertificateDialog.dismiss();
1029 showSSLCertificate(
1030 mSSLCertificateView);
1031 }
1032 if (mSSLCertificateOnErrorDialog != null) {
1033 mSSLCertificateOnErrorDialog.dismiss();
1034 showSSLCertificateOnError(
1035 mSSLCertificateOnErrorView,
1036 mSSLCertificateOnErrorHandler,
1037 mSSLCertificateOnErrorError);
1038 }
1039 if (mHttpAuthenticationDialog != null) {
1040 String title = ((TextView) mHttpAuthenticationDialog
1041 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1042 .toString();
1043 String name = ((TextView) mHttpAuthenticationDialog
1044 .findViewById(R.id.username_edit)).getText().toString();
1045 String password = ((TextView) mHttpAuthenticationDialog
1046 .findViewById(R.id.password_edit)).getText().toString();
1047 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1048 .getId();
1049 mHttpAuthenticationDialog.dismiss();
1050 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1051 name, password, focusId);
1052 }
1053 if (mFindDialog != null && mFindDialog.isShowing()) {
1054 mFindDialog.onConfigurationChanged(newConfig);
1055 }
1056 }
1057
Grace Kloba22ac16e2009-10-07 18:00:23 -07001058 @Override
1059 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001060 super.onLowMemory();
1061 mTabControl.freeMemory();
1062 }
1063
Mike Reed7bfa63b2009-05-28 11:08:32 -04001064 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001065 Tab tab = mTabControl.getCurrentTab();
1066 boolean inLoad = tab.inLoad();
1067 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001068 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001069 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001070 if (w != null) {
1071 w.resumeTimers();
1072 }
1073 return true;
1074 } else {
1075 return false;
1076 }
1077 }
1078
Mike Reed7bfa63b2009-05-28 11:08:32 -04001079 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001080 Tab tab = mTabControl.getCurrentTab();
1081 boolean inLoad = tab.inLoad();
1082 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001083 CookieSyncManager.getInstance().stopSync();
1084 WebView w = mTabControl.getCurrentWebView();
1085 if (w != null) {
1086 w.pauseTimers();
1087 }
1088 return true;
1089 } else {
1090 return false;
1091 }
1092 }
1093
Leon Scroggins1f005d32009-08-10 17:36:42 -04001094 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001095 /*
1096 * This function is called when we are launching for the first time. We
1097 * are waiting for the login credentials before loading Google home
1098 * pages. This way the user will be logged in straight away.
1099 */
1100 private void waitForCredentials() {
1101 // Show a toast
1102 mCredsDlg = new ProgressDialog(this);
1103 mCredsDlg.setIndeterminate(true);
1104 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1105 // If the user cancels the operation, then cancel the Google
1106 // Credentials request.
1107 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1108 mCredsDlg.show();
1109
1110 // We set a timeout for the retrieval of credentials in onResume()
1111 // as that is when we have freed up some CPU time to get
1112 // the login credentials.
1113 }
1114
1115 /*
1116 * If we have received the credentials or we have timed out and we are
1117 * showing the credentials dialog, then it is time to move on.
1118 */
1119 private void resumeAfterCredentials() {
1120 if (mCredsDlg == null) {
1121 return;
1122 }
1123
1124 // Clear the toast
1125 if (mCredsDlg.isShowing()) {
1126 mCredsDlg.dismiss();
1127 }
1128 mCredsDlg = null;
1129
1130 // Clear any pending timeout
1131 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1132
1133 // Load the page
1134 WebView w = mTabControl.getCurrentWebView();
1135 if (w != null) {
1136 w.loadUrl(mSettings.getHomePage());
1137 }
1138
1139 // Update the settings, need to do this last as it can take a moment
1140 // to persist the settings. In the mean time we could be loading
1141 // content.
1142 mSettings.setLoginInitialized(this);
1143 }
1144
1145 // Open the icon database and retain all the icons for visited sites.
1146 private void retainIconsOnStartup() {
1147 final WebIconDatabase db = WebIconDatabase.getInstance();
1148 db.open(getDir("icons", 0).getPath());
1149 try {
1150 Cursor c = Browser.getAllBookmarks(mResolver);
1151 if (!c.moveToFirst()) {
1152 c.deactivate();
1153 return;
1154 }
1155 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1156 do {
1157 String url = c.getString(urlIndex);
1158 db.retainIconForPageUrl(url);
1159 } while (c.moveToNext());
1160 c.deactivate();
1161 } catch (IllegalStateException e) {
1162 Log.e(LOGTAG, "retainIconsOnStartup", e);
1163 }
1164 }
1165
1166 // Helper method for getting the top window.
1167 WebView getTopWindow() {
1168 return mTabControl.getCurrentTopWebView();
1169 }
1170
Grace Kloba22ac16e2009-10-07 18:00:23 -07001171 TabControl getTabControl() {
1172 return mTabControl;
1173 }
1174
The Android Open Source Project0c908882009-03-03 19:32:16 -08001175 @Override
1176 public boolean onCreateOptionsMenu(Menu menu) {
1177 super.onCreateOptionsMenu(menu);
1178
1179 MenuInflater inflater = getMenuInflater();
1180 inflater.inflate(R.menu.browser, menu);
1181 mMenu = menu;
1182 updateInLoadMenuItems();
1183 return true;
1184 }
1185
1186 /**
1187 * As the menu can be open when loading state changes
1188 * we must manually update the state of the stop/reload menu
1189 * item
1190 */
1191 private void updateInLoadMenuItems() {
1192 if (mMenu == null) {
1193 return;
1194 }
1195 MenuItem src = mInLoad ?
1196 mMenu.findItem(R.id.stop_menu_id):
1197 mMenu.findItem(R.id.reload_menu_id);
1198 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1199 dest.setIcon(src.getIcon());
1200 dest.setTitle(src.getTitle());
1201 }
1202
1203 @Override
1204 public boolean onContextItemSelected(MenuItem item) {
1205 // chording is not an issue with context menus, but we use the same
1206 // options selector, so set mCanChord to true so we can access them.
1207 mCanChord = true;
1208 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001209 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001210 // For the context menu from the title bar
1211 case R.id.title_bar_share_page_url:
1212 case R.id.title_bar_copy_page_url:
1213 WebView mainView = mTabControl.getCurrentWebView();
1214 if (null == mainView) {
1215 return false;
1216 }
1217 if (id == R.id.title_bar_share_page_url) {
1218 Browser.sendString(this, mainView.getUrl());
1219 } else {
1220 copy(mainView.getUrl());
1221 }
1222 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001223 // -- Browser context menu
1224 case R.id.open_context_menu_id:
1225 case R.id.open_newtab_context_menu_id:
1226 case R.id.bookmark_context_menu_id:
1227 case R.id.save_link_context_menu_id:
1228 case R.id.share_link_context_menu_id:
1229 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001230 final WebView webView = getTopWindow();
1231 if (null == webView) {
1232 return false;
1233 }
1234 final HashMap hrefMap = new HashMap();
1235 hrefMap.put("webview", webView);
1236 final Message msg = mHandler.obtainMessage(
1237 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001238 webView.requestFocusNodeHref(msg);
1239 break;
1240
1241 default:
1242 // For other context menus
1243 return onOptionsItemSelected(item);
1244 }
1245 mCanChord = false;
1246 return true;
1247 }
1248
1249 private Bundle createGoogleSearchSourceBundle(String source) {
1250 Bundle bundle = new Bundle();
1251 bundle.putString(SearchManager.SOURCE, source);
1252 return bundle;
1253 }
1254
1255 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001256 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001257 */
1258 @Override
1259 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001260 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001261 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001262 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001263 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001264 return true;
1265 }
1266
1267 @Override
1268 public void startSearch(String initialQuery, boolean selectInitialQuery,
1269 Bundle appSearchData, boolean globalSearch) {
1270 if (appSearchData == null) {
1271 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1272 }
1273 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1274 }
1275
Leon Scroggins1f005d32009-08-10 17:36:42 -04001276 /**
1277 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1278 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001279 * @param index Index of the tab to change to, as defined by
1280 * mTabControl.getTabIndex(Tab t).
1281 * @return boolean True if we successfully switched to a different tab. If
1282 * the indexth tab is null, or if that tab is the same as
1283 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001284 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001285 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001286 Tab tab = mTabControl.getTab(index);
1287 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001288 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001289 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001290 }
1291 if (currentTab != null) {
1292 // currentTab may be null if it was just removed. In that case,
1293 // we do not need to remove it
1294 removeTabFromContentView(currentTab);
1295 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001296 mTabControl.setCurrentTab(tab);
1297 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001298 resetTitleIconAndProgress();
1299 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001300 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001301 }
1302
Grace Kloba22ac16e2009-10-07 18:00:23 -07001303 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001304 return openTabAndShow(mSettings.getHomePage(), false, null);
1305 }
1306
Leon Scroggins1f005d32009-08-10 17:36:42 -04001307 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001308 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001309 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001310 // This is the last tab. Open a new one, with the home
1311 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001312 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001313 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001314 return;
1315 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001316 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001317 int indexToShow = -1;
1318 if (parent != null) {
1319 indexToShow = mTabControl.getTabIndex(parent);
1320 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001321 final int currentIndex = mTabControl.getCurrentIndex();
1322 // Try to move to the tab to the right
1323 indexToShow = currentIndex + 1;
1324 if (indexToShow > mTabControl.getTabCount() - 1) {
1325 // Try to move to the tab to the left
1326 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001327 }
1328 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001329 if (switchToTab(indexToShow)) {
1330 // Close window
1331 closeTab(current);
1332 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001333 }
1334
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001335 private ActiveTabsPage mActiveTabsPage;
1336
1337 /**
1338 * Remove the active tabs page.
1339 * @param needToAttach If true, the active tabs page did not attach a tab
1340 * to the content view, so we need to do that here.
1341 */
1342 /* package */ void removeActiveTabPage(boolean needToAttach) {
1343 mContentView.removeView(mActiveTabsPage);
1344 mActiveTabsPage = null;
1345 mMenuState = R.id.MAIN_MENU;
1346 if (needToAttach) {
1347 attachTabToContentView(mTabControl.getCurrentTab());
1348 }
1349 getTopWindow().requestFocus();
1350 }
1351
The Android Open Source Project0c908882009-03-03 19:32:16 -08001352 @Override
1353 public boolean onOptionsItemSelected(MenuItem item) {
1354 if (!mCanChord) {
1355 // The user has already fired a shortcut with this hold down of the
1356 // menu key.
1357 return false;
1358 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001359 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001360 return false;
1361 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001362 if (mMenuIsDown) {
1363 // The shortcut action consumes the MENU. Even if it is still down,
1364 // it won't trigger the next shortcut action. In the case of the
1365 // shortcut action triggering a new activity, like Bookmarks, we
1366 // won't get onKeyUp for MENU. So it is important to reset it here.
1367 mMenuIsDown = false;
1368 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001369 switch (item.getItemId()) {
1370 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001371 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001372 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001373 break;
1374
Leon Scroggins64b80f32009-08-07 12:03:34 -04001375 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001376 onSearchRequested();
1377 break;
1378
1379 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001380 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001381 break;
1382
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001383 case R.id.active_tabs_menu_id:
1384 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1385 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001386 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001387 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1388 mActiveTabsPage.requestFocus();
1389 mMenuState = EMPTY_MENU;
1390 break;
1391
Leon Scroggins1f005d32009-08-10 17:36:42 -04001392 case R.id.add_bookmark_menu_id:
1393 Intent i = new Intent(BrowserActivity.this,
1394 AddBookmarkPage.class);
1395 WebView w = getTopWindow();
1396 i.putExtra("url", w.getUrl());
1397 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001398 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001399 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001400 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001401 break;
1402
1403 case R.id.stop_reload_menu_id:
1404 if (mInLoad) {
1405 stopLoading();
1406 } else {
1407 getTopWindow().reload();
1408 }
1409 break;
1410
1411 case R.id.back_menu_id:
1412 getTopWindow().goBack();
1413 break;
1414
1415 case R.id.forward_menu_id:
1416 getTopWindow().goForward();
1417 break;
1418
1419 case R.id.close_menu_id:
1420 // Close the subwindow if it exists.
1421 if (mTabControl.getCurrentSubWindow() != null) {
1422 dismissSubWindow(mTabControl.getCurrentTab());
1423 break;
1424 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001425 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001426 break;
1427
1428 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001429 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001430 if (current != null) {
1431 dismissSubWindow(current);
1432 current.getWebView().loadUrl(mSettings.getHomePage());
1433 }
1434 break;
1435
1436 case R.id.preferences_menu_id:
1437 Intent intent = new Intent(this,
1438 BrowserPreferencesPage.class);
1439 startActivityForResult(intent, PREFERENCES_PAGE);
1440 break;
1441
1442 case R.id.find_menu_id:
1443 if (null == mFindDialog) {
1444 mFindDialog = new FindDialog(this);
1445 }
1446 mFindDialog.setWebView(getTopWindow());
1447 mFindDialog.show();
1448 mMenuState = EMPTY_MENU;
1449 break;
1450
1451 case R.id.select_text_id:
1452 getTopWindow().emulateShiftHeld();
1453 break;
1454 case R.id.page_info_menu_id:
1455 showPageInfo(mTabControl.getCurrentTab(), false);
1456 break;
1457
1458 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001459 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001460 break;
1461
1462 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001463 Browser.sendString(this, getTopWindow().getUrl(),
1464 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001465 break;
1466
1467 case R.id.dump_nav_menu_id:
1468 getTopWindow().debugDump();
1469 break;
1470
1471 case R.id.zoom_in_menu_id:
1472 getTopWindow().zoomIn();
1473 break;
1474
1475 case R.id.zoom_out_menu_id:
1476 getTopWindow().zoomOut();
1477 break;
1478
1479 case R.id.view_downloads_menu_id:
1480 viewDownloads(null);
1481 break;
1482
The Android Open Source Project0c908882009-03-03 19:32:16 -08001483 case R.id.window_one_menu_id:
1484 case R.id.window_two_menu_id:
1485 case R.id.window_three_menu_id:
1486 case R.id.window_four_menu_id:
1487 case R.id.window_five_menu_id:
1488 case R.id.window_six_menu_id:
1489 case R.id.window_seven_menu_id:
1490 case R.id.window_eight_menu_id:
1491 {
1492 int menuid = item.getItemId();
1493 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1494 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001495 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001496 if (desiredTab != null &&
1497 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001498 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001499 }
1500 break;
1501 }
1502 }
1503 }
1504 break;
1505
1506 default:
1507 if (!super.onOptionsItemSelected(item)) {
1508 return false;
1509 }
1510 // Otherwise fall through.
1511 }
1512 mCanChord = false;
1513 return true;
1514 }
1515
1516 public void closeFind() {
1517 mMenuState = R.id.MAIN_MENU;
1518 }
1519
Grace Kloba22ac16e2009-10-07 18:00:23 -07001520 @Override
1521 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001522 // This happens when the user begins to hold down the menu key, so
1523 // allow them to chord to get a shortcut.
1524 mCanChord = true;
1525 // Note: setVisible will decide whether an item is visible; while
1526 // setEnabled() will decide whether an item is enabled, which also means
1527 // whether the matching shortcut key will function.
1528 super.onPrepareOptionsMenu(menu);
1529 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001530 case EMPTY_MENU:
1531 if (mCurrentMenuState != mMenuState) {
1532 menu.setGroupVisible(R.id.MAIN_MENU, false);
1533 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1534 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001535 }
1536 break;
1537 default:
1538 if (mCurrentMenuState != mMenuState) {
1539 menu.setGroupVisible(R.id.MAIN_MENU, true);
1540 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1541 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001542 }
1543 final WebView w = getTopWindow();
1544 boolean canGoBack = false;
1545 boolean canGoForward = false;
1546 boolean isHome = false;
1547 if (w != null) {
1548 canGoBack = w.canGoBack();
1549 canGoForward = w.canGoForward();
1550 isHome = mSettings.getHomePage().equals(w.getUrl());
1551 }
1552 final MenuItem back = menu.findItem(R.id.back_menu_id);
1553 back.setEnabled(canGoBack);
1554
1555 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1556 home.setEnabled(!isHome);
1557
1558 menu.findItem(R.id.forward_menu_id)
1559 .setEnabled(canGoForward);
1560
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001561 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001562 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001563
The Android Open Source Project0c908882009-03-03 19:32:16 -08001564 // decide whether to show the share link option
1565 PackageManager pm = getPackageManager();
1566 Intent send = new Intent(Intent.ACTION_SEND);
1567 send.setType("text/plain");
1568 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1569 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1570
The Android Open Source Project0c908882009-03-03 19:32:16 -08001571 boolean isNavDump = mSettings.isNavDump();
1572 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1573 nav.setVisible(isNavDump);
1574 nav.setEnabled(isNavDump);
1575 break;
1576 }
1577 mCurrentMenuState = mMenuState;
1578 return true;
1579 }
1580
1581 @Override
1582 public void onCreateContextMenu(ContextMenu menu, View v,
1583 ContextMenuInfo menuInfo) {
1584 WebView webview = (WebView) v;
1585 WebView.HitTestResult result = webview.getHitTestResult();
1586 if (result == null) {
1587 return;
1588 }
1589
1590 int type = result.getType();
1591 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1592 Log.w(LOGTAG,
1593 "We should not show context menu when nothing is touched");
1594 return;
1595 }
1596 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1597 // let TextView handles context menu
1598 return;
1599 }
1600
1601 // Note, http://b/issue?id=1106666 is requesting that
1602 // an inflated menu can be used again. This is not available
1603 // yet, so inflate each time (yuk!)
1604 MenuInflater inflater = getMenuInflater();
1605 inflater.inflate(R.menu.browsercontext, menu);
1606
1607 // Show the correct menu group
1608 String extra = result.getExtra();
1609 menu.setGroupVisible(R.id.PHONE_MENU,
1610 type == WebView.HitTestResult.PHONE_TYPE);
1611 menu.setGroupVisible(R.id.EMAIL_MENU,
1612 type == WebView.HitTestResult.EMAIL_TYPE);
1613 menu.setGroupVisible(R.id.GEO_MENU,
1614 type == WebView.HitTestResult.GEO_TYPE);
1615 menu.setGroupVisible(R.id.IMAGE_MENU,
1616 type == WebView.HitTestResult.IMAGE_TYPE
1617 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1618 menu.setGroupVisible(R.id.ANCHOR_MENU,
1619 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1620 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1621
1622 // Setup custom handling depending on the type
1623 switch (type) {
1624 case WebView.HitTestResult.PHONE_TYPE:
1625 menu.setHeaderTitle(Uri.decode(extra));
1626 menu.findItem(R.id.dial_context_menu_id).setIntent(
1627 new Intent(Intent.ACTION_VIEW, Uri
1628 .parse(WebView.SCHEME_TEL + extra)));
1629 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1630 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001631 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001632 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1633 addIntent);
1634 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1635 new Copy(extra));
1636 break;
1637
1638 case WebView.HitTestResult.EMAIL_TYPE:
1639 menu.setHeaderTitle(extra);
1640 menu.findItem(R.id.email_context_menu_id).setIntent(
1641 new Intent(Intent.ACTION_VIEW, Uri
1642 .parse(WebView.SCHEME_MAILTO + extra)));
1643 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1644 new Copy(extra));
1645 break;
1646
1647 case WebView.HitTestResult.GEO_TYPE:
1648 menu.setHeaderTitle(extra);
1649 menu.findItem(R.id.map_context_menu_id).setIntent(
1650 new Intent(Intent.ACTION_VIEW, Uri
1651 .parse(WebView.SCHEME_GEO
1652 + URLEncoder.encode(extra))));
1653 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1654 new Copy(extra));
1655 break;
1656
1657 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1658 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1659 TextView titleView = (TextView) LayoutInflater.from(this)
1660 .inflate(android.R.layout.browser_link_context_header,
1661 null);
1662 titleView.setText(extra);
1663 menu.setHeaderView(titleView);
1664 // decide whether to show the open link in new tab option
1665 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001666 mTabControl.canCreateNewTab());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001667 PackageManager pm = getPackageManager();
1668 Intent send = new Intent(Intent.ACTION_SEND);
1669 send.setType("text/plain");
1670 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1671 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1672 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1673 break;
1674 }
1675 // otherwise fall through to handle image part
1676 case WebView.HitTestResult.IMAGE_TYPE:
1677 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1678 menu.setHeaderTitle(extra);
1679 }
1680 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1681 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1682 menu.findItem(R.id.download_context_menu_id).
1683 setOnMenuItemClickListener(new Download(extra));
1684 break;
1685
1686 default:
1687 Log.w(LOGTAG, "We should not get here.");
1688 break;
1689 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001690 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001691 }
1692
The Android Open Source Project0c908882009-03-03 19:32:16 -08001693 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001694 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001695 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001696 // Attach the container that contains the main WebView and any other UI
1697 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001698 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001699
1700 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001701 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001702 if (errorConsole.numberOfErrors() == 0) {
1703 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1704 } else {
1705 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1706 }
1707
1708 mErrorConsoleContainer.addView(errorConsole,
1709 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1710 ViewGroup.LayoutParams.WRAP_CONTENT));
1711 }
1712
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001713 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001714 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001715 // Request focus on the top window.
1716 t.getTopWindow().requestFocus();
1717 }
1718
1719 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001720 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001721 t.attachSubWindow(mContentView);
1722 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001723 }
1724
1725 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001726 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001727 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001728 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001729
Grace Kloba22ac16e2009-10-07 18:00:23 -07001730 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1731 if (errorConsole != null) {
1732 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001733 }
1734
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001735 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001736 if (view != null) {
1737 view.setEmbeddedTitleBar(null);
1738 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001739 }
1740
1741 // Remove the sub window if it exists. Also called by TabControl when the
1742 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001743 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001744 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001745 // dismiss the subwindow. This will destroy the WebView.
1746 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001747 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001748 }
1749
Leon Scroggins1f005d32009-08-10 17:36:42 -04001750 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001751 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001752 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001753 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001754 }
1755
1756 // This method does a ton of stuff. It will attempt to create a new tab
1757 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001758 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001759 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1760 String appId) {
1761 final Tab currentTab = mTabControl.getCurrentTab();
1762 if (mTabControl.canCreateNewTab()) {
1763 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1764 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001765 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001766 // If the last tab was removed from the active tabs page, currentTab
1767 // will be null.
1768 if (currentTab != null) {
1769 removeTabFromContentView(currentTab);
1770 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001771 // We must set the new tab as the current tab to reflect the old
1772 // animation behavior.
1773 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001774 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001775 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001776 urlData.loadIn(webview);
1777 }
1778 return tab;
1779 } else {
1780 // Get rid of the subwindow if it exists
1781 dismissSubWindow(currentTab);
1782 if (!urlData.isEmpty()) {
1783 // Load the given url.
1784 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001785 }
1786 }
Grace Klobac9181842009-04-14 08:53:22 -07001787 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001788 }
1789
Grace Kloba22ac16e2009-10-07 18:00:23 -07001790 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001791 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001792 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001793 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001794 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001795 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001796 }
Grace Klobac9181842009-04-14 08:53:22 -07001797 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001798 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001799 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001800 }
1801 }
1802
1803 private class Copy implements OnMenuItemClickListener {
1804 private CharSequence mText;
1805
1806 public boolean onMenuItemClick(MenuItem item) {
1807 copy(mText);
1808 return true;
1809 }
1810
1811 public Copy(CharSequence toCopy) {
1812 mText = toCopy;
1813 }
1814 }
1815
1816 private class Download implements OnMenuItemClickListener {
1817 private String mText;
1818
1819 public boolean onMenuItemClick(MenuItem item) {
1820 onDownloadStartNoStream(mText, null, null, null, -1);
1821 return true;
1822 }
1823
1824 public Download(String toDownload) {
1825 mText = toDownload;
1826 }
1827 }
1828
1829 private void copy(CharSequence text) {
1830 try {
1831 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1832 if (clip != null) {
1833 clip.setClipboardText(text);
1834 }
1835 } catch (android.os.RemoteException e) {
1836 Log.e(LOGTAG, "Copy failed", e);
1837 }
1838 }
1839
1840 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001841 * Resets the browser title-view to whatever it must be
1842 * (for example, if we had a loading error)
1843 * When we have a new page, we call resetTitle, when we
1844 * have to reset the titlebar to whatever it used to be
1845 * (for example, if the user chose to stop loading), we
1846 * call resetTitleAndRevertLockIcon.
1847 */
1848 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001849 mTabControl.getCurrentTab().revertLockIcon();
1850 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001851 resetTitleIconAndProgress();
1852 }
1853
1854 /**
1855 * Reset the title, favicon, and progress.
1856 */
1857 private void resetTitleIconAndProgress() {
1858 WebView current = mTabControl.getCurrentWebView();
1859 if (current == null) {
1860 return;
1861 }
1862 resetTitleAndIcon(current);
1863 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001864 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001865 }
1866
1867 // Reset the title and the icon based on the given item.
1868 private void resetTitleAndIcon(WebView view) {
1869 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1870 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001871 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001872 setFavicon(item.getFavicon());
1873 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001874 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001875 setFavicon(null);
1876 }
1877 }
1878
1879 /**
1880 * Sets a title composed of the URL and the title string.
1881 * @param url The URL of the site being loaded.
1882 * @param title The title of the site being loaded.
1883 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001884 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001885 mUrl = url;
1886 mTitle = title;
1887
Leon Scroggins68579392009-09-15 15:31:54 -04001888 mTitleBar.setTitleAndUrl(title, url);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001889 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001890 }
1891
1892 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001893 * @param url The URL to build a title version of the URL from.
1894 * @return The title version of the URL or null if fails.
1895 * The title version of the URL can be either the URL hostname,
1896 * or the hostname with an "https://" prefix (for secure URLs),
1897 * or an empty string if, for example, the URL in question is a
1898 * file:// URL with no hostname.
1899 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001900 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001901 String titleUrl = null;
1902
1903 if (url != null) {
1904 try {
1905 // parse the url string
1906 URL urlObj = new URL(url);
1907 if (urlObj != null) {
1908 titleUrl = "";
1909
1910 String protocol = urlObj.getProtocol();
1911 String host = urlObj.getHost();
1912
1913 if (host != null && 0 < host.length()) {
1914 titleUrl = host;
1915 if (protocol != null) {
1916 // if a secure site, add an "https://" prefix!
1917 if (protocol.equalsIgnoreCase("https")) {
1918 titleUrl = protocol + "://" + host;
1919 }
1920 }
1921 }
1922 }
1923 } catch (MalformedURLException e) {}
1924 }
1925
1926 return titleUrl;
1927 }
1928
1929 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001930 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04001931 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001932 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001933 }
1934
1935 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001936 * Close the tab, remove its associated title bar, and adjust mTabControl's
1937 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001938 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001939 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001940 int currentIndex = mTabControl.getCurrentIndex();
1941 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001942 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001943 if (currentIndex >= removeIndex && currentIndex != 0) {
1944 currentIndex--;
1945 }
1946 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01001947 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001948 }
1949
1950 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001951 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001952 if (current == null) {
1953 /*
1954 * Instead of finishing the activity, simply push this to the back
1955 * of the stack and let ActivityManager to choose the foreground
1956 * activity. As BrowserActivity is singleTask, it will be always the
1957 * root of the task. So we can use either true or false for
1958 * moveTaskToBack().
1959 */
1960 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07001961 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001962 }
1963 WebView w = current.getWebView();
1964 if (w.canGoBack()) {
1965 w.goBack();
1966 } else {
1967 // Check to see if we are closing a window that was created by
1968 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001969 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001970 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001971 switchToTab(mTabControl.getTabIndex(parent));
1972 // Now we close the other tab
1973 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001974 } else {
1975 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001976 // force the tab's inLoad() to be false as we are going to
1977 // either finish the activity or remove the tab. This will
1978 // ensure pauseWebViewTimers() taking action.
1979 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001980 if (mTabControl.getTabCount() == 1) {
1981 finish();
1982 return;
1983 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04001984 // call pauseWebViewTimers() now, we won't be able to call
1985 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07001986 // Temporarily change mActivityInPause to be true as
1987 // pauseWebViewTimers() will do nothing if mActivityInPause
1988 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07001989 boolean savedState = mActivityInPause;
1990 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07001991 Log.e(LOGTAG, "BrowserActivity is already paused "
1992 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07001993 }
1994 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001995 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07001996 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001997 removeTabFromContentView(current);
1998 mTabControl.removeTab(current);
1999 }
2000 /*
2001 * Instead of finishing the activity, simply push this to the back
2002 * of the stack and let ActivityManager to choose the foreground
2003 * activity. As BrowserActivity is singleTask, it will be always the
2004 * root of the task. So we can use either true or false for
2005 * moveTaskToBack().
2006 */
2007 moveTaskToBack(true);
2008 }
2009 }
2010 }
2011
Grace Kloba22ac16e2009-10-07 18:00:23 -07002012 boolean isMenuDown() {
2013 return mMenuIsDown;
2014 }
2015
Grace Kloba5942df02009-09-18 11:48:29 -07002016 @Override
2017 public boolean onKeyDown(int keyCode, KeyEvent event) {
2018 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2019 // still down, we don't want to trigger the search. Pretend to consume
2020 // the key and do nothing.
2021 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002022
Grace Kloba5942df02009-09-18 11:48:29 -07002023 switch(keyCode) {
2024 case KeyEvent.KEYCODE_MENU:
2025 mMenuIsDown = true;
2026 break;
2027 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002028 // WebView/WebTextView handle the keys in the KeyDown. As
2029 // the Activity's shortcut keys are only handled when WebView
2030 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2031 if (event.isShiftPressed()) {
2032 getTopWindow().pageUp(false);
2033 } else {
2034 getTopWindow().pageDown(false);
2035 }
Grace Kloba5942df02009-09-18 11:48:29 -07002036 return true;
2037 case KeyEvent.KEYCODE_BACK:
2038 if (event.getRepeatCount() == 0) {
2039 event.startTracking();
2040 return true;
2041 } else if (mCustomView == null && mActiveTabsPage == null
2042 && event.isLongPress()) {
2043 bookmarksOrHistoryPicker(true);
2044 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002045 }
Grace Kloba5942df02009-09-18 11:48:29 -07002046 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002047 }
Grace Kloba5942df02009-09-18 11:48:29 -07002048 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002049 }
2050
Grace Kloba5942df02009-09-18 11:48:29 -07002051 @Override
2052 public boolean onKeyUp(int keyCode, KeyEvent event) {
2053 switch(keyCode) {
2054 case KeyEvent.KEYCODE_MENU:
2055 mMenuIsDown = false;
2056 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002057 case KeyEvent.KEYCODE_BACK:
2058 if (event.isTracking() && !event.isCanceled()) {
2059 if (mCustomView != null) {
2060 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002061 mTabControl.getCurrentWebView().getWebChromeClient()
2062 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002063 } else if (mActiveTabsPage != null) {
2064 // if tab page is showing, hide it
2065 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002066 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002067 WebView subwindow = mTabControl.getCurrentSubWindow();
2068 if (subwindow != null) {
2069 if (subwindow.canGoBack()) {
2070 subwindow.goBack();
2071 } else {
2072 dismissSubWindow(mTabControl.getCurrentTab());
2073 }
2074 } else {
2075 goBackOnePageOrQuit();
2076 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002077 }
Grace Kloba5942df02009-09-18 11:48:29 -07002078 return true;
2079 }
2080 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002081 }
Grace Kloba5942df02009-09-18 11:48:29 -07002082 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002083 }
2084
Leon Scroggins68579392009-09-15 15:31:54 -04002085 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002086 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002087 resetTitleAndRevertLockIcon();
2088 WebView w = getTopWindow();
2089 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002090 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2091 // same logic here. But for subwindow case, should we call into the main
2092 // WebView's onPageFinished as we never call its onPageStarted and if
2093 // the page finishes itself, we don't call onPageFinished.
2094 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2095 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002096
2097 cancelStopToast();
2098 mStopToast = Toast
2099 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2100 mStopToast.show();
2101 }
2102
Grace Kloba22ac16e2009-10-07 18:00:23 -07002103 boolean didUserStopLoading() {
2104 return mDidStopLoad;
2105 }
2106
The Android Open Source Project0c908882009-03-03 19:32:16 -08002107 private void cancelStopToast() {
2108 if (mStopToast != null) {
2109 mStopToast.cancel();
2110 mStopToast = null;
2111 }
2112 }
2113
Grace Kloba22ac16e2009-10-07 18:00:23 -07002114 // called by a UI or non-UI thread to post the message
2115 public void postMessage(int what, int arg1, int arg2, Object obj,
2116 long delayMillis) {
2117 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2118 obj), delayMillis);
2119 }
2120
2121 // called by a UI or non-UI thread to remove the message
2122 void removeMessages(int what, Object object) {
2123 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002124 }
2125
2126 // public message ids
2127 public final static int LOAD_URL = 1001;
2128 public final static int STOP_LOAD = 1002;
2129
2130 // Message Ids
2131 private static final int FOCUS_NODE_HREF = 102;
2132 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002133 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002134
Grace Kloba22ac16e2009-10-07 18:00:23 -07002135 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002136
The Android Open Source Project0c908882009-03-03 19:32:16 -08002137 // Private handler for handling javascript and saving passwords
2138 private Handler mHandler = new Handler() {
2139
2140 public void handleMessage(Message msg) {
2141 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002142 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002143 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002144 String url = (String) msg.getData().get("url");
2145 if (url == null || url.length() == 0) {
2146 break;
2147 }
2148 HashMap focusNodeMap = (HashMap) msg.obj;
2149 WebView view = (WebView) focusNodeMap.get("webview");
2150 // Only apply the action if the top window did not change.
2151 if (getTopWindow() != view) {
2152 break;
2153 }
2154 switch (msg.arg1) {
2155 case R.id.open_context_menu_id:
2156 case R.id.view_image_context_menu_id:
2157 loadURL(getTopWindow(), url);
2158 break;
2159 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002160 final Tab parent = mTabControl.getCurrentTab();
2161 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002162 if (newTab != parent) {
2163 parent.addChildTab(newTab);
2164 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002165 break;
2166 case R.id.bookmark_context_menu_id:
2167 Intent intent = new Intent(BrowserActivity.this,
2168 AddBookmarkPage.class);
2169 intent.putExtra("url", url);
2170 startActivity(intent);
2171 break;
2172 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002173 Browser.sendString(BrowserActivity.this, url,
2174 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002175 break;
2176 case R.id.copy_link_context_menu_id:
2177 copy(url);
2178 break;
2179 case R.id.save_link_context_menu_id:
2180 case R.id.download_context_menu_id:
2181 onDownloadStartNoStream(url, null, null, null, -1);
2182 break;
2183 }
2184 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002185 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002186
2187 case LOAD_URL:
2188 loadURL(getTopWindow(), (String) msg.obj);
2189 break;
2190
2191 case STOP_LOAD:
2192 stopLoading();
2193 break;
2194
2195 case CANCEL_CREDS_REQUEST:
2196 resumeAfterCredentials();
2197 break;
2198
The Android Open Source Project0c908882009-03-03 19:32:16 -08002199 case RELEASE_WAKELOCK:
2200 if (mWakeLock.isHeld()) {
2201 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002202 // if we reach here, Browser should be still in the
2203 // background loading after WAKELOCK_TIMEOUT (5-min).
2204 // To avoid burning the battery, stop loading.
2205 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002206 }
2207 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002208
2209 case UPDATE_BOOKMARK_THUMBNAIL:
2210 WebView view = (WebView) msg.obj;
2211 if (view != null) {
2212 updateScreenshot(view);
2213 }
2214 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002215 }
2216 }
2217 };
2218
Leon Scroggins89c6d362009-07-15 16:54:37 -04002219 private void updateScreenshot(WebView view) {
2220 // If this is a bookmarked site, add a screenshot to the database.
2221 // FIXME: When should we update? Every time?
2222 // FIXME: Would like to make sure there is actually something to
2223 // draw, but the API for that (WebViewCore.pictureReady()) is not
2224 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002225
Patrick Scott3918d442009-08-04 13:22:29 -04002226 ContentResolver cr = getContentResolver();
2227 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002228 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002229 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002230 boolean succeed = c.moveToFirst();
2231 ContentValues values = null;
2232 while (succeed) {
2233 if (values == null) {
2234 final ByteArrayOutputStream os
2235 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002236 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002237 if (bm == null) {
2238 c.close();
2239 return;
2240 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002241 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2242 values = new ContentValues();
2243 values.put(Browser.BookmarkColumns.THUMBNAIL,
2244 os.toByteArray());
2245 }
2246 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2247 c.getInt(0)), values, null, null);
2248 succeed = c.moveToNext();
2249 }
2250 c.close();
2251 }
2252 }
2253
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002254 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002255 * Values for the size of the thumbnail created when taking a screenshot.
2256 * Lazily initialized. Instead of using these directly, use
2257 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002258 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002259 private static int THUMBNAIL_WIDTH = 0;
2260 private static int THUMBNAIL_HEIGHT = 0;
2261
2262 /**
2263 * Return the desired width for thumbnail screenshots, which are stored in
2264 * the database, and used on the bookmarks screen.
2265 * @param context Context for finding out the density of the screen.
2266 * @return int desired width for thumbnail screenshot.
2267 */
2268 /* package */ static int getDesiredThumbnailWidth(Context context) {
2269 if (THUMBNAIL_WIDTH == 0) {
2270 float density = context.getResources().getDisplayMetrics().density;
2271 THUMBNAIL_WIDTH = (int) (90 * density);
2272 THUMBNAIL_HEIGHT = (int) (80 * density);
2273 }
2274 return THUMBNAIL_WIDTH;
2275 }
2276
2277 /**
2278 * Return the desired height for thumbnail screenshots, which are stored in
2279 * the database, and used on the bookmarks screen.
2280 * @param context Context for finding out the density of the screen.
2281 * @return int desired height for thumbnail screenshot.
2282 */
2283 /* package */ static int getDesiredThumbnailHeight(Context context) {
2284 // To ensure that they are both initialized.
2285 getDesiredThumbnailWidth(context);
2286 return THUMBNAIL_HEIGHT;
2287 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002288
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002289 private Bitmap createScreenshot(WebView view) {
2290 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002291 if (thumbnail == null) {
2292 return null;
2293 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002294 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2295 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002296 Canvas canvas = new Canvas(bm);
2297 // May need to tweak these values to determine what is the
2298 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002299 int thumbnailWidth = thumbnail.getWidth();
2300 if (thumbnailWidth > 0) {
2301 float scaleFactor = (float) getDesiredThumbnailWidth(this) /
2302 (float)thumbnailWidth;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002303 canvas.scale(scaleFactor, scaleFactor);
2304 }
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002305 thumbnail.draw(canvas);
2306 return bm;
2307 }
2308
The Android Open Source Project0c908882009-03-03 19:32:16 -08002309 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002310 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002311 //-------------------------------------------------------------------------
2312
2313 // Use in overrideUrlLoading
2314 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2315 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2316 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2317 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2318
Grace Kloba22ac16e2009-10-07 18:00:23 -07002319 void onPageStarted(WebView view, String url, Bitmap favicon) {
2320 // when BrowserActivity just starts, onPageStarted may be called before
2321 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2322 // to start the timer. As we won't switch tabs while an activity is in
2323 // pause state, we can ensure calling resume and pause in pair.
2324 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002325
Grace Kloba22ac16e2009-10-07 18:00:23 -07002326 resetLockIcon(url);
2327 setUrlTitle(url, null);
2328 setFavicon(favicon);
2329 mInLoad = true;
2330 mDidStopLoad = false;
2331 showFakeTitleBar();
2332 updateInLoadMenuItems();
2333 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002334
Grace Kloba22ac16e2009-10-07 18:00:23 -07002335 if (mSettings.isTracing()) {
2336 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002337 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002338 WebAddress uri = new WebAddress(url);
2339 host = uri.mHost;
2340 } catch (android.net.ParseException ex) {
2341 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002342 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002343 host = host.replace('.', '_');
2344 host += ".trace";
2345 mInTrace = true;
2346 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2347 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002348
Grace Kloba22ac16e2009-10-07 18:00:23 -07002349 // Performance probe
2350 if (false) {
2351 mStart = SystemClock.uptimeMillis();
2352 mProcessStart = Process.getElapsedCpuTime();
2353 long[] sysCpu = new long[7];
2354 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2355 sysCpu, null)) {
2356 mUserStart = sysCpu[0] + sysCpu[1];
2357 mSystemStart = sysCpu[2];
2358 mIdleStart = sysCpu[3];
2359 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2360 }
2361 mUiStart = SystemClock.currentThreadTimeMillis();
2362 }
2363 }
2364
2365 void onPageFinished(WebView view, String url) {
2366 // Reset the title and icon in case we stopped a provisional load.
2367 resetTitleAndIcon(view);
2368 // Update the lock icon image only once we are done loading
2369 updateLockIconToLatest();
2370 // pause the WebView timer and release the wake lock if it is finished
2371 // while BrowserActivity is in pause state.
2372 if (mActivityInPause && pauseWebViewTimers()) {
2373 if (mWakeLock.isHeld()) {
2374 mHandler.removeMessages(RELEASE_WAKELOCK);
2375 mWakeLock.release();
2376 }
2377 }
2378
2379 // Performance probe
2380 if (false) {
2381 long[] sysCpu = new long[7];
2382 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2383 sysCpu, null)) {
2384 String uiInfo = "UI thread used "
2385 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2386 + " ms";
2387 if (LOGD_ENABLED) {
2388 Log.d(LOGTAG, uiInfo);
2389 }
2390 //The string that gets written to the log
2391 String performanceString = "It took total "
2392 + (SystemClock.uptimeMillis() - mStart)
2393 + " ms clock time to load the page."
2394 + "\nbrowser process used "
2395 + (Process.getElapsedCpuTime() - mProcessStart)
2396 + " ms, user processes used "
2397 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2398 + " ms, kernel used "
2399 + (sysCpu[2] - mSystemStart) * 10
2400 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2401 + " ms and irq took "
2402 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2403 * 10 + " ms, " + uiInfo;
2404 if (LOGD_ENABLED) {
2405 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2406 }
2407 if (url != null) {
2408 // strip the url to maintain consistency
2409 String newUrl = new String(url);
2410 if (newUrl.startsWith("http://www.")) {
2411 newUrl = newUrl.substring(11);
2412 } else if (newUrl.startsWith("http://")) {
2413 newUrl = newUrl.substring(7);
2414 } else if (newUrl.startsWith("https://www.")) {
2415 newUrl = newUrl.substring(12);
2416 } else if (newUrl.startsWith("https://")) {
2417 newUrl = newUrl.substring(8);
2418 }
2419 if (LOGD_ENABLED) {
2420 Log.d(LOGTAG, newUrl + " loaded");
2421 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002422 }
2423 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002424 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002425
Grace Kloba22ac16e2009-10-07 18:00:23 -07002426 if (mInTrace) {
2427 mInTrace = false;
2428 Debug.stopMethodTracing();
2429 }
2430 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002431
Grace Kloba22ac16e2009-10-07 18:00:23 -07002432 boolean shouldOverrideUrlLoading(WebView view, String url) {
2433 if (url.startsWith(SCHEME_WTAI)) {
2434 // wtai://wp/mc;number
2435 // number=string(phone-number)
2436 if (url.startsWith(SCHEME_WTAI_MC)) {
2437 Intent intent = new Intent(Intent.ACTION_VIEW,
2438 Uri.parse(WebView.SCHEME_TEL +
2439 url.substring(SCHEME_WTAI_MC.length())));
2440 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002441 return true;
2442 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002443 // wtai://wp/sd;dtmf
2444 // dtmf=string(dialstring)
2445 if (url.startsWith(SCHEME_WTAI_SD)) {
2446 // TODO: only send when there is active voice connection
2447 return false;
2448 }
2449 // wtai://wp/ap;number;name
2450 // number=string(phone-number)
2451 // name=string
2452 if (url.startsWith(SCHEME_WTAI_AP)) {
2453 // TODO
2454 return false;
2455 }
2456 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002457
Grace Kloba22ac16e2009-10-07 18:00:23 -07002458 // The "about:" schemes are internal to the browser; don't want these to
2459 // be dispatched to other apps.
2460 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002461 return false;
2462 }
2463
Grace Kloba22ac16e2009-10-07 18:00:23 -07002464 Intent intent;
2465 // perform generic parsing of the URI to turn it into an Intent.
2466 try {
2467 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2468 } catch (URISyntaxException ex) {
2469 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2470 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002471 }
2472
Grace Kloba22ac16e2009-10-07 18:00:23 -07002473 // check whether the intent can be resolved. If not, we will see
2474 // whether we can download it from the Market.
2475 if (getPackageManager().resolveActivity(intent, 0) == null) {
2476 String packagename = intent.getPackage();
2477 if (packagename != null) {
2478 intent = new Intent(Intent.ACTION_VIEW, Uri
2479 .parse("market://search?q=pname:" + packagename));
2480 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2481 startActivity(intent);
2482 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002483 } else {
2484 return false;
2485 }
2486 }
2487
Grace Kloba22ac16e2009-10-07 18:00:23 -07002488 // sanitize the Intent, ensuring web pages can not bypass browser
2489 // security (only access to BROWSABLE activities).
2490 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2491 intent.setComponent(null);
2492 try {
2493 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002494 return true;
2495 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002496 } catch (ActivityNotFoundException ex) {
2497 // ignore the error. If no application can handle the URL,
2498 // eg about:blank, assume the browser can handle it.
2499 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002500
Grace Kloba22ac16e2009-10-07 18:00:23 -07002501 if (mMenuIsDown) {
2502 openTab(url);
2503 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002504 return true;
2505 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002506 return false;
2507 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002508
Grace Kloba22ac16e2009-10-07 18:00:23 -07002509 // -------------------------------------------------------------------------
2510 // Helper function for WebChromeClient
2511 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002512
Grace Kloba22ac16e2009-10-07 18:00:23 -07002513 void onProgressChanged(WebView view, int newProgress) {
2514 mTitleBar.setProgress(newProgress);
2515 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002516
Grace Kloba22ac16e2009-10-07 18:00:23 -07002517 if (newProgress == 100) {
2518 // onProgressChanged() may continue to be called after the main
2519 // frame has finished loading, as any remaining sub frames continue
2520 // to load. We'll only get called once though with newProgress as
2521 // 100 when everything is loaded. (onPageFinished is called once
2522 // when the main frame completes loading regardless of the state of
2523 // any sub frames so calls to onProgressChanges may continue after
2524 // onPageFinished has executed)
2525 if (mInLoad) {
2526 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002527 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002528 // If the options menu is open, leave the title bar
2529 if (!mOptionsMenuOpen || !mIconView) {
2530 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002531 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002532 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002533 } else if (!mInLoad) {
2534 // onPageFinished may have already been called but a subframe is
2535 // still loading and updating the progress. Reset mInLoad and update
2536 // the menu items.
2537 mInLoad = true;
2538 updateInLoadMenuItems();
2539 if (!mOptionsMenuOpen || mIconView) {
2540 // This page has begun to load, so show the title bar
2541 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002542 }
2543 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002544 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002545
Grace Kloba22ac16e2009-10-07 18:00:23 -07002546 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2547 if (mCustomView != null)
2548 return;
2549
2550 // Add the custom view to its container.
2551 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2552 mCustomView = view;
2553 mCustomViewCallback = callback;
2554 // Save the menu state and set it to empty while the custom
2555 // view is showing.
2556 mOldMenuState = mMenuState;
2557 mMenuState = EMPTY_MENU;
2558 // Hide the content view.
2559 mContentView.setVisibility(View.GONE);
2560 // Finally show the custom view container.
2561 mCustomViewContainer.setVisibility(View.VISIBLE);
2562 mCustomViewContainer.bringToFront();
2563 }
2564
2565 void onHideCustomView() {
2566 if (mCustomView == null)
2567 return;
2568
2569 // Hide the custom view.
2570 mCustomView.setVisibility(View.GONE);
2571 // Remove the custom view from its container.
2572 mCustomViewContainer.removeView(mCustomView);
2573 mCustomView = null;
2574 // Reset the old menu state.
2575 mMenuState = mOldMenuState;
2576 mOldMenuState = EMPTY_MENU;
2577 mCustomViewContainer.setVisibility(View.GONE);
2578 mCustomViewCallback.onCustomViewHidden();
2579 // Show the content view.
2580 mContentView.setVisibility(View.VISIBLE);
2581 }
2582
2583 Bitmap getDefaultVideoPoster() {
2584 if (mDefaultVideoPoster == null) {
2585 mDefaultVideoPoster = BitmapFactory.decodeResource(
2586 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002587 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002588 return mDefaultVideoPoster;
2589 }
Patrick Scott3918d442009-08-04 13:22:29 -04002590
Grace Kloba22ac16e2009-10-07 18:00:23 -07002591 View getVideoLoadingProgressView() {
2592 if (mVideoProgressView == null) {
2593 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2594 mVideoProgressView = inflater.inflate(
2595 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002596 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002597 return mVideoProgressView;
2598 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002599
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002600 /*
2601 * The Object used to inform the WebView of the file to upload.
2602 */
2603 private ValueCallback<Uri> mUploadMessage;
2604
Grace Kloba22ac16e2009-10-07 18:00:23 -07002605 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2606 if (mUploadMessage != null) return;
2607 mUploadMessage = uploadMsg;
2608 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2609 i.addCategory(Intent.CATEGORY_OPENABLE);
2610 i.setType("*/*");
2611 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2612 getString(R.string.choose_upload)), FILE_SELECTED);
2613 }
2614
2615 // -------------------------------------------------------------------------
2616 // Implement functions for DownloadListener
2617 // -------------------------------------------------------------------------
2618
The Android Open Source Project0c908882009-03-03 19:32:16 -08002619 /**
2620 * Notify the host application a download should be done, or that
2621 * the data should be streamed if a streaming viewer is available.
2622 * @param url The full url to the content that should be downloaded
2623 * @param contentDisposition Content-disposition http header, if
2624 * present.
2625 * @param mimetype The mimetype of the content reported by the server
2626 * @param contentLength The file size reported by the server
2627 */
2628 public void onDownloadStart(String url, String userAgent,
2629 String contentDisposition, String mimetype, long contentLength) {
2630 // if we're dealing wih A/V content that's not explicitly marked
2631 // for download, check if it's streamable.
2632 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002633 || !contentDisposition.regionMatches(
2634 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002635 // query the package manager to see if there's a registered handler
2636 // that matches.
2637 Intent intent = new Intent(Intent.ACTION_VIEW);
2638 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002639 ResolveInfo info = getPackageManager().resolveActivity(intent,
2640 PackageManager.MATCH_DEFAULT_ONLY);
2641 if (info != null) {
2642 ComponentName myName = getComponentName();
2643 // If we resolved to ourselves, we don't want to attempt to
2644 // load the url only to try and download it again.
2645 if (!myName.getPackageName().equals(
2646 info.activityInfo.packageName)
2647 || !myName.getClassName().equals(
2648 info.activityInfo.name)) {
2649 // someone (other than us) knows how to handle this mime
2650 // type with this scheme, don't download.
2651 try {
2652 startActivity(intent);
2653 return;
2654 } catch (ActivityNotFoundException ex) {
2655 if (LOGD_ENABLED) {
2656 Log.d(LOGTAG, "activity not found for " + mimetype
2657 + " over " + Uri.parse(url).getScheme(),
2658 ex);
2659 }
2660 // Best behavior is to fall back to a download in this
2661 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002662 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002663 }
2664 }
2665 }
2666 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2667 }
2668
2669 /**
2670 * Notify the host application a download should be done, even if there
2671 * is a streaming viewer available for thise type.
2672 * @param url The full url to the content that should be downloaded
2673 * @param contentDisposition Content-disposition http header, if
2674 * present.
2675 * @param mimetype The mimetype of the content reported by the server
2676 * @param contentLength The file size reported by the server
2677 */
2678 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2679 String contentDisposition, String mimetype, long contentLength) {
2680
2681 String filename = URLUtil.guessFileName(url,
2682 contentDisposition, mimetype);
2683
2684 // Check to see if we have an SDCard
2685 String status = Environment.getExternalStorageState();
2686 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2687 int title;
2688 String msg;
2689
2690 // Check to see if the SDCard is busy, same as the music app
2691 if (status.equals(Environment.MEDIA_SHARED)) {
2692 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2693 title = R.string.download_sdcard_busy_dlg_title;
2694 } else {
2695 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2696 title = R.string.download_no_sdcard_dlg_title;
2697 }
2698
2699 new AlertDialog.Builder(this)
2700 .setTitle(title)
2701 .setIcon(android.R.drawable.ic_dialog_alert)
2702 .setMessage(msg)
2703 .setPositiveButton(R.string.ok, null)
2704 .show();
2705 return;
2706 }
2707
2708 // java.net.URI is a lot stricter than KURL so we have to undo
2709 // KURL's percent-encoding and redo the encoding using java.net.URI.
2710 URI uri = null;
2711 try {
2712 // Undo the percent-encoding that KURL may have done.
2713 String newUrl = new String(URLUtil.decode(url.getBytes()));
2714 // Parse the url into pieces
2715 WebAddress w = new WebAddress(newUrl);
2716 String frag = null;
2717 String query = null;
2718 String path = w.mPath;
2719 // Break the path into path, query, and fragment
2720 if (path.length() > 0) {
2721 // Strip the fragment
2722 int idx = path.lastIndexOf('#');
2723 if (idx != -1) {
2724 frag = path.substring(idx + 1);
2725 path = path.substring(0, idx);
2726 }
2727 idx = path.lastIndexOf('?');
2728 if (idx != -1) {
2729 query = path.substring(idx + 1);
2730 path = path.substring(0, idx);
2731 }
2732 }
2733 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2734 query, frag);
2735 } catch (Exception e) {
2736 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2737 return;
2738 }
2739
2740 // XXX: Have to use the old url since the cookies were stored using the
2741 // old percent-encoded url.
2742 String cookies = CookieManager.getInstance().getCookie(url);
2743
2744 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002745 values.put(Downloads.COLUMN_URI, uri.toString());
2746 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
2747 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
2748 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002749 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002750 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002751 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002752 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2753 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
2754 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
2755 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002756 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002757 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002758 }
2759 if (mimetype == null) {
2760 // We must have long pressed on a link or image to download it. We
2761 // are not sure of the mimetype in this case, so do a head request
2762 new FetchUrlMimeType(this).execute(values);
2763 } else {
2764 final Uri contentUri =
2765 getContentResolver().insert(Downloads.CONTENT_URI, values);
2766 viewDownloads(contentUri);
2767 }
2768
2769 }
2770
Grace Kloba22ac16e2009-10-07 18:00:23 -07002771 // -------------------------------------------------------------------------
2772
The Android Open Source Project0c908882009-03-03 19:32:16 -08002773 /**
2774 * Resets the lock icon. This method is called when we start a new load and
2775 * know the url to be loaded.
2776 */
2777 private void resetLockIcon(String url) {
2778 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002779 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002780 updateLockIconImage(LOCK_ICON_UNSECURE);
2781 }
2782
The Android Open Source Project0c908882009-03-03 19:32:16 -08002783 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002784 * Update the lock icon to correspond to our latest state.
2785 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002786 private void updateLockIconToLatest() {
2787 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002788 }
2789
2790 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002791 * Updates the lock-icon image in the title-bar.
2792 */
2793 private void updateLockIconImage(int lockIconType) {
2794 Drawable d = null;
2795 if (lockIconType == LOCK_ICON_SECURE) {
2796 d = mSecLockIcon;
2797 } else if (lockIconType == LOCK_ICON_MIXED) {
2798 d = mMixLockIcon;
2799 }
Leon Scroggins68579392009-09-15 15:31:54 -04002800 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002801 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002802 }
2803
2804 /**
2805 * Displays a page-info dialog.
2806 * @param tab The tab to show info about
2807 * @param fromShowSSLCertificateOnError The flag that indicates whether
2808 * this dialog was opened from the SSL-certificate-on-error dialog or
2809 * not. This is important, since we need to know whether to return to
2810 * the parent dialog or simply dismiss.
2811 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002812 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002813 final boolean fromShowSSLCertificateOnError) {
2814 final LayoutInflater factory = LayoutInflater
2815 .from(this);
2816
2817 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2818
2819 final WebView view = tab.getWebView();
2820
2821 String url = null;
2822 String title = null;
2823
2824 if (view == null) {
2825 url = tab.getUrl();
2826 title = tab.getTitle();
2827 } else if (view == mTabControl.getCurrentWebView()) {
2828 // Use the cached title and url if this is the current WebView
2829 url = mUrl;
2830 title = mTitle;
2831 } else {
2832 url = view.getUrl();
2833 title = view.getTitle();
2834 }
2835
2836 if (url == null) {
2837 url = "";
2838 }
2839 if (title == null) {
2840 title = "";
2841 }
2842
2843 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2844 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2845
2846 mPageInfoView = tab;
2847 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
2848
2849 AlertDialog.Builder alertDialogBuilder =
2850 new AlertDialog.Builder(this)
2851 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2852 .setView(pageInfoView)
2853 .setPositiveButton(
2854 R.string.ok,
2855 new DialogInterface.OnClickListener() {
2856 public void onClick(DialogInterface dialog,
2857 int whichButton) {
2858 mPageInfoDialog = null;
2859 mPageInfoView = null;
2860 mPageInfoFromShowSSLCertificateOnError = null;
2861
2862 // if we came here from the SSL error dialog
2863 if (fromShowSSLCertificateOnError) {
2864 // go back to the SSL error dialog
2865 showSSLCertificateOnError(
2866 mSSLCertificateOnErrorView,
2867 mSSLCertificateOnErrorHandler,
2868 mSSLCertificateOnErrorError);
2869 }
2870 }
2871 })
2872 .setOnCancelListener(
2873 new DialogInterface.OnCancelListener() {
2874 public void onCancel(DialogInterface dialog) {
2875 mPageInfoDialog = null;
2876 mPageInfoView = null;
2877 mPageInfoFromShowSSLCertificateOnError = null;
2878
2879 // if we came here from the SSL error dialog
2880 if (fromShowSSLCertificateOnError) {
2881 // go back to the SSL error dialog
2882 showSSLCertificateOnError(
2883 mSSLCertificateOnErrorView,
2884 mSSLCertificateOnErrorHandler,
2885 mSSLCertificateOnErrorError);
2886 }
2887 }
2888 });
2889
2890 // if we have a main top-level page SSL certificate set or a certificate
2891 // error
2892 if (fromShowSSLCertificateOnError ||
2893 (view != null && view.getCertificate() != null)) {
2894 // add a 'View Certificate' button
2895 alertDialogBuilder.setNeutralButton(
2896 R.string.view_certificate,
2897 new DialogInterface.OnClickListener() {
2898 public void onClick(DialogInterface dialog,
2899 int whichButton) {
2900 mPageInfoDialog = null;
2901 mPageInfoView = null;
2902 mPageInfoFromShowSSLCertificateOnError = null;
2903
2904 // if we came here from the SSL error dialog
2905 if (fromShowSSLCertificateOnError) {
2906 // go back to the SSL error dialog
2907 showSSLCertificateOnError(
2908 mSSLCertificateOnErrorView,
2909 mSSLCertificateOnErrorHandler,
2910 mSSLCertificateOnErrorError);
2911 } else {
2912 // otherwise, display the top-most certificate from
2913 // the chain
2914 if (view.getCertificate() != null) {
2915 showSSLCertificate(tab);
2916 }
2917 }
2918 }
2919 });
2920 }
2921
2922 mPageInfoDialog = alertDialogBuilder.show();
2923 }
2924
2925 /**
2926 * Displays the main top-level page SSL certificate dialog
2927 * (accessible from the Page-Info dialog).
2928 * @param tab The tab to show certificate for.
2929 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002930 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002931 final View certificateView =
2932 inflateCertificateView(tab.getWebView().getCertificate());
2933 if (certificateView == null) {
2934 return;
2935 }
2936
2937 LayoutInflater factory = LayoutInflater.from(this);
2938
2939 final LinearLayout placeholder =
2940 (LinearLayout)certificateView.findViewById(R.id.placeholder);
2941
2942 LinearLayout ll = (LinearLayout) factory.inflate(
2943 R.layout.ssl_success, placeholder);
2944 ((TextView)ll.findViewById(R.id.success))
2945 .setText(R.string.ssl_certificate_is_valid);
2946
2947 mSSLCertificateView = tab;
2948 mSSLCertificateDialog =
2949 new AlertDialog.Builder(this)
2950 .setTitle(R.string.ssl_certificate).setIcon(
2951 R.drawable.ic_dialog_browser_certificate_secure)
2952 .setView(certificateView)
2953 .setPositiveButton(R.string.ok,
2954 new DialogInterface.OnClickListener() {
2955 public void onClick(DialogInterface dialog,
2956 int whichButton) {
2957 mSSLCertificateDialog = null;
2958 mSSLCertificateView = null;
2959
2960 showPageInfo(tab, false);
2961 }
2962 })
2963 .setOnCancelListener(
2964 new DialogInterface.OnCancelListener() {
2965 public void onCancel(DialogInterface dialog) {
2966 mSSLCertificateDialog = null;
2967 mSSLCertificateView = null;
2968
2969 showPageInfo(tab, false);
2970 }
2971 })
2972 .show();
2973 }
2974
2975 /**
2976 * Displays the SSL error certificate dialog.
2977 * @param view The target web-view.
2978 * @param handler The SSL error handler responsible for cancelling the
2979 * connection that resulted in an SSL error or proceeding per user request.
2980 * @param error The SSL error object.
2981 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002982 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08002983 final WebView view, final SslErrorHandler handler, final SslError error) {
2984
2985 final View certificateView =
2986 inflateCertificateView(error.getCertificate());
2987 if (certificateView == null) {
2988 return;
2989 }
2990
2991 LayoutInflater factory = LayoutInflater.from(this);
2992
2993 final LinearLayout placeholder =
2994 (LinearLayout)certificateView.findViewById(R.id.placeholder);
2995
2996 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2997 LinearLayout ll = (LinearLayout)factory
2998 .inflate(R.layout.ssl_warning, placeholder);
2999 ((TextView)ll.findViewById(R.id.warning))
3000 .setText(R.string.ssl_untrusted);
3001 }
3002
3003 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3004 LinearLayout ll = (LinearLayout)factory
3005 .inflate(R.layout.ssl_warning, placeholder);
3006 ((TextView)ll.findViewById(R.id.warning))
3007 .setText(R.string.ssl_mismatch);
3008 }
3009
3010 if (error.hasError(SslError.SSL_EXPIRED)) {
3011 LinearLayout ll = (LinearLayout)factory
3012 .inflate(R.layout.ssl_warning, placeholder);
3013 ((TextView)ll.findViewById(R.id.warning))
3014 .setText(R.string.ssl_expired);
3015 }
3016
3017 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3018 LinearLayout ll = (LinearLayout)factory
3019 .inflate(R.layout.ssl_warning, placeholder);
3020 ((TextView)ll.findViewById(R.id.warning))
3021 .setText(R.string.ssl_not_yet_valid);
3022 }
3023
3024 mSSLCertificateOnErrorHandler = handler;
3025 mSSLCertificateOnErrorView = view;
3026 mSSLCertificateOnErrorError = error;
3027 mSSLCertificateOnErrorDialog =
3028 new AlertDialog.Builder(this)
3029 .setTitle(R.string.ssl_certificate).setIcon(
3030 R.drawable.ic_dialog_browser_certificate_partially_secure)
3031 .setView(certificateView)
3032 .setPositiveButton(R.string.ok,
3033 new DialogInterface.OnClickListener() {
3034 public void onClick(DialogInterface dialog,
3035 int whichButton) {
3036 mSSLCertificateOnErrorDialog = null;
3037 mSSLCertificateOnErrorView = null;
3038 mSSLCertificateOnErrorHandler = null;
3039 mSSLCertificateOnErrorError = null;
3040
Grace Kloba22ac16e2009-10-07 18:00:23 -07003041 view.getWebViewClient().onReceivedSslError(
3042 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003043 }
3044 })
3045 .setNeutralButton(R.string.page_info_view,
3046 new DialogInterface.OnClickListener() {
3047 public void onClick(DialogInterface dialog,
3048 int whichButton) {
3049 mSSLCertificateOnErrorDialog = null;
3050
3051 // do not clear the dialog state: we will
3052 // need to show the dialog again once the
3053 // user is done exploring the page-info details
3054
3055 showPageInfo(mTabControl.getTabFromView(view),
3056 true);
3057 }
3058 })
3059 .setOnCancelListener(
3060 new DialogInterface.OnCancelListener() {
3061 public void onCancel(DialogInterface dialog) {
3062 mSSLCertificateOnErrorDialog = null;
3063 mSSLCertificateOnErrorView = null;
3064 mSSLCertificateOnErrorHandler = null;
3065 mSSLCertificateOnErrorError = null;
3066
Grace Kloba22ac16e2009-10-07 18:00:23 -07003067 view.getWebViewClient().onReceivedSslError(
3068 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003069 }
3070 })
3071 .show();
3072 }
3073
3074 /**
3075 * Inflates the SSL certificate view (helper method).
3076 * @param certificate The SSL certificate.
3077 * @return The resultant certificate view with issued-to, issued-by,
3078 * issued-on, expires-on, and possibly other fields set.
3079 * If the input certificate is null, returns null.
3080 */
3081 private View inflateCertificateView(SslCertificate certificate) {
3082 if (certificate == null) {
3083 return null;
3084 }
3085
3086 LayoutInflater factory = LayoutInflater.from(this);
3087
3088 View certificateView = factory.inflate(
3089 R.layout.ssl_certificate, null);
3090
3091 // issued to:
3092 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3093 if (issuedTo != null) {
3094 ((TextView) certificateView.findViewById(R.id.to_common))
3095 .setText(issuedTo.getCName());
3096 ((TextView) certificateView.findViewById(R.id.to_org))
3097 .setText(issuedTo.getOName());
3098 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3099 .setText(issuedTo.getUName());
3100 }
3101
3102 // issued by:
3103 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3104 if (issuedBy != null) {
3105 ((TextView) certificateView.findViewById(R.id.by_common))
3106 .setText(issuedBy.getCName());
3107 ((TextView) certificateView.findViewById(R.id.by_org))
3108 .setText(issuedBy.getOName());
3109 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3110 .setText(issuedBy.getUName());
3111 }
3112
3113 // issued on:
3114 String issuedOn = reformatCertificateDate(
3115 certificate.getValidNotBefore());
3116 ((TextView) certificateView.findViewById(R.id.issued_on))
3117 .setText(issuedOn);
3118
3119 // expires on:
3120 String expiresOn = reformatCertificateDate(
3121 certificate.getValidNotAfter());
3122 ((TextView) certificateView.findViewById(R.id.expires_on))
3123 .setText(expiresOn);
3124
3125 return certificateView;
3126 }
3127
3128 /**
3129 * Re-formats the certificate date (Date.toString()) string to
3130 * a properly localized date string.
3131 * @return Properly localized version of the certificate date string and
3132 * the original certificate date string if fails to localize.
3133 * If the original string is null, returns an empty string "".
3134 */
3135 private String reformatCertificateDate(String certificateDate) {
3136 String reformattedDate = null;
3137
3138 if (certificateDate != null) {
3139 Date date = null;
3140 try {
3141 date = java.text.DateFormat.getInstance().parse(certificateDate);
3142 } catch (ParseException e) {
3143 date = null;
3144 }
3145
3146 if (date != null) {
3147 reformattedDate =
3148 DateFormat.getDateFormat(this).format(date);
3149 }
3150 }
3151
3152 return reformattedDate != null ? reformattedDate :
3153 (certificateDate != null ? certificateDate : "");
3154 }
3155
3156 /**
3157 * Displays an http-authentication dialog.
3158 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003159 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003160 final String host, final String realm, final String title,
3161 final String name, final String password, int focusId) {
3162 LayoutInflater factory = LayoutInflater.from(this);
3163 final View v = factory
3164 .inflate(R.layout.http_authentication, null);
3165 if (name != null) {
3166 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3167 }
3168 if (password != null) {
3169 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3170 }
3171
3172 String titleText = title;
3173 if (titleText == null) {
3174 titleText = getText(R.string.sign_in_to).toString().replace(
3175 "%s1", host).replace("%s2", realm);
3176 }
3177
3178 mHttpAuthHandler = handler;
3179 AlertDialog dialog = new AlertDialog.Builder(this)
3180 .setTitle(titleText)
3181 .setIcon(android.R.drawable.ic_dialog_alert)
3182 .setView(v)
3183 .setPositiveButton(R.string.action,
3184 new DialogInterface.OnClickListener() {
3185 public void onClick(DialogInterface dialog,
3186 int whichButton) {
3187 String nm = ((EditText) v
3188 .findViewById(R.id.username_edit))
3189 .getText().toString();
3190 String pw = ((EditText) v
3191 .findViewById(R.id.password_edit))
3192 .getText().toString();
3193 BrowserActivity.this.setHttpAuthUsernamePassword
3194 (host, realm, nm, pw);
3195 handler.proceed(nm, pw);
3196 mHttpAuthenticationDialog = null;
3197 mHttpAuthHandler = null;
3198 }})
3199 .setNegativeButton(R.string.cancel,
3200 new DialogInterface.OnClickListener() {
3201 public void onClick(DialogInterface dialog,
3202 int whichButton) {
3203 handler.cancel();
3204 BrowserActivity.this.resetTitleAndRevertLockIcon();
3205 mHttpAuthenticationDialog = null;
3206 mHttpAuthHandler = null;
3207 }})
3208 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3209 public void onCancel(DialogInterface dialog) {
3210 handler.cancel();
3211 BrowserActivity.this.resetTitleAndRevertLockIcon();
3212 mHttpAuthenticationDialog = null;
3213 mHttpAuthHandler = null;
3214 }})
3215 .create();
3216 // Make the IME appear when the dialog is displayed if applicable.
3217 dialog.getWindow().setSoftInputMode(
3218 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3219 dialog.show();
3220 if (focusId != 0) {
3221 dialog.findViewById(focusId).requestFocus();
3222 } else {
3223 v.findViewById(R.id.username_edit).requestFocus();
3224 }
3225 mHttpAuthenticationDialog = dialog;
3226 }
3227
3228 public int getProgress() {
3229 WebView w = mTabControl.getCurrentWebView();
3230 if (w != null) {
3231 return w.getProgress();
3232 } else {
3233 return 100;
3234 }
3235 }
3236
3237 /**
3238 * Set HTTP authentication password.
3239 *
3240 * @param host The host for the password
3241 * @param realm The realm for the password
3242 * @param username The username for the password. If it is null, it means
3243 * password can't be saved.
3244 * @param password The password
3245 */
3246 public void setHttpAuthUsernamePassword(String host, String realm,
3247 String username,
3248 String password) {
3249 WebView w = mTabControl.getCurrentWebView();
3250 if (w != null) {
3251 w.setHttpAuthUsernamePassword(host, realm, username, password);
3252 }
3253 }
3254
3255 /**
3256 * connectivity manager says net has come or gone... inform the user
3257 * @param up true if net has come up, false if net has gone down
3258 */
3259 public void onNetworkToggle(boolean up) {
3260 if (up == mIsNetworkUp) {
3261 return;
3262 } else if (up) {
3263 mIsNetworkUp = true;
3264 if (mAlertDialog != null) {
3265 mAlertDialog.cancel();
3266 mAlertDialog = null;
3267 }
3268 } else {
3269 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003270 if (mInLoad) {
3271 createAndShowNetworkDialog();
3272 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003273 }
3274 WebView w = mTabControl.getCurrentWebView();
3275 if (w != null) {
3276 w.setNetworkAvailable(up);
3277 }
3278 }
3279
Grace Kloba22ac16e2009-10-07 18:00:23 -07003280 boolean isNetworkUp() {
3281 return mIsNetworkUp;
3282 }
3283
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003284 // This method shows the network dialog alerting the user that the net is
3285 // down. It will only show the dialog if mAlertDialog is null.
3286 private void createAndShowNetworkDialog() {
3287 if (mAlertDialog == null) {
3288 mAlertDialog = new AlertDialog.Builder(this)
3289 .setTitle(R.string.loadSuspendedTitle)
3290 .setMessage(R.string.loadSuspended)
3291 .setPositiveButton(R.string.ok, null)
3292 .show();
3293 }
3294 }
3295
The Android Open Source Project0c908882009-03-03 19:32:16 -08003296 @Override
3297 protected void onActivityResult(int requestCode, int resultCode,
3298 Intent intent) {
3299 switch (requestCode) {
3300 case COMBO_PAGE:
3301 if (resultCode == RESULT_OK && intent != null) {
3302 String data = intent.getAction();
3303 Bundle extras = intent.getExtras();
3304 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003305 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003306 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003307 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003308 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003309 dismissSubWindow(currentTab);
3310 if (data != null && data.length() != 0) {
3311 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003312 }
3313 }
3314 }
3315 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003316 // Choose a file from the file picker.
3317 case FILE_SELECTED:
3318 if (null == mUploadMessage) break;
3319 Uri result = intent == null || resultCode != RESULT_OK ? null
3320 : intent.getData();
3321 mUploadMessage.onReceiveValue(result);
3322 mUploadMessage = null;
3323 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003324 default:
3325 break;
3326 }
Leon Scroggins30444232009-09-04 18:36:20 -04003327 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003328 }
3329
3330 /*
3331 * This method is called as a result of the user selecting the options
3332 * menu to see the download window, or when a download changes state. It
3333 * shows the download window ontop of the current window.
3334 */
3335 /* package */ void viewDownloads(Uri downloadRecord) {
3336 Intent intent = new Intent(this,
3337 BrowserDownloadPage.class);
3338 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003339 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003340
3341 }
3342
Leon Scroggins160a7e72009-08-14 18:28:01 -04003343 /**
3344 * Open the Go page.
3345 * @param startWithHistory If true, open starting on the history tab.
3346 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003347 */
Leon Scroggins30444232009-09-04 18:36:20 -04003348 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003349 WebView current = mTabControl.getCurrentWebView();
3350 if (current == null) {
3351 return;
3352 }
3353 Intent intent = new Intent(this,
3354 CombinedBookmarkHistoryActivity.class);
3355 String title = current.getTitle();
3356 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003357 Bitmap thumbnail = createScreenshot(current);
3358
The Android Open Source Project0c908882009-03-03 19:32:16 -08003359 // Just in case the user opens bookmarks before a page finishes loading
3360 // so the current history item, and therefore the page, is null.
3361 if (null == url) {
3362 url = mLastEnteredUrl;
3363 // This can happen.
3364 if (null == url) {
3365 url = mSettings.getHomePage();
3366 }
3367 }
3368 // In case the web page has not yet received its associated title.
3369 if (title == null) {
3370 title = url;
3371 }
3372 intent.putExtra("title", title);
3373 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003374 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003375 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003376 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003377 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003378 if (startWithHistory) {
3379 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3380 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3381 }
3382 startActivityForResult(intent, COMBO_PAGE);
3383 }
3384
3385 // Called when loading from context menu or LOAD_URL message
3386 private void loadURL(WebView view, String url) {
3387 // In case the user enters nothing.
3388 if (url != null && url.length() != 0 && view != null) {
3389 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003390 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003391 view.loadUrl(url);
3392 }
3393 }
3394 }
3395
The Android Open Source Project0c908882009-03-03 19:32:16 -08003396 private String smartUrlFilter(Uri inUri) {
3397 if (inUri != null) {
3398 return smartUrlFilter(inUri.toString());
3399 }
3400 return null;
3401 }
3402
Feng Qianb34f87a2009-03-24 21:27:26 -07003403 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003404 "(?i)" + // switch on case insensitive matching
3405 "(" + // begin group for schema
3406 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003407 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003408 ")" +
3409 "(.*)" );
3410
3411 /**
3412 * Attempts to determine whether user input is a URL or search
3413 * terms. Anything with a space is passed to search.
3414 *
3415 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3416 * "Http://" converts to "http://"
3417 *
3418 * @return Original or modified URL
3419 *
3420 */
3421 String smartUrlFilter(String url) {
3422
3423 String inUrl = url.trim();
3424 boolean hasSpace = inUrl.indexOf(' ') != -1;
3425
3426 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3427 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003428 // force scheme to lowercase
3429 String scheme = matcher.group(1);
3430 String lcScheme = scheme.toLowerCase();
3431 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003432 inUrl = lcScheme + matcher.group(2);
3433 }
3434 if (hasSpace) {
3435 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003436 }
3437 return inUrl;
3438 }
3439 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003440 // FIXME: Is this the correct place to add to searches?
3441 // what if someone else calls this function?
3442 int shortcut = parseUrlShortcut(inUrl);
3443 if (shortcut != SHORTCUT_INVALID) {
3444 Browser.addSearchUrl(mResolver, inUrl);
3445 String query = inUrl.substring(2);
3446 switch (shortcut) {
3447 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003448 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003449 case SHORTCUT_WIKIPEDIA_SEARCH:
3450 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3451 case SHORTCUT_DICTIONARY_SEARCH:
3452 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3453 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003454 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003455 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003456 }
3457 }
3458 } else {
3459 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
3460 return URLUtil.guessUrl(inUrl);
3461 }
3462 }
3463
3464 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003465 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003466 }
3467
Ben Murdochbff2d602009-07-01 20:19:05 +01003468 /* package */ void setShouldShowErrorConsole(boolean flag) {
3469 if (flag == mShouldShowErrorConsole) {
3470 // Nothing to do.
3471 return;
3472 }
3473
3474 mShouldShowErrorConsole = flag;
3475
Grace Kloba22ac16e2009-10-07 18:00:23 -07003476 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3477 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003478
3479 if (flag) {
3480 // Setting the show state of the console will cause it's the layout to be inflated.
3481 if (errorConsole.numberOfErrors() > 0) {
3482 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3483 } else {
3484 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3485 }
3486
3487 // Now we can add it to the main view.
3488 mErrorConsoleContainer.addView(errorConsole,
3489 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
3490 ViewGroup.LayoutParams.WRAP_CONTENT));
3491 } else {
3492 mErrorConsoleContainer.removeView(errorConsole);
3493 }
3494
3495 }
3496
Grace Kloba22ac16e2009-10-07 18:00:23 -07003497 boolean shouldShowErrorConsole() {
3498 return mShouldShowErrorConsole;
3499 }
3500
Grace Klobaeb6eef42009-09-15 17:56:32 -07003501 final static int LOCK_ICON_UNSECURE = 0;
3502 final static int LOCK_ICON_SECURE = 1;
3503 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003504
The Android Open Source Project0c908882009-03-03 19:32:16 -08003505 private BrowserSettings mSettings;
3506 private TabControl mTabControl;
3507 private ContentResolver mResolver;
3508 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003509 private View mCustomView;
3510 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003511 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003512
3513 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3514 // view, we should rewrite this.
3515 private int mCurrentMenuState = 0;
3516 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003517 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003518 private static final int EMPTY_MENU = -1;
3519 private Menu mMenu;
3520
3521 private FindDialog mFindDialog;
3522 // Used to prevent chording to result in firing two shortcuts immediately
3523 // one after another. Fixes bug 1211714.
3524 boolean mCanChord;
3525
3526 private boolean mInLoad;
3527 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003528 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003529
The Android Open Source Project0c908882009-03-03 19:32:16 -08003530 private boolean mActivityInPause = true;
3531
3532 private boolean mMenuIsDown;
3533
The Android Open Source Project0c908882009-03-03 19:32:16 -08003534 private static boolean mInTrace;
3535
3536 // Performance probe
3537 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3538 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3539 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3540 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3541 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3542 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3543 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3544 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3545 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3546 };
3547
3548 private long mStart;
3549 private long mProcessStart;
3550 private long mUserStart;
3551 private long mSystemStart;
3552 private long mIdleStart;
3553 private long mIrqStart;
3554
3555 private long mUiStart;
3556
3557 private Drawable mMixLockIcon;
3558 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003559
3560 /* hold a ref so we can auto-cancel if necessary */
3561 private AlertDialog mAlertDialog;
3562
3563 // Wait for credentials before loading google.com
3564 private ProgressDialog mCredsDlg;
3565
3566 // The up-to-date URL and title (these can be different from those stored
3567 // in WebView, since it takes some time for the information in WebView to
3568 // get updated)
3569 private String mUrl;
3570 private String mTitle;
3571
3572 // As PageInfo has different style for landscape / portrait, we have
3573 // to re-open it when configuration changed
3574 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003575 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003576 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3577 // dialog, we should not just dismiss it, but should get back to the
3578 // SSL-certificate-on-error dialog. This flag is used to store this state
3579 private Boolean mPageInfoFromShowSSLCertificateOnError;
3580
3581 // as SSLCertificateOnError has different style for landscape / portrait,
3582 // we have to re-open it when configuration changed
3583 private AlertDialog mSSLCertificateOnErrorDialog;
3584 private WebView mSSLCertificateOnErrorView;
3585 private SslErrorHandler mSSLCertificateOnErrorHandler;
3586 private SslError mSSLCertificateOnErrorError;
3587
3588 // as SSLCertificate has different style for landscape / portrait, we
3589 // have to re-open it when configuration changed
3590 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003591 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003592
3593 // as HttpAuthentication has different style for landscape / portrait, we
3594 // have to re-open it when configuration changed
3595 private AlertDialog mHttpAuthenticationDialog;
3596 private HttpAuthHandler mHttpAuthHandler;
3597
3598 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3599 new FrameLayout.LayoutParams(
3600 ViewGroup.LayoutParams.FILL_PARENT,
3601 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003602 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3603 new FrameLayout.LayoutParams(
3604 ViewGroup.LayoutParams.FILL_PARENT,
3605 ViewGroup.LayoutParams.FILL_PARENT,
3606 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003607 // Google search
3608 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003609 // Wikipedia search
3610 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3611 // Dictionary search
3612 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3613 // Google Mobile Local search
3614 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3615
3616 final static String QUERY_PLACE_HOLDER = "%s";
3617
3618 // "source" parameter for Google search through search key
3619 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3620 // "source" parameter for Google search through goto menu
3621 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3622 // "source" parameter for Google search through simplily type
3623 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3624 // "source" parameter for Google search suggested by the browser
3625 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3626 // "source" parameter for Google search from unknown source
3627 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3628
3629 private final static String LOGTAG = "browser";
3630
The Android Open Source Project0c908882009-03-03 19:32:16 -08003631 private String mLastEnteredUrl;
3632
3633 private PowerManager.WakeLock mWakeLock;
3634 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3635
3636 private Toast mStopToast;
3637
Leon Scroggins68579392009-09-15 15:31:54 -04003638 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003639
Ben Murdochbff2d602009-07-01 20:19:05 +01003640 private LinearLayout mErrorConsoleContainer = null;
3641 private boolean mShouldShowErrorConsole = false;
3642
The Android Open Source Project0c908882009-03-03 19:32:16 -08003643 // As the ids are dynamically created, we can't guarantee that they will
3644 // be in sequence, so this static array maps ids to a window number.
3645 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3646 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3647 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3648 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3649
3650 // monitor platform changes
3651 private IntentFilter mNetworkStateChangedFilter;
3652 private BroadcastReceiver mNetworkStateIntentReceiver;
3653
Grace Klobab4da0ad2009-05-14 14:45:40 -07003654 private BroadcastReceiver mPackageInstallationReceiver;
3655
The Android Open Source Project0c908882009-03-03 19:32:16 -08003656 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003657 final static int COMBO_PAGE = 1;
3658 final static int DOWNLOAD_PAGE = 2;
3659 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003660 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003661
Andrei Popescu540035d2009-09-18 18:59:20 +01003662 // the default <video> poster
3663 private Bitmap mDefaultVideoPoster;
3664 // the video progress view
3665 private View mVideoProgressView;
3666
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003667 /**
3668 * A UrlData class to abstract how the content will be set to WebView.
3669 * This base class uses loadUrl to show the content.
3670 */
3671 private static class UrlData {
3672 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07003673 byte[] mPostData;
3674
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003675 UrlData(String url) {
3676 this.mUrl = url;
3677 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003678
3679 void setPostData(byte[] postData) {
3680 mPostData = postData;
3681 }
3682
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003683 boolean isEmpty() {
3684 return mUrl == null || mUrl.length() == 0;
3685 }
3686
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003687 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07003688 if (mPostData != null) {
3689 webView.postUrl(mUrl, mPostData);
3690 } else {
3691 webView.loadUrl(mUrl);
3692 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003693 }
3694 };
3695
3696 /**
3697 * A subclass of UrlData class that can display inlined content using
3698 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3699 */
3700 private static class InlinedUrlData extends UrlData {
3701 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3702 super(failUrl);
3703 mInlined = inlined;
3704 mMimeType = mimeType;
3705 mEncoding = encoding;
3706 }
3707 String mMimeType;
3708 String mInlined;
3709 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003710 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003711 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01003712 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003713 }
3714
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003715 @Override
3716 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003717 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3718 }
3719 }
3720
Leon Scroggins1f005d32009-08-10 17:36:42 -04003721 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003722}