blob: c9d5393f893ac884de7b472cf352124081a00b8f [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 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001054 }
1055
Grace Kloba22ac16e2009-10-07 18:00:23 -07001056 @Override
1057 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001058 super.onLowMemory();
1059 mTabControl.freeMemory();
1060 }
1061
Mike Reed7bfa63b2009-05-28 11:08:32 -04001062 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001063 Tab tab = mTabControl.getCurrentTab();
1064 boolean inLoad = tab.inLoad();
1065 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001066 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001067 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001068 if (w != null) {
1069 w.resumeTimers();
1070 }
1071 return true;
1072 } else {
1073 return false;
1074 }
1075 }
1076
Mike Reed7bfa63b2009-05-28 11:08:32 -04001077 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001078 Tab tab = mTabControl.getCurrentTab();
1079 boolean inLoad = tab.inLoad();
1080 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001081 CookieSyncManager.getInstance().stopSync();
1082 WebView w = mTabControl.getCurrentWebView();
1083 if (w != null) {
1084 w.pauseTimers();
1085 }
1086 return true;
1087 } else {
1088 return false;
1089 }
1090 }
1091
Leon Scroggins1f005d32009-08-10 17:36:42 -04001092 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001093 /*
1094 * This function is called when we are launching for the first time. We
1095 * are waiting for the login credentials before loading Google home
1096 * pages. This way the user will be logged in straight away.
1097 */
1098 private void waitForCredentials() {
1099 // Show a toast
1100 mCredsDlg = new ProgressDialog(this);
1101 mCredsDlg.setIndeterminate(true);
1102 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1103 // If the user cancels the operation, then cancel the Google
1104 // Credentials request.
1105 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1106 mCredsDlg.show();
1107
1108 // We set a timeout for the retrieval of credentials in onResume()
1109 // as that is when we have freed up some CPU time to get
1110 // the login credentials.
1111 }
1112
1113 /*
1114 * If we have received the credentials or we have timed out and we are
1115 * showing the credentials dialog, then it is time to move on.
1116 */
1117 private void resumeAfterCredentials() {
1118 if (mCredsDlg == null) {
1119 return;
1120 }
1121
1122 // Clear the toast
1123 if (mCredsDlg.isShowing()) {
1124 mCredsDlg.dismiss();
1125 }
1126 mCredsDlg = null;
1127
1128 // Clear any pending timeout
1129 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1130
1131 // Load the page
1132 WebView w = mTabControl.getCurrentWebView();
1133 if (w != null) {
1134 w.loadUrl(mSettings.getHomePage());
1135 }
1136
1137 // Update the settings, need to do this last as it can take a moment
1138 // to persist the settings. In the mean time we could be loading
1139 // content.
1140 mSettings.setLoginInitialized(this);
1141 }
1142
1143 // Open the icon database and retain all the icons for visited sites.
1144 private void retainIconsOnStartup() {
1145 final WebIconDatabase db = WebIconDatabase.getInstance();
1146 db.open(getDir("icons", 0).getPath());
1147 try {
1148 Cursor c = Browser.getAllBookmarks(mResolver);
1149 if (!c.moveToFirst()) {
1150 c.deactivate();
1151 return;
1152 }
1153 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1154 do {
1155 String url = c.getString(urlIndex);
1156 db.retainIconForPageUrl(url);
1157 } while (c.moveToNext());
1158 c.deactivate();
1159 } catch (IllegalStateException e) {
1160 Log.e(LOGTAG, "retainIconsOnStartup", e);
1161 }
1162 }
1163
1164 // Helper method for getting the top window.
1165 WebView getTopWindow() {
1166 return mTabControl.getCurrentTopWebView();
1167 }
1168
Grace Kloba22ac16e2009-10-07 18:00:23 -07001169 TabControl getTabControl() {
1170 return mTabControl;
1171 }
1172
The Android Open Source Project0c908882009-03-03 19:32:16 -08001173 @Override
1174 public boolean onCreateOptionsMenu(Menu menu) {
1175 super.onCreateOptionsMenu(menu);
1176
1177 MenuInflater inflater = getMenuInflater();
1178 inflater.inflate(R.menu.browser, menu);
1179 mMenu = menu;
1180 updateInLoadMenuItems();
1181 return true;
1182 }
1183
1184 /**
1185 * As the menu can be open when loading state changes
1186 * we must manually update the state of the stop/reload menu
1187 * item
1188 */
1189 private void updateInLoadMenuItems() {
1190 if (mMenu == null) {
1191 return;
1192 }
1193 MenuItem src = mInLoad ?
1194 mMenu.findItem(R.id.stop_menu_id):
1195 mMenu.findItem(R.id.reload_menu_id);
1196 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1197 dest.setIcon(src.getIcon());
1198 dest.setTitle(src.getTitle());
1199 }
1200
1201 @Override
1202 public boolean onContextItemSelected(MenuItem item) {
1203 // chording is not an issue with context menus, but we use the same
1204 // options selector, so set mCanChord to true so we can access them.
1205 mCanChord = true;
1206 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001207 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001208 // For the context menu from the title bar
1209 case R.id.title_bar_share_page_url:
1210 case R.id.title_bar_copy_page_url:
1211 WebView mainView = mTabControl.getCurrentWebView();
1212 if (null == mainView) {
1213 return false;
1214 }
1215 if (id == R.id.title_bar_share_page_url) {
1216 Browser.sendString(this, mainView.getUrl());
1217 } else {
1218 copy(mainView.getUrl());
1219 }
1220 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001221 // -- Browser context menu
1222 case R.id.open_context_menu_id:
1223 case R.id.open_newtab_context_menu_id:
1224 case R.id.bookmark_context_menu_id:
1225 case R.id.save_link_context_menu_id:
1226 case R.id.share_link_context_menu_id:
1227 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001228 final WebView webView = getTopWindow();
1229 if (null == webView) {
1230 return false;
1231 }
1232 final HashMap hrefMap = new HashMap();
1233 hrefMap.put("webview", webView);
1234 final Message msg = mHandler.obtainMessage(
1235 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001236 webView.requestFocusNodeHref(msg);
1237 break;
1238
1239 default:
1240 // For other context menus
1241 return onOptionsItemSelected(item);
1242 }
1243 mCanChord = false;
1244 return true;
1245 }
1246
1247 private Bundle createGoogleSearchSourceBundle(String source) {
1248 Bundle bundle = new Bundle();
1249 bundle.putString(SearchManager.SOURCE, source);
1250 return bundle;
1251 }
1252
1253 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001254 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001255 */
1256 @Override
1257 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001258 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001259 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001260 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001261 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001262 return true;
1263 }
1264
1265 @Override
1266 public void startSearch(String initialQuery, boolean selectInitialQuery,
1267 Bundle appSearchData, boolean globalSearch) {
1268 if (appSearchData == null) {
1269 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1270 }
1271 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1272 }
1273
Leon Scroggins1f005d32009-08-10 17:36:42 -04001274 /**
1275 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1276 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001277 * @param index Index of the tab to change to, as defined by
1278 * mTabControl.getTabIndex(Tab t).
1279 * @return boolean True if we successfully switched to a different tab. If
1280 * the indexth tab is null, or if that tab is the same as
1281 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001282 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001283 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001284 Tab tab = mTabControl.getTab(index);
1285 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001286 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001287 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001288 }
1289 if (currentTab != null) {
1290 // currentTab may be null if it was just removed. In that case,
1291 // we do not need to remove it
1292 removeTabFromContentView(currentTab);
1293 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001294 mTabControl.setCurrentTab(tab);
1295 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001296 resetTitleIconAndProgress();
1297 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001298 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001299 }
1300
Grace Kloba22ac16e2009-10-07 18:00:23 -07001301 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001302 return openTabAndShow(mSettings.getHomePage(), false, null);
1303 }
1304
Leon Scroggins1f005d32009-08-10 17:36:42 -04001305 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001306 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001307 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001308 // This is the last tab. Open a new one, with the home
1309 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001310 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001311 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001312 return;
1313 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001314 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001315 int indexToShow = -1;
1316 if (parent != null) {
1317 indexToShow = mTabControl.getTabIndex(parent);
1318 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001319 final int currentIndex = mTabControl.getCurrentIndex();
1320 // Try to move to the tab to the right
1321 indexToShow = currentIndex + 1;
1322 if (indexToShow > mTabControl.getTabCount() - 1) {
1323 // Try to move to the tab to the left
1324 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001325 }
1326 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001327 if (switchToTab(indexToShow)) {
1328 // Close window
1329 closeTab(current);
1330 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001331 }
1332
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001333 private ActiveTabsPage mActiveTabsPage;
1334
1335 /**
1336 * Remove the active tabs page.
1337 * @param needToAttach If true, the active tabs page did not attach a tab
1338 * to the content view, so we need to do that here.
1339 */
1340 /* package */ void removeActiveTabPage(boolean needToAttach) {
1341 mContentView.removeView(mActiveTabsPage);
1342 mActiveTabsPage = null;
1343 mMenuState = R.id.MAIN_MENU;
1344 if (needToAttach) {
1345 attachTabToContentView(mTabControl.getCurrentTab());
1346 }
1347 getTopWindow().requestFocus();
1348 }
1349
The Android Open Source Project0c908882009-03-03 19:32:16 -08001350 @Override
1351 public boolean onOptionsItemSelected(MenuItem item) {
1352 if (!mCanChord) {
1353 // The user has already fired a shortcut with this hold down of the
1354 // menu key.
1355 return false;
1356 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001357 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001358 return false;
1359 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001360 if (mMenuIsDown) {
1361 // The shortcut action consumes the MENU. Even if it is still down,
1362 // it won't trigger the next shortcut action. In the case of the
1363 // shortcut action triggering a new activity, like Bookmarks, we
1364 // won't get onKeyUp for MENU. So it is important to reset it here.
1365 mMenuIsDown = false;
1366 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001367 switch (item.getItemId()) {
1368 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001369 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001370 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001371 break;
1372
Leon Scroggins64b80f32009-08-07 12:03:34 -04001373 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001374 onSearchRequested();
1375 break;
1376
1377 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001378 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001379 break;
1380
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001381 case R.id.active_tabs_menu_id:
1382 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1383 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001384 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001385 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1386 mActiveTabsPage.requestFocus();
1387 mMenuState = EMPTY_MENU;
1388 break;
1389
Leon Scroggins1f005d32009-08-10 17:36:42 -04001390 case R.id.add_bookmark_menu_id:
1391 Intent i = new Intent(BrowserActivity.this,
1392 AddBookmarkPage.class);
1393 WebView w = getTopWindow();
1394 i.putExtra("url", w.getUrl());
1395 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001396 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001397 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001398 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001399 break;
1400
1401 case R.id.stop_reload_menu_id:
1402 if (mInLoad) {
1403 stopLoading();
1404 } else {
1405 getTopWindow().reload();
1406 }
1407 break;
1408
1409 case R.id.back_menu_id:
1410 getTopWindow().goBack();
1411 break;
1412
1413 case R.id.forward_menu_id:
1414 getTopWindow().goForward();
1415 break;
1416
1417 case R.id.close_menu_id:
1418 // Close the subwindow if it exists.
1419 if (mTabControl.getCurrentSubWindow() != null) {
1420 dismissSubWindow(mTabControl.getCurrentTab());
1421 break;
1422 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001423 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001424 break;
1425
1426 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001427 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001428 if (current != null) {
1429 dismissSubWindow(current);
1430 current.getWebView().loadUrl(mSettings.getHomePage());
1431 }
1432 break;
1433
1434 case R.id.preferences_menu_id:
1435 Intent intent = new Intent(this,
1436 BrowserPreferencesPage.class);
1437 startActivityForResult(intent, PREFERENCES_PAGE);
1438 break;
1439
1440 case R.id.find_menu_id:
1441 if (null == mFindDialog) {
1442 mFindDialog = new FindDialog(this);
1443 }
1444 mFindDialog.setWebView(getTopWindow());
1445 mFindDialog.show();
1446 mMenuState = EMPTY_MENU;
1447 break;
1448
1449 case R.id.select_text_id:
1450 getTopWindow().emulateShiftHeld();
1451 break;
1452 case R.id.page_info_menu_id:
1453 showPageInfo(mTabControl.getCurrentTab(), false);
1454 break;
1455
1456 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001457 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001458 break;
1459
1460 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001461 Browser.sendString(this, getTopWindow().getUrl(),
1462 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001463 break;
1464
1465 case R.id.dump_nav_menu_id:
1466 getTopWindow().debugDump();
1467 break;
1468
1469 case R.id.zoom_in_menu_id:
1470 getTopWindow().zoomIn();
1471 break;
1472
1473 case R.id.zoom_out_menu_id:
1474 getTopWindow().zoomOut();
1475 break;
1476
1477 case R.id.view_downloads_menu_id:
1478 viewDownloads(null);
1479 break;
1480
The Android Open Source Project0c908882009-03-03 19:32:16 -08001481 case R.id.window_one_menu_id:
1482 case R.id.window_two_menu_id:
1483 case R.id.window_three_menu_id:
1484 case R.id.window_four_menu_id:
1485 case R.id.window_five_menu_id:
1486 case R.id.window_six_menu_id:
1487 case R.id.window_seven_menu_id:
1488 case R.id.window_eight_menu_id:
1489 {
1490 int menuid = item.getItemId();
1491 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1492 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001493 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001494 if (desiredTab != null &&
1495 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001496 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001497 }
1498 break;
1499 }
1500 }
1501 }
1502 break;
1503
1504 default:
1505 if (!super.onOptionsItemSelected(item)) {
1506 return false;
1507 }
1508 // Otherwise fall through.
1509 }
1510 mCanChord = false;
1511 return true;
1512 }
1513
1514 public void closeFind() {
1515 mMenuState = R.id.MAIN_MENU;
1516 }
1517
Grace Kloba22ac16e2009-10-07 18:00:23 -07001518 @Override
1519 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001520 // This happens when the user begins to hold down the menu key, so
1521 // allow them to chord to get a shortcut.
1522 mCanChord = true;
1523 // Note: setVisible will decide whether an item is visible; while
1524 // setEnabled() will decide whether an item is enabled, which also means
1525 // whether the matching shortcut key will function.
1526 super.onPrepareOptionsMenu(menu);
1527 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001528 case EMPTY_MENU:
1529 if (mCurrentMenuState != mMenuState) {
1530 menu.setGroupVisible(R.id.MAIN_MENU, false);
1531 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1532 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001533 }
1534 break;
1535 default:
1536 if (mCurrentMenuState != mMenuState) {
1537 menu.setGroupVisible(R.id.MAIN_MENU, true);
1538 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1539 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001540 }
1541 final WebView w = getTopWindow();
1542 boolean canGoBack = false;
1543 boolean canGoForward = false;
1544 boolean isHome = false;
1545 if (w != null) {
1546 canGoBack = w.canGoBack();
1547 canGoForward = w.canGoForward();
1548 isHome = mSettings.getHomePage().equals(w.getUrl());
1549 }
1550 final MenuItem back = menu.findItem(R.id.back_menu_id);
1551 back.setEnabled(canGoBack);
1552
1553 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1554 home.setEnabled(!isHome);
1555
1556 menu.findItem(R.id.forward_menu_id)
1557 .setEnabled(canGoForward);
1558
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001559 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001560 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001561
The Android Open Source Project0c908882009-03-03 19:32:16 -08001562 // decide whether to show the share link option
1563 PackageManager pm = getPackageManager();
1564 Intent send = new Intent(Intent.ACTION_SEND);
1565 send.setType("text/plain");
1566 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1567 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1568
The Android Open Source Project0c908882009-03-03 19:32:16 -08001569 boolean isNavDump = mSettings.isNavDump();
1570 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1571 nav.setVisible(isNavDump);
1572 nav.setEnabled(isNavDump);
1573 break;
1574 }
1575 mCurrentMenuState = mMenuState;
1576 return true;
1577 }
1578
1579 @Override
1580 public void onCreateContextMenu(ContextMenu menu, View v,
1581 ContextMenuInfo menuInfo) {
1582 WebView webview = (WebView) v;
1583 WebView.HitTestResult result = webview.getHitTestResult();
1584 if (result == null) {
1585 return;
1586 }
1587
1588 int type = result.getType();
1589 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1590 Log.w(LOGTAG,
1591 "We should not show context menu when nothing is touched");
1592 return;
1593 }
1594 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1595 // let TextView handles context menu
1596 return;
1597 }
1598
1599 // Note, http://b/issue?id=1106666 is requesting that
1600 // an inflated menu can be used again. This is not available
1601 // yet, so inflate each time (yuk!)
1602 MenuInflater inflater = getMenuInflater();
1603 inflater.inflate(R.menu.browsercontext, menu);
1604
1605 // Show the correct menu group
1606 String extra = result.getExtra();
1607 menu.setGroupVisible(R.id.PHONE_MENU,
1608 type == WebView.HitTestResult.PHONE_TYPE);
1609 menu.setGroupVisible(R.id.EMAIL_MENU,
1610 type == WebView.HitTestResult.EMAIL_TYPE);
1611 menu.setGroupVisible(R.id.GEO_MENU,
1612 type == WebView.HitTestResult.GEO_TYPE);
1613 menu.setGroupVisible(R.id.IMAGE_MENU,
1614 type == WebView.HitTestResult.IMAGE_TYPE
1615 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1616 menu.setGroupVisible(R.id.ANCHOR_MENU,
1617 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1618 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1619
1620 // Setup custom handling depending on the type
1621 switch (type) {
1622 case WebView.HitTestResult.PHONE_TYPE:
1623 menu.setHeaderTitle(Uri.decode(extra));
1624 menu.findItem(R.id.dial_context_menu_id).setIntent(
1625 new Intent(Intent.ACTION_VIEW, Uri
1626 .parse(WebView.SCHEME_TEL + extra)));
1627 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1628 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001629 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001630 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1631 addIntent);
1632 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1633 new Copy(extra));
1634 break;
1635
1636 case WebView.HitTestResult.EMAIL_TYPE:
1637 menu.setHeaderTitle(extra);
1638 menu.findItem(R.id.email_context_menu_id).setIntent(
1639 new Intent(Intent.ACTION_VIEW, Uri
1640 .parse(WebView.SCHEME_MAILTO + extra)));
1641 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1642 new Copy(extra));
1643 break;
1644
1645 case WebView.HitTestResult.GEO_TYPE:
1646 menu.setHeaderTitle(extra);
1647 menu.findItem(R.id.map_context_menu_id).setIntent(
1648 new Intent(Intent.ACTION_VIEW, Uri
1649 .parse(WebView.SCHEME_GEO
1650 + URLEncoder.encode(extra))));
1651 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1652 new Copy(extra));
1653 break;
1654
1655 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1656 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1657 TextView titleView = (TextView) LayoutInflater.from(this)
1658 .inflate(android.R.layout.browser_link_context_header,
1659 null);
1660 titleView.setText(extra);
1661 menu.setHeaderView(titleView);
1662 // decide whether to show the open link in new tab option
1663 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001664 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001665 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1666 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001667 PackageManager pm = getPackageManager();
1668 Intent send = new Intent(Intent.ACTION_SEND);
1669 send.setType("text/plain");
1670 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1671 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1672 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1673 break;
1674 }
1675 // otherwise fall through to handle image part
1676 case WebView.HitTestResult.IMAGE_TYPE:
1677 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1678 menu.setHeaderTitle(extra);
1679 }
1680 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1681 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1682 menu.findItem(R.id.download_context_menu_id).
1683 setOnMenuItemClickListener(new Download(extra));
1684 break;
1685
1686 default:
1687 Log.w(LOGTAG, "We should not get here.");
1688 break;
1689 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001690 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001691 }
1692
The Android Open Source Project0c908882009-03-03 19:32:16 -08001693 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001694 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001695 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001696 // Attach the container that contains the main WebView and any other UI
1697 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001698 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001699
1700 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001701 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001702 if (errorConsole.numberOfErrors() == 0) {
1703 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1704 } else {
1705 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1706 }
1707
1708 mErrorConsoleContainer.addView(errorConsole,
1709 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1710 ViewGroup.LayoutParams.WRAP_CONTENT));
1711 }
1712
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001713 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001714 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001715 // Request focus on the top window.
1716 t.getTopWindow().requestFocus();
1717 }
1718
1719 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001720 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001721 t.attachSubWindow(mContentView);
1722 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001723 }
1724
1725 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001726 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001727 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001728 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001729
Grace Kloba22ac16e2009-10-07 18:00:23 -07001730 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1731 if (errorConsole != null) {
1732 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001733 }
1734
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001735 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001736 if (view != null) {
1737 view.setEmbeddedTitleBar(null);
1738 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001739 }
1740
1741 // Remove the sub window if it exists. Also called by TabControl when the
1742 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001743 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001744 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001745 // dismiss the subwindow. This will destroy the WebView.
1746 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001747 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001748 }
1749
Leon Scroggins1f005d32009-08-10 17:36:42 -04001750 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001751 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001752 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001753 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001754 }
1755
1756 // This method does a ton of stuff. It will attempt to create a new tab
1757 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001758 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001759 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1760 String appId) {
1761 final Tab currentTab = mTabControl.getCurrentTab();
1762 if (mTabControl.canCreateNewTab()) {
1763 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1764 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001765 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001766 // If the last tab was removed from the active tabs page, currentTab
1767 // will be null.
1768 if (currentTab != null) {
1769 removeTabFromContentView(currentTab);
1770 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001771 // We must set the new tab as the current tab to reflect the old
1772 // animation behavior.
1773 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001774 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001775 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001776 urlData.loadIn(webview);
1777 }
1778 return tab;
1779 } else {
1780 // Get rid of the subwindow if it exists
1781 dismissSubWindow(currentTab);
1782 if (!urlData.isEmpty()) {
1783 // Load the given url.
1784 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001785 }
1786 }
Grace Klobac9181842009-04-14 08:53:22 -07001787 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001788 }
1789
Grace Kloba22ac16e2009-10-07 18:00:23 -07001790 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001791 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001792 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001793 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001794 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001795 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001796 }
Grace Klobac9181842009-04-14 08:53:22 -07001797 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001798 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001799 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001800 }
1801 }
1802
1803 private class Copy implements OnMenuItemClickListener {
1804 private CharSequence mText;
1805
1806 public boolean onMenuItemClick(MenuItem item) {
1807 copy(mText);
1808 return true;
1809 }
1810
1811 public Copy(CharSequence toCopy) {
1812 mText = toCopy;
1813 }
1814 }
1815
1816 private class Download implements OnMenuItemClickListener {
1817 private String mText;
1818
1819 public boolean onMenuItemClick(MenuItem item) {
1820 onDownloadStartNoStream(mText, null, null, null, -1);
1821 return true;
1822 }
1823
1824 public Download(String toDownload) {
1825 mText = toDownload;
1826 }
1827 }
1828
1829 private void copy(CharSequence text) {
1830 try {
1831 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1832 if (clip != null) {
1833 clip.setClipboardText(text);
1834 }
1835 } catch (android.os.RemoteException e) {
1836 Log.e(LOGTAG, "Copy failed", e);
1837 }
1838 }
1839
1840 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001841 * Resets the browser title-view to whatever it must be
1842 * (for example, if we had a loading error)
1843 * When we have a new page, we call resetTitle, when we
1844 * have to reset the titlebar to whatever it used to be
1845 * (for example, if the user chose to stop loading), we
1846 * call resetTitleAndRevertLockIcon.
1847 */
1848 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001849 mTabControl.getCurrentTab().revertLockIcon();
1850 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001851 resetTitleIconAndProgress();
1852 }
1853
1854 /**
1855 * Reset the title, favicon, and progress.
1856 */
1857 private void resetTitleIconAndProgress() {
1858 WebView current = mTabControl.getCurrentWebView();
1859 if (current == null) {
1860 return;
1861 }
1862 resetTitleAndIcon(current);
1863 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001864 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001865 }
1866
1867 // Reset the title and the icon based on the given item.
1868 private void resetTitleAndIcon(WebView view) {
1869 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1870 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001871 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001872 setFavicon(item.getFavicon());
1873 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001874 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001875 setFavicon(null);
1876 }
1877 }
1878
1879 /**
1880 * Sets a title composed of the URL and the title string.
1881 * @param url The URL of the site being loaded.
1882 * @param title The title of the site being loaded.
1883 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001884 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001885 mUrl = url;
1886 mTitle = title;
1887
Leon Scroggins68579392009-09-15 15:31:54 -04001888 mTitleBar.setTitleAndUrl(title, url);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001889 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001890 }
1891
1892 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001893 * @param url The URL to build a title version of the URL from.
1894 * @return The title version of the URL or null if fails.
1895 * The title version of the URL can be either the URL hostname,
1896 * or the hostname with an "https://" prefix (for secure URLs),
1897 * or an empty string if, for example, the URL in question is a
1898 * file:// URL with no hostname.
1899 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001900 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001901 String titleUrl = null;
1902
1903 if (url != null) {
1904 try {
1905 // parse the url string
1906 URL urlObj = new URL(url);
1907 if (urlObj != null) {
1908 titleUrl = "";
1909
1910 String protocol = urlObj.getProtocol();
1911 String host = urlObj.getHost();
1912
1913 if (host != null && 0 < host.length()) {
1914 titleUrl = host;
1915 if (protocol != null) {
1916 // if a secure site, add an "https://" prefix!
1917 if (protocol.equalsIgnoreCase("https")) {
1918 titleUrl = protocol + "://" + host;
1919 }
1920 }
1921 }
1922 }
1923 } catch (MalformedURLException e) {}
1924 }
1925
1926 return titleUrl;
1927 }
1928
1929 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001930 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04001931 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001932 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001933 }
1934
1935 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001936 * Close the tab, remove its associated title bar, and adjust mTabControl's
1937 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001938 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001939 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001940 int currentIndex = mTabControl.getCurrentIndex();
1941 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001942 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001943 if (currentIndex >= removeIndex && currentIndex != 0) {
1944 currentIndex--;
1945 }
1946 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01001947 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001948 }
1949
1950 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001951 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001952 if (current == null) {
1953 /*
1954 * Instead of finishing the activity, simply push this to the back
1955 * of the stack and let ActivityManager to choose the foreground
1956 * activity. As BrowserActivity is singleTask, it will be always the
1957 * root of the task. So we can use either true or false for
1958 * moveTaskToBack().
1959 */
1960 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07001961 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001962 }
1963 WebView w = current.getWebView();
1964 if (w.canGoBack()) {
1965 w.goBack();
1966 } else {
1967 // Check to see if we are closing a window that was created by
1968 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001969 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001970 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001971 switchToTab(mTabControl.getTabIndex(parent));
1972 // Now we close the other tab
1973 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001974 } else {
1975 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001976 // force the tab's inLoad() to be false as we are going to
1977 // either finish the activity or remove the tab. This will
1978 // ensure pauseWebViewTimers() taking action.
1979 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001980 if (mTabControl.getTabCount() == 1) {
1981 finish();
1982 return;
1983 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04001984 // call pauseWebViewTimers() now, we won't be able to call
1985 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07001986 // Temporarily change mActivityInPause to be true as
1987 // pauseWebViewTimers() will do nothing if mActivityInPause
1988 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07001989 boolean savedState = mActivityInPause;
1990 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07001991 Log.e(LOGTAG, "BrowserActivity is already paused "
1992 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07001993 }
1994 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001995 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07001996 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001997 removeTabFromContentView(current);
1998 mTabControl.removeTab(current);
1999 }
2000 /*
2001 * Instead of finishing the activity, simply push this to the back
2002 * of the stack and let ActivityManager to choose the foreground
2003 * activity. As BrowserActivity is singleTask, it will be always the
2004 * root of the task. So we can use either true or false for
2005 * moveTaskToBack().
2006 */
2007 moveTaskToBack(true);
2008 }
2009 }
2010 }
2011
Grace Kloba22ac16e2009-10-07 18:00:23 -07002012 boolean isMenuDown() {
2013 return mMenuIsDown;
2014 }
2015
Grace Kloba5942df02009-09-18 11:48:29 -07002016 @Override
2017 public boolean onKeyDown(int keyCode, KeyEvent event) {
2018 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2019 // still down, we don't want to trigger the search. Pretend to consume
2020 // the key and do nothing.
2021 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002022
Grace Kloba5942df02009-09-18 11:48:29 -07002023 switch(keyCode) {
2024 case KeyEvent.KEYCODE_MENU:
2025 mMenuIsDown = true;
2026 break;
2027 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002028 // WebView/WebTextView handle the keys in the KeyDown. As
2029 // the Activity's shortcut keys are only handled when WebView
2030 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2031 if (event.isShiftPressed()) {
2032 getTopWindow().pageUp(false);
2033 } else {
2034 getTopWindow().pageDown(false);
2035 }
Grace Kloba5942df02009-09-18 11:48:29 -07002036 return true;
2037 case KeyEvent.KEYCODE_BACK:
2038 if (event.getRepeatCount() == 0) {
2039 event.startTracking();
2040 return true;
2041 } else if (mCustomView == null && mActiveTabsPage == null
2042 && event.isLongPress()) {
2043 bookmarksOrHistoryPicker(true);
2044 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002045 }
Grace Kloba5942df02009-09-18 11:48:29 -07002046 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002047 }
Grace Kloba5942df02009-09-18 11:48:29 -07002048 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002049 }
2050
Grace Kloba5942df02009-09-18 11:48:29 -07002051 @Override
2052 public boolean onKeyUp(int keyCode, KeyEvent event) {
2053 switch(keyCode) {
2054 case KeyEvent.KEYCODE_MENU:
2055 mMenuIsDown = false;
2056 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002057 case KeyEvent.KEYCODE_BACK:
2058 if (event.isTracking() && !event.isCanceled()) {
2059 if (mCustomView != null) {
2060 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002061 mTabControl.getCurrentWebView().getWebChromeClient()
2062 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002063 } else if (mActiveTabsPage != null) {
2064 // if tab page is showing, hide it
2065 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002066 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002067 WebView subwindow = mTabControl.getCurrentSubWindow();
2068 if (subwindow != null) {
2069 if (subwindow.canGoBack()) {
2070 subwindow.goBack();
2071 } else {
2072 dismissSubWindow(mTabControl.getCurrentTab());
2073 }
2074 } else {
2075 goBackOnePageOrQuit();
2076 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002077 }
Grace Kloba5942df02009-09-18 11:48:29 -07002078 return true;
2079 }
2080 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002081 }
Grace Kloba5942df02009-09-18 11:48:29 -07002082 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002083 }
2084
Leon Scroggins68579392009-09-15 15:31:54 -04002085 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002086 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002087 resetTitleAndRevertLockIcon();
2088 WebView w = getTopWindow();
2089 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002090 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2091 // same logic here. But for subwindow case, should we call into the main
2092 // WebView's onPageFinished as we never call its onPageStarted and if
2093 // the page finishes itself, we don't call onPageFinished.
2094 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2095 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002096
2097 cancelStopToast();
2098 mStopToast = Toast
2099 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2100 mStopToast.show();
2101 }
2102
Grace Kloba22ac16e2009-10-07 18:00:23 -07002103 boolean didUserStopLoading() {
2104 return mDidStopLoad;
2105 }
2106
The Android Open Source Project0c908882009-03-03 19:32:16 -08002107 private void cancelStopToast() {
2108 if (mStopToast != null) {
2109 mStopToast.cancel();
2110 mStopToast = null;
2111 }
2112 }
2113
Grace Kloba22ac16e2009-10-07 18:00:23 -07002114 // called by a UI or non-UI thread to post the message
2115 public void postMessage(int what, int arg1, int arg2, Object obj,
2116 long delayMillis) {
2117 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2118 obj), delayMillis);
2119 }
2120
2121 // called by a UI or non-UI thread to remove the message
2122 void removeMessages(int what, Object object) {
2123 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002124 }
2125
2126 // public message ids
2127 public final static int LOAD_URL = 1001;
2128 public final static int STOP_LOAD = 1002;
2129
2130 // Message Ids
2131 private static final int FOCUS_NODE_HREF = 102;
2132 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002133 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002134
Grace Kloba22ac16e2009-10-07 18:00:23 -07002135 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002136
The Android Open Source Project0c908882009-03-03 19:32:16 -08002137 // Private handler for handling javascript and saving passwords
2138 private Handler mHandler = new Handler() {
2139
2140 public void handleMessage(Message msg) {
2141 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002142 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002143 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002144 String url = (String) msg.getData().get("url");
2145 if (url == null || url.length() == 0) {
2146 break;
2147 }
2148 HashMap focusNodeMap = (HashMap) msg.obj;
2149 WebView view = (WebView) focusNodeMap.get("webview");
2150 // Only apply the action if the top window did not change.
2151 if (getTopWindow() != view) {
2152 break;
2153 }
2154 switch (msg.arg1) {
2155 case R.id.open_context_menu_id:
2156 case R.id.view_image_context_menu_id:
2157 loadURL(getTopWindow(), url);
2158 break;
2159 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002160 final Tab parent = mTabControl.getCurrentTab();
2161 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002162 if (newTab != parent) {
2163 parent.addChildTab(newTab);
2164 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002165 break;
2166 case R.id.bookmark_context_menu_id:
2167 Intent intent = new Intent(BrowserActivity.this,
2168 AddBookmarkPage.class);
2169 intent.putExtra("url", url);
2170 startActivity(intent);
2171 break;
2172 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002173 Browser.sendString(BrowserActivity.this, url,
2174 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002175 break;
2176 case R.id.copy_link_context_menu_id:
2177 copy(url);
2178 break;
2179 case R.id.save_link_context_menu_id:
2180 case R.id.download_context_menu_id:
2181 onDownloadStartNoStream(url, null, null, null, -1);
2182 break;
2183 }
2184 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002185 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002186
2187 case LOAD_URL:
2188 loadURL(getTopWindow(), (String) msg.obj);
2189 break;
2190
2191 case STOP_LOAD:
2192 stopLoading();
2193 break;
2194
2195 case CANCEL_CREDS_REQUEST:
2196 resumeAfterCredentials();
2197 break;
2198
The Android Open Source Project0c908882009-03-03 19:32:16 -08002199 case RELEASE_WAKELOCK:
2200 if (mWakeLock.isHeld()) {
2201 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002202 // if we reach here, Browser should be still in the
2203 // background loading after WAKELOCK_TIMEOUT (5-min).
2204 // To avoid burning the battery, stop loading.
2205 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002206 }
2207 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002208
2209 case UPDATE_BOOKMARK_THUMBNAIL:
2210 WebView view = (WebView) msg.obj;
2211 if (view != null) {
2212 updateScreenshot(view);
2213 }
2214 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002215 }
2216 }
2217 };
2218
Leon Scroggins89c6d362009-07-15 16:54:37 -04002219 private void updateScreenshot(WebView view) {
2220 // If this is a bookmarked site, add a screenshot to the database.
2221 // FIXME: When should we update? Every time?
2222 // FIXME: Would like to make sure there is actually something to
2223 // draw, but the API for that (WebViewCore.pictureReady()) is not
2224 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002225
Patrick Scott3918d442009-08-04 13:22:29 -04002226 ContentResolver cr = getContentResolver();
2227 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002228 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002229 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002230 boolean succeed = c.moveToFirst();
2231 ContentValues values = null;
2232 while (succeed) {
2233 if (values == null) {
2234 final ByteArrayOutputStream os
2235 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002236 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002237 if (bm == null) {
2238 c.close();
2239 return;
2240 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002241 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2242 values = new ContentValues();
2243 values.put(Browser.BookmarkColumns.THUMBNAIL,
2244 os.toByteArray());
2245 }
2246 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2247 c.getInt(0)), values, null, null);
2248 succeed = c.moveToNext();
2249 }
2250 c.close();
2251 }
2252 }
2253
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002254 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002255 * Values for the size of the thumbnail created when taking a screenshot.
2256 * Lazily initialized. Instead of using these directly, use
2257 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002258 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002259 private static int THUMBNAIL_WIDTH = 0;
2260 private static int THUMBNAIL_HEIGHT = 0;
2261
2262 /**
2263 * Return the desired width for thumbnail screenshots, which are stored in
2264 * the database, and used on the bookmarks screen.
2265 * @param context Context for finding out the density of the screen.
2266 * @return int desired width for thumbnail screenshot.
2267 */
2268 /* package */ static int getDesiredThumbnailWidth(Context context) {
2269 if (THUMBNAIL_WIDTH == 0) {
2270 float density = context.getResources().getDisplayMetrics().density;
2271 THUMBNAIL_WIDTH = (int) (90 * density);
2272 THUMBNAIL_HEIGHT = (int) (80 * density);
2273 }
2274 return THUMBNAIL_WIDTH;
2275 }
2276
2277 /**
2278 * Return the desired height for thumbnail screenshots, which are stored in
2279 * the database, and used on the bookmarks screen.
2280 * @param context Context for finding out the density of the screen.
2281 * @return int desired height for thumbnail screenshot.
2282 */
2283 /* package */ static int getDesiredThumbnailHeight(Context context) {
2284 // To ensure that they are both initialized.
2285 getDesiredThumbnailWidth(context);
2286 return THUMBNAIL_HEIGHT;
2287 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002288
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002289 private Bitmap createScreenshot(WebView view) {
2290 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002291 if (thumbnail == null) {
2292 return null;
2293 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002294 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2295 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002296 Canvas canvas = new Canvas(bm);
2297 // May need to tweak these values to determine what is the
2298 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002299 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002300 int thumbnailHeight = thumbnail.getHeight();
2301 float scaleFactorX = 1.0f;
2302 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002303 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002304 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002305 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002306 } else {
2307 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002308 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002309
2310 if (view.getWidth() > view.getHeight() &&
2311 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2312 // If the device is in landscape and the page is shorter
2313 // than the height of the view, stretch the thumbnail to fill the
2314 // space.
2315 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2316 (float)thumbnailHeight;
2317 } else {
2318 // In the portrait case, this looks nice.
2319 scaleFactorY = scaleFactorX;
2320 }
2321
2322 canvas.scale(scaleFactorX, scaleFactorY);
2323
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002324 thumbnail.draw(canvas);
2325 return bm;
2326 }
2327
The Android Open Source Project0c908882009-03-03 19:32:16 -08002328 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002329 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002330 //-------------------------------------------------------------------------
2331
2332 // Use in overrideUrlLoading
2333 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2334 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2335 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2336 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2337
Grace Kloba22ac16e2009-10-07 18:00:23 -07002338 void onPageStarted(WebView view, String url, Bitmap favicon) {
2339 // when BrowserActivity just starts, onPageStarted may be called before
2340 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2341 // to start the timer. As we won't switch tabs while an activity is in
2342 // pause state, we can ensure calling resume and pause in pair.
2343 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002344
Grace Kloba22ac16e2009-10-07 18:00:23 -07002345 resetLockIcon(url);
2346 setUrlTitle(url, null);
2347 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002348 // Keep this initial progress in sync with initialProgressValue (* 100)
2349 // in ProgressTracker.cpp
2350 // Show some progress so that the user knows the page is beginning to
2351 // load
2352 onProgressChanged(view, 10);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002353 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002354 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002355
Grace Kloba22ac16e2009-10-07 18:00:23 -07002356 if (mSettings.isTracing()) {
2357 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002358 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002359 WebAddress uri = new WebAddress(url);
2360 host = uri.mHost;
2361 } catch (android.net.ParseException ex) {
2362 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002363 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002364 host = host.replace('.', '_');
2365 host += ".trace";
2366 mInTrace = true;
2367 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2368 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002369
Grace Kloba22ac16e2009-10-07 18:00:23 -07002370 // Performance probe
2371 if (false) {
2372 mStart = SystemClock.uptimeMillis();
2373 mProcessStart = Process.getElapsedCpuTime();
2374 long[] sysCpu = new long[7];
2375 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2376 sysCpu, null)) {
2377 mUserStart = sysCpu[0] + sysCpu[1];
2378 mSystemStart = sysCpu[2];
2379 mIdleStart = sysCpu[3];
2380 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2381 }
2382 mUiStart = SystemClock.currentThreadTimeMillis();
2383 }
2384 }
2385
2386 void onPageFinished(WebView view, String url) {
2387 // Reset the title and icon in case we stopped a provisional load.
2388 resetTitleAndIcon(view);
2389 // Update the lock icon image only once we are done loading
2390 updateLockIconToLatest();
2391 // pause the WebView timer and release the wake lock if it is finished
2392 // while BrowserActivity is in pause state.
2393 if (mActivityInPause && pauseWebViewTimers()) {
2394 if (mWakeLock.isHeld()) {
2395 mHandler.removeMessages(RELEASE_WAKELOCK);
2396 mWakeLock.release();
2397 }
2398 }
2399
2400 // Performance probe
2401 if (false) {
2402 long[] sysCpu = new long[7];
2403 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2404 sysCpu, null)) {
2405 String uiInfo = "UI thread used "
2406 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2407 + " ms";
2408 if (LOGD_ENABLED) {
2409 Log.d(LOGTAG, uiInfo);
2410 }
2411 //The string that gets written to the log
2412 String performanceString = "It took total "
2413 + (SystemClock.uptimeMillis() - mStart)
2414 + " ms clock time to load the page."
2415 + "\nbrowser process used "
2416 + (Process.getElapsedCpuTime() - mProcessStart)
2417 + " ms, user processes used "
2418 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2419 + " ms, kernel used "
2420 + (sysCpu[2] - mSystemStart) * 10
2421 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2422 + " ms and irq took "
2423 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2424 * 10 + " ms, " + uiInfo;
2425 if (LOGD_ENABLED) {
2426 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2427 }
2428 if (url != null) {
2429 // strip the url to maintain consistency
2430 String newUrl = new String(url);
2431 if (newUrl.startsWith("http://www.")) {
2432 newUrl = newUrl.substring(11);
2433 } else if (newUrl.startsWith("http://")) {
2434 newUrl = newUrl.substring(7);
2435 } else if (newUrl.startsWith("https://www.")) {
2436 newUrl = newUrl.substring(12);
2437 } else if (newUrl.startsWith("https://")) {
2438 newUrl = newUrl.substring(8);
2439 }
2440 if (LOGD_ENABLED) {
2441 Log.d(LOGTAG, newUrl + " loaded");
2442 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002443 }
2444 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002445 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002446
Grace Kloba22ac16e2009-10-07 18:00:23 -07002447 if (mInTrace) {
2448 mInTrace = false;
2449 Debug.stopMethodTracing();
2450 }
2451 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002452
Grace Kloba22ac16e2009-10-07 18:00:23 -07002453 boolean shouldOverrideUrlLoading(WebView view, String url) {
2454 if (url.startsWith(SCHEME_WTAI)) {
2455 // wtai://wp/mc;number
2456 // number=string(phone-number)
2457 if (url.startsWith(SCHEME_WTAI_MC)) {
2458 Intent intent = new Intent(Intent.ACTION_VIEW,
2459 Uri.parse(WebView.SCHEME_TEL +
2460 url.substring(SCHEME_WTAI_MC.length())));
2461 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002462 return true;
2463 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002464 // wtai://wp/sd;dtmf
2465 // dtmf=string(dialstring)
2466 if (url.startsWith(SCHEME_WTAI_SD)) {
2467 // TODO: only send when there is active voice connection
2468 return false;
2469 }
2470 // wtai://wp/ap;number;name
2471 // number=string(phone-number)
2472 // name=string
2473 if (url.startsWith(SCHEME_WTAI_AP)) {
2474 // TODO
2475 return false;
2476 }
2477 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002478
Grace Kloba22ac16e2009-10-07 18:00:23 -07002479 // The "about:" schemes are internal to the browser; don't want these to
2480 // be dispatched to other apps.
2481 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002482 return false;
2483 }
2484
Grace Kloba22ac16e2009-10-07 18:00:23 -07002485 Intent intent;
2486 // perform generic parsing of the URI to turn it into an Intent.
2487 try {
2488 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2489 } catch (URISyntaxException ex) {
2490 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2491 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002492 }
2493
Grace Kloba22ac16e2009-10-07 18:00:23 -07002494 // check whether the intent can be resolved. If not, we will see
2495 // whether we can download it from the Market.
2496 if (getPackageManager().resolveActivity(intent, 0) == null) {
2497 String packagename = intent.getPackage();
2498 if (packagename != null) {
2499 intent = new Intent(Intent.ACTION_VIEW, Uri
2500 .parse("market://search?q=pname:" + packagename));
2501 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2502 startActivity(intent);
2503 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002504 } else {
2505 return false;
2506 }
2507 }
2508
Grace Kloba22ac16e2009-10-07 18:00:23 -07002509 // sanitize the Intent, ensuring web pages can not bypass browser
2510 // security (only access to BROWSABLE activities).
2511 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2512 intent.setComponent(null);
2513 try {
2514 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002515 return true;
2516 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002517 } catch (ActivityNotFoundException ex) {
2518 // ignore the error. If no application can handle the URL,
2519 // eg about:blank, assume the browser can handle it.
2520 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002521
Grace Kloba22ac16e2009-10-07 18:00:23 -07002522 if (mMenuIsDown) {
2523 openTab(url);
2524 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002525 return true;
2526 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002527 return false;
2528 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002529
Grace Kloba22ac16e2009-10-07 18:00:23 -07002530 // -------------------------------------------------------------------------
2531 // Helper function for WebChromeClient
2532 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002533
Grace Kloba22ac16e2009-10-07 18:00:23 -07002534 void onProgressChanged(WebView view, int newProgress) {
2535 mTitleBar.setProgress(newProgress);
2536 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002537
Grace Kloba22ac16e2009-10-07 18:00:23 -07002538 if (newProgress == 100) {
2539 // onProgressChanged() may continue to be called after the main
2540 // frame has finished loading, as any remaining sub frames continue
2541 // to load. We'll only get called once though with newProgress as
2542 // 100 when everything is loaded. (onPageFinished is called once
2543 // when the main frame completes loading regardless of the state of
2544 // any sub frames so calls to onProgressChanges may continue after
2545 // onPageFinished has executed)
2546 if (mInLoad) {
2547 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002548 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002549 // If the options menu is open, leave the title bar
2550 if (!mOptionsMenuOpen || !mIconView) {
2551 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002552 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002553 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002554 } else if (!mInLoad) {
2555 // onPageFinished may have already been called but a subframe is
2556 // still loading and updating the progress. Reset mInLoad and update
2557 // the menu items.
2558 mInLoad = true;
2559 updateInLoadMenuItems();
2560 if (!mOptionsMenuOpen || mIconView) {
2561 // This page has begun to load, so show the title bar
2562 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002563 }
2564 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002565 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002566
Grace Kloba22ac16e2009-10-07 18:00:23 -07002567 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2568 if (mCustomView != null)
2569 return;
2570
2571 // Add the custom view to its container.
2572 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2573 mCustomView = view;
2574 mCustomViewCallback = callback;
2575 // Save the menu state and set it to empty while the custom
2576 // view is showing.
2577 mOldMenuState = mMenuState;
2578 mMenuState = EMPTY_MENU;
2579 // Hide the content view.
2580 mContentView.setVisibility(View.GONE);
2581 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002582 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002583 mCustomViewContainer.setVisibility(View.VISIBLE);
2584 mCustomViewContainer.bringToFront();
2585 }
2586
2587 void onHideCustomView() {
2588 if (mCustomView == null)
2589 return;
2590
2591 // Hide the custom view.
2592 mCustomView.setVisibility(View.GONE);
2593 // Remove the custom view from its container.
2594 mCustomViewContainer.removeView(mCustomView);
2595 mCustomView = null;
2596 // Reset the old menu state.
2597 mMenuState = mOldMenuState;
2598 mOldMenuState = EMPTY_MENU;
2599 mCustomViewContainer.setVisibility(View.GONE);
2600 mCustomViewCallback.onCustomViewHidden();
2601 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002602 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002603 mContentView.setVisibility(View.VISIBLE);
2604 }
2605
2606 Bitmap getDefaultVideoPoster() {
2607 if (mDefaultVideoPoster == null) {
2608 mDefaultVideoPoster = BitmapFactory.decodeResource(
2609 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002610 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002611 return mDefaultVideoPoster;
2612 }
Patrick Scott3918d442009-08-04 13:22:29 -04002613
Grace Kloba22ac16e2009-10-07 18:00:23 -07002614 View getVideoLoadingProgressView() {
2615 if (mVideoProgressView == null) {
2616 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2617 mVideoProgressView = inflater.inflate(
2618 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002619 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002620 return mVideoProgressView;
2621 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002622
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002623 /*
2624 * The Object used to inform the WebView of the file to upload.
2625 */
2626 private ValueCallback<Uri> mUploadMessage;
2627
Grace Kloba22ac16e2009-10-07 18:00:23 -07002628 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2629 if (mUploadMessage != null) return;
2630 mUploadMessage = uploadMsg;
2631 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2632 i.addCategory(Intent.CATEGORY_OPENABLE);
2633 i.setType("*/*");
2634 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2635 getString(R.string.choose_upload)), FILE_SELECTED);
2636 }
2637
2638 // -------------------------------------------------------------------------
2639 // Implement functions for DownloadListener
2640 // -------------------------------------------------------------------------
2641
The Android Open Source Project0c908882009-03-03 19:32:16 -08002642 /**
2643 * Notify the host application a download should be done, or that
2644 * the data should be streamed if a streaming viewer is available.
2645 * @param url The full url to the content that should be downloaded
2646 * @param contentDisposition Content-disposition http header, if
2647 * present.
2648 * @param mimetype The mimetype of the content reported by the server
2649 * @param contentLength The file size reported by the server
2650 */
2651 public void onDownloadStart(String url, String userAgent,
2652 String contentDisposition, String mimetype, long contentLength) {
2653 // if we're dealing wih A/V content that's not explicitly marked
2654 // for download, check if it's streamable.
2655 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002656 || !contentDisposition.regionMatches(
2657 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002658 // query the package manager to see if there's a registered handler
2659 // that matches.
2660 Intent intent = new Intent(Intent.ACTION_VIEW);
2661 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002662 ResolveInfo info = getPackageManager().resolveActivity(intent,
2663 PackageManager.MATCH_DEFAULT_ONLY);
2664 if (info != null) {
2665 ComponentName myName = getComponentName();
2666 // If we resolved to ourselves, we don't want to attempt to
2667 // load the url only to try and download it again.
2668 if (!myName.getPackageName().equals(
2669 info.activityInfo.packageName)
2670 || !myName.getClassName().equals(
2671 info.activityInfo.name)) {
2672 // someone (other than us) knows how to handle this mime
2673 // type with this scheme, don't download.
2674 try {
2675 startActivity(intent);
2676 return;
2677 } catch (ActivityNotFoundException ex) {
2678 if (LOGD_ENABLED) {
2679 Log.d(LOGTAG, "activity not found for " + mimetype
2680 + " over " + Uri.parse(url).getScheme(),
2681 ex);
2682 }
2683 // Best behavior is to fall back to a download in this
2684 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002685 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002686 }
2687 }
2688 }
2689 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2690 }
2691
2692 /**
2693 * Notify the host application a download should be done, even if there
2694 * is a streaming viewer available for thise type.
2695 * @param url The full url to the content that should be downloaded
2696 * @param contentDisposition Content-disposition http header, if
2697 * present.
2698 * @param mimetype The mimetype of the content reported by the server
2699 * @param contentLength The file size reported by the server
2700 */
2701 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2702 String contentDisposition, String mimetype, long contentLength) {
2703
2704 String filename = URLUtil.guessFileName(url,
2705 contentDisposition, mimetype);
2706
2707 // Check to see if we have an SDCard
2708 String status = Environment.getExternalStorageState();
2709 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2710 int title;
2711 String msg;
2712
2713 // Check to see if the SDCard is busy, same as the music app
2714 if (status.equals(Environment.MEDIA_SHARED)) {
2715 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2716 title = R.string.download_sdcard_busy_dlg_title;
2717 } else {
2718 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2719 title = R.string.download_no_sdcard_dlg_title;
2720 }
2721
2722 new AlertDialog.Builder(this)
2723 .setTitle(title)
2724 .setIcon(android.R.drawable.ic_dialog_alert)
2725 .setMessage(msg)
2726 .setPositiveButton(R.string.ok, null)
2727 .show();
2728 return;
2729 }
2730
2731 // java.net.URI is a lot stricter than KURL so we have to undo
2732 // KURL's percent-encoding and redo the encoding using java.net.URI.
2733 URI uri = null;
2734 try {
2735 // Undo the percent-encoding that KURL may have done.
2736 String newUrl = new String(URLUtil.decode(url.getBytes()));
2737 // Parse the url into pieces
2738 WebAddress w = new WebAddress(newUrl);
2739 String frag = null;
2740 String query = null;
2741 String path = w.mPath;
2742 // Break the path into path, query, and fragment
2743 if (path.length() > 0) {
2744 // Strip the fragment
2745 int idx = path.lastIndexOf('#');
2746 if (idx != -1) {
2747 frag = path.substring(idx + 1);
2748 path = path.substring(0, idx);
2749 }
2750 idx = path.lastIndexOf('?');
2751 if (idx != -1) {
2752 query = path.substring(idx + 1);
2753 path = path.substring(0, idx);
2754 }
2755 }
2756 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2757 query, frag);
2758 } catch (Exception e) {
2759 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2760 return;
2761 }
2762
2763 // XXX: Have to use the old url since the cookies were stored using the
2764 // old percent-encoded url.
2765 String cookies = CookieManager.getInstance().getCookie(url);
2766
2767 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002768 values.put(Downloads.COLUMN_URI, uri.toString());
2769 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
2770 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
2771 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002772 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002773 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002774 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002775 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2776 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
2777 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
2778 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002779 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002780 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002781 }
2782 if (mimetype == null) {
2783 // We must have long pressed on a link or image to download it. We
2784 // are not sure of the mimetype in this case, so do a head request
2785 new FetchUrlMimeType(this).execute(values);
2786 } else {
2787 final Uri contentUri =
2788 getContentResolver().insert(Downloads.CONTENT_URI, values);
2789 viewDownloads(contentUri);
2790 }
2791
2792 }
2793
Grace Kloba22ac16e2009-10-07 18:00:23 -07002794 // -------------------------------------------------------------------------
2795
The Android Open Source Project0c908882009-03-03 19:32:16 -08002796 /**
2797 * Resets the lock icon. This method is called when we start a new load and
2798 * know the url to be loaded.
2799 */
2800 private void resetLockIcon(String url) {
2801 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002802 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002803 updateLockIconImage(LOCK_ICON_UNSECURE);
2804 }
2805
The Android Open Source Project0c908882009-03-03 19:32:16 -08002806 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002807 * Update the lock icon to correspond to our latest state.
2808 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002809 private void updateLockIconToLatest() {
2810 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002811 }
2812
2813 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002814 * Updates the lock-icon image in the title-bar.
2815 */
2816 private void updateLockIconImage(int lockIconType) {
2817 Drawable d = null;
2818 if (lockIconType == LOCK_ICON_SECURE) {
2819 d = mSecLockIcon;
2820 } else if (lockIconType == LOCK_ICON_MIXED) {
2821 d = mMixLockIcon;
2822 }
Leon Scroggins68579392009-09-15 15:31:54 -04002823 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002824 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002825 }
2826
2827 /**
2828 * Displays a page-info dialog.
2829 * @param tab The tab to show info about
2830 * @param fromShowSSLCertificateOnError The flag that indicates whether
2831 * this dialog was opened from the SSL-certificate-on-error dialog or
2832 * not. This is important, since we need to know whether to return to
2833 * the parent dialog or simply dismiss.
2834 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002835 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002836 final boolean fromShowSSLCertificateOnError) {
2837 final LayoutInflater factory = LayoutInflater
2838 .from(this);
2839
2840 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2841
2842 final WebView view = tab.getWebView();
2843
2844 String url = null;
2845 String title = null;
2846
2847 if (view == null) {
2848 url = tab.getUrl();
2849 title = tab.getTitle();
2850 } else if (view == mTabControl.getCurrentWebView()) {
2851 // Use the cached title and url if this is the current WebView
2852 url = mUrl;
2853 title = mTitle;
2854 } else {
2855 url = view.getUrl();
2856 title = view.getTitle();
2857 }
2858
2859 if (url == null) {
2860 url = "";
2861 }
2862 if (title == null) {
2863 title = "";
2864 }
2865
2866 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2867 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2868
2869 mPageInfoView = tab;
2870 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
2871
2872 AlertDialog.Builder alertDialogBuilder =
2873 new AlertDialog.Builder(this)
2874 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2875 .setView(pageInfoView)
2876 .setPositiveButton(
2877 R.string.ok,
2878 new DialogInterface.OnClickListener() {
2879 public void onClick(DialogInterface dialog,
2880 int whichButton) {
2881 mPageInfoDialog = null;
2882 mPageInfoView = null;
2883 mPageInfoFromShowSSLCertificateOnError = null;
2884
2885 // if we came here from the SSL error dialog
2886 if (fromShowSSLCertificateOnError) {
2887 // go back to the SSL error dialog
2888 showSSLCertificateOnError(
2889 mSSLCertificateOnErrorView,
2890 mSSLCertificateOnErrorHandler,
2891 mSSLCertificateOnErrorError);
2892 }
2893 }
2894 })
2895 .setOnCancelListener(
2896 new DialogInterface.OnCancelListener() {
2897 public void onCancel(DialogInterface dialog) {
2898 mPageInfoDialog = null;
2899 mPageInfoView = null;
2900 mPageInfoFromShowSSLCertificateOnError = null;
2901
2902 // if we came here from the SSL error dialog
2903 if (fromShowSSLCertificateOnError) {
2904 // go back to the SSL error dialog
2905 showSSLCertificateOnError(
2906 mSSLCertificateOnErrorView,
2907 mSSLCertificateOnErrorHandler,
2908 mSSLCertificateOnErrorError);
2909 }
2910 }
2911 });
2912
2913 // if we have a main top-level page SSL certificate set or a certificate
2914 // error
2915 if (fromShowSSLCertificateOnError ||
2916 (view != null && view.getCertificate() != null)) {
2917 // add a 'View Certificate' button
2918 alertDialogBuilder.setNeutralButton(
2919 R.string.view_certificate,
2920 new DialogInterface.OnClickListener() {
2921 public void onClick(DialogInterface dialog,
2922 int whichButton) {
2923 mPageInfoDialog = null;
2924 mPageInfoView = null;
2925 mPageInfoFromShowSSLCertificateOnError = null;
2926
2927 // if we came here from the SSL error dialog
2928 if (fromShowSSLCertificateOnError) {
2929 // go back to the SSL error dialog
2930 showSSLCertificateOnError(
2931 mSSLCertificateOnErrorView,
2932 mSSLCertificateOnErrorHandler,
2933 mSSLCertificateOnErrorError);
2934 } else {
2935 // otherwise, display the top-most certificate from
2936 // the chain
2937 if (view.getCertificate() != null) {
2938 showSSLCertificate(tab);
2939 }
2940 }
2941 }
2942 });
2943 }
2944
2945 mPageInfoDialog = alertDialogBuilder.show();
2946 }
2947
2948 /**
2949 * Displays the main top-level page SSL certificate dialog
2950 * (accessible from the Page-Info dialog).
2951 * @param tab The tab to show certificate for.
2952 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002953 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002954 final View certificateView =
2955 inflateCertificateView(tab.getWebView().getCertificate());
2956 if (certificateView == null) {
2957 return;
2958 }
2959
2960 LayoutInflater factory = LayoutInflater.from(this);
2961
2962 final LinearLayout placeholder =
2963 (LinearLayout)certificateView.findViewById(R.id.placeholder);
2964
2965 LinearLayout ll = (LinearLayout) factory.inflate(
2966 R.layout.ssl_success, placeholder);
2967 ((TextView)ll.findViewById(R.id.success))
2968 .setText(R.string.ssl_certificate_is_valid);
2969
2970 mSSLCertificateView = tab;
2971 mSSLCertificateDialog =
2972 new AlertDialog.Builder(this)
2973 .setTitle(R.string.ssl_certificate).setIcon(
2974 R.drawable.ic_dialog_browser_certificate_secure)
2975 .setView(certificateView)
2976 .setPositiveButton(R.string.ok,
2977 new DialogInterface.OnClickListener() {
2978 public void onClick(DialogInterface dialog,
2979 int whichButton) {
2980 mSSLCertificateDialog = null;
2981 mSSLCertificateView = null;
2982
2983 showPageInfo(tab, false);
2984 }
2985 })
2986 .setOnCancelListener(
2987 new DialogInterface.OnCancelListener() {
2988 public void onCancel(DialogInterface dialog) {
2989 mSSLCertificateDialog = null;
2990 mSSLCertificateView = null;
2991
2992 showPageInfo(tab, false);
2993 }
2994 })
2995 .show();
2996 }
2997
2998 /**
2999 * Displays the SSL error certificate dialog.
3000 * @param view The target web-view.
3001 * @param handler The SSL error handler responsible for cancelling the
3002 * connection that resulted in an SSL error or proceeding per user request.
3003 * @param error The SSL error object.
3004 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003005 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003006 final WebView view, final SslErrorHandler handler, final SslError error) {
3007
3008 final View certificateView =
3009 inflateCertificateView(error.getCertificate());
3010 if (certificateView == null) {
3011 return;
3012 }
3013
3014 LayoutInflater factory = LayoutInflater.from(this);
3015
3016 final LinearLayout placeholder =
3017 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3018
3019 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3020 LinearLayout ll = (LinearLayout)factory
3021 .inflate(R.layout.ssl_warning, placeholder);
3022 ((TextView)ll.findViewById(R.id.warning))
3023 .setText(R.string.ssl_untrusted);
3024 }
3025
3026 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3027 LinearLayout ll = (LinearLayout)factory
3028 .inflate(R.layout.ssl_warning, placeholder);
3029 ((TextView)ll.findViewById(R.id.warning))
3030 .setText(R.string.ssl_mismatch);
3031 }
3032
3033 if (error.hasError(SslError.SSL_EXPIRED)) {
3034 LinearLayout ll = (LinearLayout)factory
3035 .inflate(R.layout.ssl_warning, placeholder);
3036 ((TextView)ll.findViewById(R.id.warning))
3037 .setText(R.string.ssl_expired);
3038 }
3039
3040 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3041 LinearLayout ll = (LinearLayout)factory
3042 .inflate(R.layout.ssl_warning, placeholder);
3043 ((TextView)ll.findViewById(R.id.warning))
3044 .setText(R.string.ssl_not_yet_valid);
3045 }
3046
3047 mSSLCertificateOnErrorHandler = handler;
3048 mSSLCertificateOnErrorView = view;
3049 mSSLCertificateOnErrorError = error;
3050 mSSLCertificateOnErrorDialog =
3051 new AlertDialog.Builder(this)
3052 .setTitle(R.string.ssl_certificate).setIcon(
3053 R.drawable.ic_dialog_browser_certificate_partially_secure)
3054 .setView(certificateView)
3055 .setPositiveButton(R.string.ok,
3056 new DialogInterface.OnClickListener() {
3057 public void onClick(DialogInterface dialog,
3058 int whichButton) {
3059 mSSLCertificateOnErrorDialog = null;
3060 mSSLCertificateOnErrorView = null;
3061 mSSLCertificateOnErrorHandler = null;
3062 mSSLCertificateOnErrorError = null;
3063
Grace Kloba22ac16e2009-10-07 18:00:23 -07003064 view.getWebViewClient().onReceivedSslError(
3065 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003066 }
3067 })
3068 .setNeutralButton(R.string.page_info_view,
3069 new DialogInterface.OnClickListener() {
3070 public void onClick(DialogInterface dialog,
3071 int whichButton) {
3072 mSSLCertificateOnErrorDialog = null;
3073
3074 // do not clear the dialog state: we will
3075 // need to show the dialog again once the
3076 // user is done exploring the page-info details
3077
3078 showPageInfo(mTabControl.getTabFromView(view),
3079 true);
3080 }
3081 })
3082 .setOnCancelListener(
3083 new DialogInterface.OnCancelListener() {
3084 public void onCancel(DialogInterface dialog) {
3085 mSSLCertificateOnErrorDialog = null;
3086 mSSLCertificateOnErrorView = null;
3087 mSSLCertificateOnErrorHandler = null;
3088 mSSLCertificateOnErrorError = null;
3089
Grace Kloba22ac16e2009-10-07 18:00:23 -07003090 view.getWebViewClient().onReceivedSslError(
3091 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003092 }
3093 })
3094 .show();
3095 }
3096
3097 /**
3098 * Inflates the SSL certificate view (helper method).
3099 * @param certificate The SSL certificate.
3100 * @return The resultant certificate view with issued-to, issued-by,
3101 * issued-on, expires-on, and possibly other fields set.
3102 * If the input certificate is null, returns null.
3103 */
3104 private View inflateCertificateView(SslCertificate certificate) {
3105 if (certificate == null) {
3106 return null;
3107 }
3108
3109 LayoutInflater factory = LayoutInflater.from(this);
3110
3111 View certificateView = factory.inflate(
3112 R.layout.ssl_certificate, null);
3113
3114 // issued to:
3115 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3116 if (issuedTo != null) {
3117 ((TextView) certificateView.findViewById(R.id.to_common))
3118 .setText(issuedTo.getCName());
3119 ((TextView) certificateView.findViewById(R.id.to_org))
3120 .setText(issuedTo.getOName());
3121 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3122 .setText(issuedTo.getUName());
3123 }
3124
3125 // issued by:
3126 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3127 if (issuedBy != null) {
3128 ((TextView) certificateView.findViewById(R.id.by_common))
3129 .setText(issuedBy.getCName());
3130 ((TextView) certificateView.findViewById(R.id.by_org))
3131 .setText(issuedBy.getOName());
3132 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3133 .setText(issuedBy.getUName());
3134 }
3135
3136 // issued on:
3137 String issuedOn = reformatCertificateDate(
3138 certificate.getValidNotBefore());
3139 ((TextView) certificateView.findViewById(R.id.issued_on))
3140 .setText(issuedOn);
3141
3142 // expires on:
3143 String expiresOn = reformatCertificateDate(
3144 certificate.getValidNotAfter());
3145 ((TextView) certificateView.findViewById(R.id.expires_on))
3146 .setText(expiresOn);
3147
3148 return certificateView;
3149 }
3150
3151 /**
3152 * Re-formats the certificate date (Date.toString()) string to
3153 * a properly localized date string.
3154 * @return Properly localized version of the certificate date string and
3155 * the original certificate date string if fails to localize.
3156 * If the original string is null, returns an empty string "".
3157 */
3158 private String reformatCertificateDate(String certificateDate) {
3159 String reformattedDate = null;
3160
3161 if (certificateDate != null) {
3162 Date date = null;
3163 try {
3164 date = java.text.DateFormat.getInstance().parse(certificateDate);
3165 } catch (ParseException e) {
3166 date = null;
3167 }
3168
3169 if (date != null) {
3170 reformattedDate =
3171 DateFormat.getDateFormat(this).format(date);
3172 }
3173 }
3174
3175 return reformattedDate != null ? reformattedDate :
3176 (certificateDate != null ? certificateDate : "");
3177 }
3178
3179 /**
3180 * Displays an http-authentication dialog.
3181 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003182 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003183 final String host, final String realm, final String title,
3184 final String name, final String password, int focusId) {
3185 LayoutInflater factory = LayoutInflater.from(this);
3186 final View v = factory
3187 .inflate(R.layout.http_authentication, null);
3188 if (name != null) {
3189 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3190 }
3191 if (password != null) {
3192 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3193 }
3194
3195 String titleText = title;
3196 if (titleText == null) {
3197 titleText = getText(R.string.sign_in_to).toString().replace(
3198 "%s1", host).replace("%s2", realm);
3199 }
3200
3201 mHttpAuthHandler = handler;
3202 AlertDialog dialog = new AlertDialog.Builder(this)
3203 .setTitle(titleText)
3204 .setIcon(android.R.drawable.ic_dialog_alert)
3205 .setView(v)
3206 .setPositiveButton(R.string.action,
3207 new DialogInterface.OnClickListener() {
3208 public void onClick(DialogInterface dialog,
3209 int whichButton) {
3210 String nm = ((EditText) v
3211 .findViewById(R.id.username_edit))
3212 .getText().toString();
3213 String pw = ((EditText) v
3214 .findViewById(R.id.password_edit))
3215 .getText().toString();
3216 BrowserActivity.this.setHttpAuthUsernamePassword
3217 (host, realm, nm, pw);
3218 handler.proceed(nm, pw);
3219 mHttpAuthenticationDialog = null;
3220 mHttpAuthHandler = null;
3221 }})
3222 .setNegativeButton(R.string.cancel,
3223 new DialogInterface.OnClickListener() {
3224 public void onClick(DialogInterface dialog,
3225 int whichButton) {
3226 handler.cancel();
3227 BrowserActivity.this.resetTitleAndRevertLockIcon();
3228 mHttpAuthenticationDialog = null;
3229 mHttpAuthHandler = null;
3230 }})
3231 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3232 public void onCancel(DialogInterface dialog) {
3233 handler.cancel();
3234 BrowserActivity.this.resetTitleAndRevertLockIcon();
3235 mHttpAuthenticationDialog = null;
3236 mHttpAuthHandler = null;
3237 }})
3238 .create();
3239 // Make the IME appear when the dialog is displayed if applicable.
3240 dialog.getWindow().setSoftInputMode(
3241 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3242 dialog.show();
3243 if (focusId != 0) {
3244 dialog.findViewById(focusId).requestFocus();
3245 } else {
3246 v.findViewById(R.id.username_edit).requestFocus();
3247 }
3248 mHttpAuthenticationDialog = dialog;
3249 }
3250
3251 public int getProgress() {
3252 WebView w = mTabControl.getCurrentWebView();
3253 if (w != null) {
3254 return w.getProgress();
3255 } else {
3256 return 100;
3257 }
3258 }
3259
3260 /**
3261 * Set HTTP authentication password.
3262 *
3263 * @param host The host for the password
3264 * @param realm The realm for the password
3265 * @param username The username for the password. If it is null, it means
3266 * password can't be saved.
3267 * @param password The password
3268 */
3269 public void setHttpAuthUsernamePassword(String host, String realm,
3270 String username,
3271 String password) {
3272 WebView w = mTabControl.getCurrentWebView();
3273 if (w != null) {
3274 w.setHttpAuthUsernamePassword(host, realm, username, password);
3275 }
3276 }
3277
3278 /**
3279 * connectivity manager says net has come or gone... inform the user
3280 * @param up true if net has come up, false if net has gone down
3281 */
3282 public void onNetworkToggle(boolean up) {
3283 if (up == mIsNetworkUp) {
3284 return;
3285 } else if (up) {
3286 mIsNetworkUp = true;
3287 if (mAlertDialog != null) {
3288 mAlertDialog.cancel();
3289 mAlertDialog = null;
3290 }
3291 } else {
3292 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003293 if (mInLoad) {
3294 createAndShowNetworkDialog();
3295 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003296 }
3297 WebView w = mTabControl.getCurrentWebView();
3298 if (w != null) {
3299 w.setNetworkAvailable(up);
3300 }
3301 }
3302
Grace Kloba22ac16e2009-10-07 18:00:23 -07003303 boolean isNetworkUp() {
3304 return mIsNetworkUp;
3305 }
3306
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003307 // This method shows the network dialog alerting the user that the net is
3308 // down. It will only show the dialog if mAlertDialog is null.
3309 private void createAndShowNetworkDialog() {
3310 if (mAlertDialog == null) {
3311 mAlertDialog = new AlertDialog.Builder(this)
3312 .setTitle(R.string.loadSuspendedTitle)
3313 .setMessage(R.string.loadSuspended)
3314 .setPositiveButton(R.string.ok, null)
3315 .show();
3316 }
3317 }
3318
The Android Open Source Project0c908882009-03-03 19:32:16 -08003319 @Override
3320 protected void onActivityResult(int requestCode, int resultCode,
3321 Intent intent) {
3322 switch (requestCode) {
3323 case COMBO_PAGE:
3324 if (resultCode == RESULT_OK && intent != null) {
3325 String data = intent.getAction();
3326 Bundle extras = intent.getExtras();
3327 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003328 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003329 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003330 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003331 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003332 dismissSubWindow(currentTab);
3333 if (data != null && data.length() != 0) {
3334 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003335 }
3336 }
3337 }
3338 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003339 // Choose a file from the file picker.
3340 case FILE_SELECTED:
3341 if (null == mUploadMessage) break;
3342 Uri result = intent == null || resultCode != RESULT_OK ? null
3343 : intent.getData();
3344 mUploadMessage.onReceiveValue(result);
3345 mUploadMessage = null;
3346 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003347 default:
3348 break;
3349 }
Leon Scroggins30444232009-09-04 18:36:20 -04003350 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003351 }
3352
3353 /*
3354 * This method is called as a result of the user selecting the options
3355 * menu to see the download window, or when a download changes state. It
3356 * shows the download window ontop of the current window.
3357 */
3358 /* package */ void viewDownloads(Uri downloadRecord) {
3359 Intent intent = new Intent(this,
3360 BrowserDownloadPage.class);
3361 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003362 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003363
3364 }
3365
Leon Scroggins160a7e72009-08-14 18:28:01 -04003366 /**
3367 * Open the Go page.
3368 * @param startWithHistory If true, open starting on the history tab.
3369 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003370 */
Leon Scroggins30444232009-09-04 18:36:20 -04003371 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003372 WebView current = mTabControl.getCurrentWebView();
3373 if (current == null) {
3374 return;
3375 }
3376 Intent intent = new Intent(this,
3377 CombinedBookmarkHistoryActivity.class);
3378 String title = current.getTitle();
3379 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003380 Bitmap thumbnail = createScreenshot(current);
3381
The Android Open Source Project0c908882009-03-03 19:32:16 -08003382 // Just in case the user opens bookmarks before a page finishes loading
3383 // so the current history item, and therefore the page, is null.
3384 if (null == url) {
3385 url = mLastEnteredUrl;
3386 // This can happen.
3387 if (null == url) {
3388 url = mSettings.getHomePage();
3389 }
3390 }
3391 // In case the web page has not yet received its associated title.
3392 if (title == null) {
3393 title = url;
3394 }
3395 intent.putExtra("title", title);
3396 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003397 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003398 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003399 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003400 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003401 if (startWithHistory) {
3402 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3403 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3404 }
3405 startActivityForResult(intent, COMBO_PAGE);
3406 }
3407
3408 // Called when loading from context menu or LOAD_URL message
3409 private void loadURL(WebView view, String url) {
3410 // In case the user enters nothing.
3411 if (url != null && url.length() != 0 && view != null) {
3412 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003413 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003414 view.loadUrl(url);
3415 }
3416 }
3417 }
3418
The Android Open Source Project0c908882009-03-03 19:32:16 -08003419 private String smartUrlFilter(Uri inUri) {
3420 if (inUri != null) {
3421 return smartUrlFilter(inUri.toString());
3422 }
3423 return null;
3424 }
3425
Feng Qianb34f87a2009-03-24 21:27:26 -07003426 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003427 "(?i)" + // switch on case insensitive matching
3428 "(" + // begin group for schema
3429 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003430 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003431 ")" +
3432 "(.*)" );
3433
3434 /**
3435 * Attempts to determine whether user input is a URL or search
3436 * terms. Anything with a space is passed to search.
3437 *
3438 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3439 * "Http://" converts to "http://"
3440 *
3441 * @return Original or modified URL
3442 *
3443 */
3444 String smartUrlFilter(String url) {
3445
3446 String inUrl = url.trim();
3447 boolean hasSpace = inUrl.indexOf(' ') != -1;
3448
3449 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3450 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003451 // force scheme to lowercase
3452 String scheme = matcher.group(1);
3453 String lcScheme = scheme.toLowerCase();
3454 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003455 inUrl = lcScheme + matcher.group(2);
3456 }
3457 if (hasSpace) {
3458 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003459 }
3460 return inUrl;
3461 }
3462 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003463 // FIXME: Is this the correct place to add to searches?
3464 // what if someone else calls this function?
3465 int shortcut = parseUrlShortcut(inUrl);
3466 if (shortcut != SHORTCUT_INVALID) {
3467 Browser.addSearchUrl(mResolver, inUrl);
3468 String query = inUrl.substring(2);
3469 switch (shortcut) {
3470 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003471 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003472 case SHORTCUT_WIKIPEDIA_SEARCH:
3473 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3474 case SHORTCUT_DICTIONARY_SEARCH:
3475 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3476 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003477 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003478 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003479 }
3480 }
3481 } else {
3482 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
3483 return URLUtil.guessUrl(inUrl);
3484 }
3485 }
3486
3487 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003488 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003489 }
3490
Ben Murdochbff2d602009-07-01 20:19:05 +01003491 /* package */ void setShouldShowErrorConsole(boolean flag) {
3492 if (flag == mShouldShowErrorConsole) {
3493 // Nothing to do.
3494 return;
3495 }
3496
3497 mShouldShowErrorConsole = flag;
3498
Grace Kloba22ac16e2009-10-07 18:00:23 -07003499 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3500 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003501
3502 if (flag) {
3503 // Setting the show state of the console will cause it's the layout to be inflated.
3504 if (errorConsole.numberOfErrors() > 0) {
3505 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3506 } else {
3507 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3508 }
3509
3510 // Now we can add it to the main view.
3511 mErrorConsoleContainer.addView(errorConsole,
3512 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
3513 ViewGroup.LayoutParams.WRAP_CONTENT));
3514 } else {
3515 mErrorConsoleContainer.removeView(errorConsole);
3516 }
3517
3518 }
3519
Grace Kloba22ac16e2009-10-07 18:00:23 -07003520 boolean shouldShowErrorConsole() {
3521 return mShouldShowErrorConsole;
3522 }
3523
Andrei Popescu163ab742009-10-20 17:58:23 +01003524 private void setStatusBarVisibility(boolean visible) {
3525 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3526 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3527 }
3528
Grace Klobaeb6eef42009-09-15 17:56:32 -07003529 final static int LOCK_ICON_UNSECURE = 0;
3530 final static int LOCK_ICON_SECURE = 1;
3531 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003532
The Android Open Source Project0c908882009-03-03 19:32:16 -08003533 private BrowserSettings mSettings;
3534 private TabControl mTabControl;
3535 private ContentResolver mResolver;
3536 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003537 private View mCustomView;
3538 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003539 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003540
3541 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3542 // view, we should rewrite this.
3543 private int mCurrentMenuState = 0;
3544 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003545 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003546 private static final int EMPTY_MENU = -1;
3547 private Menu mMenu;
3548
3549 private FindDialog mFindDialog;
3550 // Used to prevent chording to result in firing two shortcuts immediately
3551 // one after another. Fixes bug 1211714.
3552 boolean mCanChord;
3553
3554 private boolean mInLoad;
3555 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003556 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003557
The Android Open Source Project0c908882009-03-03 19:32:16 -08003558 private boolean mActivityInPause = true;
3559
3560 private boolean mMenuIsDown;
3561
The Android Open Source Project0c908882009-03-03 19:32:16 -08003562 private static boolean mInTrace;
3563
3564 // Performance probe
3565 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3566 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3567 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3568 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3569 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3570 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3571 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3572 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3573 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3574 };
3575
3576 private long mStart;
3577 private long mProcessStart;
3578 private long mUserStart;
3579 private long mSystemStart;
3580 private long mIdleStart;
3581 private long mIrqStart;
3582
3583 private long mUiStart;
3584
3585 private Drawable mMixLockIcon;
3586 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003587
3588 /* hold a ref so we can auto-cancel if necessary */
3589 private AlertDialog mAlertDialog;
3590
3591 // Wait for credentials before loading google.com
3592 private ProgressDialog mCredsDlg;
3593
3594 // The up-to-date URL and title (these can be different from those stored
3595 // in WebView, since it takes some time for the information in WebView to
3596 // get updated)
3597 private String mUrl;
3598 private String mTitle;
3599
3600 // As PageInfo has different style for landscape / portrait, we have
3601 // to re-open it when configuration changed
3602 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003603 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003604 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3605 // dialog, we should not just dismiss it, but should get back to the
3606 // SSL-certificate-on-error dialog. This flag is used to store this state
3607 private Boolean mPageInfoFromShowSSLCertificateOnError;
3608
3609 // as SSLCertificateOnError has different style for landscape / portrait,
3610 // we have to re-open it when configuration changed
3611 private AlertDialog mSSLCertificateOnErrorDialog;
3612 private WebView mSSLCertificateOnErrorView;
3613 private SslErrorHandler mSSLCertificateOnErrorHandler;
3614 private SslError mSSLCertificateOnErrorError;
3615
3616 // as SSLCertificate has different style for landscape / portrait, we
3617 // have to re-open it when configuration changed
3618 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003619 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003620
3621 // as HttpAuthentication has different style for landscape / portrait, we
3622 // have to re-open it when configuration changed
3623 private AlertDialog mHttpAuthenticationDialog;
3624 private HttpAuthHandler mHttpAuthHandler;
3625
3626 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3627 new FrameLayout.LayoutParams(
3628 ViewGroup.LayoutParams.FILL_PARENT,
3629 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003630 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3631 new FrameLayout.LayoutParams(
3632 ViewGroup.LayoutParams.FILL_PARENT,
3633 ViewGroup.LayoutParams.FILL_PARENT,
3634 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003635 // Google search
3636 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003637 // Wikipedia search
3638 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3639 // Dictionary search
3640 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3641 // Google Mobile Local search
3642 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3643
3644 final static String QUERY_PLACE_HOLDER = "%s";
3645
3646 // "source" parameter for Google search through search key
3647 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3648 // "source" parameter for Google search through goto menu
3649 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3650 // "source" parameter for Google search through simplily type
3651 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3652 // "source" parameter for Google search suggested by the browser
3653 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3654 // "source" parameter for Google search from unknown source
3655 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3656
3657 private final static String LOGTAG = "browser";
3658
The Android Open Source Project0c908882009-03-03 19:32:16 -08003659 private String mLastEnteredUrl;
3660
3661 private PowerManager.WakeLock mWakeLock;
3662 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3663
3664 private Toast mStopToast;
3665
Leon Scroggins68579392009-09-15 15:31:54 -04003666 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003667
Ben Murdochbff2d602009-07-01 20:19:05 +01003668 private LinearLayout mErrorConsoleContainer = null;
3669 private boolean mShouldShowErrorConsole = false;
3670
The Android Open Source Project0c908882009-03-03 19:32:16 -08003671 // As the ids are dynamically created, we can't guarantee that they will
3672 // be in sequence, so this static array maps ids to a window number.
3673 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3674 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3675 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3676 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3677
3678 // monitor platform changes
3679 private IntentFilter mNetworkStateChangedFilter;
3680 private BroadcastReceiver mNetworkStateIntentReceiver;
3681
Grace Klobab4da0ad2009-05-14 14:45:40 -07003682 private BroadcastReceiver mPackageInstallationReceiver;
3683
The Android Open Source Project0c908882009-03-03 19:32:16 -08003684 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003685 final static int COMBO_PAGE = 1;
3686 final static int DOWNLOAD_PAGE = 2;
3687 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003688 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003689
Andrei Popescu540035d2009-09-18 18:59:20 +01003690 // the default <video> poster
3691 private Bitmap mDefaultVideoPoster;
3692 // the video progress view
3693 private View mVideoProgressView;
3694
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003695 /**
3696 * A UrlData class to abstract how the content will be set to WebView.
3697 * This base class uses loadUrl to show the content.
3698 */
3699 private static class UrlData {
3700 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07003701 byte[] mPostData;
3702
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003703 UrlData(String url) {
3704 this.mUrl = url;
3705 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003706
3707 void setPostData(byte[] postData) {
3708 mPostData = postData;
3709 }
3710
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003711 boolean isEmpty() {
3712 return mUrl == null || mUrl.length() == 0;
3713 }
3714
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003715 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07003716 if (mPostData != null) {
3717 webView.postUrl(mUrl, mPostData);
3718 } else {
3719 webView.loadUrl(mUrl);
3720 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003721 }
3722 };
3723
3724 /**
3725 * A subclass of UrlData class that can display inlined content using
3726 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3727 */
3728 private static class InlinedUrlData extends UrlData {
3729 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3730 super(failUrl);
3731 mInlined = inlined;
3732 mMimeType = mimeType;
3733 mEncoding = encoding;
3734 }
3735 String mMimeType;
3736 String mInlined;
3737 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003738 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003739 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01003740 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003741 }
3742
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003743 @Override
3744 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003745 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3746 }
3747 }
3748
Leon Scroggins1f005d32009-08-10 17:36:42 -04003749 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003750}