blob: a167b099dae0cfde8471eb91cfbb44a2ec539431 [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)) {
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700312 boolean noConnectivity = intent.getBooleanExtra(
313 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
314 onNetworkToggle(!noConnectivity);
Grace Klobaa34f6862009-07-31 16:28:17 -0700315 }
316 }
317 };
318
Grace Kloba615c6c92009-08-03 10:22:44 -0700319 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
320 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
321 filter.addDataScheme("package");
322 mPackageInstallationReceiver = new BroadcastReceiver() {
323 @Override
324 public void onReceive(Context context, Intent intent) {
325 final String action = intent.getAction();
326 final String packageName = intent.getData()
327 .getSchemeSpecificPart();
328 final boolean replacing = intent.getBooleanExtra(
329 Intent.EXTRA_REPLACING, false);
330 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
331 // if it is replacing, refreshPlugins() when adding
332 return;
333 }
334 PackageManager pm = BrowserActivity.this.getPackageManager();
335 PackageInfo pkgInfo = null;
336 try {
337 pkgInfo = pm.getPackageInfo(packageName,
338 PackageManager.GET_PERMISSIONS);
339 } catch (PackageManager.NameNotFoundException e) {
340 return;
341 }
342 if (pkgInfo != null) {
343 String permissions[] = pkgInfo.requestedPermissions;
344 if (permissions == null) {
345 return;
346 }
347 boolean permissionOk = false;
348 for (String permit : permissions) {
349 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
350 permissionOk = true;
351 break;
352 }
353 }
354 if (permissionOk) {
355 PluginManager.getInstance(BrowserActivity.this)
356 .refreshPlugins(
357 Intent.ACTION_PACKAGE_ADDED
358 .equals(action));
359 }
360 }
361 }
362 };
363 registerReceiver(mPackageInstallationReceiver, filter);
364
The Android Open Source Project0c908882009-03-03 19:32:16 -0800365 if (!mTabControl.restoreState(icicle)) {
366 // clear up the thumbnail directory if we can't restore the state as
367 // none of the files in the directory are referenced any more.
368 new ClearThumbnails().execute(
369 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700370 // there is no quit on Android. But if we can't restore the state,
371 // we can treat it as a new Browser, remove the old session cookies.
372 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800373 final Intent intent = getIntent();
374 final Bundle extra = intent.getExtras();
375 // Create an initial tab.
376 // If the intent is ACTION_VIEW and data is not null, the Browser is
377 // invoked to view the content by another application. In this case,
378 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700379 UrlData urlData = getUrlDataFromIntent(intent);
380
Grace Kloba22ac16e2009-10-07 18:00:23 -0700381 final Tab t = mTabControl.createNewTab(
The Android Open Source Project0c908882009-03-03 19:32:16 -0800382 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700383 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700384 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800385 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800386 attachTabToContentView(t);
387 WebView webView = t.getWebView();
388 if (extra != null) {
389 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
390 if (scale > 0 && scale <= 1000) {
391 webView.setInitialScale(scale);
392 }
393 }
394 // If we are not restoring from an icicle, then there is a high
395 // likely hood this is the first run. So, check to see if the
396 // homepage needs to be configured and copy any plugins from our
397 // asset directory to the data partition.
398 if ((extra == null || !extra.getBoolean("testing"))
399 && !mSettings.isLoginInitialized()) {
400 setupHomePage();
401 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800402
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700403 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400404 if (mSettings.isLoginInitialized()) {
405 webView.loadUrl(mSettings.getHomePage());
406 } else {
407 waitForCredentials();
408 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800409 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700410 if (extra != null) {
411 urlData.setPostData(extra
412 .getByteArray(Browser.EXTRA_POST_DATA));
413 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700414 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800415 }
416 } else {
417 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400418 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800419 attachTabToContentView(mTabControl.getCurrentTab());
420 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700421
Feng Qianb3c02da2009-06-29 15:58:08 -0700422 // Read JavaScript flags if it exists.
423 String jsFlags = mSettings.getJsFlags();
424 if (jsFlags.trim().length() != 0) {
425 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
426 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800427 }
428
429 @Override
430 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700431 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800432 // When a tab is closed on exit, the current tab index is set to -1.
433 // Reset before proceed as Browser requires the current tab to be set.
434 if (current == null) {
435 // Try to reset the tab in case the index was incorrect.
436 current = mTabControl.getTab(0);
437 if (current == null) {
438 // No tabs at all so just ignore this intent.
439 return;
440 }
441 mTabControl.setCurrentTab(current);
442 attachTabToContentView(current);
443 resetTitleAndIcon(current.getWebView());
444 }
445 final String action = intent.getAction();
446 final int flags = intent.getFlags();
447 if (Intent.ACTION_MAIN.equals(action) ||
448 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
449 // just resume the browser
450 return;
451 }
452 if (Intent.ACTION_VIEW.equals(action)
453 || Intent.ACTION_SEARCH.equals(action)
454 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
455 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100456 // If this was a search request (e.g. search query directly typed into the address bar),
457 // pass it on to the default web search provider.
458 if (handleWebSearchIntent(intent)) {
459 return;
460 }
461
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700462 UrlData urlData = getUrlDataFromIntent(intent);
463 if (urlData.isEmpty()) {
464 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800465 }
Grace Kloba81678d92009-06-30 07:09:56 -0700466 urlData.setPostData(intent
467 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700468
Grace Klobacc634032009-07-28 15:58:19 -0700469 final String appId = intent
470 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
471 if (Intent.ACTION_VIEW.equals(action)
472 && !getPackageName().equals(appId)
473 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700474 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700475 if (appTab != null) {
476 Log.i(LOGTAG, "Reusing tab for " + appId);
477 // Dismiss the subwindow if applicable.
478 dismissSubWindow(appTab);
479 // Since we might kill the WebView, remove it from the
480 // content view first.
481 removeTabFromContentView(appTab);
482 // Recreate the main WebView after destroying the old one.
483 // If the WebView has the same original url and is on that
484 // page, it can be reused.
485 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700486 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100487
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700488 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400489 switchToTab(mTabControl.getTabIndex(appTab));
490 if (needsLoad) {
491 urlData.loadIn(appTab.getWebView());
492 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700493 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400494 // If the tab was the current tab, we have to attach
495 // it to the view system again.
496 attachTabToContentView(appTab);
497 if (needsLoad) {
498 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700499 }
500 }
501 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400502 } else {
503 // No matching application tab, try to find a regular tab
504 // with a matching url.
505 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400506 if (appTab != null) {
507 if (current != appTab) {
508 switchToTab(mTabControl.getTabIndex(appTab));
509 }
510 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400511 } else {
512 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
513 // will be opened in a new tab unless we have reached
514 // MAX_TABS. Then the url will be opened in the current
515 // tab. If a new tab is created, it will have "true" for
516 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400517 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400518 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700519 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800520 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700521 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800522 mSettings.toggleDebugSettings();
523 return;
524 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400525 // Get rid of the subwindow if it exists
526 dismissSubWindow(current);
527 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800528 }
529 }
530 }
531
Satish Sampath565505b2009-05-29 15:37:27 +0100532 private int parseUrlShortcut(String url) {
533 if (url == null) return SHORTCUT_INVALID;
534
535 // FIXME: quick search, need to be customized by setting
536 if (url.length() > 2 && url.charAt(1) == ' ') {
537 switch (url.charAt(0)) {
538 case 'g': return SHORTCUT_GOOGLE_SEARCH;
539 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
540 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
541 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
542 }
543 }
544 return SHORTCUT_INVALID;
545 }
546
547 /**
548 * Launches the default web search activity with the query parameters if the given intent's data
549 * are identified as plain search terms and not URLs/shortcuts.
550 * @return true if the intent was handled and web search activity was launched, false if not.
551 */
552 private boolean handleWebSearchIntent(Intent intent) {
553 if (intent == null) return false;
554
555 String url = null;
556 final String action = intent.getAction();
557 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700558 Uri data = intent.getData();
559 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100560 } else if (Intent.ACTION_SEARCH.equals(action)
561 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
562 || Intent.ACTION_WEB_SEARCH.equals(action)) {
563 url = intent.getStringExtra(SearchManager.QUERY);
564 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100565 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
566 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100567 }
568
569 /**
570 * Launches the default web search activity with the query parameters if the given url string
571 * was identified as plain search terms and not URL/shortcut.
572 * @return true if the request was handled and web search activity was launched, false if not.
573 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100574 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100575 if (inUrl == null) return false;
576
577 // In general, we shouldn't modify URL from Intent.
578 // But currently, we get the user-typed URL from search box as well.
579 String url = fixUrl(inUrl).trim();
580
581 // URLs and site specific search shortcuts are handled by the regular flow of control, so
582 // return early.
583 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100584 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100585 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
586 return false;
587 }
588
589 Browser.updateVisitedHistory(mResolver, url, false);
590 Browser.addSearchUrl(mResolver, url);
591
592 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
593 intent.addCategory(Intent.CATEGORY_DEFAULT);
594 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100595 if (appData != null) {
596 intent.putExtra(SearchManager.APP_DATA, appData);
597 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100598 if (extraData != null) {
599 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
600 }
Grace Klobacc634032009-07-28 15:58:19 -0700601 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100602 startActivity(intent);
603
604 return true;
605 }
606
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700607 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800608 String url = null;
609 if (intent != null) {
610 final String action = intent.getAction();
611 if (Intent.ACTION_VIEW.equals(action)) {
612 url = smartUrlFilter(intent.getData());
613 if (url != null && url.startsWith("content:")) {
614 /* Append mimetype so webview knows how to display */
615 String mimeType = intent.resolveType(getContentResolver());
616 if (mimeType != null) {
617 url += "?" + mimeType;
618 }
619 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700620 if ("inline:".equals(url)) {
621 return new InlinedUrlData(
622 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
623 intent.getType(),
624 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
625 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
626 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800627 } else if (Intent.ACTION_SEARCH.equals(action)
628 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
629 || Intent.ACTION_WEB_SEARCH.equals(action)) {
630 url = intent.getStringExtra(SearchManager.QUERY);
631 if (url != null) {
632 mLastEnteredUrl = url;
633 // Don't add Urls, just search terms.
634 // Urls will get added when the page is loaded.
635 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
636 Browser.updateVisitedHistory(mResolver, url, false);
637 }
638 // In general, we shouldn't modify URL from Intent.
639 // But currently, we get the user-typed URL from search box as well.
640 url = fixUrl(url);
641 url = smartUrlFilter(url);
642 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
643 if (url.contains(searchSource)) {
644 String source = null;
645 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
646 if (appData != null) {
647 source = appData.getString(SearchManager.SOURCE);
648 }
649 if (TextUtils.isEmpty(source)) {
650 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
651 }
652 url = url.replace(searchSource, "&source=android-"+source+"&");
653 }
654 }
655 }
656 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700657 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800658 }
659
660 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400661 // FIXME: Converting the url to lower case
662 // duplicates functionality in smartUrlFilter().
663 // However, changing all current callers of fixUrl to
664 // call smartUrlFilter in addition may have unwanted
665 // consequences, and is deferred for now.
666 int colon = inUrl.indexOf(':');
667 boolean allLower = true;
668 for (int index = 0; index < colon; index++) {
669 char ch = inUrl.charAt(index);
670 if (!Character.isLetter(ch)) {
671 break;
672 }
673 allLower &= Character.isLowerCase(ch);
674 if (index == colon - 1 && !allLower) {
675 inUrl = inUrl.substring(0, colon).toLowerCase()
676 + inUrl.substring(colon);
677 }
678 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800679 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
680 return inUrl;
681 if (inUrl.startsWith("http:") ||
682 inUrl.startsWith("https:")) {
683 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
684 inUrl = inUrl.replaceFirst("/", "//");
685 } else inUrl = inUrl.replaceFirst(":", "://");
686 }
687 return inUrl;
688 }
689
Grace Kloba22ac16e2009-10-07 18:00:23 -0700690 @Override
691 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800692 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700693 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800694 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
695 }
696
697 if (!mActivityInPause) {
698 Log.e(LOGTAG, "BrowserActivity is already resumed.");
699 return;
700 }
701
Mike Reed7bfa63b2009-05-28 11:08:32 -0400702 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800703 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400704 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800705
706 if (mWakeLock.isHeld()) {
707 mHandler.removeMessages(RELEASE_WAKELOCK);
708 mWakeLock.release();
709 }
710
711 if (mCredsDlg != null) {
712 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
713 // In case credential request never comes back
714 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
715 }
716 }
717
718 registerReceiver(mNetworkStateIntentReceiver,
719 mNetworkStateChangedFilter);
720 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800721 }
722
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400723 /**
724 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400725 * would change its appearance, use a different TitleBar to show overlayed
726 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400727 */
728 private TitleBar mFakeTitleBar;
729
730 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400731 * Holder for the fake title bar. It will have a foreground shadow, as well
732 * as a white background, so the fake title bar looks like the real one.
733 */
734 private ViewGroup mFakeTitleBarHolder;
735
736 /**
737 * Layout parameters for the fake title bar within mFakeTitleBarHolder
738 */
739 private FrameLayout.LayoutParams mFakeTitleBarParams
740 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400741 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400742 ViewGroup.LayoutParams.WRAP_CONTENT);
743 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400744 * Keeps track of whether the options menu is open. This is important in
745 * determining whether to show or hide the title bar overlay.
746 */
747 private boolean mOptionsMenuOpen;
748
749 /**
750 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
751 * of whether the configuration has changed. The first onMenuOpened call
752 * after a configuration change is simply a reopening of the same menu
753 * (i.e. mIconView did not change).
754 */
755 private boolean mConfigChanged;
756
757 /**
758 * Whether or not the options menu is in its smaller, icon menu form. When
759 * true, we want the title bar overlay to be up. When false, we do not.
760 * Only meaningful if mOptionsMenuOpen is true.
761 */
762 private boolean mIconView;
763
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400764 @Override
765 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400766 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
767 if (mOptionsMenuOpen) {
768 if (mConfigChanged) {
769 // We do not need to make any changes to the state of the
770 // title bar, since the only thing that happened was a
771 // change in orientation
772 mConfigChanged = false;
773 } else {
774 if (mIconView) {
775 // Switching the menu to expanded view, so hide the
776 // title bar.
777 hideFakeTitleBar();
778 mIconView = false;
779 } else {
780 // Switching the menu back to icon view, so show the
781 // title bar once again.
782 showFakeTitleBar();
783 mIconView = true;
784 }
785 }
786 } else {
787 // The options menu is closed, so open it, and show the title
788 showFakeTitleBar();
789 mOptionsMenuOpen = true;
790 mConfigChanged = false;
791 mIconView = true;
792 }
793 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400794 return true;
795 }
796
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400797 /**
798 * Special class used exclusively for the shadow drawn underneath the fake
799 * title bar. The shadow does not need to be drawn if the WebView
800 * underneath is scrolled to the top, because it will draw directly on top
801 * of the embedded shadow.
802 */
803 private static class Shadow extends View {
804 private WebView mWebView;
805
806 public Shadow(Context context, AttributeSet attrs) {
807 super(context, attrs);
808 }
809
810 public void setWebView(WebView view) {
811 mWebView = view;
812 }
813
814 @Override
815 public void draw(Canvas canvas) {
816 // In general onDraw is the method to override, but we care about
817 // whether or not the background gets drawn, which happens in draw()
818 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
819 super.draw(canvas);
820 }
821 // Need to invalidate so that if the scroll position changes, we
822 // still draw as appropriate.
823 invalidate();
824 }
825 }
826
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400827 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400828 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400829 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400830 && !mActivityInPause && decor != null
831 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400832 Rect visRect = new Rect();
833 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
834 if (LOGD_ENABLED) {
835 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
836 }
837 return;
838 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400839
840 WindowManager manager
841 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
842
843 // Add the title bar to the window manager so it can receive touches
844 // while the menu is up
845 WindowManager.LayoutParams params
846 = new WindowManager.LayoutParams(
847 ViewGroup.LayoutParams.FILL_PARENT,
848 ViewGroup.LayoutParams.WRAP_CONTENT,
849 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
850 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400851 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400852 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400853 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400854 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400855 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400856 // XXX : Without providing an offset, the fake title bar will be
857 // placed underneath the status bar. Use the global visible rect
858 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400859 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400860 // Add a holder for the title bar. It also holds a shadow to show
861 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400862 if (mFakeTitleBarHolder == null) {
863 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
864 .inflate(R.layout.title_bar_bg, null);
865 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400866 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
867 R.id.shadow);
868 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400869 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400870 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400871 }
872 }
873
874 @Override
875 public void onOptionsMenuClosed(Menu menu) {
876 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400877 if (!mInLoad) {
878 hideFakeTitleBar();
879 } else if (!mIconView) {
880 // The page is currently loading, and we are in expanded mode, so
881 // we were not showing the menu. Show it once again. It will be
882 // removed when the page finishes.
883 showFakeTitleBar();
884 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400885 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700886
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400887 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400888 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400889 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
890 mFakeTitleBarHolder.getLayoutParams();
891 WebView mainView = mTabControl.getCurrentWebView();
892 // Although we decided whether or not to animate based on the current
893 // scroll position, the scroll position may have changed since the
894 // fake title bar was displayed. Make sure it has the appropriate
895 // animation/lack thereof before removing.
896 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400897 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400898 WindowManager manager
899 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400900 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400901 mFakeTitleBarHolder.removeView(mFakeTitleBar);
902 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400903 }
904
The Android Open Source Project0c908882009-03-03 19:32:16 -0800905 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400906 * Special method for the fake title bar to call when displaying its context
907 * menu, since it is in its own Window, and its parent does not show a
908 * context menu.
909 */
910 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400911 if (null == mTitleBar.getParent()) {
912 return;
913 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400914 openContextMenu(mTitleBar);
915 }
916
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400917 @Override
918 public void onContextMenuClosed(Menu menu) {
919 super.onContextMenuClosed(menu);
920 if (mInLoad) {
921 showFakeTitleBar();
922 }
923 }
924
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400925 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800926 * onSaveInstanceState(Bundle map)
927 * onSaveInstanceState is called right before onStop(). The map contains
928 * the saved state.
929 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700930 @Override
931 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700932 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800933 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
934 }
935 // the default implementation requires each view to have an id. As the
936 // browser handles the state itself and it doesn't use id for the views,
937 // don't call the default implementation. Otherwise it will trigger the
938 // warning like this, "couldn't save which view has focus because the
939 // focused view XXX has no id".
940
941 // Save all the tabs
942 mTabControl.saveState(outState);
943 }
944
Grace Kloba22ac16e2009-10-07 18:00:23 -0700945 @Override
946 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800947 super.onPause();
948
949 if (mActivityInPause) {
950 Log.e(LOGTAG, "BrowserActivity is already paused.");
951 return;
952 }
953
Mike Reed7bfa63b2009-05-28 11:08:32 -0400954 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800955 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400956 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800957 mWakeLock.acquire();
958 mHandler.sendMessageDelayed(mHandler
959 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
960 }
961
962 // Clear the credentials toast if it is up
963 if (mCredsDlg != null && mCredsDlg.isShowing()) {
964 mCredsDlg.dismiss();
965 }
966 mCredsDlg = null;
967
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400968 // FIXME: This removes the active tabs page and resets the menu to
969 // MAIN_MENU. A better solution might be to do this work in onNewIntent
970 // but then we would need to save it in onSaveInstanceState and restore
971 // it in onCreate/onRestoreInstanceState
972 if (mActiveTabsPage != null) {
973 removeActiveTabPage(true);
974 }
975
The Android Open Source Project0c908882009-03-03 19:32:16 -0800976 cancelStopToast();
977
978 // unregister network state listener
979 unregisterReceiver(mNetworkStateIntentReceiver);
980 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800981 }
982
Grace Kloba22ac16e2009-10-07 18:00:23 -0700983 @Override
984 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700985 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800986 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
987 }
988 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700989
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400990 if (mUploadMessage != null) {
991 mUploadMessage.onReceiveValue(null);
992 mUploadMessage = null;
993 }
994
Grace Kloba0923d692009-09-23 21:37:25 -0700995 if (mTabControl == null) return;
996
Grace Kloba1fc98a32009-10-21 13:23:08 -0700997 // Remove the fake title bar if it is there
998 hideFakeTitleBar();
999
The Android Open Source Project0c908882009-03-03 19:32:16 -08001000 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001001 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001002 if (t != null) {
1003 dismissSubWindow(t);
1004 removeTabFromContentView(t);
1005 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001006 // Destroy all the tabs
1007 mTabControl.destroy();
1008 WebIconDatabase.getInstance().close();
1009 if (mGlsConnection != null) {
1010 unbindService(mGlsConnection);
1011 mGlsConnection = null;
1012 }
1013
Grace Klobab4da0ad2009-05-14 14:45:40 -07001014 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001015 }
1016
1017 @Override
1018 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001019 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001020 super.onConfigurationChanged(newConfig);
1021
1022 if (mPageInfoDialog != null) {
1023 mPageInfoDialog.dismiss();
1024 showPageInfo(
1025 mPageInfoView,
1026 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1027 }
1028 if (mSSLCertificateDialog != null) {
1029 mSSLCertificateDialog.dismiss();
1030 showSSLCertificate(
1031 mSSLCertificateView);
1032 }
1033 if (mSSLCertificateOnErrorDialog != null) {
1034 mSSLCertificateOnErrorDialog.dismiss();
1035 showSSLCertificateOnError(
1036 mSSLCertificateOnErrorView,
1037 mSSLCertificateOnErrorHandler,
1038 mSSLCertificateOnErrorError);
1039 }
1040 if (mHttpAuthenticationDialog != null) {
1041 String title = ((TextView) mHttpAuthenticationDialog
1042 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1043 .toString();
1044 String name = ((TextView) mHttpAuthenticationDialog
1045 .findViewById(R.id.username_edit)).getText().toString();
1046 String password = ((TextView) mHttpAuthenticationDialog
1047 .findViewById(R.id.password_edit)).getText().toString();
1048 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1049 .getId();
1050 mHttpAuthenticationDialog.dismiss();
1051 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1052 name, password, focusId);
1053 }
1054 if (mFindDialog != null && mFindDialog.isShowing()) {
1055 mFindDialog.onConfigurationChanged(newConfig);
1056 }
1057 }
1058
Grace Kloba22ac16e2009-10-07 18:00:23 -07001059 @Override
1060 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001061 super.onLowMemory();
1062 mTabControl.freeMemory();
1063 }
1064
Mike Reed7bfa63b2009-05-28 11:08:32 -04001065 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001066 Tab tab = mTabControl.getCurrentTab();
1067 boolean inLoad = tab.inLoad();
1068 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001069 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001070 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001071 if (w != null) {
1072 w.resumeTimers();
1073 }
1074 return true;
1075 } else {
1076 return false;
1077 }
1078 }
1079
Mike Reed7bfa63b2009-05-28 11:08:32 -04001080 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001081 Tab tab = mTabControl.getCurrentTab();
1082 boolean inLoad = tab.inLoad();
1083 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001084 CookieSyncManager.getInstance().stopSync();
1085 WebView w = mTabControl.getCurrentWebView();
1086 if (w != null) {
1087 w.pauseTimers();
1088 }
1089 return true;
1090 } else {
1091 return false;
1092 }
1093 }
1094
Leon Scroggins1f005d32009-08-10 17:36:42 -04001095 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001096 /*
1097 * This function is called when we are launching for the first time. We
1098 * are waiting for the login credentials before loading Google home
1099 * pages. This way the user will be logged in straight away.
1100 */
1101 private void waitForCredentials() {
1102 // Show a toast
1103 mCredsDlg = new ProgressDialog(this);
1104 mCredsDlg.setIndeterminate(true);
1105 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1106 // If the user cancels the operation, then cancel the Google
1107 // Credentials request.
1108 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1109 mCredsDlg.show();
1110
1111 // We set a timeout for the retrieval of credentials in onResume()
1112 // as that is when we have freed up some CPU time to get
1113 // the login credentials.
1114 }
1115
1116 /*
1117 * If we have received the credentials or we have timed out and we are
1118 * showing the credentials dialog, then it is time to move on.
1119 */
1120 private void resumeAfterCredentials() {
1121 if (mCredsDlg == null) {
1122 return;
1123 }
1124
1125 // Clear the toast
1126 if (mCredsDlg.isShowing()) {
1127 mCredsDlg.dismiss();
1128 }
1129 mCredsDlg = null;
1130
1131 // Clear any pending timeout
1132 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1133
1134 // Load the page
1135 WebView w = mTabControl.getCurrentWebView();
1136 if (w != null) {
1137 w.loadUrl(mSettings.getHomePage());
1138 }
1139
1140 // Update the settings, need to do this last as it can take a moment
1141 // to persist the settings. In the mean time we could be loading
1142 // content.
1143 mSettings.setLoginInitialized(this);
1144 }
1145
1146 // Open the icon database and retain all the icons for visited sites.
1147 private void retainIconsOnStartup() {
1148 final WebIconDatabase db = WebIconDatabase.getInstance();
1149 db.open(getDir("icons", 0).getPath());
1150 try {
1151 Cursor c = Browser.getAllBookmarks(mResolver);
1152 if (!c.moveToFirst()) {
1153 c.deactivate();
1154 return;
1155 }
1156 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1157 do {
1158 String url = c.getString(urlIndex);
1159 db.retainIconForPageUrl(url);
1160 } while (c.moveToNext());
1161 c.deactivate();
1162 } catch (IllegalStateException e) {
1163 Log.e(LOGTAG, "retainIconsOnStartup", e);
1164 }
1165 }
1166
1167 // Helper method for getting the top window.
1168 WebView getTopWindow() {
1169 return mTabControl.getCurrentTopWebView();
1170 }
1171
Grace Kloba22ac16e2009-10-07 18:00:23 -07001172 TabControl getTabControl() {
1173 return mTabControl;
1174 }
1175
The Android Open Source Project0c908882009-03-03 19:32:16 -08001176 @Override
1177 public boolean onCreateOptionsMenu(Menu menu) {
1178 super.onCreateOptionsMenu(menu);
1179
1180 MenuInflater inflater = getMenuInflater();
1181 inflater.inflate(R.menu.browser, menu);
1182 mMenu = menu;
1183 updateInLoadMenuItems();
1184 return true;
1185 }
1186
1187 /**
1188 * As the menu can be open when loading state changes
1189 * we must manually update the state of the stop/reload menu
1190 * item
1191 */
1192 private void updateInLoadMenuItems() {
1193 if (mMenu == null) {
1194 return;
1195 }
1196 MenuItem src = mInLoad ?
1197 mMenu.findItem(R.id.stop_menu_id):
1198 mMenu.findItem(R.id.reload_menu_id);
1199 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1200 dest.setIcon(src.getIcon());
1201 dest.setTitle(src.getTitle());
1202 }
1203
1204 @Override
1205 public boolean onContextItemSelected(MenuItem item) {
1206 // chording is not an issue with context menus, but we use the same
1207 // options selector, so set mCanChord to true so we can access them.
1208 mCanChord = true;
1209 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001210 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001211 // For the context menu from the title bar
1212 case R.id.title_bar_share_page_url:
1213 case R.id.title_bar_copy_page_url:
1214 WebView mainView = mTabControl.getCurrentWebView();
1215 if (null == mainView) {
1216 return false;
1217 }
1218 if (id == R.id.title_bar_share_page_url) {
1219 Browser.sendString(this, mainView.getUrl());
1220 } else {
1221 copy(mainView.getUrl());
1222 }
1223 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001224 // -- Browser context menu
1225 case R.id.open_context_menu_id:
1226 case R.id.open_newtab_context_menu_id:
1227 case R.id.bookmark_context_menu_id:
1228 case R.id.save_link_context_menu_id:
1229 case R.id.share_link_context_menu_id:
1230 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001231 final WebView webView = getTopWindow();
1232 if (null == webView) {
1233 return false;
1234 }
1235 final HashMap hrefMap = new HashMap();
1236 hrefMap.put("webview", webView);
1237 final Message msg = mHandler.obtainMessage(
1238 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001239 webView.requestFocusNodeHref(msg);
1240 break;
1241
1242 default:
1243 // For other context menus
1244 return onOptionsItemSelected(item);
1245 }
1246 mCanChord = false;
1247 return true;
1248 }
1249
1250 private Bundle createGoogleSearchSourceBundle(String source) {
1251 Bundle bundle = new Bundle();
1252 bundle.putString(SearchManager.SOURCE, source);
1253 return bundle;
1254 }
1255
1256 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001257 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001258 */
1259 @Override
1260 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001261 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001262 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001263 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001264 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001265 return true;
1266 }
1267
1268 @Override
1269 public void startSearch(String initialQuery, boolean selectInitialQuery,
1270 Bundle appSearchData, boolean globalSearch) {
1271 if (appSearchData == null) {
1272 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1273 }
1274 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1275 }
1276
Leon Scroggins1f005d32009-08-10 17:36:42 -04001277 /**
1278 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1279 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001280 * @param index Index of the tab to change to, as defined by
1281 * mTabControl.getTabIndex(Tab t).
1282 * @return boolean True if we successfully switched to a different tab. If
1283 * the indexth tab is null, or if that tab is the same as
1284 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001285 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001286 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001287 Tab tab = mTabControl.getTab(index);
1288 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001289 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001290 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001291 }
1292 if (currentTab != null) {
1293 // currentTab may be null if it was just removed. In that case,
1294 // we do not need to remove it
1295 removeTabFromContentView(currentTab);
1296 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001297 mTabControl.setCurrentTab(tab);
1298 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001299 resetTitleIconAndProgress();
1300 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001301 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001302 }
1303
Grace Kloba22ac16e2009-10-07 18:00:23 -07001304 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001305 return openTabAndShow(mSettings.getHomePage(), false, null);
1306 }
1307
Leon Scroggins1f005d32009-08-10 17:36:42 -04001308 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001309 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001310 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001311 // This is the last tab. Open a new one, with the home
1312 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001313 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001314 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001315 return;
1316 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001317 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001318 int indexToShow = -1;
1319 if (parent != null) {
1320 indexToShow = mTabControl.getTabIndex(parent);
1321 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001322 final int currentIndex = mTabControl.getCurrentIndex();
1323 // Try to move to the tab to the right
1324 indexToShow = currentIndex + 1;
1325 if (indexToShow > mTabControl.getTabCount() - 1) {
1326 // Try to move to the tab to the left
1327 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001328 }
1329 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001330 if (switchToTab(indexToShow)) {
1331 // Close window
1332 closeTab(current);
1333 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001334 }
1335
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001336 private ActiveTabsPage mActiveTabsPage;
1337
1338 /**
1339 * Remove the active tabs page.
1340 * @param needToAttach If true, the active tabs page did not attach a tab
1341 * to the content view, so we need to do that here.
1342 */
1343 /* package */ void removeActiveTabPage(boolean needToAttach) {
1344 mContentView.removeView(mActiveTabsPage);
1345 mActiveTabsPage = null;
1346 mMenuState = R.id.MAIN_MENU;
1347 if (needToAttach) {
1348 attachTabToContentView(mTabControl.getCurrentTab());
1349 }
1350 getTopWindow().requestFocus();
1351 }
1352
The Android Open Source Project0c908882009-03-03 19:32:16 -08001353 @Override
1354 public boolean onOptionsItemSelected(MenuItem item) {
1355 if (!mCanChord) {
1356 // The user has already fired a shortcut with this hold down of the
1357 // menu key.
1358 return false;
1359 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001360 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001361 return false;
1362 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001363 if (mMenuIsDown) {
1364 // The shortcut action consumes the MENU. Even if it is still down,
1365 // it won't trigger the next shortcut action. In the case of the
1366 // shortcut action triggering a new activity, like Bookmarks, we
1367 // won't get onKeyUp for MENU. So it is important to reset it here.
1368 mMenuIsDown = false;
1369 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001370 switch (item.getItemId()) {
1371 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001372 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001373 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001374 break;
1375
Leon Scroggins64b80f32009-08-07 12:03:34 -04001376 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001377 onSearchRequested();
1378 break;
1379
1380 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001381 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001382 break;
1383
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001384 case R.id.active_tabs_menu_id:
1385 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1386 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001387 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001388 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1389 mActiveTabsPage.requestFocus();
1390 mMenuState = EMPTY_MENU;
1391 break;
1392
Leon Scroggins1f005d32009-08-10 17:36:42 -04001393 case R.id.add_bookmark_menu_id:
1394 Intent i = new Intent(BrowserActivity.this,
1395 AddBookmarkPage.class);
1396 WebView w = getTopWindow();
1397 i.putExtra("url", w.getUrl());
1398 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001399 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001400 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001401 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001402 break;
1403
1404 case R.id.stop_reload_menu_id:
1405 if (mInLoad) {
1406 stopLoading();
1407 } else {
1408 getTopWindow().reload();
1409 }
1410 break;
1411
1412 case R.id.back_menu_id:
1413 getTopWindow().goBack();
1414 break;
1415
1416 case R.id.forward_menu_id:
1417 getTopWindow().goForward();
1418 break;
1419
1420 case R.id.close_menu_id:
1421 // Close the subwindow if it exists.
1422 if (mTabControl.getCurrentSubWindow() != null) {
1423 dismissSubWindow(mTabControl.getCurrentTab());
1424 break;
1425 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001426 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001427 break;
1428
1429 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001430 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001431 if (current != null) {
1432 dismissSubWindow(current);
1433 current.getWebView().loadUrl(mSettings.getHomePage());
1434 }
1435 break;
1436
1437 case R.id.preferences_menu_id:
1438 Intent intent = new Intent(this,
1439 BrowserPreferencesPage.class);
1440 startActivityForResult(intent, PREFERENCES_PAGE);
1441 break;
1442
1443 case R.id.find_menu_id:
1444 if (null == mFindDialog) {
1445 mFindDialog = new FindDialog(this);
1446 }
1447 mFindDialog.setWebView(getTopWindow());
1448 mFindDialog.show();
1449 mMenuState = EMPTY_MENU;
1450 break;
1451
1452 case R.id.select_text_id:
1453 getTopWindow().emulateShiftHeld();
1454 break;
1455 case R.id.page_info_menu_id:
1456 showPageInfo(mTabControl.getCurrentTab(), false);
1457 break;
1458
1459 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001460 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001461 break;
1462
1463 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001464 Browser.sendString(this, getTopWindow().getUrl(),
1465 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001466 break;
1467
1468 case R.id.dump_nav_menu_id:
1469 getTopWindow().debugDump();
1470 break;
1471
1472 case R.id.zoom_in_menu_id:
1473 getTopWindow().zoomIn();
1474 break;
1475
1476 case R.id.zoom_out_menu_id:
1477 getTopWindow().zoomOut();
1478 break;
1479
1480 case R.id.view_downloads_menu_id:
1481 viewDownloads(null);
1482 break;
1483
The Android Open Source Project0c908882009-03-03 19:32:16 -08001484 case R.id.window_one_menu_id:
1485 case R.id.window_two_menu_id:
1486 case R.id.window_three_menu_id:
1487 case R.id.window_four_menu_id:
1488 case R.id.window_five_menu_id:
1489 case R.id.window_six_menu_id:
1490 case R.id.window_seven_menu_id:
1491 case R.id.window_eight_menu_id:
1492 {
1493 int menuid = item.getItemId();
1494 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1495 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001496 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001497 if (desiredTab != null &&
1498 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001499 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001500 }
1501 break;
1502 }
1503 }
1504 }
1505 break;
1506
1507 default:
1508 if (!super.onOptionsItemSelected(item)) {
1509 return false;
1510 }
1511 // Otherwise fall through.
1512 }
1513 mCanChord = false;
1514 return true;
1515 }
1516
1517 public void closeFind() {
1518 mMenuState = R.id.MAIN_MENU;
1519 }
1520
Grace Kloba22ac16e2009-10-07 18:00:23 -07001521 @Override
1522 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001523 // This happens when the user begins to hold down the menu key, so
1524 // allow them to chord to get a shortcut.
1525 mCanChord = true;
1526 // Note: setVisible will decide whether an item is visible; while
1527 // setEnabled() will decide whether an item is enabled, which also means
1528 // whether the matching shortcut key will function.
1529 super.onPrepareOptionsMenu(menu);
1530 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001531 case EMPTY_MENU:
1532 if (mCurrentMenuState != mMenuState) {
1533 menu.setGroupVisible(R.id.MAIN_MENU, false);
1534 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1535 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001536 }
1537 break;
1538 default:
1539 if (mCurrentMenuState != mMenuState) {
1540 menu.setGroupVisible(R.id.MAIN_MENU, true);
1541 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1542 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001543 }
1544 final WebView w = getTopWindow();
1545 boolean canGoBack = false;
1546 boolean canGoForward = false;
1547 boolean isHome = false;
1548 if (w != null) {
1549 canGoBack = w.canGoBack();
1550 canGoForward = w.canGoForward();
1551 isHome = mSettings.getHomePage().equals(w.getUrl());
1552 }
1553 final MenuItem back = menu.findItem(R.id.back_menu_id);
1554 back.setEnabled(canGoBack);
1555
1556 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1557 home.setEnabled(!isHome);
1558
1559 menu.findItem(R.id.forward_menu_id)
1560 .setEnabled(canGoForward);
1561
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001562 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001563 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001564
The Android Open Source Project0c908882009-03-03 19:32:16 -08001565 // decide whether to show the share link option
1566 PackageManager pm = getPackageManager();
1567 Intent send = new Intent(Intent.ACTION_SEND);
1568 send.setType("text/plain");
1569 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1570 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1571
The Android Open Source Project0c908882009-03-03 19:32:16 -08001572 boolean isNavDump = mSettings.isNavDump();
1573 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1574 nav.setVisible(isNavDump);
1575 nav.setEnabled(isNavDump);
1576 break;
1577 }
1578 mCurrentMenuState = mMenuState;
1579 return true;
1580 }
1581
1582 @Override
1583 public void onCreateContextMenu(ContextMenu menu, View v,
1584 ContextMenuInfo menuInfo) {
1585 WebView webview = (WebView) v;
1586 WebView.HitTestResult result = webview.getHitTestResult();
1587 if (result == null) {
1588 return;
1589 }
1590
1591 int type = result.getType();
1592 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1593 Log.w(LOGTAG,
1594 "We should not show context menu when nothing is touched");
1595 return;
1596 }
1597 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1598 // let TextView handles context menu
1599 return;
1600 }
1601
1602 // Note, http://b/issue?id=1106666 is requesting that
1603 // an inflated menu can be used again. This is not available
1604 // yet, so inflate each time (yuk!)
1605 MenuInflater inflater = getMenuInflater();
1606 inflater.inflate(R.menu.browsercontext, menu);
1607
1608 // Show the correct menu group
1609 String extra = result.getExtra();
1610 menu.setGroupVisible(R.id.PHONE_MENU,
1611 type == WebView.HitTestResult.PHONE_TYPE);
1612 menu.setGroupVisible(R.id.EMAIL_MENU,
1613 type == WebView.HitTestResult.EMAIL_TYPE);
1614 menu.setGroupVisible(R.id.GEO_MENU,
1615 type == WebView.HitTestResult.GEO_TYPE);
1616 menu.setGroupVisible(R.id.IMAGE_MENU,
1617 type == WebView.HitTestResult.IMAGE_TYPE
1618 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1619 menu.setGroupVisible(R.id.ANCHOR_MENU,
1620 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1621 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1622
1623 // Setup custom handling depending on the type
1624 switch (type) {
1625 case WebView.HitTestResult.PHONE_TYPE:
1626 menu.setHeaderTitle(Uri.decode(extra));
1627 menu.findItem(R.id.dial_context_menu_id).setIntent(
1628 new Intent(Intent.ACTION_VIEW, Uri
1629 .parse(WebView.SCHEME_TEL + extra)));
1630 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1631 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001632 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001633 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1634 addIntent);
1635 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1636 new Copy(extra));
1637 break;
1638
1639 case WebView.HitTestResult.EMAIL_TYPE:
1640 menu.setHeaderTitle(extra);
1641 menu.findItem(R.id.email_context_menu_id).setIntent(
1642 new Intent(Intent.ACTION_VIEW, Uri
1643 .parse(WebView.SCHEME_MAILTO + extra)));
1644 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1645 new Copy(extra));
1646 break;
1647
1648 case WebView.HitTestResult.GEO_TYPE:
1649 menu.setHeaderTitle(extra);
1650 menu.findItem(R.id.map_context_menu_id).setIntent(
1651 new Intent(Intent.ACTION_VIEW, Uri
1652 .parse(WebView.SCHEME_GEO
1653 + URLEncoder.encode(extra))));
1654 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1655 new Copy(extra));
1656 break;
1657
1658 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1659 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1660 TextView titleView = (TextView) LayoutInflater.from(this)
1661 .inflate(android.R.layout.browser_link_context_header,
1662 null);
1663 titleView.setText(extra);
1664 menu.setHeaderView(titleView);
1665 // decide whether to show the open link in new tab option
1666 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001667 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001668 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1669 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001670 PackageManager pm = getPackageManager();
1671 Intent send = new Intent(Intent.ACTION_SEND);
1672 send.setType("text/plain");
1673 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1674 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1675 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1676 break;
1677 }
1678 // otherwise fall through to handle image part
1679 case WebView.HitTestResult.IMAGE_TYPE:
1680 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1681 menu.setHeaderTitle(extra);
1682 }
1683 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1684 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1685 menu.findItem(R.id.download_context_menu_id).
1686 setOnMenuItemClickListener(new Download(extra));
1687 break;
1688
1689 default:
1690 Log.w(LOGTAG, "We should not get here.");
1691 break;
1692 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001693 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001694 }
1695
The Android Open Source Project0c908882009-03-03 19:32:16 -08001696 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001697 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001698 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001699 // Attach the container that contains the main WebView and any other UI
1700 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001701 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001702
1703 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001704 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001705 if (errorConsole.numberOfErrors() == 0) {
1706 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1707 } else {
1708 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1709 }
1710
1711 mErrorConsoleContainer.addView(errorConsole,
1712 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1713 ViewGroup.LayoutParams.WRAP_CONTENT));
1714 }
1715
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001716 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001717 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001718 // Request focus on the top window.
1719 t.getTopWindow().requestFocus();
1720 }
1721
1722 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001723 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001724 t.attachSubWindow(mContentView);
1725 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001726 }
1727
1728 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001729 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001730 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001731 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001732
Grace Kloba22ac16e2009-10-07 18:00:23 -07001733 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1734 if (errorConsole != null) {
1735 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001736 }
1737
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001738 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001739 if (view != null) {
1740 view.setEmbeddedTitleBar(null);
1741 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001742 }
1743
1744 // Remove the sub window if it exists. Also called by TabControl when the
1745 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001746 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001747 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001748 // dismiss the subwindow. This will destroy the WebView.
1749 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001750 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001751 }
1752
Leon Scroggins1f005d32009-08-10 17:36:42 -04001753 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001754 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001755 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001756 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001757 }
1758
1759 // This method does a ton of stuff. It will attempt to create a new tab
1760 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001761 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001762 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1763 String appId) {
1764 final Tab currentTab = mTabControl.getCurrentTab();
1765 if (mTabControl.canCreateNewTab()) {
1766 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1767 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001768 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001769 // If the last tab was removed from the active tabs page, currentTab
1770 // will be null.
1771 if (currentTab != null) {
1772 removeTabFromContentView(currentTab);
1773 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001774 // We must set the new tab as the current tab to reflect the old
1775 // animation behavior.
1776 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001777 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001778 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001779 urlData.loadIn(webview);
1780 }
1781 return tab;
1782 } else {
1783 // Get rid of the subwindow if it exists
1784 dismissSubWindow(currentTab);
1785 if (!urlData.isEmpty()) {
1786 // Load the given url.
1787 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001788 }
1789 }
Grace Klobac9181842009-04-14 08:53:22 -07001790 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001791 }
1792
Grace Kloba22ac16e2009-10-07 18:00:23 -07001793 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001794 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001795 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001796 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001797 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001798 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001799 }
Grace Klobac9181842009-04-14 08:53:22 -07001800 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001801 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001802 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001803 }
1804 }
1805
1806 private class Copy implements OnMenuItemClickListener {
1807 private CharSequence mText;
1808
1809 public boolean onMenuItemClick(MenuItem item) {
1810 copy(mText);
1811 return true;
1812 }
1813
1814 public Copy(CharSequence toCopy) {
1815 mText = toCopy;
1816 }
1817 }
1818
1819 private class Download implements OnMenuItemClickListener {
1820 private String mText;
1821
1822 public boolean onMenuItemClick(MenuItem item) {
1823 onDownloadStartNoStream(mText, null, null, null, -1);
1824 return true;
1825 }
1826
1827 public Download(String toDownload) {
1828 mText = toDownload;
1829 }
1830 }
1831
1832 private void copy(CharSequence text) {
1833 try {
1834 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1835 if (clip != null) {
1836 clip.setClipboardText(text);
1837 }
1838 } catch (android.os.RemoteException e) {
1839 Log.e(LOGTAG, "Copy failed", e);
1840 }
1841 }
1842
1843 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001844 * Resets the browser title-view to whatever it must be
1845 * (for example, if we had a loading error)
1846 * When we have a new page, we call resetTitle, when we
1847 * have to reset the titlebar to whatever it used to be
1848 * (for example, if the user chose to stop loading), we
1849 * call resetTitleAndRevertLockIcon.
1850 */
1851 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001852 mTabControl.getCurrentTab().revertLockIcon();
1853 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001854 resetTitleIconAndProgress();
1855 }
1856
1857 /**
1858 * Reset the title, favicon, and progress.
1859 */
1860 private void resetTitleIconAndProgress() {
1861 WebView current = mTabControl.getCurrentWebView();
1862 if (current == null) {
1863 return;
1864 }
1865 resetTitleAndIcon(current);
1866 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001867 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001868 }
1869
1870 // Reset the title and the icon based on the given item.
1871 private void resetTitleAndIcon(WebView view) {
1872 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1873 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001874 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001875 setFavicon(item.getFavicon());
1876 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001877 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001878 setFavicon(null);
1879 }
1880 }
1881
1882 /**
1883 * Sets a title composed of the URL and the title string.
1884 * @param url The URL of the site being loaded.
1885 * @param title The title of the site being loaded.
1886 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001887 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001888 mUrl = url;
1889 mTitle = title;
1890
Leon Scroggins68579392009-09-15 15:31:54 -04001891 mTitleBar.setTitleAndUrl(title, url);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001892 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001893 }
1894
1895 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001896 * @param url The URL to build a title version of the URL from.
1897 * @return The title version of the URL or null if fails.
1898 * The title version of the URL can be either the URL hostname,
1899 * or the hostname with an "https://" prefix (for secure URLs),
1900 * or an empty string if, for example, the URL in question is a
1901 * file:// URL with no hostname.
1902 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001903 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001904 String titleUrl = null;
1905
1906 if (url != null) {
1907 try {
1908 // parse the url string
1909 URL urlObj = new URL(url);
1910 if (urlObj != null) {
1911 titleUrl = "";
1912
1913 String protocol = urlObj.getProtocol();
1914 String host = urlObj.getHost();
1915
1916 if (host != null && 0 < host.length()) {
1917 titleUrl = host;
1918 if (protocol != null) {
1919 // if a secure site, add an "https://" prefix!
1920 if (protocol.equalsIgnoreCase("https")) {
1921 titleUrl = protocol + "://" + host;
1922 }
1923 }
1924 }
1925 }
1926 } catch (MalformedURLException e) {}
1927 }
1928
1929 return titleUrl;
1930 }
1931
1932 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001933 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04001934 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001935 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001936 }
1937
1938 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001939 * Close the tab, remove its associated title bar, and adjust mTabControl's
1940 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001941 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001942 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001943 int currentIndex = mTabControl.getCurrentIndex();
1944 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001945 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001946 if (currentIndex >= removeIndex && currentIndex != 0) {
1947 currentIndex--;
1948 }
1949 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01001950 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001951 }
1952
1953 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001954 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001955 if (current == null) {
1956 /*
1957 * Instead of finishing the activity, simply push this to the back
1958 * of the stack and let ActivityManager to choose the foreground
1959 * activity. As BrowserActivity is singleTask, it will be always the
1960 * root of the task. So we can use either true or false for
1961 * moveTaskToBack().
1962 */
1963 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07001964 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001965 }
1966 WebView w = current.getWebView();
1967 if (w.canGoBack()) {
1968 w.goBack();
1969 } else {
1970 // Check to see if we are closing a window that was created by
1971 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001972 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001973 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001974 switchToTab(mTabControl.getTabIndex(parent));
1975 // Now we close the other tab
1976 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001977 } else {
1978 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001979 // force the tab's inLoad() to be false as we are going to
1980 // either finish the activity or remove the tab. This will
1981 // ensure pauseWebViewTimers() taking action.
1982 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001983 if (mTabControl.getTabCount() == 1) {
1984 finish();
1985 return;
1986 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04001987 // call pauseWebViewTimers() now, we won't be able to call
1988 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07001989 // Temporarily change mActivityInPause to be true as
1990 // pauseWebViewTimers() will do nothing if mActivityInPause
1991 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07001992 boolean savedState = mActivityInPause;
1993 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07001994 Log.e(LOGTAG, "BrowserActivity is already paused "
1995 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07001996 }
1997 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001998 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07001999 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002000 removeTabFromContentView(current);
2001 mTabControl.removeTab(current);
2002 }
2003 /*
2004 * Instead of finishing the activity, simply push this to the back
2005 * of the stack and let ActivityManager to choose the foreground
2006 * activity. As BrowserActivity is singleTask, it will be always the
2007 * root of the task. So we can use either true or false for
2008 * moveTaskToBack().
2009 */
2010 moveTaskToBack(true);
2011 }
2012 }
2013 }
2014
Grace Kloba22ac16e2009-10-07 18:00:23 -07002015 boolean isMenuDown() {
2016 return mMenuIsDown;
2017 }
2018
Grace Kloba5942df02009-09-18 11:48:29 -07002019 @Override
2020 public boolean onKeyDown(int keyCode, KeyEvent event) {
2021 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2022 // still down, we don't want to trigger the search. Pretend to consume
2023 // the key and do nothing.
2024 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002025
Grace Kloba5942df02009-09-18 11:48:29 -07002026 switch(keyCode) {
2027 case KeyEvent.KEYCODE_MENU:
2028 mMenuIsDown = true;
2029 break;
2030 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002031 // WebView/WebTextView handle the keys in the KeyDown. As
2032 // the Activity's shortcut keys are only handled when WebView
2033 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2034 if (event.isShiftPressed()) {
2035 getTopWindow().pageUp(false);
2036 } else {
2037 getTopWindow().pageDown(false);
2038 }
Grace Kloba5942df02009-09-18 11:48:29 -07002039 return true;
2040 case KeyEvent.KEYCODE_BACK:
2041 if (event.getRepeatCount() == 0) {
2042 event.startTracking();
2043 return true;
2044 } else if (mCustomView == null && mActiveTabsPage == null
2045 && event.isLongPress()) {
2046 bookmarksOrHistoryPicker(true);
2047 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002048 }
Grace Kloba5942df02009-09-18 11:48:29 -07002049 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002050 }
Grace Kloba5942df02009-09-18 11:48:29 -07002051 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002052 }
2053
Grace Kloba5942df02009-09-18 11:48:29 -07002054 @Override
2055 public boolean onKeyUp(int keyCode, KeyEvent event) {
2056 switch(keyCode) {
2057 case KeyEvent.KEYCODE_MENU:
2058 mMenuIsDown = false;
2059 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002060 case KeyEvent.KEYCODE_BACK:
2061 if (event.isTracking() && !event.isCanceled()) {
2062 if (mCustomView != null) {
2063 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002064 mTabControl.getCurrentWebView().getWebChromeClient()
2065 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002066 } else if (mActiveTabsPage != null) {
2067 // if tab page is showing, hide it
2068 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002069 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002070 WebView subwindow = mTabControl.getCurrentSubWindow();
2071 if (subwindow != null) {
2072 if (subwindow.canGoBack()) {
2073 subwindow.goBack();
2074 } else {
2075 dismissSubWindow(mTabControl.getCurrentTab());
2076 }
2077 } else {
2078 goBackOnePageOrQuit();
2079 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002080 }
Grace Kloba5942df02009-09-18 11:48:29 -07002081 return true;
2082 }
2083 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002084 }
Grace Kloba5942df02009-09-18 11:48:29 -07002085 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002086 }
2087
Leon Scroggins68579392009-09-15 15:31:54 -04002088 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002089 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002090 resetTitleAndRevertLockIcon();
2091 WebView w = getTopWindow();
2092 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002093 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2094 // same logic here. But for subwindow case, should we call into the main
2095 // WebView's onPageFinished as we never call its onPageStarted and if
2096 // the page finishes itself, we don't call onPageFinished.
2097 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2098 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002099
2100 cancelStopToast();
2101 mStopToast = Toast
2102 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2103 mStopToast.show();
2104 }
2105
Grace Kloba22ac16e2009-10-07 18:00:23 -07002106 boolean didUserStopLoading() {
2107 return mDidStopLoad;
2108 }
2109
The Android Open Source Project0c908882009-03-03 19:32:16 -08002110 private void cancelStopToast() {
2111 if (mStopToast != null) {
2112 mStopToast.cancel();
2113 mStopToast = null;
2114 }
2115 }
2116
Grace Kloba22ac16e2009-10-07 18:00:23 -07002117 // called by a UI or non-UI thread to post the message
2118 public void postMessage(int what, int arg1, int arg2, Object obj,
2119 long delayMillis) {
2120 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2121 obj), delayMillis);
2122 }
2123
2124 // called by a UI or non-UI thread to remove the message
2125 void removeMessages(int what, Object object) {
2126 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002127 }
2128
2129 // public message ids
2130 public final static int LOAD_URL = 1001;
2131 public final static int STOP_LOAD = 1002;
2132
2133 // Message Ids
2134 private static final int FOCUS_NODE_HREF = 102;
2135 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002136 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002137
Grace Kloba22ac16e2009-10-07 18:00:23 -07002138 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002139
The Android Open Source Project0c908882009-03-03 19:32:16 -08002140 // Private handler for handling javascript and saving passwords
2141 private Handler mHandler = new Handler() {
2142
2143 public void handleMessage(Message msg) {
2144 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002145 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002146 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002147 String url = (String) msg.getData().get("url");
2148 if (url == null || url.length() == 0) {
2149 break;
2150 }
2151 HashMap focusNodeMap = (HashMap) msg.obj;
2152 WebView view = (WebView) focusNodeMap.get("webview");
2153 // Only apply the action if the top window did not change.
2154 if (getTopWindow() != view) {
2155 break;
2156 }
2157 switch (msg.arg1) {
2158 case R.id.open_context_menu_id:
2159 case R.id.view_image_context_menu_id:
2160 loadURL(getTopWindow(), url);
2161 break;
2162 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002163 final Tab parent = mTabControl.getCurrentTab();
2164 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002165 if (newTab != parent) {
2166 parent.addChildTab(newTab);
2167 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002168 break;
2169 case R.id.bookmark_context_menu_id:
2170 Intent intent = new Intent(BrowserActivity.this,
2171 AddBookmarkPage.class);
2172 intent.putExtra("url", url);
2173 startActivity(intent);
2174 break;
2175 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002176 Browser.sendString(BrowserActivity.this, url,
2177 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002178 break;
2179 case R.id.copy_link_context_menu_id:
2180 copy(url);
2181 break;
2182 case R.id.save_link_context_menu_id:
2183 case R.id.download_context_menu_id:
2184 onDownloadStartNoStream(url, null, null, null, -1);
2185 break;
2186 }
2187 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002188 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002189
2190 case LOAD_URL:
2191 loadURL(getTopWindow(), (String) msg.obj);
2192 break;
2193
2194 case STOP_LOAD:
2195 stopLoading();
2196 break;
2197
2198 case CANCEL_CREDS_REQUEST:
2199 resumeAfterCredentials();
2200 break;
2201
The Android Open Source Project0c908882009-03-03 19:32:16 -08002202 case RELEASE_WAKELOCK:
2203 if (mWakeLock.isHeld()) {
2204 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002205 // if we reach here, Browser should be still in the
2206 // background loading after WAKELOCK_TIMEOUT (5-min).
2207 // To avoid burning the battery, stop loading.
2208 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002209 }
2210 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002211
2212 case UPDATE_BOOKMARK_THUMBNAIL:
2213 WebView view = (WebView) msg.obj;
2214 if (view != null) {
2215 updateScreenshot(view);
2216 }
2217 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002218 }
2219 }
2220 };
2221
Leon Scroggins89c6d362009-07-15 16:54:37 -04002222 private void updateScreenshot(WebView view) {
2223 // If this is a bookmarked site, add a screenshot to the database.
2224 // FIXME: When should we update? Every time?
2225 // FIXME: Would like to make sure there is actually something to
2226 // draw, but the API for that (WebViewCore.pictureReady()) is not
2227 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002228
Patrick Scott3918d442009-08-04 13:22:29 -04002229 ContentResolver cr = getContentResolver();
2230 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002231 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002232 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002233 boolean succeed = c.moveToFirst();
2234 ContentValues values = null;
2235 while (succeed) {
2236 if (values == null) {
2237 final ByteArrayOutputStream os
2238 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002239 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002240 if (bm == null) {
2241 c.close();
2242 return;
2243 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002244 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2245 values = new ContentValues();
2246 values.put(Browser.BookmarkColumns.THUMBNAIL,
2247 os.toByteArray());
2248 }
2249 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2250 c.getInt(0)), values, null, null);
2251 succeed = c.moveToNext();
2252 }
2253 c.close();
2254 }
2255 }
2256
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002257 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002258 * Values for the size of the thumbnail created when taking a screenshot.
2259 * Lazily initialized. Instead of using these directly, use
2260 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002261 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002262 private static int THUMBNAIL_WIDTH = 0;
2263 private static int THUMBNAIL_HEIGHT = 0;
2264
2265 /**
2266 * Return the desired width for thumbnail screenshots, which are stored in
2267 * the database, and used on the bookmarks screen.
2268 * @param context Context for finding out the density of the screen.
2269 * @return int desired width for thumbnail screenshot.
2270 */
2271 /* package */ static int getDesiredThumbnailWidth(Context context) {
2272 if (THUMBNAIL_WIDTH == 0) {
2273 float density = context.getResources().getDisplayMetrics().density;
2274 THUMBNAIL_WIDTH = (int) (90 * density);
2275 THUMBNAIL_HEIGHT = (int) (80 * density);
2276 }
2277 return THUMBNAIL_WIDTH;
2278 }
2279
2280 /**
2281 * Return the desired height for thumbnail screenshots, which are stored in
2282 * the database, and used on the bookmarks screen.
2283 * @param context Context for finding out the density of the screen.
2284 * @return int desired height for thumbnail screenshot.
2285 */
2286 /* package */ static int getDesiredThumbnailHeight(Context context) {
2287 // To ensure that they are both initialized.
2288 getDesiredThumbnailWidth(context);
2289 return THUMBNAIL_HEIGHT;
2290 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002291
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002292 private Bitmap createScreenshot(WebView view) {
2293 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002294 if (thumbnail == null) {
2295 return null;
2296 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002297 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2298 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002299 Canvas canvas = new Canvas(bm);
2300 // May need to tweak these values to determine what is the
2301 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002302 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002303 int thumbnailHeight = thumbnail.getHeight();
2304 float scaleFactorX = 1.0f;
2305 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002306 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002307 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002308 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002309 } else {
2310 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002311 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002312
2313 if (view.getWidth() > view.getHeight() &&
2314 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2315 // If the device is in landscape and the page is shorter
2316 // than the height of the view, stretch the thumbnail to fill the
2317 // space.
2318 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2319 (float)thumbnailHeight;
2320 } else {
2321 // In the portrait case, this looks nice.
2322 scaleFactorY = scaleFactorX;
2323 }
2324
2325 canvas.scale(scaleFactorX, scaleFactorY);
2326
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002327 thumbnail.draw(canvas);
2328 return bm;
2329 }
2330
The Android Open Source Project0c908882009-03-03 19:32:16 -08002331 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002332 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002333 //-------------------------------------------------------------------------
2334
2335 // Use in overrideUrlLoading
2336 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2337 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2338 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2339 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2340
Grace Kloba22ac16e2009-10-07 18:00:23 -07002341 void onPageStarted(WebView view, String url, Bitmap favicon) {
2342 // when BrowserActivity just starts, onPageStarted may be called before
2343 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2344 // to start the timer. As we won't switch tabs while an activity is in
2345 // pause state, we can ensure calling resume and pause in pair.
2346 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002347
Grace Kloba22ac16e2009-10-07 18:00:23 -07002348 resetLockIcon(url);
2349 setUrlTitle(url, null);
2350 setFavicon(favicon);
2351 mInLoad = true;
2352 mDidStopLoad = false;
2353 showFakeTitleBar();
2354 updateInLoadMenuItems();
2355 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002356
Grace Kloba22ac16e2009-10-07 18:00:23 -07002357 if (mSettings.isTracing()) {
2358 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002359 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002360 WebAddress uri = new WebAddress(url);
2361 host = uri.mHost;
2362 } catch (android.net.ParseException ex) {
2363 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002364 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002365 host = host.replace('.', '_');
2366 host += ".trace";
2367 mInTrace = true;
2368 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2369 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002370
Grace Kloba22ac16e2009-10-07 18:00:23 -07002371 // Performance probe
2372 if (false) {
2373 mStart = SystemClock.uptimeMillis();
2374 mProcessStart = Process.getElapsedCpuTime();
2375 long[] sysCpu = new long[7];
2376 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2377 sysCpu, null)) {
2378 mUserStart = sysCpu[0] + sysCpu[1];
2379 mSystemStart = sysCpu[2];
2380 mIdleStart = sysCpu[3];
2381 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2382 }
2383 mUiStart = SystemClock.currentThreadTimeMillis();
2384 }
2385 }
2386
2387 void onPageFinished(WebView view, String url) {
2388 // Reset the title and icon in case we stopped a provisional load.
2389 resetTitleAndIcon(view);
2390 // Update the lock icon image only once we are done loading
2391 updateLockIconToLatest();
2392 // pause the WebView timer and release the wake lock if it is finished
2393 // while BrowserActivity is in pause state.
2394 if (mActivityInPause && pauseWebViewTimers()) {
2395 if (mWakeLock.isHeld()) {
2396 mHandler.removeMessages(RELEASE_WAKELOCK);
2397 mWakeLock.release();
2398 }
2399 }
2400
2401 // Performance probe
2402 if (false) {
2403 long[] sysCpu = new long[7];
2404 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2405 sysCpu, null)) {
2406 String uiInfo = "UI thread used "
2407 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2408 + " ms";
2409 if (LOGD_ENABLED) {
2410 Log.d(LOGTAG, uiInfo);
2411 }
2412 //The string that gets written to the log
2413 String performanceString = "It took total "
2414 + (SystemClock.uptimeMillis() - mStart)
2415 + " ms clock time to load the page."
2416 + "\nbrowser process used "
2417 + (Process.getElapsedCpuTime() - mProcessStart)
2418 + " ms, user processes used "
2419 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2420 + " ms, kernel used "
2421 + (sysCpu[2] - mSystemStart) * 10
2422 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2423 + " ms and irq took "
2424 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2425 * 10 + " ms, " + uiInfo;
2426 if (LOGD_ENABLED) {
2427 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2428 }
2429 if (url != null) {
2430 // strip the url to maintain consistency
2431 String newUrl = new String(url);
2432 if (newUrl.startsWith("http://www.")) {
2433 newUrl = newUrl.substring(11);
2434 } else if (newUrl.startsWith("http://")) {
2435 newUrl = newUrl.substring(7);
2436 } else if (newUrl.startsWith("https://www.")) {
2437 newUrl = newUrl.substring(12);
2438 } else if (newUrl.startsWith("https://")) {
2439 newUrl = newUrl.substring(8);
2440 }
2441 if (LOGD_ENABLED) {
2442 Log.d(LOGTAG, newUrl + " loaded");
2443 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002444 }
2445 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002446 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002447
Grace Kloba22ac16e2009-10-07 18:00:23 -07002448 if (mInTrace) {
2449 mInTrace = false;
2450 Debug.stopMethodTracing();
2451 }
2452 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002453
Grace Kloba22ac16e2009-10-07 18:00:23 -07002454 boolean shouldOverrideUrlLoading(WebView view, String url) {
2455 if (url.startsWith(SCHEME_WTAI)) {
2456 // wtai://wp/mc;number
2457 // number=string(phone-number)
2458 if (url.startsWith(SCHEME_WTAI_MC)) {
2459 Intent intent = new Intent(Intent.ACTION_VIEW,
2460 Uri.parse(WebView.SCHEME_TEL +
2461 url.substring(SCHEME_WTAI_MC.length())));
2462 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002463 return true;
2464 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002465 // wtai://wp/sd;dtmf
2466 // dtmf=string(dialstring)
2467 if (url.startsWith(SCHEME_WTAI_SD)) {
2468 // TODO: only send when there is active voice connection
2469 return false;
2470 }
2471 // wtai://wp/ap;number;name
2472 // number=string(phone-number)
2473 // name=string
2474 if (url.startsWith(SCHEME_WTAI_AP)) {
2475 // TODO
2476 return false;
2477 }
2478 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002479
Grace Kloba22ac16e2009-10-07 18:00:23 -07002480 // The "about:" schemes are internal to the browser; don't want these to
2481 // be dispatched to other apps.
2482 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002483 return false;
2484 }
2485
Grace Kloba22ac16e2009-10-07 18:00:23 -07002486 Intent intent;
2487 // perform generic parsing of the URI to turn it into an Intent.
2488 try {
2489 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2490 } catch (URISyntaxException ex) {
2491 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2492 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002493 }
2494
Grace Kloba22ac16e2009-10-07 18:00:23 -07002495 // check whether the intent can be resolved. If not, we will see
2496 // whether we can download it from the Market.
2497 if (getPackageManager().resolveActivity(intent, 0) == null) {
2498 String packagename = intent.getPackage();
2499 if (packagename != null) {
2500 intent = new Intent(Intent.ACTION_VIEW, Uri
2501 .parse("market://search?q=pname:" + packagename));
2502 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2503 startActivity(intent);
2504 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002505 } else {
2506 return false;
2507 }
2508 }
2509
Grace Kloba22ac16e2009-10-07 18:00:23 -07002510 // sanitize the Intent, ensuring web pages can not bypass browser
2511 // security (only access to BROWSABLE activities).
2512 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2513 intent.setComponent(null);
2514 try {
2515 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002516 return true;
2517 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002518 } catch (ActivityNotFoundException ex) {
2519 // ignore the error. If no application can handle the URL,
2520 // eg about:blank, assume the browser can handle it.
2521 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002522
Grace Kloba22ac16e2009-10-07 18:00:23 -07002523 if (mMenuIsDown) {
2524 openTab(url);
2525 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002526 return true;
2527 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002528 return false;
2529 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002530
Grace Kloba22ac16e2009-10-07 18:00:23 -07002531 // -------------------------------------------------------------------------
2532 // Helper function for WebChromeClient
2533 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002534
Grace Kloba22ac16e2009-10-07 18:00:23 -07002535 void onProgressChanged(WebView view, int newProgress) {
2536 mTitleBar.setProgress(newProgress);
2537 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002538
Grace Kloba22ac16e2009-10-07 18:00:23 -07002539 if (newProgress == 100) {
2540 // onProgressChanged() may continue to be called after the main
2541 // frame has finished loading, as any remaining sub frames continue
2542 // to load. We'll only get called once though with newProgress as
2543 // 100 when everything is loaded. (onPageFinished is called once
2544 // when the main frame completes loading regardless of the state of
2545 // any sub frames so calls to onProgressChanges may continue after
2546 // onPageFinished has executed)
2547 if (mInLoad) {
2548 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002549 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002550 // If the options menu is open, leave the title bar
2551 if (!mOptionsMenuOpen || !mIconView) {
2552 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002553 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002554 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002555 } else if (!mInLoad) {
2556 // onPageFinished may have already been called but a subframe is
2557 // still loading and updating the progress. Reset mInLoad and update
2558 // the menu items.
2559 mInLoad = true;
2560 updateInLoadMenuItems();
2561 if (!mOptionsMenuOpen || mIconView) {
2562 // This page has begun to load, so show the title bar
2563 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002564 }
2565 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002566 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002567
Grace Kloba22ac16e2009-10-07 18:00:23 -07002568 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2569 if (mCustomView != null)
2570 return;
2571
2572 // Add the custom view to its container.
2573 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2574 mCustomView = view;
2575 mCustomViewCallback = callback;
2576 // Save the menu state and set it to empty while the custom
2577 // view is showing.
2578 mOldMenuState = mMenuState;
2579 mMenuState = EMPTY_MENU;
2580 // Hide the content view.
2581 mContentView.setVisibility(View.GONE);
2582 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002583 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002584 mCustomViewContainer.setVisibility(View.VISIBLE);
2585 mCustomViewContainer.bringToFront();
2586 }
2587
2588 void onHideCustomView() {
2589 if (mCustomView == null)
2590 return;
2591
2592 // Hide the custom view.
2593 mCustomView.setVisibility(View.GONE);
2594 // Remove the custom view from its container.
2595 mCustomViewContainer.removeView(mCustomView);
2596 mCustomView = null;
2597 // Reset the old menu state.
2598 mMenuState = mOldMenuState;
2599 mOldMenuState = EMPTY_MENU;
2600 mCustomViewContainer.setVisibility(View.GONE);
2601 mCustomViewCallback.onCustomViewHidden();
2602 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002603 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002604 mContentView.setVisibility(View.VISIBLE);
2605 }
2606
2607 Bitmap getDefaultVideoPoster() {
2608 if (mDefaultVideoPoster == null) {
2609 mDefaultVideoPoster = BitmapFactory.decodeResource(
2610 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002611 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002612 return mDefaultVideoPoster;
2613 }
Patrick Scott3918d442009-08-04 13:22:29 -04002614
Grace Kloba22ac16e2009-10-07 18:00:23 -07002615 View getVideoLoadingProgressView() {
2616 if (mVideoProgressView == null) {
2617 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2618 mVideoProgressView = inflater.inflate(
2619 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002620 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002621 return mVideoProgressView;
2622 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002623
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002624 /*
2625 * The Object used to inform the WebView of the file to upload.
2626 */
2627 private ValueCallback<Uri> mUploadMessage;
2628
Grace Kloba22ac16e2009-10-07 18:00:23 -07002629 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2630 if (mUploadMessage != null) return;
2631 mUploadMessage = uploadMsg;
2632 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2633 i.addCategory(Intent.CATEGORY_OPENABLE);
2634 i.setType("*/*");
2635 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2636 getString(R.string.choose_upload)), FILE_SELECTED);
2637 }
2638
2639 // -------------------------------------------------------------------------
2640 // Implement functions for DownloadListener
2641 // -------------------------------------------------------------------------
2642
The Android Open Source Project0c908882009-03-03 19:32:16 -08002643 /**
2644 * Notify the host application a download should be done, or that
2645 * the data should be streamed if a streaming viewer is available.
2646 * @param url The full url to the content that should be downloaded
2647 * @param contentDisposition Content-disposition http header, if
2648 * present.
2649 * @param mimetype The mimetype of the content reported by the server
2650 * @param contentLength The file size reported by the server
2651 */
2652 public void onDownloadStart(String url, String userAgent,
2653 String contentDisposition, String mimetype, long contentLength) {
2654 // if we're dealing wih A/V content that's not explicitly marked
2655 // for download, check if it's streamable.
2656 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002657 || !contentDisposition.regionMatches(
2658 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002659 // query the package manager to see if there's a registered handler
2660 // that matches.
2661 Intent intent = new Intent(Intent.ACTION_VIEW);
2662 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002663 ResolveInfo info = getPackageManager().resolveActivity(intent,
2664 PackageManager.MATCH_DEFAULT_ONLY);
2665 if (info != null) {
2666 ComponentName myName = getComponentName();
2667 // If we resolved to ourselves, we don't want to attempt to
2668 // load the url only to try and download it again.
2669 if (!myName.getPackageName().equals(
2670 info.activityInfo.packageName)
2671 || !myName.getClassName().equals(
2672 info.activityInfo.name)) {
2673 // someone (other than us) knows how to handle this mime
2674 // type with this scheme, don't download.
2675 try {
2676 startActivity(intent);
2677 return;
2678 } catch (ActivityNotFoundException ex) {
2679 if (LOGD_ENABLED) {
2680 Log.d(LOGTAG, "activity not found for " + mimetype
2681 + " over " + Uri.parse(url).getScheme(),
2682 ex);
2683 }
2684 // Best behavior is to fall back to a download in this
2685 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002686 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002687 }
2688 }
2689 }
2690 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2691 }
2692
2693 /**
2694 * Notify the host application a download should be done, even if there
2695 * is a streaming viewer available for thise type.
2696 * @param url The full url to the content that should be downloaded
2697 * @param contentDisposition Content-disposition http header, if
2698 * present.
2699 * @param mimetype The mimetype of the content reported by the server
2700 * @param contentLength The file size reported by the server
2701 */
2702 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2703 String contentDisposition, String mimetype, long contentLength) {
2704
2705 String filename = URLUtil.guessFileName(url,
2706 contentDisposition, mimetype);
2707
2708 // Check to see if we have an SDCard
2709 String status = Environment.getExternalStorageState();
2710 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2711 int title;
2712 String msg;
2713
2714 // Check to see if the SDCard is busy, same as the music app
2715 if (status.equals(Environment.MEDIA_SHARED)) {
2716 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2717 title = R.string.download_sdcard_busy_dlg_title;
2718 } else {
2719 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2720 title = R.string.download_no_sdcard_dlg_title;
2721 }
2722
2723 new AlertDialog.Builder(this)
2724 .setTitle(title)
2725 .setIcon(android.R.drawable.ic_dialog_alert)
2726 .setMessage(msg)
2727 .setPositiveButton(R.string.ok, null)
2728 .show();
2729 return;
2730 }
2731
2732 // java.net.URI is a lot stricter than KURL so we have to undo
2733 // KURL's percent-encoding and redo the encoding using java.net.URI.
2734 URI uri = null;
2735 try {
2736 // Undo the percent-encoding that KURL may have done.
2737 String newUrl = new String(URLUtil.decode(url.getBytes()));
2738 // Parse the url into pieces
2739 WebAddress w = new WebAddress(newUrl);
2740 String frag = null;
2741 String query = null;
2742 String path = w.mPath;
2743 // Break the path into path, query, and fragment
2744 if (path.length() > 0) {
2745 // Strip the fragment
2746 int idx = path.lastIndexOf('#');
2747 if (idx != -1) {
2748 frag = path.substring(idx + 1);
2749 path = path.substring(0, idx);
2750 }
2751 idx = path.lastIndexOf('?');
2752 if (idx != -1) {
2753 query = path.substring(idx + 1);
2754 path = path.substring(0, idx);
2755 }
2756 }
2757 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2758 query, frag);
2759 } catch (Exception e) {
2760 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2761 return;
2762 }
2763
2764 // XXX: Have to use the old url since the cookies were stored using the
2765 // old percent-encoded url.
2766 String cookies = CookieManager.getInstance().getCookie(url);
2767
2768 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002769 values.put(Downloads.COLUMN_URI, uri.toString());
2770 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
2771 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
2772 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002773 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002774 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002775 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002776 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2777 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
2778 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
2779 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002780 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002781 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002782 }
2783 if (mimetype == null) {
2784 // We must have long pressed on a link or image to download it. We
2785 // are not sure of the mimetype in this case, so do a head request
2786 new FetchUrlMimeType(this).execute(values);
2787 } else {
2788 final Uri contentUri =
2789 getContentResolver().insert(Downloads.CONTENT_URI, values);
2790 viewDownloads(contentUri);
2791 }
2792
2793 }
2794
Grace Kloba22ac16e2009-10-07 18:00:23 -07002795 // -------------------------------------------------------------------------
2796
The Android Open Source Project0c908882009-03-03 19:32:16 -08002797 /**
2798 * Resets the lock icon. This method is called when we start a new load and
2799 * know the url to be loaded.
2800 */
2801 private void resetLockIcon(String url) {
2802 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002803 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002804 updateLockIconImage(LOCK_ICON_UNSECURE);
2805 }
2806
The Android Open Source Project0c908882009-03-03 19:32:16 -08002807 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002808 * Update the lock icon to correspond to our latest state.
2809 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002810 private void updateLockIconToLatest() {
2811 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002812 }
2813
2814 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002815 * Updates the lock-icon image in the title-bar.
2816 */
2817 private void updateLockIconImage(int lockIconType) {
2818 Drawable d = null;
2819 if (lockIconType == LOCK_ICON_SECURE) {
2820 d = mSecLockIcon;
2821 } else if (lockIconType == LOCK_ICON_MIXED) {
2822 d = mMixLockIcon;
2823 }
Leon Scroggins68579392009-09-15 15:31:54 -04002824 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002825 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002826 }
2827
2828 /**
2829 * Displays a page-info dialog.
2830 * @param tab The tab to show info about
2831 * @param fromShowSSLCertificateOnError The flag that indicates whether
2832 * this dialog was opened from the SSL-certificate-on-error dialog or
2833 * not. This is important, since we need to know whether to return to
2834 * the parent dialog or simply dismiss.
2835 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002836 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002837 final boolean fromShowSSLCertificateOnError) {
2838 final LayoutInflater factory = LayoutInflater
2839 .from(this);
2840
2841 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2842
2843 final WebView view = tab.getWebView();
2844
2845 String url = null;
2846 String title = null;
2847
2848 if (view == null) {
2849 url = tab.getUrl();
2850 title = tab.getTitle();
2851 } else if (view == mTabControl.getCurrentWebView()) {
2852 // Use the cached title and url if this is the current WebView
2853 url = mUrl;
2854 title = mTitle;
2855 } else {
2856 url = view.getUrl();
2857 title = view.getTitle();
2858 }
2859
2860 if (url == null) {
2861 url = "";
2862 }
2863 if (title == null) {
2864 title = "";
2865 }
2866
2867 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2868 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2869
2870 mPageInfoView = tab;
2871 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
2872
2873 AlertDialog.Builder alertDialogBuilder =
2874 new AlertDialog.Builder(this)
2875 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2876 .setView(pageInfoView)
2877 .setPositiveButton(
2878 R.string.ok,
2879 new DialogInterface.OnClickListener() {
2880 public void onClick(DialogInterface dialog,
2881 int whichButton) {
2882 mPageInfoDialog = null;
2883 mPageInfoView = null;
2884 mPageInfoFromShowSSLCertificateOnError = null;
2885
2886 // if we came here from the SSL error dialog
2887 if (fromShowSSLCertificateOnError) {
2888 // go back to the SSL error dialog
2889 showSSLCertificateOnError(
2890 mSSLCertificateOnErrorView,
2891 mSSLCertificateOnErrorHandler,
2892 mSSLCertificateOnErrorError);
2893 }
2894 }
2895 })
2896 .setOnCancelListener(
2897 new DialogInterface.OnCancelListener() {
2898 public void onCancel(DialogInterface dialog) {
2899 mPageInfoDialog = null;
2900 mPageInfoView = null;
2901 mPageInfoFromShowSSLCertificateOnError = null;
2902
2903 // if we came here from the SSL error dialog
2904 if (fromShowSSLCertificateOnError) {
2905 // go back to the SSL error dialog
2906 showSSLCertificateOnError(
2907 mSSLCertificateOnErrorView,
2908 mSSLCertificateOnErrorHandler,
2909 mSSLCertificateOnErrorError);
2910 }
2911 }
2912 });
2913
2914 // if we have a main top-level page SSL certificate set or a certificate
2915 // error
2916 if (fromShowSSLCertificateOnError ||
2917 (view != null && view.getCertificate() != null)) {
2918 // add a 'View Certificate' button
2919 alertDialogBuilder.setNeutralButton(
2920 R.string.view_certificate,
2921 new DialogInterface.OnClickListener() {
2922 public void onClick(DialogInterface dialog,
2923 int whichButton) {
2924 mPageInfoDialog = null;
2925 mPageInfoView = null;
2926 mPageInfoFromShowSSLCertificateOnError = null;
2927
2928 // if we came here from the SSL error dialog
2929 if (fromShowSSLCertificateOnError) {
2930 // go back to the SSL error dialog
2931 showSSLCertificateOnError(
2932 mSSLCertificateOnErrorView,
2933 mSSLCertificateOnErrorHandler,
2934 mSSLCertificateOnErrorError);
2935 } else {
2936 // otherwise, display the top-most certificate from
2937 // the chain
2938 if (view.getCertificate() != null) {
2939 showSSLCertificate(tab);
2940 }
2941 }
2942 }
2943 });
2944 }
2945
2946 mPageInfoDialog = alertDialogBuilder.show();
2947 }
2948
2949 /**
2950 * Displays the main top-level page SSL certificate dialog
2951 * (accessible from the Page-Info dialog).
2952 * @param tab The tab to show certificate for.
2953 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002954 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002955 final View certificateView =
2956 inflateCertificateView(tab.getWebView().getCertificate());
2957 if (certificateView == null) {
2958 return;
2959 }
2960
2961 LayoutInflater factory = LayoutInflater.from(this);
2962
2963 final LinearLayout placeholder =
2964 (LinearLayout)certificateView.findViewById(R.id.placeholder);
2965
2966 LinearLayout ll = (LinearLayout) factory.inflate(
2967 R.layout.ssl_success, placeholder);
2968 ((TextView)ll.findViewById(R.id.success))
2969 .setText(R.string.ssl_certificate_is_valid);
2970
2971 mSSLCertificateView = tab;
2972 mSSLCertificateDialog =
2973 new AlertDialog.Builder(this)
2974 .setTitle(R.string.ssl_certificate).setIcon(
2975 R.drawable.ic_dialog_browser_certificate_secure)
2976 .setView(certificateView)
2977 .setPositiveButton(R.string.ok,
2978 new DialogInterface.OnClickListener() {
2979 public void onClick(DialogInterface dialog,
2980 int whichButton) {
2981 mSSLCertificateDialog = null;
2982 mSSLCertificateView = null;
2983
2984 showPageInfo(tab, false);
2985 }
2986 })
2987 .setOnCancelListener(
2988 new DialogInterface.OnCancelListener() {
2989 public void onCancel(DialogInterface dialog) {
2990 mSSLCertificateDialog = null;
2991 mSSLCertificateView = null;
2992
2993 showPageInfo(tab, false);
2994 }
2995 })
2996 .show();
2997 }
2998
2999 /**
3000 * Displays the SSL error certificate dialog.
3001 * @param view The target web-view.
3002 * @param handler The SSL error handler responsible for cancelling the
3003 * connection that resulted in an SSL error or proceeding per user request.
3004 * @param error The SSL error object.
3005 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003006 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003007 final WebView view, final SslErrorHandler handler, final SslError error) {
3008
3009 final View certificateView =
3010 inflateCertificateView(error.getCertificate());
3011 if (certificateView == null) {
3012 return;
3013 }
3014
3015 LayoutInflater factory = LayoutInflater.from(this);
3016
3017 final LinearLayout placeholder =
3018 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3019
3020 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3021 LinearLayout ll = (LinearLayout)factory
3022 .inflate(R.layout.ssl_warning, placeholder);
3023 ((TextView)ll.findViewById(R.id.warning))
3024 .setText(R.string.ssl_untrusted);
3025 }
3026
3027 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3028 LinearLayout ll = (LinearLayout)factory
3029 .inflate(R.layout.ssl_warning, placeholder);
3030 ((TextView)ll.findViewById(R.id.warning))
3031 .setText(R.string.ssl_mismatch);
3032 }
3033
3034 if (error.hasError(SslError.SSL_EXPIRED)) {
3035 LinearLayout ll = (LinearLayout)factory
3036 .inflate(R.layout.ssl_warning, placeholder);
3037 ((TextView)ll.findViewById(R.id.warning))
3038 .setText(R.string.ssl_expired);
3039 }
3040
3041 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3042 LinearLayout ll = (LinearLayout)factory
3043 .inflate(R.layout.ssl_warning, placeholder);
3044 ((TextView)ll.findViewById(R.id.warning))
3045 .setText(R.string.ssl_not_yet_valid);
3046 }
3047
3048 mSSLCertificateOnErrorHandler = handler;
3049 mSSLCertificateOnErrorView = view;
3050 mSSLCertificateOnErrorError = error;
3051 mSSLCertificateOnErrorDialog =
3052 new AlertDialog.Builder(this)
3053 .setTitle(R.string.ssl_certificate).setIcon(
3054 R.drawable.ic_dialog_browser_certificate_partially_secure)
3055 .setView(certificateView)
3056 .setPositiveButton(R.string.ok,
3057 new DialogInterface.OnClickListener() {
3058 public void onClick(DialogInterface dialog,
3059 int whichButton) {
3060 mSSLCertificateOnErrorDialog = null;
3061 mSSLCertificateOnErrorView = null;
3062 mSSLCertificateOnErrorHandler = null;
3063 mSSLCertificateOnErrorError = null;
3064
Grace Kloba22ac16e2009-10-07 18:00:23 -07003065 view.getWebViewClient().onReceivedSslError(
3066 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003067 }
3068 })
3069 .setNeutralButton(R.string.page_info_view,
3070 new DialogInterface.OnClickListener() {
3071 public void onClick(DialogInterface dialog,
3072 int whichButton) {
3073 mSSLCertificateOnErrorDialog = null;
3074
3075 // do not clear the dialog state: we will
3076 // need to show the dialog again once the
3077 // user is done exploring the page-info details
3078
3079 showPageInfo(mTabControl.getTabFromView(view),
3080 true);
3081 }
3082 })
3083 .setOnCancelListener(
3084 new DialogInterface.OnCancelListener() {
3085 public void onCancel(DialogInterface dialog) {
3086 mSSLCertificateOnErrorDialog = null;
3087 mSSLCertificateOnErrorView = null;
3088 mSSLCertificateOnErrorHandler = null;
3089 mSSLCertificateOnErrorError = null;
3090
Grace Kloba22ac16e2009-10-07 18:00:23 -07003091 view.getWebViewClient().onReceivedSslError(
3092 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003093 }
3094 })
3095 .show();
3096 }
3097
3098 /**
3099 * Inflates the SSL certificate view (helper method).
3100 * @param certificate The SSL certificate.
3101 * @return The resultant certificate view with issued-to, issued-by,
3102 * issued-on, expires-on, and possibly other fields set.
3103 * If the input certificate is null, returns null.
3104 */
3105 private View inflateCertificateView(SslCertificate certificate) {
3106 if (certificate == null) {
3107 return null;
3108 }
3109
3110 LayoutInflater factory = LayoutInflater.from(this);
3111
3112 View certificateView = factory.inflate(
3113 R.layout.ssl_certificate, null);
3114
3115 // issued to:
3116 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3117 if (issuedTo != null) {
3118 ((TextView) certificateView.findViewById(R.id.to_common))
3119 .setText(issuedTo.getCName());
3120 ((TextView) certificateView.findViewById(R.id.to_org))
3121 .setText(issuedTo.getOName());
3122 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3123 .setText(issuedTo.getUName());
3124 }
3125
3126 // issued by:
3127 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3128 if (issuedBy != null) {
3129 ((TextView) certificateView.findViewById(R.id.by_common))
3130 .setText(issuedBy.getCName());
3131 ((TextView) certificateView.findViewById(R.id.by_org))
3132 .setText(issuedBy.getOName());
3133 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3134 .setText(issuedBy.getUName());
3135 }
3136
3137 // issued on:
3138 String issuedOn = reformatCertificateDate(
3139 certificate.getValidNotBefore());
3140 ((TextView) certificateView.findViewById(R.id.issued_on))
3141 .setText(issuedOn);
3142
3143 // expires on:
3144 String expiresOn = reformatCertificateDate(
3145 certificate.getValidNotAfter());
3146 ((TextView) certificateView.findViewById(R.id.expires_on))
3147 .setText(expiresOn);
3148
3149 return certificateView;
3150 }
3151
3152 /**
3153 * Re-formats the certificate date (Date.toString()) string to
3154 * a properly localized date string.
3155 * @return Properly localized version of the certificate date string and
3156 * the original certificate date string if fails to localize.
3157 * If the original string is null, returns an empty string "".
3158 */
3159 private String reformatCertificateDate(String certificateDate) {
3160 String reformattedDate = null;
3161
3162 if (certificateDate != null) {
3163 Date date = null;
3164 try {
3165 date = java.text.DateFormat.getInstance().parse(certificateDate);
3166 } catch (ParseException e) {
3167 date = null;
3168 }
3169
3170 if (date != null) {
3171 reformattedDate =
3172 DateFormat.getDateFormat(this).format(date);
3173 }
3174 }
3175
3176 return reformattedDate != null ? reformattedDate :
3177 (certificateDate != null ? certificateDate : "");
3178 }
3179
3180 /**
3181 * Displays an http-authentication dialog.
3182 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003183 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003184 final String host, final String realm, final String title,
3185 final String name, final String password, int focusId) {
3186 LayoutInflater factory = LayoutInflater.from(this);
3187 final View v = factory
3188 .inflate(R.layout.http_authentication, null);
3189 if (name != null) {
3190 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3191 }
3192 if (password != null) {
3193 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3194 }
3195
3196 String titleText = title;
3197 if (titleText == null) {
3198 titleText = getText(R.string.sign_in_to).toString().replace(
3199 "%s1", host).replace("%s2", realm);
3200 }
3201
3202 mHttpAuthHandler = handler;
3203 AlertDialog dialog = new AlertDialog.Builder(this)
3204 .setTitle(titleText)
3205 .setIcon(android.R.drawable.ic_dialog_alert)
3206 .setView(v)
3207 .setPositiveButton(R.string.action,
3208 new DialogInterface.OnClickListener() {
3209 public void onClick(DialogInterface dialog,
3210 int whichButton) {
3211 String nm = ((EditText) v
3212 .findViewById(R.id.username_edit))
3213 .getText().toString();
3214 String pw = ((EditText) v
3215 .findViewById(R.id.password_edit))
3216 .getText().toString();
3217 BrowserActivity.this.setHttpAuthUsernamePassword
3218 (host, realm, nm, pw);
3219 handler.proceed(nm, pw);
3220 mHttpAuthenticationDialog = null;
3221 mHttpAuthHandler = null;
3222 }})
3223 .setNegativeButton(R.string.cancel,
3224 new DialogInterface.OnClickListener() {
3225 public void onClick(DialogInterface dialog,
3226 int whichButton) {
3227 handler.cancel();
3228 BrowserActivity.this.resetTitleAndRevertLockIcon();
3229 mHttpAuthenticationDialog = null;
3230 mHttpAuthHandler = null;
3231 }})
3232 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3233 public void onCancel(DialogInterface dialog) {
3234 handler.cancel();
3235 BrowserActivity.this.resetTitleAndRevertLockIcon();
3236 mHttpAuthenticationDialog = null;
3237 mHttpAuthHandler = null;
3238 }})
3239 .create();
3240 // Make the IME appear when the dialog is displayed if applicable.
3241 dialog.getWindow().setSoftInputMode(
3242 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3243 dialog.show();
3244 if (focusId != 0) {
3245 dialog.findViewById(focusId).requestFocus();
3246 } else {
3247 v.findViewById(R.id.username_edit).requestFocus();
3248 }
3249 mHttpAuthenticationDialog = dialog;
3250 }
3251
3252 public int getProgress() {
3253 WebView w = mTabControl.getCurrentWebView();
3254 if (w != null) {
3255 return w.getProgress();
3256 } else {
3257 return 100;
3258 }
3259 }
3260
3261 /**
3262 * Set HTTP authentication password.
3263 *
3264 * @param host The host for the password
3265 * @param realm The realm for the password
3266 * @param username The username for the password. If it is null, it means
3267 * password can't be saved.
3268 * @param password The password
3269 */
3270 public void setHttpAuthUsernamePassword(String host, String realm,
3271 String username,
3272 String password) {
3273 WebView w = mTabControl.getCurrentWebView();
3274 if (w != null) {
3275 w.setHttpAuthUsernamePassword(host, realm, username, password);
3276 }
3277 }
3278
3279 /**
3280 * connectivity manager says net has come or gone... inform the user
3281 * @param up true if net has come up, false if net has gone down
3282 */
3283 public void onNetworkToggle(boolean up) {
3284 if (up == mIsNetworkUp) {
3285 return;
3286 } else if (up) {
3287 mIsNetworkUp = true;
3288 if (mAlertDialog != null) {
3289 mAlertDialog.cancel();
3290 mAlertDialog = null;
3291 }
3292 } else {
3293 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003294 if (mInLoad) {
3295 createAndShowNetworkDialog();
3296 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003297 }
3298 WebView w = mTabControl.getCurrentWebView();
3299 if (w != null) {
3300 w.setNetworkAvailable(up);
3301 }
3302 }
3303
Grace Kloba22ac16e2009-10-07 18:00:23 -07003304 boolean isNetworkUp() {
3305 return mIsNetworkUp;
3306 }
3307
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003308 // This method shows the network dialog alerting the user that the net is
3309 // down. It will only show the dialog if mAlertDialog is null.
3310 private void createAndShowNetworkDialog() {
3311 if (mAlertDialog == null) {
3312 mAlertDialog = new AlertDialog.Builder(this)
3313 .setTitle(R.string.loadSuspendedTitle)
3314 .setMessage(R.string.loadSuspended)
3315 .setPositiveButton(R.string.ok, null)
3316 .show();
3317 }
3318 }
3319
The Android Open Source Project0c908882009-03-03 19:32:16 -08003320 @Override
3321 protected void onActivityResult(int requestCode, int resultCode,
3322 Intent intent) {
3323 switch (requestCode) {
3324 case COMBO_PAGE:
3325 if (resultCode == RESULT_OK && intent != null) {
3326 String data = intent.getAction();
3327 Bundle extras = intent.getExtras();
3328 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003329 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003330 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003331 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003332 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003333 dismissSubWindow(currentTab);
3334 if (data != null && data.length() != 0) {
3335 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003336 }
3337 }
3338 }
3339 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003340 // Choose a file from the file picker.
3341 case FILE_SELECTED:
3342 if (null == mUploadMessage) break;
3343 Uri result = intent == null || resultCode != RESULT_OK ? null
3344 : intent.getData();
3345 mUploadMessage.onReceiveValue(result);
3346 mUploadMessage = null;
3347 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003348 default:
3349 break;
3350 }
Leon Scroggins30444232009-09-04 18:36:20 -04003351 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003352 }
3353
3354 /*
3355 * This method is called as a result of the user selecting the options
3356 * menu to see the download window, or when a download changes state. It
3357 * shows the download window ontop of the current window.
3358 */
3359 /* package */ void viewDownloads(Uri downloadRecord) {
3360 Intent intent = new Intent(this,
3361 BrowserDownloadPage.class);
3362 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003363 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003364
3365 }
3366
Leon Scroggins160a7e72009-08-14 18:28:01 -04003367 /**
3368 * Open the Go page.
3369 * @param startWithHistory If true, open starting on the history tab.
3370 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003371 */
Leon Scroggins30444232009-09-04 18:36:20 -04003372 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003373 WebView current = mTabControl.getCurrentWebView();
3374 if (current == null) {
3375 return;
3376 }
3377 Intent intent = new Intent(this,
3378 CombinedBookmarkHistoryActivity.class);
3379 String title = current.getTitle();
3380 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003381 Bitmap thumbnail = createScreenshot(current);
3382
The Android Open Source Project0c908882009-03-03 19:32:16 -08003383 // Just in case the user opens bookmarks before a page finishes loading
3384 // so the current history item, and therefore the page, is null.
3385 if (null == url) {
3386 url = mLastEnteredUrl;
3387 // This can happen.
3388 if (null == url) {
3389 url = mSettings.getHomePage();
3390 }
3391 }
3392 // In case the web page has not yet received its associated title.
3393 if (title == null) {
3394 title = url;
3395 }
3396 intent.putExtra("title", title);
3397 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003398 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003399 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003400 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003401 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003402 if (startWithHistory) {
3403 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3404 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3405 }
3406 startActivityForResult(intent, COMBO_PAGE);
3407 }
3408
3409 // Called when loading from context menu or LOAD_URL message
3410 private void loadURL(WebView view, String url) {
3411 // In case the user enters nothing.
3412 if (url != null && url.length() != 0 && view != null) {
3413 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003414 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003415 view.loadUrl(url);
3416 }
3417 }
3418 }
3419
The Android Open Source Project0c908882009-03-03 19:32:16 -08003420 private String smartUrlFilter(Uri inUri) {
3421 if (inUri != null) {
3422 return smartUrlFilter(inUri.toString());
3423 }
3424 return null;
3425 }
3426
Feng Qianb34f87a2009-03-24 21:27:26 -07003427 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003428 "(?i)" + // switch on case insensitive matching
3429 "(" + // begin group for schema
3430 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003431 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003432 ")" +
3433 "(.*)" );
3434
3435 /**
3436 * Attempts to determine whether user input is a URL or search
3437 * terms. Anything with a space is passed to search.
3438 *
3439 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3440 * "Http://" converts to "http://"
3441 *
3442 * @return Original or modified URL
3443 *
3444 */
3445 String smartUrlFilter(String url) {
3446
3447 String inUrl = url.trim();
3448 boolean hasSpace = inUrl.indexOf(' ') != -1;
3449
3450 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3451 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003452 // force scheme to lowercase
3453 String scheme = matcher.group(1);
3454 String lcScheme = scheme.toLowerCase();
3455 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003456 inUrl = lcScheme + matcher.group(2);
3457 }
3458 if (hasSpace) {
3459 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003460 }
3461 return inUrl;
3462 }
3463 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003464 // FIXME: Is this the correct place to add to searches?
3465 // what if someone else calls this function?
3466 int shortcut = parseUrlShortcut(inUrl);
3467 if (shortcut != SHORTCUT_INVALID) {
3468 Browser.addSearchUrl(mResolver, inUrl);
3469 String query = inUrl.substring(2);
3470 switch (shortcut) {
3471 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003472 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003473 case SHORTCUT_WIKIPEDIA_SEARCH:
3474 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3475 case SHORTCUT_DICTIONARY_SEARCH:
3476 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3477 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003478 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003479 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003480 }
3481 }
3482 } else {
3483 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
3484 return URLUtil.guessUrl(inUrl);
3485 }
3486 }
3487
3488 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003489 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003490 }
3491
Ben Murdochbff2d602009-07-01 20:19:05 +01003492 /* package */ void setShouldShowErrorConsole(boolean flag) {
3493 if (flag == mShouldShowErrorConsole) {
3494 // Nothing to do.
3495 return;
3496 }
3497
3498 mShouldShowErrorConsole = flag;
3499
Grace Kloba22ac16e2009-10-07 18:00:23 -07003500 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3501 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003502
3503 if (flag) {
3504 // Setting the show state of the console will cause it's the layout to be inflated.
3505 if (errorConsole.numberOfErrors() > 0) {
3506 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3507 } else {
3508 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3509 }
3510
3511 // Now we can add it to the main view.
3512 mErrorConsoleContainer.addView(errorConsole,
3513 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
3514 ViewGroup.LayoutParams.WRAP_CONTENT));
3515 } else {
3516 mErrorConsoleContainer.removeView(errorConsole);
3517 }
3518
3519 }
3520
Grace Kloba22ac16e2009-10-07 18:00:23 -07003521 boolean shouldShowErrorConsole() {
3522 return mShouldShowErrorConsole;
3523 }
3524
Andrei Popescu163ab742009-10-20 17:58:23 +01003525 private void setStatusBarVisibility(boolean visible) {
3526 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3527 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3528 }
3529
Grace Klobaeb6eef42009-09-15 17:56:32 -07003530 final static int LOCK_ICON_UNSECURE = 0;
3531 final static int LOCK_ICON_SECURE = 1;
3532 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003533
The Android Open Source Project0c908882009-03-03 19:32:16 -08003534 private BrowserSettings mSettings;
3535 private TabControl mTabControl;
3536 private ContentResolver mResolver;
3537 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003538 private View mCustomView;
3539 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003540 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003541
3542 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3543 // view, we should rewrite this.
3544 private int mCurrentMenuState = 0;
3545 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003546 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003547 private static final int EMPTY_MENU = -1;
3548 private Menu mMenu;
3549
3550 private FindDialog mFindDialog;
3551 // Used to prevent chording to result in firing two shortcuts immediately
3552 // one after another. Fixes bug 1211714.
3553 boolean mCanChord;
3554
3555 private boolean mInLoad;
3556 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003557 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003558
The Android Open Source Project0c908882009-03-03 19:32:16 -08003559 private boolean mActivityInPause = true;
3560
3561 private boolean mMenuIsDown;
3562
The Android Open Source Project0c908882009-03-03 19:32:16 -08003563 private static boolean mInTrace;
3564
3565 // Performance probe
3566 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3567 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3568 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3569 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3570 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3571 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3572 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3573 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3574 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3575 };
3576
3577 private long mStart;
3578 private long mProcessStart;
3579 private long mUserStart;
3580 private long mSystemStart;
3581 private long mIdleStart;
3582 private long mIrqStart;
3583
3584 private long mUiStart;
3585
3586 private Drawable mMixLockIcon;
3587 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003588
3589 /* hold a ref so we can auto-cancel if necessary */
3590 private AlertDialog mAlertDialog;
3591
3592 // Wait for credentials before loading google.com
3593 private ProgressDialog mCredsDlg;
3594
3595 // The up-to-date URL and title (these can be different from those stored
3596 // in WebView, since it takes some time for the information in WebView to
3597 // get updated)
3598 private String mUrl;
3599 private String mTitle;
3600
3601 // As PageInfo has different style for landscape / portrait, we have
3602 // to re-open it when configuration changed
3603 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003604 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003605 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3606 // dialog, we should not just dismiss it, but should get back to the
3607 // SSL-certificate-on-error dialog. This flag is used to store this state
3608 private Boolean mPageInfoFromShowSSLCertificateOnError;
3609
3610 // as SSLCertificateOnError has different style for landscape / portrait,
3611 // we have to re-open it when configuration changed
3612 private AlertDialog mSSLCertificateOnErrorDialog;
3613 private WebView mSSLCertificateOnErrorView;
3614 private SslErrorHandler mSSLCertificateOnErrorHandler;
3615 private SslError mSSLCertificateOnErrorError;
3616
3617 // as SSLCertificate has different style for landscape / portrait, we
3618 // have to re-open it when configuration changed
3619 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003620 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003621
3622 // as HttpAuthentication has different style for landscape / portrait, we
3623 // have to re-open it when configuration changed
3624 private AlertDialog mHttpAuthenticationDialog;
3625 private HttpAuthHandler mHttpAuthHandler;
3626
3627 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3628 new FrameLayout.LayoutParams(
3629 ViewGroup.LayoutParams.FILL_PARENT,
3630 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003631 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3632 new FrameLayout.LayoutParams(
3633 ViewGroup.LayoutParams.FILL_PARENT,
3634 ViewGroup.LayoutParams.FILL_PARENT,
3635 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003636 // Google search
3637 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003638 // Wikipedia search
3639 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3640 // Dictionary search
3641 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3642 // Google Mobile Local search
3643 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3644
3645 final static String QUERY_PLACE_HOLDER = "%s";
3646
3647 // "source" parameter for Google search through search key
3648 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3649 // "source" parameter for Google search through goto menu
3650 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3651 // "source" parameter for Google search through simplily type
3652 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3653 // "source" parameter for Google search suggested by the browser
3654 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3655 // "source" parameter for Google search from unknown source
3656 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3657
3658 private final static String LOGTAG = "browser";
3659
The Android Open Source Project0c908882009-03-03 19:32:16 -08003660 private String mLastEnteredUrl;
3661
3662 private PowerManager.WakeLock mWakeLock;
3663 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3664
3665 private Toast mStopToast;
3666
Leon Scroggins68579392009-09-15 15:31:54 -04003667 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003668
Ben Murdochbff2d602009-07-01 20:19:05 +01003669 private LinearLayout mErrorConsoleContainer = null;
3670 private boolean mShouldShowErrorConsole = false;
3671
The Android Open Source Project0c908882009-03-03 19:32:16 -08003672 // As the ids are dynamically created, we can't guarantee that they will
3673 // be in sequence, so this static array maps ids to a window number.
3674 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3675 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3676 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3677 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3678
3679 // monitor platform changes
3680 private IntentFilter mNetworkStateChangedFilter;
3681 private BroadcastReceiver mNetworkStateIntentReceiver;
3682
Grace Klobab4da0ad2009-05-14 14:45:40 -07003683 private BroadcastReceiver mPackageInstallationReceiver;
3684
The Android Open Source Project0c908882009-03-03 19:32:16 -08003685 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003686 final static int COMBO_PAGE = 1;
3687 final static int DOWNLOAD_PAGE = 2;
3688 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003689 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003690
Andrei Popescu540035d2009-09-18 18:59:20 +01003691 // the default <video> poster
3692 private Bitmap mDefaultVideoPoster;
3693 // the video progress view
3694 private View mVideoProgressView;
3695
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003696 /**
3697 * A UrlData class to abstract how the content will be set to WebView.
3698 * This base class uses loadUrl to show the content.
3699 */
3700 private static class UrlData {
3701 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07003702 byte[] mPostData;
3703
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003704 UrlData(String url) {
3705 this.mUrl = url;
3706 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003707
3708 void setPostData(byte[] postData) {
3709 mPostData = postData;
3710 }
3711
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003712 boolean isEmpty() {
3713 return mUrl == null || mUrl.length() == 0;
3714 }
3715
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003716 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07003717 if (mPostData != null) {
3718 webView.postUrl(mUrl, mPostData);
3719 } else {
3720 webView.loadUrl(mUrl);
3721 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003722 }
3723 };
3724
3725 /**
3726 * A subclass of UrlData class that can display inlined content using
3727 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3728 */
3729 private static class InlinedUrlData extends UrlData {
3730 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3731 super(failUrl);
3732 mInlined = inlined;
3733 mMimeType = mimeType;
3734 mEncoding = encoding;
3735 }
3736 String mMimeType;
3737 String mInlined;
3738 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003739 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003740 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01003741 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003742 }
3743
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003744 @Override
3745 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003746 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3747 }
3748 }
3749
Leon Scroggins1f005d32009-08-10 17:36:42 -04003750 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003751}